spinoso_random/random/
mod.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
use alloc::vec::Vec;
use core::fmt;
use core::mem::size_of;

use rand_mt::Mt;

use crate::{InitializeError, NewSeedError};

#[cfg(feature = "rand_core")]
mod rand;

const DEFAULT_SEED_CNT: usize = 4;
const DEFAULT_SEED_BYTES: usize = size_of::<u32>() * DEFAULT_SEED_CNT;

const DEFAULT_SEED: u32 = 5489_u32;

/// Random provides an interface to Ruby's pseudo-random number generator, or
/// PRNG.
///
/// The PRNG produces a deterministic sequence of bits which approximate true
/// randomness. The sequence may be represented by integers, floats, or binary
/// strings.
///
/// The generator may be initialized with either a system-generated or
/// user-supplied seed value.
///
/// PRNGs are currently implemented as a modified Mersenne Twister with a period
/// of 2**19937-1.
///
/// This RNG reproduces the same random bytes and floats as MRI. It may differ
/// when returning elements confined to a distribution.
///
/// # Examples
///
/// Create an RNG with a random seed:
///
/// ```
/// use spinoso_random::{Error, Random};
///
/// # fn example() -> Result<(), Error> {
/// let mut random = Random::new()?;
/// let next = random.next_int32();
/// # Ok(())
/// # }
/// # example().unwrap();
/// ```
///
/// Create a RNG with a fixed seed:
///
/// ```
/// use spinoso_random::Random;
///
/// let seed = 5489_u32;
/// let mut random = Random::with_seed(seed);
/// let rand = random.next_int32();
///
/// let seed = [627457_u32, 697550, 16438, 41926];
/// let mut random = Random::with_array_seed(seed);
/// let rand = random.next_int32();
/// ```
#[derive(Clone, Hash, PartialEq, Eq)]
pub struct Random {
    mt: Mt,
    seed: Vec<u32>,
}

impl Default for Random {
    #[inline]
    fn default() -> Self {
        if let Ok(random) = Random::new() {
            random
        } else {
            Random::with_seed(DEFAULT_SEED)
        }
    }
}

impl fmt::Debug for Random {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Random {}")
    }
}

impl From<u32> for Random {
    #[inline]
    fn from(seed: u32) -> Self {
        Self::with_seed(seed)
    }
}

impl From<[u32; DEFAULT_SEED_CNT]> for Random {
    #[inline]
    fn from(seed: [u32; DEFAULT_SEED_CNT]) -> Self {
        Self::with_array_seed(seed)
    }
}

impl From<&[u32]> for Random {
    #[inline]
    fn from(seed: &[u32]) -> Self {
        Self::with_array_seed(seed.iter().copied())
    }
}

impl From<[u8; DEFAULT_SEED_BYTES]> for Random {
    #[inline]
    fn from(seed: [u8; DEFAULT_SEED_BYTES]) -> Self {
        Self::with_byte_array_seed(seed)
    }
}

impl Random {
    /// Create a new Mersenne Twister random number generator with a randomly
    /// generated seed.
    ///
    /// This method initializes the Mersenne Twister random number generator
    /// with a seed derived from a cryptographically secure source of
    /// randomness.
    ///
    /// # Examples
    ///
    /// ```
    /// use spinoso_random::{Error, Random};
    ///
    /// # fn example() -> Result<(), Error> {
    /// let mut random = Random::new()?;
    /// let next = random.next_int32();
    /// # Ok(())
    /// # }
    /// # example().unwrap();
    /// ```
    ///
    /// # Errors
    ///
    /// If the randomness feature provided by the platform is not present or
    /// failed to completely generate a seed, an error is returned. This error
    /// should be raised as a [Ruby `RuntimeError`].
    ///
    /// [Ruby `RuntimeError`]: https://ruby-doc.org/core-3.1.2/RuntimeError.html
    #[inline]
    pub fn new() -> Result<Self, InitializeError> {
        if let Ok(seed) = new_seed() {
            let mt = Mt::new_with_key(seed.iter().copied());
            Ok(Self {
                mt,
                seed: seed.to_vec(),
            })
        } else {
            Err(InitializeError::new())
        }
    }

