]> mj.ucw.cz Git - libucw.git/blob - lib/random.c
Unaligned access functions (formerly macros) work in native, big and little endian.
[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   ASSERT(max <= (1 << 30));
23   l = (RAND_MAX + 1U) - ((RAND_MAX + 1U) % max);
24   do
25     r = random();
26   while (r >= l);
27   return r % max;
28 }
29
30 u64
31 random_u64(void)
32 {
33   return
34     ((u64)(random() & 0xffff) << 48) |
35     ((u64)(random() & 0xffffff) << 24) |
36     (random() & 0xffffff);
37 }
38
39 u64
40 random_max_u64(u64 max)
41 {
42   if (max < (1 << 30))
43     return random_max(max);
44
45   u64 r, l, m;
46   m = 0xffffffffffffffff;
47   l = m - (m % max);
48   do
49     r = random_u64();
50   while (r >= l);
51   return r % max;
52 }