Skip to main content

byteflow/
prng.rs

1//! Deterministic PRNG for in-crate property-style tests (no external crates).
2//!
3//! Used by integration tests (`tests/properties_*`) and CapTable stress
4//! suites. Not for CapId entropy — see [`crate::entropy`].
5
6/// Odd multiplier from Vigna's xorshift64*. It is applied to the returned
7/// word only; folding it into the state would collapse the period.
8const STAR: u64 = 0x2545_F491_4F6C_DD1D;
9
10/// Stand-in for a zero seed. The all-zero state is a fixed point of the
11/// shifts, so it is the one seed this generator cannot run.
12const NONZERO_SEED: u64 = 0x9E37_79B9_7F4A_7C15;
13
14/// xorshift64* — enough for stress loops; not for CapId entropy.
15#[derive(Clone, Debug)]
16pub struct XorShift64(u64);
17
18impl XorShift64 {
19    pub fn new(seed: u64) -> Self {
20        XorShift64(if seed == 0 { NONZERO_SEED } else { seed })
21    }
22
23    pub fn next_u64(&mut self) -> u64 {
24        let mut x = self.0;
25        x ^= x >> 12;
26        x ^= x << 25;
27        x ^= x >> 27;
28        self.0 = x;
29        x.wrapping_mul(STAR)
30    }
31
32    /// High half of [`Self::next_u64`]. The multiply already mixes the low
33    /// bits; narrowing still keeps the half that moved farthest.
34    pub fn next_u32(&mut self) -> u32 {
35        (self.next_u64() >> 32) as u32
36    }
37
38    pub fn next_i64(&mut self) -> i64 {
39        self.next_u64() as i64
40    }
41
42    pub fn next_i32(&mut self) -> i32 {
43        self.next_u32() as i32
44    }
45
46    /// Inclusive `lo..=hi` when `lo <= hi`. When `lo > hi`, returns `lo`.
47    ///
48    /// Draws that would fall in the incomplete residue class are discarded,
49    /// so each value in the span is equally likely.
50    pub fn next_u32_inclusive(&mut self, lo: u32, hi: u32) -> u32 {
51        if lo >= hi {
52            return lo;
53        }
54        let span = u64::from(hi - lo) + 1;
55        let limit = span * (u64::MAX / span);
56        loop {
57            let draw = self.next_u64();
58            if draw < limit {
59                return lo + (draw % span) as u32;
60            }
61        }
62    }
63
64    pub fn fill_bytes(&mut self, buf: &mut [u8]) {
65        let mut i = 0;
66        while i < buf.len() {
67            let word = self.next_u64().to_le_bytes();
68            let take = (buf.len() - i).min(word.len());
69            buf[i..i + take].copy_from_slice(&word[..take]);
70            i += take;
71        }
72    }
73}
74
75#[cfg(test)]
76mod tests {
77    use super::*;
78
79    #[test]
80    fn zero_seed_is_forced_nonzero_and_deterministic() {
81        let mut a = XorShift64::new(0);
82        let mut b = XorShift64::new(0);
83        let x = a.next_u64();
84        let y = b.next_u64();
85        assert_ne!(x, 0);
86        assert_eq!(x, y);
87        assert_eq!(a.next_u64(), b.next_u64());
88    }
89
90    #[test]
91    fn seeds_that_differ_by_one_diverge() {
92        let mut even = XorShift64::new(2);
93        let mut odd = XorShift64::new(3);
94        assert_ne!(even.next_u64(), odd.next_u64());
95    }
96
97    #[test]
98    fn first_word_matches_xorshift64_star() {
99        // seed 1 → state 0x2000001, times the star constant.
100        let mut rng = XorShift64::new(1);
101        assert_eq!(rng.next_u64(), 0x47e4_ce4b_896c_dd1d);
102    }
103
104    #[test]
105    fn width_helpers_and_fill_are_wired() {
106        let mut rng = XorShift64::new(0x71E5_7001);
107        let _ = rng.next_u32();
108        let _ = rng.next_i64();
109        let _ = rng.next_i32();
110        assert_eq!(rng.next_u32_inclusive(5, 5), 5);
111        assert_eq!(rng.next_u32_inclusive(4, 1), 4);
112        for _ in 0..64 {
113            let n = rng.next_u32_inclusive(1, 4);
114            assert!((1..=4).contains(&n));
115        }
116        let mut buf = [0u8; 20];
117        rng.fill_bytes(&mut buf);
118        assert!(buf.iter().any(|&b| b != 0));
119    }
120}