```rust // `core::random` /// A source of random data pub trait RandomSource { /// Fill `buf` with random bytes. /// /// This is the baseline method that must be implemented. fn gen_bytes(&mut self, buf: &mut [u8]); // Overridable functions for performance. // This is similar to the Hasher trait. fn gen_u8(&mut self) -> u8; fn gen_u16(&mut self) -> u16; fn gen_u32(&mut self) -> u32; // etc } /// A trait for types which can be created from a RandomSource. pub trait Random { fn random(random_source: &mut impl RandomSource) -> Self; } // `std::random` /// Random source that produces cryptographically secure random numbers at a reasonable speed. /// /// This generator does not encapsulate any state, and cannot be seeded or replayed. #[derive(Default, Copy, Clone, Debug)] pub struct DefaultRng; impl RandomSource for DefaultRng { /* ... */ } /// Generate a random value pub fn random<T: Random>() -> T { <T as Random>::gen(DefaultRng) } ``` Future work: ```rust impl<T> [T] { /// Shuffle a slice into a random order pub fn shuffle(&mut self); /// Shuffle a slice into a random order, using the specified random source pub fn shuffle_with(&mut self, rng: &mut impl RandomSource); } impl Iterator { pub fn choose(&mut self) } ``` ```rust // `std::random` pub trait RandomSample<T> { fn sample() -> T } pub fn sample<R: RandomSample<T>>(range: R) -> /// Generate a random value in the specified range pub fn range<T: RandomRange>(bounds: impl RangeBounds<T>) -> T { /* ... */ } pub fn distribution<T, D: Distribution<T>>(bounds: D) -> T { /* ... */ } pub fn range<T, D: Distribution<T> + RangeBounds<T>>(bounds: D) -> T { /* ... */ } // Also a method on RandomSource if you need a specific RNG pub fn choose<T, D: Distribution<T>>(distribution: D) -> T { /* ... */ } pub trait Distribution<T> { fn sample(&self) -> T { self.sample_with(DefaultRng) } fn sample_with<R: RandomSource + ?Sized>(&self, rng: &mut R) -> T; } impl Distribution<i32> for Range<i32> { fn sample<R: RandomSource>(&self, rng: &mut R) -> T; } impl<'a, T> Distribution<&'a T> for &'a [T] { fn sample<R: RandomSource>(&self, rng: &mut R) -> &'a T; } impl<T: Clone, N: usize> Distribution<T> for [T; N] { fn sample<R: RandomSource>(&self, rng: &mut R) -> T; } struct StandardDistribution; impl Distribution<T: Random> for StandardDistribution { fn sample<R: RandomSource + ?Sized>(&self, rng: &mut R) -> T { T::gen(rng) } } ``` From the rand crate: ```rust! pub trait Distribution<T> { fn sample<R: RandomSource + ?Sized>(&self, rng: &mut R) -> T; } ```