]> mj.ucw.cz Git - libucw.git/blob - lib/random.c
Added random_u64() and random_max_u64().
[libucw.git] / lib / random.c
1 /*
2  *      UCW Library -- Unbiased Random Numbers
3  *
4  *      (c) 1998--2006 Martin Mares <mj@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #include "lib/lib.h"
11
12 #include <stdlib.h>
13
14 /* We expect the random generator in libc to give at least 30 bits of randomness */
15 COMPILE_ASSERT(RAND_MAX_RANGE_TEST, RAND_MAX >= (1 << 30)-1);
16
17 uns
18 random_max(uns max)
19 {
20   uns r, l;
21
22   l = (RAND_MAX + 1U) - ((RAND_MAX + 1U) % max);
23   do
24     r = random();
25   while (r >= l);
26   return r % max;
27 }
28
29 u64
30 random_u64(void)
31 {
32   return
33     ((u64)(random() & 0xffff) << 48) |
34     ((u64)(random() & 0xffffff) << 24) |
35     (random() & 0xffffff);
36 }
37
38 u64
39 random_max_u64(u64 max)
40 {
41   if (max < (1 << 30))
42     return random_max(max);
43
44   u64 r, l, m;
45   m = 0xffffffffffffffff;
46   l = m - (m % max);
47   do
48     r = random_u64();
49   while (r >= l);
50   return r % max;
51 }