src/rng.rs 14.0 KiB raw
1
//! Random number generator.
2
// (c) Simon Heath, some quality nuggets from their `oorandom` crate
3
// (c) Wang Yi, WyRand algorithm
4
// (c) The `fastrand` authors, various tidbits
5
#![warn(missing_docs)]
6
#![allow(clippy::panic)]
7
8
use std::collections::hash_map::DefaultHasher;
9
use std::hash::{Hash, Hasher};
10
use std::ops::{Add, Bound, RangeBounds, Sub};
11
use std::time::Instant;
12
use std::{fmt, thread};
13
14
use crate::math::traits::Integer;
15
use crate::math::{Bounded, One};
16
17
/// Trait for sources of entropy.
18
pub trait Entropy {
19
    /// Generate a random [`u64`].
20
    fn gen_u64(&mut self) -> u64;
21
22
    /// Generate a random [`u32`].
23
    #[inline]
24
    fn gen_u32(&mut self) -> u32 {
25
        self.gen_u64() as u32
26
    }
27
}
28
29
/// A type that can be randomly generated
30
/// A probability distribution that can generate random values.
31
/// Implementations define how to sample values of type T from a random source.
32
pub trait Distribution<T> {
33
    /// Generates a random value from this distribution using the given entropy source.
34
    fn sample<R: Entropy>(&self, rng: &mut R) -> T;
35
}
36
37
#[cfg(target_os = "linux")]
38
unsafe extern "C" {
39
    fn getrandom(buf: *mut u8, buflen: usize, flags: u32) -> isize;
40
}
41
42
/// Attempts to fill a buffer from the operating system's non-blocking entropy source.
43
#[cfg(target_os = "linux")]
44
fn random(out: &mut [u8]) -> bool {
45
    const GRND_NONBLOCK: u32 = 0x0001;
46
47
    unsafe { getrandom(out.as_mut_ptr(), out.len(), GRND_NONBLOCK) as usize == out.len() }
48
}
49
50
/// Reports unavailable direct system entropy on unsupported targets.
51
#[cfg(not(target_os = "linux"))]
52
fn random(_out: &mut [u8]) -> bool {
53
    false
54
}
55
56
/// The main RNG using WyRand algorithm
57
#[derive(Debug, Clone)]
58
pub struct Rng {
59
    state: u64,
60
}
61
62
impl Default for Rng {
63
    fn default() -> Self {
64
        Self::new()
65
    }
66
}
67
68
impl Rng {
69
    /// Creates a new RNG with a random seed derived from system entropy.
70
    #[inline]
71
    pub fn new() -> Self {
72
        let mut bytes = [0u8; 8];
73
        let seed = if random(&mut bytes) {
74
            u64::from_ne_bytes(bytes)
75
        } else {
76
            let mut hasher = DefaultHasher::new();
77
            Instant::now().hash(&mut hasher);
78
            thread::current().id().hash(&mut hasher);
79
80
            hasher.finish()
81
        };
82
        Self::with_seed(seed)
83
    }
84
85
    /// Samples a value from the given distribution.
86
    pub fn sample<T>(&mut self, dist: &impl Distribution<T>) -> T {
87
        dist.sample(self)
88
    }
89
90
    /// Creates a new RNG with the specified seed for deterministic generation.
91
    #[inline]
92
    pub fn with_seed(seed: u64) -> Self {
93
        Self { state: seed }
94
    }
95
96
    /// Generates a random float in the range `[0.0, 1.0)` with 53 bits of precision.
97
    ///
98
    /// This provides high-quality uniformly distributed floating point numbers suitable
99
    /// for most applications requiring random real numbers.
100
    pub fn fraction(&mut self) -> f64 {
101
        const PRECISION: u32 = f64::MANTISSA_DIGITS;
102
        const MANTISSA_SCALE: f64 = 1.0 / ((1u64 << PRECISION) as f64);
103
104
        let mut r = self.gen_u64();
105
106
        r >>= 64 - PRECISION;
107
        r as f64 * MANTISSA_SCALE
108
    }
109
110
    /// Generates a random value of type `T` within the given range.
111
    /// Panics if the range is empty.
112
    #[inline]
113
    pub fn generate<T>(&mut self, range: impl RangeBounds<T>) -> T
114
    where
115
        T: Copy + PartialOrd + Sub<Output = T> + Add<Output = T> + Bounded + One + fmt::Debug,
116
        Uniform<T>: Distribution<T>,
117
    {
118
        Uniform::from_range(range).sample(self)
119
    }
120
121
    /// Generates a random boolean with 50/50 probability.
122
    #[inline]
123
    pub fn flip(&mut self) -> bool {
124
        self.gen_u32() & 1 == 1
125
    }
126
127
    /// Clones the generator by deterministically deriving a new generator based on the initial
128
    /// seed.
129
    ///
130
    /// This function can be used to create a new generator that is a "spinoff" of the old
131
    /// generator. The new generator will not produce the same sequence of values as the
132
    /// old generator.
133
    #[inline]
134
    #[must_use]
135
    pub fn fork(&mut self) -> Self {
136
        Rng::with_seed(self.gen_u64())
137
    }
138
139
    /// Randomly shuffles the elements of the slice in place using Fisher-Yates algorithm.
140
    #[inline]
141
    pub fn shuffle<T>(&mut self, slice: &mut [T]) {
142
        for i in 1..slice.len() {
143
            slice.swap(i, self.generate(..=i));
144
        }
145
    }
146
147
    /// Fills a byte slice with random values.
148
    pub fn fill(&mut self, slice: &mut [u8]) {
149
        // We fill the slice by chunks of 8 bytes, or one block of
150
        // WyRand output per new state.
151
        let mut chunks = slice.chunks_exact_mut(core::mem::size_of::<u64>());
152
        for chunk in chunks.by_ref() {
153
            let n = self.gen_u64().to_ne_bytes();
154
            // Safe because the chunks are always 8 bytes exactly.
155
            chunk.copy_from_slice(&n);
156
        }
157
158
        // Any remainder will always be less than 8 bytes.
159
        let remainder = chunks.into_remainder();
160
        if !remainder.is_empty() {
161
            // Generate one last block of 8 bytes of entropy
162
            let n = self.gen_u64().to_ne_bytes();
163
            // Use the remaining length to copy from block
164
            remainder.copy_from_slice(&n[..remainder.len()]);
165
        }
166
    }
167
168
    /// Returns a random reference to an element from the slice, or None if empty.
169
    #[inline]
170
    pub fn choose<'a, T>(&mut self, slice: &'a [T]) -> Option<&'a T> {
