#[derive(Clone, Debug)]
pub struct Rng {
state: u64,
}
impl Rng {
pub fn new(seed: u64) -> Self {
let mut s = seed.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut out = 0u64;
for _ in 0..4 {
s = s.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = s;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
out = z ^ (z >> 31);
}
Self { state: out }
}
pub fn next_u64(&mut self) -> u64 {
let mut x = self.state;
x ^= x >> 12;
x ^= x << 25;
x ^= x >> 27;
self.state = x;
x.wrapping_mul(0x2545_F491_4F6C_DD1D)
}
pub fn next_f32(&mut self) -> f32 {
((self.next_u64() >> 40) as f32) / ((1u32 << 24) as f32)
}
pub fn next_symmetric(&mut self, r: f32) -> f32 {
(self.next_f32() * 2.0 - 1.0) * r
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn same_seed_same_sequence() {
let mut a = Rng::new(42);
let mut b = Rng::new(42);
for _ in 0..1000 {
assert_eq!(a.next_u64(), b.next_u64());
}
}
#[test]
fn different_seed_diverges() {
let mut a = Rng::new(1);
let mut b = Rng::new(2);
let sa: Vec<u64> = (0..16).map(|_| a.next_u64()).collect();
let sb: Vec<u64> = (0..16).map(|_| b.next_u64()).collect();
assert_ne!(sa, sb);
}
#[test]
fn f32_in_range() {
let mut r = Rng::new(7);
for _ in 0..10_000 {
let v = r.next_f32();
assert!((0.0..1.0).contains(&v));
let s = r.next_symmetric(3.0);
assert!((-3.0..3.0).contains(&s));
}
}
}