pub trait Random {
fn next_u64(&mut self) -> u64;
fn below(&mut self, len: usize) -> usize {
let len = u64::try_from(len).expect("a slice length fits in u64");
usize::try_from(self.next_u64() % len).expect("an index below a length fits in usize")
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SplitMix64 {
state: u64,
}
impl SplitMix64 {
#[must_use]
pub const fn new(seed: u64) -> Self {
Self { state: seed }
}
}
impl Random for SplitMix64 {
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)
}
}
#[cfg(feature = "rand_core")]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RandCore<R>(pub R);
#[cfg(feature = "rand_core")]
impl<R: rand_core::Rng> Random for RandCore<R> {
fn next_u64(&mut self) -> u64 {
self.0.next_u64()
}
}
#[cfg(test)]
mod tests {
use super::{Random, SplitMix64};
#[test]
fn matches_the_reference_sequence() {
assert_eq!(SplitMix64::new(0).next_u64(), 0xe220_a839_7b1d_cdaf);
}
#[test]
fn indices_stay_in_range() {
let mut rng = SplitMix64::new(3);
assert!((0..1000).all(|_| rng.below(7) < 7));
assert_eq!(rng.below(1), 0);
}
}