171
        if slice.is_empty() {
172
            None
173
        } else {
174
            Some(&slice[self.generate(..slice.len())])
175
        }
176
    }
177
178
    /// Returns a random mutable reference to an element from the slice, or None if empty.
179
    #[inline]
180
    pub fn choose_mut<'a, T>(&mut self, slice: &'a mut [T]) -> Option<&'a mut T> {
181
        if slice.is_empty() {
182
            None
183
        } else {
184
            let idx = self.generate(0..slice.len());
185
            Some(&mut slice[idx])
186
        }
187
    }
188
}
189
190
impl Entropy for Rng {
191
    #[inline(always)]
192
    fn gen_u64(&mut self) -> u64 {
193
        self.state = self.state.wrapping_add(0x2d35_8dcc_aa6c_78a5);
194
        let t = u128::from(self.state) * u128::from(self.state ^ 0x8bb8_4b93_962e_acc9);
195
        (t as u64) ^ (t >> 64) as u64
196
    }
197
}
198
199
/// Uniform distribution over a range.
200
#[derive(Debug, Clone, Copy)]
201
pub struct Uniform<T> {
202
    low: T,
203
    high: T,
204
}
205
206
impl<T> Uniform<T> {
207
    /// Creates a new uniform distribution over the range `[low, high]`.
208
    #[inline]
209
    pub const fn new(low: T, high: T) -> Self {
210
        Self { low, high }
211
    }
212
}
213
214
impl<T: Bounded> Uniform<T> {
215
    /// Creates a uniform distribution over the full range of the type `T`.
216
    ///
217
    /// This distribution will generate values across the entire range of valid values
218
    /// for the bounded type `T`, from `T::MIN` to `T::MAX` inclusive.
219
    #[inline]
220
    pub const fn full() -> Self {
221
        Self::new(T::MIN, T::MAX)
222
    }
223
224
    /// Like [`Self::full`], but with a specified range.
225
    #[inline]
226
    pub fn from_range<R: RangeBounds<T>>(range: R) -> Self
227
    where
228
        T: Copy + PartialOrd + Add<Output = T> + Sub<Output = T> + fmt::Debug + One,
229
    {
230
        let low = match range.start_bound() {
231
            Bound::Unbounded => T::MIN,
232
            Bound::Included(&x) => x,
233
            Bound::Excluded(&x) if x < T::MAX => x + T::ONE,
234
            Bound::Excluded(_) => panic!(
235
                "Uniform::from_range: empty range {:?}..{:?}",
236
                range.start_bound(),
237
                range.end_bound()
238
            ),
239
        };
240
        let high = match range.end_bound() {
241
            Bound::Unbounded => T::MAX,
242
            Bound::Included(&x) => x,
243
            Bound::Excluded(&x) if x > T::MIN => x - T::ONE,
244
            Bound::Excluded(_) => panic!(
245
                "Uniform::from_range: empty range {:?}..{:?}",
246
                range.start_bound(),
247
                range.end_bound()
248
            ),
249
        };
250
        assert!(
251
            low <= high,
252
            "Uniform::from_range: empty range {:?}..{:?}",
253
            range.start_bound(),
254
            range.end_bound()
255
        );
256
        Self { low, high }
257
    }
258
}
259
260
impl<T> Distribution<T> for Uniform<T>
261
where
262
    T: Copy + PartialOrd + Integer,
