#[derive(Clone, Debug)]
pub struct SplitMix64 {
state: u64,
}
impl SplitMix64 {
pub const fn new(seed: u64) -> Self {
Self { state: seed }
}
pub const fn next_u64(&mut self) -> u64 {
self.state = self.state.wrapping_add(0x9e37_79b9_7f4a_7c15);
let mut z = self.state;
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
z ^ (z >> 31)
}
pub const fn below(&mut self, bound: u64) -> u64 {
if bound == 0 {
return 0;
}
self.next_u64() % bound
}
}
#[cfg(test)]
mod tests {
use super::SplitMix64;
#[test]
fn matches_the_reference_sequence() {
let mut rng = SplitMix64::new(0);
assert_eq!(rng.next_u64(), 0xe220_a839_7b1d_cdaf);
assert_eq!(rng.next_u64(), 0x6e78_9e6a_a1b9_65f4);
}
#[test]
fn below_stays_in_range() {
let mut rng = SplitMix64::new(42);
assert!((0..1000).all(|_| rng.below(7) < 7));
assert_eq!(rng.below(0), 0);
}
}