Skip to main content

quantum_planning/
rng.rs

1//! Random draws over [`rand_core::Rng`], and a small seeded generator.
2//!
3//! The simulator and the searches take any `R: Rng`, so a fixed seed gives reproducible
4//! measurements and BBHT rounds. [`SplitMix64`] is a dependency-free generator for callers
5//! that have none.
6
7use core::convert::Infallible;
8
9use rand_core::{Rng, TryRng};
10
11/// The `SplitMix64` generator: fast, seedable and reproducible on every platform.
12///
13/// It is not cryptographically secure. Use it only to sample measurements and to pick
14/// iteration counts.
15#[derive(Clone, Debug)]
16pub struct SplitMix64 {
17    /// The generator state. Each step adds the golden-ratio increment to it.
18    state: u64,
19}
20
21impl SplitMix64 {
22    /// Makes a generator from `seed`. The same seed gives the same sequence.
23    #[must_use]
24    pub const fn new(seed: u64) -> Self {
25        Self { state: seed }
26    }
27
28    /// Advances the state and returns the next 64 random bits.
29    fn step(&mut self) -> u64 {
30        self.state = self.state.wrapping_add(0x9E37_79B9_7F4A_7C15);
31
32        let mut z = self.state;
33        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
34        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
35
36        z ^ (z >> 31)
37    }
38}
39
40/// The generator cannot fail, so it is an [`Rng`] through the blanket impl of `rand_core`.
41impl TryRng for SplitMix64 {
42    type Error = Infallible;
43
44    fn try_next_u32(&mut self) -> Result<u32, Infallible> {
45        // The upper half of the output has the better bits; the shift makes the cast lossless.
46        let upper = (self.step() >> 32) as u32;
47
48        Ok(upper)
49    }
50
51    fn try_next_u64(&mut self) -> Result<u64, Infallible> {
52        Ok(self.step())
53    }
54
55    fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Infallible> {
56        for chunk in dst.chunks_mut(8) {
57            let bytes = self.step().to_le_bytes();
58            chunk.copy_from_slice(&bytes[..chunk.len()]);
59        }
60
61        Ok(())
62    }
63}
64
65/// Returns a uniform value in `[0, 1)` with 53 random bits from `rng`.
66pub(crate) fn unit_f64<R: Rng + ?Sized>(rng: &mut R) -> f64 {
67    /// The weight of the lowest of the 53 mantissa bits, `2^-53`.
68    const UNIT: f64 = 1.0 / 9_007_199_254_740_992.0;
69
70    #[expect(
71        clippy::cast_precision_loss,
72        reason = "the value has 53 bits after the shift, so f64 holds it exactly"
73    )]
74    let bits = (rng.next_u64() >> 11) as f64;
75
76    bits * UNIT
77}
78
79/// Returns a uniform integer in `0..bound` from `rng`, or `0` when `bound` is `0`.
80///
81/// shortcut: multiply-high without rejection, so the bias is at most `bound / 2^64`; add
82/// rejection if a caller ever needs exact uniformity.
83pub(crate) fn below<R: Rng + ?Sized>(rng: &mut R, bound: usize) -> usize {
84    let wide = u128::from(rng.next_u64()) * bound as u128;
85
86    #[expect(
87        clippy::cast_possible_truncation,
88        reason = "the high word is below bound, so it fits in usize"
89    )]
90    let value = (wide >> 64) as usize;
91
92    value
93}
94
95/// Unit tests for the generator and the draws.
96#[cfg(test)]
97mod tests {
98    use super::{SplitMix64, below, unit_f64};
99    use rand_core::Rng;
100
101    /// The same seed gives the same sequence, and the draws stay in range.
102    #[test]
103    fn is_reproducible_and_in_range() {
104        let mut a = SplitMix64::new(7);
105        let mut b = SplitMix64::new(7);
106
107        for _ in 0..1000 {
108            assert_eq!(a.next_u64(), b.next_u64());
109            assert!((0.0..1.0).contains(&unit_f64(&mut a)));
110            assert!(below(&mut a, 10) < 10);
111
112            unit_f64(&mut b);
113            below(&mut b, 10);
114        }
115
116        assert_eq!(below(&mut a, 0), 0);
117    }
118
119    /// `fill_bytes` writes the little-endian words of the sequence, also into a partial chunk.
120    #[test]
121    fn fills_bytes_from_the_sequence() {
122        let mut words = SplitMix64::new(1);
123        let first = words.next_u64().to_le_bytes();
124        let second = words.next_u64().to_le_bytes();
125
126        let mut bytes = [0_u8; 11];
127        SplitMix64::new(1).fill_bytes(&mut bytes);
128
129        assert_eq!(bytes[..8], first);
130        assert_eq!(bytes[8..], second[..3]);
131        assert_eq!(
132            SplitMix64::new(1).next_u32(),
133            u32::from_le_bytes([first[4], first[5], first[6], first[7]])
134        );
135    }
136}