Skip to main content

php_std/
random.rs

1//! Random numbers: PHP's Mersenne Twister, the engine behind `mt_rand()`,
2//! `rand()`, `array_rand()` and `shuffle()`.
3//!
4//! [`Mt19937`] is the generator `ext/random` keeps as the default engine. Seeded
5//! with [`Mt19937::new`] it produces exactly the sequence PHP produces after
6//! `mt_srand($seed)`, so code that picks at random can be replayed against
7//! PHP: [`Mt19937::next_u32`] is one engine output, [`Mt19937::range`] is
8//! `mt_rand($min, $max)` (and every other bounded draw of the default
9//! engine), and [`Mt19937::array_rand`] is `array_rand()` of one key from a
10//! list.
11//!
12//! | PHP | Rust |
13//! |---|---|
14//! | `mt_srand($seed)` (`MT_RAND_MT19937`) | [`Mt19937::new`] |
15//! | the engine seeded from the OS on first use | [`Mt19937::from_entropy`] |
16//! | `mt_rand($min, $max)`, `php_mt_rand_range()` | [`Mt19937::range`] |
17//! | `array_rand($list)` | [`Mt19937::array_rand`] |
18//!
19//! ```
20//! use php_std::random::Mt19937;
21//!
22//! let mut mt = Mt19937::new(42);
23//! assert_eq!(mt.range(1, 6), 1);
24//! ```
25//!
26//! ```php
27//! mt_srand(42);
28//! echo mt_rand(1, 6), "\n"; // 1
29//! ```
30
31use crate::EngineError;
32
33const N: usize = 624;
34const M: usize = 397;
35
36/// PHP's Mersenne Twister (`Random\Engine\Mt19937` in `MT_RAND_MT19937`
37/// mode, the default engine).
38#[derive(Clone)]
39pub struct Mt19937 {
40    state: [u32; N],
41    count: usize,
42}
43
44impl std::fmt::Debug for Mt19937 {
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        f.debug_struct("Mt19937").field("count", &self.count).finish_non_exhaustive()
47    }
48}
49
50#[inline]
51fn twist(m: u32, u: u32, v: u32) -> u32 {
52    let mixed = (u & 0x8000_0000) | (v & 0x7FFF_FFFF);
53    m ^ (mixed >> 1) ^ ((v & 1).wrapping_neg() & 0x9908_B0DF)
54}
55
56impl Mt19937 {
57    /// A generator seeded like `mt_srand($seed)`: the seed is the low 32
58    /// bits of the integer, as PHP casts it.
59    pub fn new(seed: i64) -> Self {
60        let mut state = [0u32; N];
61        state[0] = seed as u32;
62        for i in 1..N {
63            let prev = state[i - 1];
64            state[i] = 1_812_433_253u32.wrapping_mul(prev ^ (prev >> 30)).wrapping_add(i as u32);
65        }
66        let mut mt = Mt19937 { state, count: N };
67        mt.reload();
68        mt
69    }
70
71    /// A generator seeded from the operating system, as PHP seeds its default
72    /// engine on first use.
73    pub fn from_entropy() -> Self {
74        let mut seed = [0u8; 4];
75        if getrandom::fill(&mut seed).is_err() {
76            let nanos = std::time::SystemTime::now()
77                .duration_since(std::time::UNIX_EPOCH)
78                .map(|d| d.subsec_nanos() ^ d.as_secs() as u32)
79                .unwrap_or(0);
80            seed = nanos.to_le_bytes();
81        }
82        Mt19937::new(i64::from(u32::from_le_bytes(seed)))
83    }
84
85    fn reload(&mut self) {
86        let s = &mut self.state;
87        for i in 0..N - M {
88            s[i] = twist(s[i + M], s[i], s[i + 1]);
89        }
90        for i in N - M..N - 1 {
91            s[i] = twist(s[i + M - N], s[i], s[i + 1]);
92        }
93        s[N - 1] = twist(s[M - 1], s[N - 1], s[0]);
94        self.count = 0;
95    }
96
97    /// One 32-bit output of the engine (`Mt19937::generate()`).
98    pub fn next_u32(&mut self) -> u32 {
99        if self.count >= N {
100            self.reload();
101        }
102        let mut s1 = self.state[self.count];
103        self.count += 1;
104        s1 ^= s1 >> 11;
105        s1 ^= (s1 << 7) & 0x9D2C_5680;
106        s1 ^= (s1 << 15) & 0xEFC6_0000;
107        s1 ^ (s1 >> 18)
108    }
109
110    /// `mt_rand($min, $max)`: uniform in `min..=max` without modulo bias
111    /// (`php_random_range`). `max` below `min` wraps the way PHP's unsigned
112    /// arithmetic does; `mt_rand()` itself refuses that before drawing.
113    pub fn range(&mut self, min: i64, max: i64) -> i64 {
114        let umax = (max as u64).wrapping_sub(min as u64);
115        let result = if umax > u64::from(u32::MAX) { self.range64(umax) } else { u64::from(self.range32(umax as u32)) };
116        result.wrapping_add(min as u64) as i64
117    }
118
119    fn range32(&mut self, umax: u32) -> u32 {
120        let mut result = self.next_u32();
121        if umax == u32::MAX {
122            return result;
123        }
124        let umax = umax + 1;
125        if umax & (umax - 1) == 0 {
126            return result & (umax - 1);
127        }
128        let limit = u32::MAX - (u32::MAX % umax) - 1;
129        while result > limit {
130            result = self.next_u32();
131        }
132        result % umax
133    }
134
135    /// Two outputs as one 64-bit value, the first in the low half (as
136    /// `php_random_range64` concatenates a 32-bit engine's results).
137    fn next_u64(&mut self) -> u64 {
138        let low = u64::from(self.next_u32());
139        low | (u64::from(self.next_u32()) << 32)
140    }
141
142    fn range64(&mut self, umax: u64) -> u64 {
143        let mut result = self.next_u64();
144        if umax == u64::MAX {
145            return result;
146        }
147        let umax = umax + 1;
148        if umax & (umax - 1) == 0 {
149            return result & (umax - 1);
150        }
151        let limit = u64::MAX - (u64::MAX % umax) - 1;
152        while result > limit {
153            result = self.next_u64();
154        }
155        result % umax
156    }
157
158    /// `array_rand($list)` for a list (a packed array without holes) of `len`
159    /// elements: the index of one. An empty list is the `ValueError` PHP
160    /// throws, and draws nothing.
161    pub fn array_rand(&mut self, len: usize) -> Result<usize, EngineError> {
162        if len == 0 {
163            return Err(EngineError::new("ValueError", "array_rand(): Argument #1 ($array) must not be empty"));
164        }
165        Ok(self.range(0, len as i64 - 1) as usize)
166    }
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172
173    #[test]
174    fn matches_the_reference_sequence() {
175        // The reference MT19937 output for seed 5489 is 3499211612, 581869302, ...
176        let mut mt = Mt19937::new(5489);
177        assert_eq!(mt.next_u32(), 3_499_211_612);
178        assert_eq!(mt.next_u32(), 581_869_302);
179    }
180
181    #[test]
182    fn ranges_stay_in_bounds() {
183        let mut mt = Mt19937::new(1);
184        for _ in 0..1000 {
185            let v = mt.range(-3, 7);
186            assert!((-3..=7).contains(&v));
187        }
188        assert!(mt.array_rand(0).is_err());
189        assert_eq!(mt.range(4, 4), 4);
190    }
191}