Skip to main content

yomi_core/vm/
rng.rs

1//! Random numbers. xoshiro256++ (`rand_xoshiro`). The state is 4 `u64`s, and it returns the same sequence on every
2//! platform.
3//!
4//! The OS random source is not used. It is made from a seed (`VmConfig::seed`), and the state is included in saves.
5
6use rand_core::{Rng as _, SeedableRng};
7use rand_xoshiro::Xoshiro256PlusPlus;
8
9/// xoshiro256++. A random generator with serializable state, used by `random` in scripts and by package commands
10/// ([`Ctx::rng`](crate::Ctx::rng)).
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct Rng {
13    inner: Xoshiro256PlusPlus,
14}
15
16impl Rng {
17    /// Makes one from a seed (the state is made with splitmix64). The same seed gives the same sequence.
18    pub(crate) fn from_seed(seed: u64) -> Self {
19        Self {
20            inner: Xoshiro256PlusPlus::seed_from_u64(seed),
21        }
22    }
23
24    /// Makes one from a saved state. An all-zero state is rejected, because its sequence would be all zeros.
25    pub(crate) fn from_state(s: [u64; 4]) -> Option<Self> {
26        if s == [0; 4] {
27            return None;
28        }
29        let mut bytes = [0u8; 32];
30        for (i, word) in s.iter().enumerate() {
31            bytes[i * 8..(i + 1) * 8].copy_from_slice(&word.to_le_bytes());
32        }
33        Some(Self {
34            inner: Xoshiro256PlusPlus::from_seed(bytes),
35        })
36    }
37
38    /// The state (put into saves).
39    pub(crate) fn state(&self) -> [u64; 4] {
40        let bytes = self.inner.state();
41        std::array::from_fn(|i| {
42            u64::from_le_bytes(bytes[i * 8..i * 8 + 8].try_into().expect("8 バイトずつ"))
43        })
44    }
45
46    /// The next 64 bits.
47    pub fn next_u64(&mut self) -> u64 {
48        self.inner.next_u64()
49    }
50
51    /// A decimal in [0.0, 1.0) (uses the upper 53 bits; the same state gives the same value on every platform).
52    pub fn unit_f64(&mut self) -> f64 {
53        (self.next_u64() >> 11) as f64 * (1.0 / (1u64 << 53) as f64)
54    }
55
56    /// An integer in `min..=max` (both ends included). If `min > max`, returns `min` (the generator does not advance).
57    ///
58    /// Maps into the range with Lemire's method (multiplication with rejection) to avoid bias. On every platform, the same
59    /// state gives the same value and consumes the same number of outputs.
60    pub fn range_inclusive(&mut self, min: i64, max: i64) -> i64 {
61        if min > max {
62            return min;
63        }
64        // The size of the range (when it cannot be represented in `u64`, it is 2^64, which becomes 0)
65        let span = (max as u64).wrapping_sub(min as u64).wrapping_add(1);
66        if span == 0 {
67            return self.next_u64() as i64;
68        }
69        let mut m = u128::from(self.next_u64()) * u128::from(span);
70        let mut low = m as u64;
71        if low < span {
72            let threshold = span.wrapping_neg() % span;
73            while low < threshold {
74                m = u128::from(self.next_u64()) * u128::from(span);
75                low = m as u64;
76            }
77        }
78        min.wrapping_add((m >> 64) as u64 as i64)
79    }
80}
81
82#[cfg(test)]
83mod tests {
84    use super::*;
85
86    #[test]
87    fn same_seed_returns_same_sequence_and_different_seed_different_one() {
88        let mut a = Rng::from_seed(1);
89        let mut b = Rng::from_seed(1);
90        let mut c = Rng::from_seed(2);
91        let xs: Vec<u64> = (0..8).map(|_| a.next_u64()).collect();
92        let ys: Vec<u64> = (0..8).map(|_| b.next_u64()).collect();
93        let zs: Vec<u64> = (0..8).map(|_| c.next_u64()).collect();
94        assert_eq!(xs, ys);
95        assert_ne!(xs, zs);
96    }
97
98    #[test]
99    fn state_is_never_zero_even_with_seed_0() {
100        let r = Rng::from_seed(0);
101        assert_ne!(r.state(), [0; 4]);
102        assert!(Rng::from_state([0; 4]).is_none());
103    }
104
105    #[test]
106    fn rebuilding_from_state_gives_same_continuing_sequence() {
107        let mut a = Rng::from_seed(5);
108        a.next_u64();
109        let mut b = Rng::from_state(a.state()).expect("0 でない状態");
110        let xs: Vec<u64> = (0..8).map(|_| a.next_u64()).collect();
111        let ys: Vec<u64> = (0..8).map(|_| b.next_u64()).collect();
112        assert_eq!(xs, ys);
113    }
114
115    #[test]
116    fn range_random_includes_both_ends_and_stays_in_range() {
117        let mut r = Rng::from_seed(7);
118        let mut seen = [false; 6];
119        for _ in 0..2_000 {
120            let v = r.range_inclusive(1, 6);
121            assert!((1..=6).contains(&v));
122            seen[(v - 1) as usize] = true;
123        }
124        assert!(
125            seen.iter().all(|&s| s),
126            "両端を含む 1 から 6 のすべてが出る"
127        );
128    }
129
130    #[test]
131    fn single_value_range_returns_that_value() {
132        let mut r = Rng::from_seed(3);
133        for _ in 0..10 {
134            assert_eq!(r.range_inclusive(5, 5), 5);
135            assert_eq!(r.range_inclusive(i64::MIN, i64::MIN), i64::MIN);
136            assert_eq!(r.range_inclusive(i64::MAX, i64::MAX), i64::MAX);
137        }
138    }
139
140    #[test]
141    fn works_over_full_and_negative_integer_ranges() {
142        let mut r = Rng::from_seed(11);
143        for _ in 0..200 {
144            let _ = r.range_inclusive(i64::MIN, i64::MAX);
145            let v = r.range_inclusive(-10, -3);
146            assert!((-10..=-3).contains(&v));
147            let w = r.range_inclusive(i64::MIN, i64::MIN + 2);
148            assert!((i64::MIN..=i64::MIN + 2).contains(&w));
149        }
150    }
151
152    #[test]
153    fn sequence_from_fixed_seed_does_not_change() {
154        // The sequence must be the same across platforms and versions (fixed for each format version).
155        let mut r = Rng::from_seed(0);
156        let first: Vec<u64> = (0..3).map(|_| r.next_u64()).collect();
157        let mut again = Rng::from_seed(0);
158        let second: Vec<u64> = (0..3).map(|_| again.next_u64()).collect();
159        assert_eq!(first, second);
160        assert_eq!(
161            first,
162            vec![FIXED[0], FIXED[1], FIXED[2]],
163            "実測値: {first:x?}"
164        );
165    }
166
167    /// The first 3 outputs of `Rng::from_seed(0)` (matching the reference implementation; if the implementation changes,
168    /// increase the format version).
169    const FIXED: [u64; 3] = [
170        0x5317_5d61_490b_23df,
171        0x61da_6f3d_c380_d507,
172        0x5c0f_df91_ec9a_7bfc,
173    ];
174}