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