pub struct Random<R: ?Sized> { /* private fields */ }Expand description
Rich interface for consuming random number generators.
Implementations§
Source§impl<R: Rng + ?Sized> Random<R>
impl<R: Rng + ?Sized> Random<R>
Sourcepub fn next_f32(&mut self) -> f32
pub fn next_f32(&mut self) -> f32
Returns a uniform random f32 in the half-open interval [1.0, 2.0).
As only 23 bits are necessary to construct a random float in this range, implementations may override this method to provide a more efficient implementation.
For high quality uniform random floats in the open interval (0.0, 1.0) without bias see the Float01 distribution.
§Examples
let value = urandom::new().next_f32();
assert!(value >= 1.0 && value < 2.0);Sourcepub fn next_f64(&mut self) -> f64
pub fn next_f64(&mut self) -> f64
Returns a uniform random f64 in the half-open interval [1.0, 2.0).
As only 52 bits are necessary to construct a random double in this range, implementations may override this method to provide a more efficient implementation.
For high quality uniform random floats in the open interval (0.0, 1.0) without bias see float01.
§Examples
let value = urandom::new().next_f64();
assert!(value >= 1.0 && value < 2.0);Sourcepub fn fill_bytes<'a, T: Pod>(&mut self, buf: &'a mut [T]) -> &'a mut [T]
pub fn fill_bytes<'a, T: Pod>(&mut self, buf: &'a mut [T]) -> &'a mut [T]
Fills the destination buffer with uniform random bytes from the Rng.
The underlying Rng may implement this as efficiently as possible.
§Examples
let mut rand = urandom::new();
let mut data = [0u32; 32];
let data = rand.fill_bytes(&mut data);
assert_ne!(data, [0u32; 32]);Sourcepub fn fill_bytes_uninit<'a, T: Pod>(
&mut self,
buf: &'a mut [MaybeUninit<T>],
) -> &'a mut [T]
pub fn fill_bytes_uninit<'a, T: Pod>( &mut self, buf: &'a mut [MaybeUninit<T>], ) -> &'a mut [T]
Fills the destination buffer with uniform random bytes from the Rng.
The underlying Rng may implement this as efficiently as possible.
§Examples
use std::mem::MaybeUninit;
use std::slice;
let mut rand = urandom::new();
let mut data = MaybeUninit::<[u32; 32]>::uninit();
let data = rand.fill_bytes_uninit(slice::from_mut(&mut data));
assert_ne!(data, [[0u32; 32]]);Sourcepub fn random_bytes<T: Pod>(&mut self) -> T
pub fn random_bytes<T: Pod>(&mut self) -> T
Fills the instance with uniform random bytes from the Rng.
The underlying Rng may implement this as efficiently as possible.
§Examples
let mut rand = urandom::new();
let value: [u32; 32] = rand.random_bytes();
assert_ne!(value, [0u32; 32]);Sourcepub fn jump(&mut self)
pub fn jump(&mut self)
Advances the internal state significantly.
Useful to produce deterministic independent random number generators for parallel computation.
Sourcepub fn split(&mut self) -> Selfwhere
Self: Clone,
pub fn split(&mut self) -> Selfwhere
Self: Clone,
Clones the current instance and advances the internal state significantly.
Useful to produce deterministic independent random number generators for parallel computation.
§Examples
let mut rand = urandom::new();
for _ in 0..10 {
parallel_computation(rand.split());
}Sourcepub fn next<T>(&mut self) -> Twhere
StandardUniform: Distribution<T>,
pub fn next<T>(&mut self) -> Twhere
StandardUniform: Distribution<T>,
Returns a sample from the StandardUniform distribution.
§Examples
let int: i8 = urandom::new().next();Sourcepub fn fill<T>(&mut self, buf: &mut [T])where
StandardUniform: Distribution<T>,
pub fn fill<T>(&mut self, buf: &mut [T])where
StandardUniform: Distribution<T>,
Fills the given slice with samples from the StandardUniform distribution.
Because of its generic nature no optimizations are applied and all values are sampled individually.
§Examples
let mut rand = urandom::new();
let mut data = [false; 32];
rand.fill(&mut data);Sourcepub fn range<T, I>(&mut self, interval: I) -> T
pub fn range<T, I>(&mut self, interval: I) -> T
Returns a sample from the Uniform distribution within the given interval.
§Examples
let eyes = urandom::new().range(1..=6);
assert!(eyes >= 1 && eyes <= 6);If more than one sample from a specific interval is desired, it is more efficient to reuse the uniform sampler.
let mut rand = urandom::new();
let distr = urandom::distr::Uniform::from(0..100);
loop {
let value = rand.sample(&distr);
assert!(value >= 0 && value < 100);
if value == 0 {
break;
}
}Sourcepub fn float01(&mut self) -> f64
pub fn float01(&mut self) -> f64
Returns a random float in the open (0.0, 1.0) interval.
This is a high quality uniform random float without bias in the low bits of the mantissa using the Float01 distribution.
Sourcepub fn sample<T, D: Distribution<T>>(&mut self, distr: &D) -> T
pub fn sample<T, D: Distribution<T>>(&mut self, distr: &D) -> T
Returns a sample from the given distribution.
See the distr documentation for a list of available distributions.
Sourcepub fn samples<T, D: Distribution<T>>(
&mut self,
distr: D,
) -> Samples<'_, R, D, T> ⓘ
pub fn samples<T, D: Distribution<T>>( &mut self, distr: D, ) -> Samples<'_, R, D, T> ⓘ
Returns an iterator of samples from the given distribution.
See the distr documentation for a list of available distributions.
Sourcepub fn coin_flip(&mut self) -> bool
pub fn coin_flip(&mut self) -> bool
Flips a coin.
Returns true when heads and false when tails with 50% probability for either result.
Simply an alias for rand.next::<bool>() but describes the intent of the caller.
Sourcepub fn single<I: IntoIterator>(&mut self, collection: I) -> Option<I::Item>
pub fn single<I: IntoIterator>(&mut self, collection: I) -> Option<I::Item>
Returns a random sample from the collection.
Returns None if and only if the collection is empty.
This method uses Iterator::size_hint for optimisation.
With an accurate hint and where Iterator::nth is a constant-time operation this method can offer O(1) performance.
For slices, prefer choose which guarantees O(1) performance.
§Examples
Sample a random fizz, buzz or fizzbuzz number up to 100:
fn is_fizzbuzz(n: &i32) -> bool {
n % 3 == 0 || n % 5 == 0
}
let mut rand = urandom::new();
let fizzbuzz = rand.single((0..100).filter(is_fizzbuzz)).unwrap();
assert!(fizzbuzz % 3 == 0 || fizzbuzz % 5 == 0);Pick a random emoji:
let mood = urandom::new().single("😀😎😐😕😠😢".chars()).unwrap();
println!("I am {mood}!");Sourcepub fn multiple<I: IntoIterator>(
&mut self,
collection: I,
buf: &mut [I::Item],
) -> usize
pub fn multiple<I: IntoIterator>( &mut self, collection: I, buf: &mut [I::Item], ) -> usize
Collect random samples from the collection into the buffer until it is filled.
Although the elements are selected randomly, the order of elements in the buffer is neither stable nor fully random. If random ordering is desired, shuffle the result.
Returns the number of elements added to the buffer. This equals the length of the buffer unless the iterator contains insufficient elements, in which case this equals the number of elements available.
Complexity is O(n) where n is the size of the collection.
Sourcepub fn index(&mut self, len: usize) -> usize
pub fn index(&mut self, len: usize) -> usize
Returns a random usize in the [0, len) interval, mostly.
If the len is zero an arbitrary value is returned directly from the Rng.
When used with indexing the bounds check should fail. Do not assume this value is inbounds.
§Examples
let mut rand = urandom::new();
for len in 1..12345 {
let index = rand.index(len);
assert!(index < len, "len:{len} index:{index} was not inbounds");
}Sourcepub fn choose<'a, T>(&mut self, slice: &'a [T]) -> Option<&'a T>
pub fn choose<'a, T>(&mut self, slice: &'a [T]) -> Option<&'a T>
Returns a shared reference to one random element of the slice, or None if the slice is empty.
Sourcepub fn choose_mut<'a, T>(&mut self, slice: &'a mut [T]) -> Option<&'a mut T>
pub fn choose_mut<'a, T>(&mut self, slice: &'a mut [T]) -> Option<&'a mut T>
Returns a unique reference to one random element of the slice, or None if the slice is empty.
Sourcepub fn shuffle<T>(&mut self, slice: &mut [T])
pub fn shuffle<T>(&mut self, slice: &mut [T])
Standard Fisher–Yates shuffle.
§Examples
let mut rand = urandom::new();
let mut array = [1, 2, 3, 4, 5];
println!("Unshuffled: {array:?}");
rand.shuffle(&mut array);
println!("Shuffled: {array:?}");Sourcepub fn partial_shuffle<T>(&mut self, slice: &mut [T], n: usize)
pub fn partial_shuffle<T>(&mut self, slice: &mut [T], n: usize)
Shuffle only the first n elements.
This is an efficient method to select n elements at random from the slice without repetition, provided the slice may be mutated.
Trait Implementations§
Source§impl<R: Rng + ?Sized> Read for Random<R>
impl<R: Rng + ?Sized> Read for Random<R>
Source§fn read(&mut self, buf: &mut [u8]) -> Result<usize>
fn read(&mut self, buf: &mut [u8]) -> Result<usize>
Source§fn read_to_end(&mut self, _buf: &mut Vec<u8>) -> Result<usize>
fn read_to_end(&mut self, _buf: &mut Vec<u8>) -> Result<usize>
buf. Read moreSource§fn read_to_string(&mut self, _buf: &mut String) -> Result<usize>
fn read_to_string(&mut self, _buf: &mut String) -> Result<usize>
buf. Read moreSource§fn read_exact(&mut self, buf: &mut [u8]) -> Result<()>
fn read_exact(&mut self, buf: &mut [u8]) -> Result<()>
buf. Read more1.36.0 · Source§fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>
fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>
read, except that it reads into a slice of buffers. Read moreSource§fn is_read_vectored(&self) -> bool
fn is_read_vectored(&self) -> bool
can_vector)Source§fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<(), Error>
fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<(), Error>
read_buf)Source§fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error>
fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error>
read_buf)cursor. Read more1.0.0 · Source§fn by_ref(&mut self) -> &mut Selfwhere
Self: Sized,
fn by_ref(&mut self) -> &mut Selfwhere
Self: Sized,
Read. Read more