]> mj.ucw.cz Git - libucw.git/blob - ucw/random-legacy.c
Random: Defined random_gen_seed() to simplify old programs.
[libucw.git] / ucw / random-legacy.c
1 /*
2  *      UCW Library -- Unbiased Random Numbers
3  *
4  *      (c) 1998--2006 Martin Mares <mj@ucw.cz>
5  *      (c) 2020 Pavel Charvat <pchar@ucw.cz>
6  *
7  *      This software may be freely distributed and used according to the terms
8  *      of the GNU Lesser General Public License.
9  */
10
11 #include <ucw/lib.h>
12 #include <ucw/random.h>
13
14 #include <stdlib.h>
15
16 /* We expect the random generator in libc to give at least 30 bits of randomness */
17 COMPILE_ASSERT(RAND_MAX_RANGE_TEST, RAND_MAX >= (1 << 30)-1);
18
19 void
20 random_set_seed(uint seed)
21 {
22   srandom(seed);
23 }
24
25 uint
26 random_gen_seed(void)
27 {
28   uint seed = fastrand_gen_seed_value();
29   random_set_seed(seed);
30   return seed;
31 }
32
33 uint
34 random_u32(void)
35 {
36   return (random() & 0xffff) | ((random() & 0xffff) << 16);
37 }
38
39 uint
40 random_max(uint max)
41 {
42   uint r, l;
43
44   ASSERT(max <= (1 << 30));
45   l = (RAND_MAX + 1U) - ((RAND_MAX + 1U) % max);
46   do
47     r = random();
48   while (r >= l);
49   return r % max;
50 }
51
52 u64
53 random_u64(void)
54 {
55   return
56     ((u64)(random() & 0xffff) << 48) |
57     ((u64)(random() & 0xffffff) << 24) |
58     (random() & 0xffffff);
59 }
60
61 u64
62 random_max_u64(u64 max)
63 {
64   if (max < (1 << 30))
65     return random_max(max);
66
67   u64 r, l, m;
68   m = 0xffffffffffffffff;
69   l = m - (m % max);
70   do
71     r = random_u64();
72   while (r >= l);
73   return r % max;
74 }