    /// Create a new random number generator using the given seed.
    ///
    /// # Examples
    ///
    /// ```
    /// use spinoso_random::Random;
    ///
    /// let seed = 33;
    /// let mut random = Random::with_seed(seed);
    /// let rand = random.next_int32();
    /// ```
    #[inline]
    #[must_use]
    pub fn with_seed(seed: u32) -> Self {
        let mt = Mt::new(seed);
        let seed = u128::from(seed).to_le_bytes();
        let seed = seed_to_key(seed);
        Self {
            mt,
            seed: seed.to_vec(),
        }
    }

    /// Create a new random number generator using the given seed.
    ///
    /// # Examples
    ///
    /// ```
    /// use spinoso_random::Random;
    ///
    /// let seed = [1_u32, 2, 3, 4];
    /// let mut random = Random::with_array_seed(seed);
    /// let rand = random.next_int32();
    /// ```
    #[inline]
    #[must_use]
    pub fn with_array_seed<T>(seed: T) -> Self
    where
        T: IntoIterator<Item = u32>,
        T::IntoIter: Clone,
    {
        let iter = seed.into_iter();
        let mt = Mt::new_with_key(iter.clone());
        Self {
            mt,
            seed: iter.collect(),
        }
    }

    /// Create a new random number generator using the given seed.
    ///
    /// # Examples
    ///
    /// ```
    /// use spinoso_random::Random;
    ///
    /// let seed = [1_u32, 2, 3, 4];
    /// let mut random = Random::with_array_seed(seed);
    /// let rand = random.next_int32();
    /// ```
    #[inline]
    #[must_use]
    pub fn with_byte_array_seed(seed: [u8; DEFAULT_SEED_BYTES]) -> Self {
        let seed = seed_to_key(seed);
        let mt = Mt::new_with_key(seed.iter().copied());
        Self {
            mt,
            seed: seed.to_vec(),
        }
    }

    /// Generate next `u32` output.
    ///
    /// Generates a random number on `(0..=0xffffffff)`-interval.
    ///
    /// `u32` is the native output of the generator. This function advances the
    /// RNG step counter by one.
    ///
    /// # Examples
    ///
    /// ```
    /// use spinoso_random::{Error, Random};
    ///
    /// # fn example() -> Result<(), Error> {
    /// let mut random = Random::new()?;
    /// assert_ne!(random.next_int32(), random.next_int32());
    /// # Ok(())
    /// # }
    /// # example().unwrap();
    /// ```
    #[inline]
    #[must_use]
    pub fn next_int32(&mut self) -> u32 {
        self.mt.next_u32()
    }

    /// Generate next `f64` output.
    ///
    /// Generates a random number on [0,1) with 53-bit resolution.
    ///
    /// # Examples
    ///
    /// ```
    /// use spinoso_random::{Error, Random};
    ///
    /// # fn example() -> Result<(), Error> {
    /// let mut random = Random::new()?;
    /// assert_ne!(random.next_real(), random.next_real());
    /// # Ok(())
    /// # }
    /// # example().unwrap();
    /// ```
    #[inline]
    #[must_use]
    pub fn next_real(&mut self) -> f64 {
        let a = self.next_int32();
        let b = self.next_int32();
        int_pair_to_real_exclusive(a, b)
    }

    /// Fill a buffer with bytes generated from the RNG.
    ///
    /// This method generates random `u32`s (the native output unit of the RNG)
    /// until `dest` is filled.
    ///
    /// This method may discard some output bits if `dest.len()` is not a
    /// multiple of 4.
    ///
    /// # Examples
    ///
    /// ```
    /// use spinoso_random::{Error, Random};
    ///
    /// # fn example() -> Result<(), Error> {
    /// let mut random = Random::new()?;
    /// let mut buf = [0; 32];
    /// random.fill_bytes(&mut buf);
    /// assert_ne!([0; 32], buf);
    /// let mut buf = [0; 31];
    /// random.fill_bytes(&mut buf);
    /// assert_ne!([0; 31], buf);
    /// # Ok(())
    /// # }
    /// # example().unwrap();
    /// ```
    #[inline]
    pub fn fill_bytes(&mut self, dest: &mut [u8]) {
        self.mt.fill_bytes(dest);
    }

