Skip to main content

sgl_core/
rng.rs

1//! Frozen `SplitMix64` stream.
2
3/// The frozen `SplitMix64` pseudo-random generator.
4#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5pub struct SplitMix64 {
6    stream_seed: u64,
7    cursor: u64,
8}
9
10impl SplitMix64 {
11    /// Starts a stream from its immutable seed.
12    #[must_use]
13    pub const fn new(seed: u64) -> Self {
14        Self {
15            stream_seed: seed,
16            cursor: seed,
17        }
18    }
19
20    /// Returns the immutable stream seed, unaffected by draws.
21    #[must_use]
22    pub const fn stream_seed(self) -> u64 {
23        self.stream_seed
24    }
25
26    /// Returns the mutable generator cursor.
27    #[must_use]
28    pub const fn cursor(self) -> u64 {
29        self.cursor
30    }
31
32    /// Produces the next frozen `SplitMix64` word.
33    pub fn next_u64(&mut self) -> u64 {
34        self.cursor = self.cursor.wrapping_add(0x9e37_79b9_7f4a_7c15);
35        let mut value = self.cursor;
36        value = (value ^ (value >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
37        value = (value ^ (value >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
38        value ^ (value >> 31)
39    }
40
41    /// Samples the inclusive range using frozen modulo reduction.
42    ///
43    /// # Panics
44    ///
45    /// Panics when `min > max`.
46    #[must_use]
47    pub fn range_inclusive(&mut self, min: u32, max: u32) -> u32 {
48        assert!(min <= max, "range_inclusive requires min <= max");
49        let width = u64::from(max - min) + 1;
50        min + u32::try_from(self.next_u64() % width)
51            .expect("modulo result fits within the requested u32 range")
52    }
53}
54
55/// Derives a deterministic stream seed from a game-owned base seed and three
56/// caller-supplied domain components.
57#[must_use]
58pub fn derive_stream_seed(base: u64, domain: u64, a: u32, b: u64) -> u64 {
59    let mut rng = SplitMix64::new(base ^ domain.rotate_left(17));
60    rng.cursor ^= u64::from(a).rotate_left(31);
61    rng.cursor ^= b.rotate_left(47);
62    rng.next_u64()
63}
64
65#[cfg(test)]
66mod tests {
67    use super::*;
68    use wasm_bindgen_test::wasm_bindgen_test;
69
70    /// #249: a fresh generator exposes its seed as both the stream seed and
71    /// the cursor; a draw moves the cursor by the `SplitMix64` increment.
72    #[wasm_bindgen_test(unsupported = test)]
73    fn a_fresh_generator_exposes_its_seed_and_cursor() {
74        let mut rng = SplitMix64::new(42);
75        assert_eq!(rng.stream_seed(), 42);
76        assert_eq!(rng.cursor(), 42);
77        rng.next_u64();
78        assert_eq!(rng.cursor(), 42u64.wrapping_add(0x9e37_79b9_7f4a_7c15));
79    }
80
81    /// #249: stream derivation mixes with XOR, so components whose rotated
82    /// bits overlap cancel rather than accumulate. Frozen values for a base
83    /// equal to its domain and for all-ones components.
84    #[wasm_bindgen_test(unsupported = test)]
85    fn derived_seeds_with_overlapping_components_are_frozen() {
86        assert_eq!(
87            (
88                derive_stream_seed(7, 7, 7, 7),
89                derive_stream_seed(u64::MAX, u64::MAX, u32::MAX, u64::MAX),
90                derive_stream_seed(1 << 47, 1 << 30, 1 << 16, 1),
91            ),
92            (
93                1_085_486_224_634_377_940,
94                1_817_513_978_328_618_816,
95                16_294_208_416_658_607_535
96            )
97        );
98    }
99
100    #[wasm_bindgen_test(unsupported = test)]
101    fn splitmix64_sequence_is_frozen() {
102        let mut rng = SplitMix64::new(0);
103        assert_eq!(rng.next_u64(), 0xe220_a839_7b1d_cdaf);
104        assert_eq!(rng.next_u64(), 0x6e78_9e6a_a1b9_65f4);
105        assert_eq!(rng.next_u64(), 0x06c4_5d18_8009_454f);
106    }
107
108    #[wasm_bindgen_test(unsupported = test)]
109    fn inclusive_range_sampling_is_stable() {
110        let mut rng = SplitMix64::new(7);
111        assert_eq!(rng.range_inclusive(3, 7), 5);
112        assert_eq!(rng.range_inclusive(3, 7), 7);
113        assert_eq!(rng.range_inclusive(3, 7), 4);
114    }
115
116    #[wasm_bindgen_test(unsupported = test)]
117    fn derived_seed_is_frozen() {
118        assert_eq!(derive_stream_seed(17, 29, 41, 53), 0x002e_c4c0_58ec_97c1);
119    }
120}