bitcoinleveldb_rand/random.rs
1crate::ix!();
2
3//-------------------------------------------[.cpp/bitcoin/src/leveldb/util/random.h]
4
5/**
6 | A very simple random number generator. Not
7 | especially good at generating truly random
8 | bits, but good enough for our needs in this
9 | package.
10 */
11pub struct Random {
12 seed: u32,
13}
14
15impl Random {
16
17 pub fn new(s: u32) -> Self {
18
19 todo!();
20 /*
21
22
23 : seed_(s & 0x7fffffffu)
24 // Avoid bad seeds.
25 if (seed_ == 0 || seed_ == 2147483647L) {
26 seed_ = 1;
27 }
28 */
29 }
30
31 pub fn next(&mut self) -> u32 {
32
33 todo!();
34 /*
35 static const uint32_t M = 2147483647L; // 2^31-1
36 static const uint64_t A = 16807; // bits 14, 8, 7, 5, 2, 1, 0
37 // We are computing
38 // seed_ = (seed_ * A) % M, where M = 2^31-1
39 //
40 // seed_ must not be zero or M, or else all subsequent computed values
41 // will be zero or M respectively. For all other values, seed_ will end
42 // up cycling through every number in [1,M-1]
43 uint64_t product = seed_ * A;
44
45 // Compute (product % M) using the fact that ((x << 31) % M) == x.
46 seed_ = static_cast<uint32_t>((product >> 31) + (product & M));
47 // The first reduction may overflow by 1 bit, so we may need to
48 // repeat. mod == M is not possible; using > allows the faster
49 // sign-bit-based test.
50 if (seed_ > M) {
51 seed_ -= M;
52 }
53 return seed_;
54 */
55 }
56
57 /**
58 | Returns a uniformly distributed value in the
59 | range [0..n-1]
60 |
61 | REQUIRES: n > 0
62 */
63 pub fn uniform(&mut self, n: i32) -> u32 {
64
65 todo!();
66 /*
67 return Next() % n;
68 */
69 }
70
71 /**
72 | Randomly returns true ~"1/n" of the time, and
73 | false otherwise.
74 |
75 | REQUIRES: n > 0
76 */
77 pub fn one_in(&mut self, n: i32) -> bool {
78
79 todo!();
80 /*
81 return (Next() % n) == 0;
82 */
83 }
84
85 /**
86 | Skewed: pick "base" uniformly from range
87 | [0,max_log] and then return "base" random
88 | bits. The effect is to pick a number in the
89 | range [0,2^max_log-1] with exponential bias
90 | towards smaller numbers.
91 */
92 pub fn skewed(&mut self, max_log: i32) -> u32 {
93
94 todo!();
95 /*
96 return Uniform(1 << Uniform(max_log + 1));
97 */
98 }
99}