    /// Returns the seed value used to initialize the generator.
    ///
    /// This may be used to initialize another generator with the same state at
    /// a later time, causing it to produce the same sequence of numbers.
    ///
    /// # Examples
    ///
    /// ```
    /// use spinoso_random::Random;
    ///
    /// let seed = [1_u32, 2, 3, 4];
    /// let random = Random::with_array_seed(seed);
    /// assert_eq!(random.seed(), seed);
    /// ```
    #[inline]
    #[must_use]
    pub fn seed(&self) -> &[u32] {
        &self.seed
    }
}

#[inline]
#[must_use]
fn int_pair_to_real_exclusive(mut a: u32, mut b: u32) -> f64 {
    a >>= 5;
    b >>= 6;
    let a = f64::from(a);
    let b = f64::from(b);
    (a * 67_108_864.0 + b) * (1.0 / 9_007_199_254_740_992.0)
}

#[inline]
#[must_use]
#[allow(dead_code)]
#[allow(clippy::cast_precision_loss)]
#[allow(clippy::cast_possible_truncation)]
fn int_pair_to_real_inclusive(a: u32, b: u32) -> f64 {
    const MANTISSA_DIGITS: i32 = 53;
    const M: u128 = 1 << MANTISSA_DIGITS | 1;
    let x = (u128::from(a) << 32) | u128::from(b);
    let r = ((x * M) >> 64) as u64 as f64;
    libm::ldexp(r, -MANTISSA_DIGITS)
}

/// Convert a byte array into a reseeding key of `u32`s.
#[inline]
#[must_use]
pub fn seed_to_key(seed: [u8; DEFAULT_SEED_BYTES]) -> [u32; DEFAULT_SEED_CNT] {
    let mut key = [0_u32; DEFAULT_SEED_CNT];
    let iter = key.iter_mut().zip(seed.chunks_exact(size_of::<u32>()));

    let mut bytes = [0; size_of::<u32>()];
    for (cell, chunk) in iter {
        bytes.copy_from_slice(chunk);
        *cell = u32::from_le_bytes(bytes);
    }
    key
}

/// Read a new [`Random`] seed, using platform-provided randomness.
///
/// # Examples
///
/// ```
/// use spinoso_random::{Error, Random};
///
/// # fn example() -> Result<(), Error> {
/// let seed = spinoso_random::new_seed()?;
/// # Ok(())
/// # }
/// example().unwrap();
/// ```
///
/// # Errors
///
/// If the randomness feature provided by the platform is not present or failed
/// to completely generate a seed, an error is returned. This error should be
/// raised as a [Ruby `RuntimeError`].
///
/// [Ruby `RuntimeError`]: https://ruby-doc.org/core-3.1.2/RuntimeError.html
#[inline]
pub fn new_seed() -> Result<[u32; DEFAULT_SEED_CNT], NewSeedError> {
    let mut seed = [0; DEFAULT_SEED_BYTES];
    if getrandom::getrandom(&mut seed).is_err() {
        return Err(NewSeedError::new());
    }
    let seed = seed_to_key(seed);
    Ok(seed)
}

#[cfg(test)]
mod tests {
    use alloc::string::String;
    use core::fmt::Write as _;

    use super::Random;

    #[test]
    fn fmt_debug_does_not_leak_seed() {
        let random = Random::with_seed(874);

        let mut buf = String::new();
        write!(&mut buf, "{random:?}").unwrap();
        assert!(!buf.contains("874"));
        assert_eq!(buf, "Random {}");

        let random = Random::with_seed(123_456);

        let mut buf = String::new();
        write!(&mut buf, "{random:?}").unwrap();
        assert!(!buf.contains("123456"));
        assert_eq!(buf, "Random {}");
    }
}