263
{
264
    fn sample<R: Entropy>(&self, rng: &mut R) -> T {
265
        let low = self.low;
266
        let high = self.high;
267
268
        if low == T::MIN && high == T::MAX {
269
            return T::from_u64(rng.gen_u64());
270
        }
271
272
        let len = high.wrapping_sub(low).as_u64() + 1;
273
        let threshold = len.wrapping_neg() % len;
274
        loop {
275
            let value = rng.gen_u64();
276
            if value >= threshold {
277
                return low.wrapping_add(T::from_u64(value % len));
278
            }
279
        }
280
    }
281
}
282
283
#[cfg(test)]
284
mod tests {
285
    use super::*;
286
    use crate::math::traits::Integer;
287
288
    struct SequenceEntropy {
289
        values: std::vec::IntoIter<u64>,
290
    }
291
292
    impl SequenceEntropy {
293
        fn new(values: Vec<u64>) -> Self {
294
            Self {
295
                values: values.into_iter(),
296
            }
297
        }
298
    }
299
300
    impl Entropy for SequenceEntropy {
301
        fn gen_u64(&mut self) -> u64 {
302
            self.values.next().unwrap()
303
        }
304
    }
305
306
    #[allow(dead_code)]
307
    fn distribution<T: Integer + std::fmt::Debug>(
308
        rng: &mut Rng,
309
        range: std::ops::Range<T>,
310
        samples: usize,
311
        buckets: usize,
312
    ) {
313
        let mut counts = vec![0; buckets];
314
        let bucket_size = (range.end - range.start).as_u64() as f64 / buckets as f64;
315
316
        for _ in 0..samples {
317
            let value = rng.generate(range.clone());
318
            let bucket = ((value - range.start).as_u64() as f64 / bucket_size) as usize;
319
            counts[bucket.min(buckets - 1)] += 1;
320
        }
321
322
        let expected = samples as f64 / buckets as f64;
323
        for (i, &count) in counts.iter().enumerate() {
324
            let deviation = (count as f64 - expected).abs() / expected * 100.0;
325
            println!("Bucket {}: {} ({:.1}% deviation)", i, count, deviation);
326
        }
327
    }
328
329
    fn distribution_f64(rng: &mut Rng, samples: usize, buckets: usize) {
330
        let mut counts = vec![0; buckets];
331
        let bucket_size = 1.0 / buckets as f64;
332
333
        for _ in 0..samples {
334
            let value = rng.fraction();
335
            let bucket = (value / bucket_size) as usize;
336
            counts[bucket.min(buckets - 1)] += 1;
337
        }
338
339
        let expected = samples as f64 / buckets as f64;
340
        for (i, &count) in counts.iter().enumerate() {
341
            let deviation = (count as f64 - expected).abs() / expected * 100.0;
342
            println!("Bucket {}: {} ({:.1}% deviation)", i, count, deviation);
343
        }
344
    }
345
346
    #[test]
347
    fn fraction_is_less_than_one() {
348
        let mut rng = Rng::with_seed(0);
349
        rng.state = 0x6fa8_99d2_ddf8_ba1d;
350
351
        assert!(rng.fraction() < 1.0);
352
    }
353
354
    #[test]
355
    fn full_i32_distribution_preserves_signed_bits() {
356
        let distribution = Uniform::<i32>::full();
357
        let mut rng = SequenceEntropy::new(vec![u64::MAX]);
358
359
        assert_eq!(distribution.sample(&mut rng), -1);
360
    }
361
362
    #[test]
363
    fn bounded_distribution_rejects_biased_prefix() {
364
        let distribution = Uniform::new(0_u64, 2);
365
        let mut rng = SequenceEntropy::new(vec![0, 2]);
366
367
        assert_eq!(distribution.sample(&mut rng), 2);
368
    }
369
370
    #[test]
371
    fn test_distribution() {
372
        let mut rng = Rng::new();
373
374
        distribution_f64(&mut rng, 100000, 10);
375
    }
376
377
    #[test]
378
    fn test_basic_generation() {
379
        let mut rng = Rng::new();
380
381
        // Using gen
382
        let _: u64 = rng.generate(..);
383
        let _: bool = rng.flip();
384
385
        // Using gen_range
386
        let n = rng.generate(1u64..=100);
387
        assert!((1..=100).contains(&n));
388
389
        for _ in 0..10 {
390
            let n = rng.generate(0..60);
391
            assert!((0..60).contains(&n), "{n}");
392
        }
393
    }
394
395
    #[test]
396
    fn test_fill_bytes() {
397
        let mut rng = Rng::with_seed(49182);
398
399
        // Test different buffer sizes
400
        let sizes = [1, 7, 8, 9, 16, 32, 64];
401
        for size in sizes {
402
            let mut buffer = vec![0u8; size];
403
            rng.fill(&mut buffer);
404
405
            // Ensure we actually wrote some non-zero bytes
406
            assert!(
407
                buffer.iter().any(|&x| x != 0),
408
                "Buffer of size {} contains only zeros",
409
                size
410
            );
411
        }
412
413
        // Test alignment handling
414
        let mut buffer = [0u8; 32];
415
        rng.fill(&mut buffer[1..31]); // Unaligned slice
416
    }
417
418
    #[test]
419
    fn test_seeded_sequences() {
420
        let mut rng1 = Rng::with_seed(12345);
421
        let mut rng2 = Rng::with_seed(12345);
422
423
        // Same seed should produce same sequence
424
        for _ in 0..100 {
425
            assert_eq!(rng1.gen_u64(), rng2.gen_u64());
426
        }
427
428
        // Different seeds should produce different sequences
429
        let mut rng3 = Rng::with_seed(12346);
430
        let val1 = rng1.gen_u64();
431
        let val2 = rng3.gen_u64();
432
        assert_ne!(val1, val2);
433
    }
434
435
    #[test]
436
    fn test_shuffle() {
437
        let mut rng = Rng::new();
438
439
        // Test with different sizes
440
        for len in [2, 3, 10, 100] {
441
            let mut v: Vec<i32> = (0..len).collect();
442
            let original = v.clone();
443
444
            rng.shuffle(&mut v);
445
446
            // Length should remain the same
447
            assert_eq!(v.len(), original.len());
448
449
            // All elements should still be present
450
            assert!(v.iter().all(|x| original.contains(x)));
451
452
            // Order should be different (for large enough arrays)
453
            if len > 10 {
454
                assert_ne!(v, original);
455
            }
456
        }
457
458
        // Test empty and single-element slices
459
        let mut empty: Vec<i32> = vec![];
460
        rng.shuffle(&mut empty);
461
        assert!(empty.is_empty());
462
463
        let mut single = vec![1];
464
        rng.shuffle(&mut single);
465
        assert_eq!(single, vec![1]);
466
    }
467
468
    #[test]
469
    fn test_consecutive_values() {
470
        let mut rng = Rng::new();
471
        let mut prev = rng.gen_u64();
472
        let mut repeats = 0;
473
474
        // Test for obvious patterns in consecutive values
475
        for _ in 0..1000 {
476
            let curr = rng.gen_u64();
477
            if curr == prev {
478
                repeats += 1;
479
            }
480
            prev = curr;
481
        }
482
483
        // Shouldn't have too many repeats
484
        assert!(repeats < 3, "Too many repeated consecutive values");
485
    }
486
}