MCPcopy Create free account
hub / github.com/F-Stack/f-stack / arc4random_uniform

Function arc4random_uniform

freebsd/libkern/arc4random_uniform.c:34–58  ·  view source on GitHub ↗

* 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

Source from the content-addressed store, hash-verified

32 * after reduction modulo upper_bound.
33 */
34uint32_t
35arc4random_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}

Callers 3

mainFunction · 0.85

Calls 1

arc4randomFunction · 0.70

Tested by

no test coverage detected