* Calculate a uniformly distributed random number less than upper_bound * avoiding "modulo bias". * * Uniformity is achieved by generating new random numbers until the one * returned is outside the range [0, 2**32 % upper_bound). This * guarantees the selected random number will be inside * [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound) * after reduction modulo upper_boun
| 32 | * after reduction modulo upper_bound. |
| 33 | */ |
| 34 | uint32_t |
| 35 | arc4random_uniform(uint32_t upper_bound) |
| 36 | { |
| 37 | uint32_t r, min; |
| 38 | |
| 39 | if (upper_bound < 2) |
| 40 | return 0; |
| 41 | |
| 42 | /* 2**32 % x == (2**32 - x) % x */ |
| 43 | min = -upper_bound % upper_bound; |
| 44 | |
| 45 | /* |
| 46 | * This could theoretically loop forever but each retry has |
| 47 | * p > 0.5 (worst case, usually far better) of selecting a |
| 48 | * number inside the range we need, so it should rarely need |
| 49 | * to re-roll. |
| 50 | */ |
| 51 | for (;;) { |
| 52 | r = arc4random(); |
| 53 | if (r >= min) |
| 54 | break; |
| 55 | } |
| 56 | |
| 57 | return r % upper_bound; |
| 58 | } |
no test coverage detected