1use core::convert::Infallible;
8
9use rand_core::{Rng, TryRng};
10
11#[derive(Clone, Debug)]
16pub struct SplitMix64 {
17 state: u64,
19}
20
21impl SplitMix64 {
22 #[must_use]
24 pub const fn new(seed: u64) -> Self {
25 Self { state: seed }
26 }
27
28 fn step(&mut self) -> u64 {
30 self.state = self.state.wrapping_add(0x9E37_79B9_7F4A_7C15);
31
32 let mut z = self.state;
33 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
34 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
35
36 z ^ (z >> 31)
37 }
38}
39
40impl TryRng for SplitMix64 {
42 type Error = Infallible;
43
44 fn try_next_u32(&mut self) -> Result<u32, Infallible> {
45 let upper = (self.step() >> 32) as u32;
47
48 Ok(upper)
49 }
50
51 fn try_next_u64(&mut self) -> Result<u64, Infallible> {
52 Ok(self.step())
53 }
54
55 fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Infallible> {
56 for chunk in dst.chunks_mut(8) {
57 let bytes = self.step().to_le_bytes();
58 chunk.copy_from_slice(&bytes[..chunk.len()]);
59 }
60
61 Ok(())
62 }
63}
64
65pub(crate) fn unit_f64<R: Rng + ?Sized>(rng: &mut R) -> f64 {
67 const UNIT: f64 = 1.0 / 9_007_199_254_740_992.0;
69
70 #[expect(
71 clippy::cast_precision_loss,
72 reason = "the value has 53 bits after the shift, so f64 holds it exactly"
73 )]
74 let bits = (rng.next_u64() >> 11) as f64;
75
76 bits * UNIT
77}
78
79pub(crate) fn below<R: Rng + ?Sized>(rng: &mut R, bound: usize) -> usize {
84 let wide = u128::from(rng.next_u64()) * bound as u128;
85
86 #[expect(
87 clippy::cast_possible_truncation,
88 reason = "the high word is below bound, so it fits in usize"
89 )]
90 let value = (wide >> 64) as usize;
91
92 value
93}
94
95#[cfg(test)]
97mod tests {
98 use super::{SplitMix64, below, unit_f64};
99 use rand_core::Rng;
100
101 #[test]
103 fn is_reproducible_and_in_range() {
104 let mut a = SplitMix64::new(7);
105 let mut b = SplitMix64::new(7);
106
107 for _ in 0..1000 {
108 assert_eq!(a.next_u64(), b.next_u64());
109 assert!((0.0..1.0).contains(&unit_f64(&mut a)));
110 assert!(below(&mut a, 10) < 10);
111
112 unit_f64(&mut b);
113 below(&mut b, 10);
114 }
115
116 assert_eq!(below(&mut a, 0), 0);
117 }
118
119 #[test]
121 fn fills_bytes_from_the_sequence() {
122 let mut words = SplitMix64::new(1);
123 let first = words.next_u64().to_le_bytes();
124 let second = words.next_u64().to_le_bytes();
125
126 let mut bytes = [0_u8; 11];
127 SplitMix64::new(1).fill_bytes(&mut bytes);
128
129 assert_eq!(bytes[..8], first);
130 assert_eq!(bytes[8..], second[..3]);
131 assert_eq!(
132 SplitMix64::new(1).next_u32(),
133 u32::from_le_bytes([first[4], first[5], first[6], first[7]])
134 );
135 }
136}