rusty_time-sim 0.3.2

timecorp, the deterministic corpus runner for rusty_time: simulated clock and network scenarios producing reproducible convergence, accuracy and server-load numbers, plus instruction-count benchmarks.
//! PCG32: small, seedable, deterministic across platforms — the property the
//! corpus needs. (Not cryptographic; never used outside simulation.)

pub struct Pcg32 {
    state: u64,
    inc: u64,
}

impl Pcg32 {
    pub fn new(seed: u64, stream: u64) -> Self {
        let mut rng = Pcg32 {
            state: 0,
            inc: (stream << 1) | 1,
        };
        rng.next_u32();
        rng.state = rng.state.wrapping_add(seed);
        rng.next_u32();
        rng
    }

    pub fn next_u32(&mut self) -> u32 {
        let old = self.state;
        self.state = old
            .wrapping_mul(6_364_136_223_846_793_005)
            .wrapping_add(self.inc);
        let xorshifted = (((old >> 18) ^ old) >> 27) as u32;
        let rot = (old >> 59) as u32;
        xorshifted.rotate_right(rot)
    }

    /// Uniform in [0, 1).
    pub fn uniform(&mut self) -> f64 {
        self.next_u32() as f64 / 4_294_967_296.0
    }

    /// Standard normal (Box–Muller; one draw per call, second discarded for
    /// simplicity — determinism matters here, elegance does not).
    pub fn normal(&mut self) -> f64 {
        let u1 = (self.uniform()).max(1e-12);
        let u2 = self.uniform();
        (-2.0 * u1.ln()).sqrt() * (core::f64::consts::TAU * u2).cos()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn deterministic_across_instances() {
        let mut a = Pcg32::new(42, 7);
        let mut b = Pcg32::new(42, 7);
        for _ in 0..1000 {
            assert_eq!(a.next_u32(), b.next_u32());
        }
    }

    #[test]
    fn normal_is_roughly_standard() {
        let mut r = Pcg32::new(1, 1);
        let n = 20_000;
        let mut sum = 0.0;
        let mut sum2 = 0.0;
        for _ in 0..n {
            let x = r.normal();
            sum += x;
            sum2 += x * x;
        }
        let mean = sum / n as f64;
        let var = sum2 / n as f64 - mean * mean;
        assert!(mean.abs() < 0.03, "mean {mean}");
        assert!((var - 1.0).abs() < 0.05, "var {var}");
    }
}