1#[derive(Clone, Debug)]
10pub struct Rng(u64);
11
12impl Rng {
13 pub fn new(seed: u64) -> Self {
15 Rng(seed)
16 }
17
18 pub fn fork(&self, tag: u64) -> Rng {
20 let mut r = Rng(self.0 ^ tag.wrapping_mul(0xD6E8_FEB8_6659_FD93));
21 r.next_u64();
22 r
23 }
24
25 pub fn next_u64(&mut self) -> u64 {
27 self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
28 let mut z = self.0;
29 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
30 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
31 z ^ (z >> 31)
32 }
33
34 pub fn frand(&mut self) -> f32 {
36 (self.next_u64() >> 40) as f32 / 16_777_216.0
37 }
38
39 pub fn below(&mut self, n: u32) -> u32 {
41 if n == 0 {
42 return 0;
43 }
44 (((self.next_u64() >> 32) * n as u64) >> 32) as u32
45 }
46}
47
48#[cfg(test)]
49mod tests {
50 use super::*;
51
52 #[test]
53 fn deterministic_and_in_range() {
54 let mut a = Rng::new(1);
55 let mut b = Rng::new(1);
56 for _ in 0..1000 {
57 let x = a.frand();
58 assert_eq!(x, b.frand());
59 assert!((0.0..1.0).contains(&x));
60 }
61 let mut c = Rng::new(2);
62 assert_ne!(Rng::new(1).next_u64(), c.next_u64());
63 for _ in 0..1000 {
64 assert!(a.below(7) < 7);
65 }
66 }
67}