//! Random number generator. // (c) Simon Heath, some quality nuggets from their `oorandom` crate // (c) Wang Yi, WyRand algorithm // (c) The `fastrand` authors, various tidbits #![warn(missing_docs)] #![allow(clippy::panic)] use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use std::ops::{Add, Bound, RangeBounds, Sub}; use std::time::Instant; use std::{fmt, thread}; use crate::math::traits::Integer; use crate::math::{Bounded, One}; /// Trait for sources of entropy. pub trait Entropy { /// Generate a random [`u64`]. fn gen_u64(&mut self) -> u64; /// Generate a random [`u32`]. #[inline] fn gen_u32(&mut self) -> u32 { self.gen_u64() as u32 } } /// A type that can be randomly generated /// A probability distribution that can generate random values. /// Implementations define how to sample values of type T from a random source. pub trait Distribution { /// Generates a random value from this distribution using the given entropy source. fn sample(&self, rng: &mut R) -> T; } #[cfg(target_os = "linux")] unsafe extern "C" { fn getrandom(buf: *mut u8, buflen: usize, flags: u32) -> isize; } /// Attempts to fill a buffer from the operating system's non-blocking entropy source. #[cfg(target_os = "linux")] fn random(out: &mut [u8]) -> bool { const GRND_NONBLOCK: u32 = 0x0001; unsafe { getrandom(out.as_mut_ptr(), out.len(), GRND_NONBLOCK) as usize == out.len() } } /// Reports unavailable direct system entropy on unsupported targets. #[cfg(not(target_os = "linux"))] fn random(_out: &mut [u8]) -> bool { false } /// The main RNG using WyRand algorithm #[derive(Debug, Clone)] pub struct Rng { state: u64, } impl Default for Rng { fn default() -> Self { Self::new() } } impl Rng { /// Creates a new RNG with a random seed derived from system entropy. #[inline] pub fn new() -> Self { let mut bytes = [0u8; 8]; let seed = if random(&mut bytes) { u64::from_ne_bytes(bytes) } else { let mut hasher = DefaultHasher::new(); Instant::now().hash(&mut hasher); thread::current().id().hash(&mut hasher); hasher.finish() }; Self::with_seed(seed) } /// Samples a value from the given distribution. pub fn sample(&mut self, dist: &impl Distribution) -> T { dist.sample(self) } /// Creates a new RNG with the specified seed for deterministic generation. #[inline] pub fn with_seed(seed: u64) -> Self { Self { state: seed } } /// Generates a random float in the range `[0.0, 1.0)` with 53 bits of precision. /// /// This provides high-quality uniformly distributed floating point numbers suitable /// for most applications requiring random real numbers. pub fn fraction(&mut self) -> f64 { const PRECISION: u32 = f64::MANTISSA_DIGITS; const MANTISSA_SCALE: f64 = 1.0 / ((1u64 << PRECISION) as f64); let mut r = self.gen_u64(); r >>= 64 - PRECISION; r as f64 * MANTISSA_SCALE } /// Generates a random value of type `T` within the given range. /// Panics if the range is empty. #[inline] pub fn generate(&mut self, range: impl RangeBounds) -> T where T: Copy + PartialOrd + Sub + Add + Bounded + One + fmt::Debug, Uniform: Distribution, { Uniform::from_range(range).sample(self) } /// Generates a random boolean with 50/50 probability. #[inline] pub fn flip(&mut self) -> bool { self.gen_u32() & 1 == 1 } /// Clones the generator by deterministically deriving a new generator based on the initial /// seed. /// /// This function can be used to create a new generator that is a "spinoff" of the old /// generator. The new generator will not produce the same sequence of values as the /// old generator. #[inline] #[must_use] pub fn fork(&mut self) -> Self { Rng::with_seed(self.gen_u64()) } /// Randomly shuffles the elements of the slice in place using Fisher-Yates algorithm. #[inline] pub fn shuffle(&mut self, slice: &mut [T]) { for i in 1..slice.len() { slice.swap(i, self.generate(..=i)); } } /// Fills a byte slice with random values. pub fn fill(&mut self, slice: &mut [u8]) { // We fill the slice by chunks of 8 bytes, or one block of // WyRand output per new state. let mut chunks = slice.chunks_exact_mut(core::mem::size_of::()); for chunk in chunks.by_ref() { let n = self.gen_u64().to_ne_bytes(); // Safe because the chunks are always 8 bytes exactly. chunk.copy_from_slice(&n); } // Any remainder will always be less than 8 bytes. let remainder = chunks.into_remainder(); if !remainder.is_empty() { // Generate one last block of 8 bytes of entropy let n = self.gen_u64().to_ne_bytes(); // Use the remaining length to copy from block remainder.copy_from_slice(&n[..remainder.len()]); } } /// Returns a random reference to an element from the slice, or None if empty. #[inline] pub fn choose<'a, T>(&mut self, slice: &'a [T]) -> Option<&'a T> { if slice.is_empty() { None } else { Some(&slice[self.generate(..slice.len())]) } } /// Returns a random mutable reference to an element from the slice, or None if empty. #[inline] pub fn choose_mut<'a, T>(&mut self, slice: &'a mut [T]) -> Option<&'a mut T> { if slice.is_empty() { None } else { let idx = self.generate(0..slice.len()); Some(&mut slice[idx]) } } } impl Entropy for Rng { #[inline(always)] fn gen_u64(&mut self) -> u64 { self.state = self.state.wrapping_add(0x2d35_8dcc_aa6c_78a5); let t = u128::from(self.state) * u128::from(self.state ^ 0x8bb8_4b93_962e_acc9); (t as u64) ^ (t >> 64) as u64 } } /// Uniform distribution over a range. #[derive(Debug, Clone, Copy)] pub struct Uniform { low: T, high: T, } impl Uniform { /// Creates a new uniform distribution over the range `[low, high]`. #[inline] pub const fn new(low: T, high: T) -> Self { Self { low, high } } } impl Uniform { /// Creates a uniform distribution over the full range of the type `T`. /// /// This distribution will generate values across the entire range of valid values /// for the bounded type `T`, from `T::MIN` to `T::MAX` inclusive. #[inline] pub const fn full() -> Self { Self::new(T::MIN, T::MAX) } /// Like [`Self::full`], but with a specified range. #[inline] pub fn from_range>(range: R) -> Self where T: Copy + PartialOrd + Add + Sub + fmt::Debug + One, { let low = match range.start_bound() { Bound::Unbounded => T::MIN, Bound::Included(&x) => x, Bound::Excluded(&x) if x < T::MAX => x + T::ONE, Bound::Excluded(_) => panic!( "Uniform::from_range: empty range {:?}..{:?}", range.start_bound(), range.end_bound() ), }; let high = match range.end_bound() { Bound::Unbounded => T::MAX, Bound::Included(&x) => x, Bound::Excluded(&x) if x > T::MIN => x - T::ONE, Bound::Excluded(_) => panic!( "Uniform::from_range: empty range {:?}..{:?}", range.start_bound(), range.end_bound() ), }; assert!( low <= high, "Uniform::from_range: empty range {:?}..{:?}", range.start_bound(), range.end_bound() ); Self { low, high } } } impl Distribution for Uniform where T: Copy + PartialOrd + Integer, { fn sample(&self, rng: &mut R) -> T { let low = self.low; let high = self.high; if low == T::MIN && high == T::MAX { return T::from_u64(rng.gen_u64()); } let len = high.wrapping_sub(low).as_u64() + 1; let threshold = len.wrapping_neg() % len; loop { let value = rng.gen_u64(); if value >= threshold { return low.wrapping_add(T::from_u64(value % len)); } } } } #[cfg(test)] mod tests { use super::*; use crate::math::traits::Integer; struct SequenceEntropy { values: std::vec::IntoIter, } impl SequenceEntropy { fn new(values: Vec) -> Self { Self { values: values.into_iter(), } } } impl Entropy for SequenceEntropy { fn gen_u64(&mut self) -> u64 { self.values.next().unwrap() } } #[allow(dead_code)] fn distribution( rng: &mut Rng, range: std::ops::Range, samples: usize, buckets: usize, ) { let mut counts = vec![0; buckets]; let bucket_size = (range.end - range.start).as_u64() as f64 / buckets as f64; for _ in 0..samples { let value = rng.generate(range.clone()); let bucket = ((value - range.start).as_u64() as f64 / bucket_size) as usize; counts[bucket.min(buckets - 1)] += 1; } let expected = samples as f64 / buckets as f64; for (i, &count) in counts.iter().enumerate() { let deviation = (count as f64 - expected).abs() / expected * 100.0; println!("Bucket {}: {} ({:.1}% deviation)", i, count, deviation); } } fn distribution_f64(rng: &mut Rng, samples: usize, buckets: usize) { let mut counts = vec![0; buckets]; let bucket_size = 1.0 / buckets as f64; for _ in 0..samples { let value = rng.fraction(); let bucket = (value / bucket_size) as usize; counts[bucket.min(buckets - 1)] += 1; } let expected = samples as f64 / buckets as f64; for (i, &count) in counts.iter().enumerate() { let deviation = (count as f64 - expected).abs() / expected * 100.0; println!("Bucket {}: {} ({:.1}% deviation)", i, count, deviation); } } #[test] fn fraction_is_less_than_one() { let mut rng = Rng::with_seed(0); rng.state = 0x6fa8_99d2_ddf8_ba1d; assert!(rng.fraction() < 1.0); } #[test] fn full_i32_distribution_preserves_signed_bits() { let distribution = Uniform::::full(); let mut rng = SequenceEntropy::new(vec![u64::MAX]); assert_eq!(distribution.sample(&mut rng), -1); } #[test] fn bounded_distribution_rejects_biased_prefix() { let distribution = Uniform::new(0_u64, 2); let mut rng = SequenceEntropy::new(vec![0, 2]); assert_eq!(distribution.sample(&mut rng), 2); } #[test] fn test_distribution() { let mut rng = Rng::new(); distribution_f64(&mut rng, 100000, 10); } #[test] fn test_basic_generation() { let mut rng = Rng::new(); // Using gen let _: u64 = rng.generate(..); let _: bool = rng.flip(); // Using gen_range let n = rng.generate(1u64..=100); assert!((1..=100).contains(&n)); for _ in 0..10 { let n = rng.generate(0..60); assert!((0..60).contains(&n), "{n}"); } } #[test] fn test_fill_bytes() { let mut rng = Rng::with_seed(49182); // Test different buffer sizes let sizes = [1, 7, 8, 9, 16, 32, 64]; for size in sizes { let mut buffer = vec![0u8; size]; rng.fill(&mut buffer); // Ensure we actually wrote some non-zero bytes assert!( buffer.iter().any(|&x| x != 0), "Buffer of size {} contains only zeros", size ); } // Test alignment handling let mut buffer = [0u8; 32]; rng.fill(&mut buffer[1..31]); // Unaligned slice } #[test] fn test_seeded_sequences() { let mut rng1 = Rng::with_seed(12345); let mut rng2 = Rng::with_seed(12345); // Same seed should produce same sequence for _ in 0..100 { assert_eq!(rng1.gen_u64(), rng2.gen_u64()); } // Different seeds should produce different sequences let mut rng3 = Rng::with_seed(12346); let val1 = rng1.gen_u64(); let val2 = rng3.gen_u64(); assert_ne!(val1, val2); } #[test] fn test_shuffle() { let mut rng = Rng::new(); // Test with different sizes for len in [2, 3, 10, 100] { let mut v: Vec = (0..len).collect(); let original = v.clone(); rng.shuffle(&mut v); // Length should remain the same assert_eq!(v.len(), original.len()); // All elements should still be present assert!(v.iter().all(|x| original.contains(x))); // Order should be different (for large enough arrays) if len > 10 { assert_ne!(v, original); } } // Test empty and single-element slices let mut empty: Vec = vec![]; rng.shuffle(&mut empty); assert!(empty.is_empty()); let mut single = vec![1]; rng.shuffle(&mut single); assert_eq!(single, vec![1]); } #[test] fn test_consecutive_values() { let mut rng = Rng::new(); let mut prev = rng.gen_u64(); let mut repeats = 0; // Test for obvious patterns in consecutive values for _ in 0..1000 { let curr = rng.gen_u64(); if curr == prev { repeats += 1; } prev = curr; } // Shouldn't have too many repeats assert!(repeats < 3, "Too many repeated consecutive values"); } }