spacedb_sim/rng.rs
1//! A seeded, zero-dependency PRNG (SplitMix64).
2//!
3//! Determinism is the whole point of the simulator: the same seed must produce a
4//! byte-identical run. So we own the randomness end to end rather than pulling in
5//! `rand` (whose defaults and version churn could change a sequence). SplitMix64 is
6//! tiny, fast, and fully specified.
7
8/// A deterministic random source.
9#[derive(Clone, Debug)]
10pub struct Rng {
11 state: u64,
12}
13
14impl Rng {
15 pub fn seed(seed: u64) -> Self {
16 Self { state: seed }
17 }
18
19 /// The next 64-bit value (SplitMix64).
20 pub fn next_u64(&mut self) -> u64 {
21 self.state = self.state.wrapping_add(0x9E37_79B9_7F4A_7C15);
22 let mut z = self.state;
23 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
24 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
25 z ^ (z >> 31)
26 }
27
28 /// A value in `[0, n)`. Returns 0 if `n == 0`.
29 pub fn below(&mut self, n: u64) -> u64 {
30 if n == 0 {
31 0
32 } else {
33 self.next_u64() % n
34 }
35 }
36
37 /// A float in `[0, 1)` with 53 bits of precision.
38 pub fn unit(&mut self) -> f64 {
39 (self.next_u64() >> 11) as f64 / (1u64 << 53) as f64
40 }
41
42 /// True with probability `p` (clamped to `[0, 1]`).
43 pub fn chance(&mut self, p: f64) -> bool {
44 if p <= 0.0 {
45 false
46 } else if p >= 1.0 {
47 true
48 } else {
49 self.unit() < p
50 }
51 }
52}