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