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