]> mj.ucw.cz Git - moe.git/blob - ucw/random.c
Box: Support systems with 64-bit kernel and 32-bit user space
[moe.git] / ucw / 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 "ucw/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_u32(void)
19 {
20   return (random() & 0xffff) | ((random() & 0xffff) << 16);
21 }
22
23 uns
24 random_max(uns max)
25 {
26   uns r, l;
27
28   ASSERT(max <= (1 << 30));
29   l = (RAND_MAX + 1U) - ((RAND_MAX + 1U) % max);
30   do
31     r = random();
32   while (r >= l);
33   return r % max;
34 }
35
36 u64
37 random_u64(void)
38 {
39   return
40     ((u64)(random() & 0xffff) << 48) |
41     ((u64)(random() & 0xffffff) << 24) |
42     (random() & 0xffffff);
43 }
44
45 u64
46 random_max_u64(u64 max)
47 {
48   if (max < (1 << 30))
49     return random_max(max);
50
51   u64 r, l, m;
52   m = 0xffffffffffffffff;
53   l = m - (m % max);
54   do
55     r = random_u64();
56   while (r >= l);
57   return r % max;
58 }