1*9ed5ae46Sbcook /* $OpenBSD: arc4random_uniform.c,v 1.3 2019/01/20 02:59:07 bcook Exp $ */
2fc506807Sderaadt
3fc506807Sderaadt /*
4fc506807Sderaadt * Copyright (c) 2008, Damien Miller <djm@openbsd.org>
5fc506807Sderaadt *
6fc506807Sderaadt * Permission to use, copy, modify, and distribute this software for any
7fc506807Sderaadt * purpose with or without fee is hereby granted, provided that the above
8fc506807Sderaadt * copyright notice and this permission notice appear in all copies.
9fc506807Sderaadt *
10fc506807Sderaadt * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11fc506807Sderaadt * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12fc506807Sderaadt * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13fc506807Sderaadt * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14fc506807Sderaadt * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15fc506807Sderaadt * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16fc506807Sderaadt * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17fc506807Sderaadt */
18fc506807Sderaadt
19*9ed5ae46Sbcook #include <stdint.h>
20fc506807Sderaadt #include <stdlib.h>
21fc506807Sderaadt
22fc506807Sderaadt /*
23fc506807Sderaadt * Calculate a uniformly distributed random number less than upper_bound
24fc506807Sderaadt * avoiding "modulo bias".
25fc506807Sderaadt *
26fc506807Sderaadt * Uniformity is achieved by generating new random numbers until the one
27fc506807Sderaadt * returned is outside the range [0, 2**32 % upper_bound). This
28fc506807Sderaadt * guarantees the selected random number will be inside
29fc506807Sderaadt * [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound)
30fc506807Sderaadt * after reduction modulo upper_bound.
31fc506807Sderaadt */
32fc506807Sderaadt uint32_t
arc4random_uniform(uint32_t upper_bound)33fc506807Sderaadt arc4random_uniform(uint32_t upper_bound)
34fc506807Sderaadt {
35fc506807Sderaadt uint32_t r, min;
36fc506807Sderaadt
37fc506807Sderaadt if (upper_bound < 2)
38fc506807Sderaadt return 0;
39fc506807Sderaadt
40fc506807Sderaadt /* 2**32 % x == (2**32 - x) % x */
41fc506807Sderaadt min = -upper_bound % upper_bound;
42fc506807Sderaadt
43fc506807Sderaadt /*
44fc506807Sderaadt * This could theoretically loop forever but each retry has
45fc506807Sderaadt * p > 0.5 (worst case, usually far better) of selecting a
46fc506807Sderaadt * number inside the range we need, so it should rarely need
47fc506807Sderaadt * to re-roll.
48fc506807Sderaadt */
49fc506807Sderaadt for (;;) {
50fc506807Sderaadt r = arc4random();
51fc506807Sderaadt if (r >= min)
52fc506807Sderaadt break;
53fc506807Sderaadt }
54fc506807Sderaadt
55fc506807Sderaadt return r % upper_bound;
56fc506807Sderaadt }
570d943ef0Sguenther DEF_WEAK(arc4random_uniform);
58