use core::convert::Infallible;
use rand_core::Rng;
#[derive(Debug, Clone)]
pub struct SplitMix64 {
state: u64,
}
impl SplitMix64 {
#[must_use]
pub const fn new(seed: u64) -> Self {
Self { state: seed }
}
pub(crate) 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(crate) fn next_unit(&mut self) -> f64 {
unit_interval(self)
}
}
impl rand_core::TryRng for SplitMix64 {
type Error = Infallible;
fn try_next_u32(&mut self) -> Result<u32, Infallible> {
Ok((self.next_u64() >> 32) as u32)
}
fn try_next_u64(&mut self) -> Result<u64, Infallible> {
Ok(self.next_u64())
}
fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Infallible> {
rand_core::utils::fill_bytes_via_next_word(dst, || self.try_next_u64())
}
}
pub fn unit_interval<R: Rng + ?Sized>(rng: &mut R) -> f64 {
const SCALE: f64 = 1.0 / 9_007_199_254_740_992.0;
#[expect(
clippy::cast_precision_loss,
reason = "the value has at most 53 bits, which f64 represents exactly"
)]
let bits = (rng.next_u64() >> 11) as f64;
bits * SCALE
}
pub(crate) fn derive_seed(seed: u64, a: u64, b: u64) -> u64 {
let first = SplitMix64::new(seed ^ a.wrapping_mul(0xD1B5_4A32_D192_ED03)).next_u64();
SplitMix64::new(first ^ b.wrapping_mul(0xA24B_AED4_963E_E407)).next_u64()
}
#[cfg(test)]
mod tests {
use super::SplitMix64;
#[test]
fn matches_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 unit_samples_are_in_range() {
let mut rng = SplitMix64::new(42);
for _ in 0..1000 {
let u = rng.next_unit();
assert!((0.0..1.0).contains(&u));
}
}
#[test]
fn derived_seeds_are_distinct_and_stable() {
use super::derive_seed;
let seeds = [
derive_seed(1, 0, 0),
derive_seed(1, 1, 0),
derive_seed(1, 0, 1),
derive_seed(2, 0, 0),
];
for (i, a) in seeds.iter().enumerate() {
for b in &seeds[i + 1..] {
assert_ne!(a, b);
}
}
assert_eq!(derive_seed(1, 1, 0), seeds[1]);
}
}