pub struct Random<R: ?Sized>(pub R);
Expand description
Rich interface for consuming random number generators.
Tuple Fields
0: R
Implementations
sourceimpl<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.
If high quality uniform random floats are desired in 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.
If high quality uniform random floats are desired in open interval (0.0, 1.0)
without bias see the Float01
distribution.
Examples
let value = urandom::new().next_f64();
assert!(value >= 1.0 && value < 2.0);
sourcepub fn fill_u32(&mut self, buffer: &mut [u32])
pub fn fill_u32(&mut self, buffer: &mut [u32])
Fills the destination buffer with random values from the Rng.
The underlying Rng may implement this as efficiently as possible and may not be the same as simply filling with next_u32
.
Examples
let mut rng = urandom::new();
let mut buffer = [0u32; 32];
rng.fill_u32(&mut buffer);
assert_ne!(buffer, [0; 32]);
sourcepub fn fill_u64(&mut self, buffer: &mut [u64])
pub fn fill_u64(&mut self, buffer: &mut [u64])
Fills the destination buffer with uniform random values from the Rng.
The underlying Rng may implement this as efficiently as possible and may not be the same as simply filling with next_u64
.
Examples
let mut rng = urandom::new();
let mut buffer = [0u64; 32];
rng.fill_u64(&mut buffer);
assert_ne!(buffer, [0; 32]);
sourcepub fn fill_bytes(&mut self, buffer: &mut [u8])
pub fn fill_bytes(&mut self, buffer: &mut [u8])
Fills the destination buffer with uniform random bytes from the Rng.
The underlying Rng may implement this as efficiently as possible.
Examples
let mut rng = urandom::new();
let mut buffer = [0u8; 32];
rng.fill_bytes(&mut buffer);
assert_ne!(buffer, [0u8; 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 rng = urandom::new();
for _ in 0..10 {
parallel_computation(rng.split());
}
sourcepub fn next<T>(&mut self) -> Twhere
Standard: Distribution<T>,
pub fn next<T>(&mut self) -> Twhere
Standard: Distribution<T>,
sourcepub fn fill<T>(&mut self, buffer: &mut [T])where
Standard: Distribution<T>,
pub fn fill<T>(&mut self, buffer: &mut [T])where
Standard: Distribution<T>,
sourcepub fn range<T, I>(&mut self, interval: I) -> Twhere
T: SampleUniform,
Uniform<T>: From<I>,
pub fn range<T, I>(&mut self, interval: I) -> Twhere
T: SampleUniform,
Uniform<T>: From<I>,
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 rng = urandom::new();
let distr = urandom::distributions::Uniform::from(0..100);
loop {
let value = rng.sample(&distr);
assert!(value >= 0 && value < 100);
if value == 0 {
break;
}
}
sourcepub fn sample<T, D>(&mut self, distr: &D) -> Twhere
D: Distribution<T>,
pub fn sample<T, D>(&mut self, distr: &D) -> Twhere
D: Distribution<T>,
Returns a sample from the given distribution.
See the distributions
documentation for a list of available distributions.
sourcepub fn samples<T, D>(&mut self, distr: D) -> Samples<'_, R, D, T>ⓘNotable traits for Samples<'a, R, D, T>impl<'a, R: ?Sized, D, T> Iterator for Samples<'a, R, D, T>where
R: Rng,
D: Distribution<T>, type Item = T;
where
D: Distribution<T>,
pub fn samples<T, D>(&mut self, distr: D) -> Samples<'_, R, D, T>ⓘNotable traits for Samples<'a, R, D, T>impl<'a, R: ?Sized, D, T> Iterator for Samples<'a, R, D, T>where
R: Rng,
D: Distribution<T>, type Item = T;
where
D: Distribution<T>,
R: Rng,
D: Distribution<T>, type Item = T;
Returns an iterator of samples from the given distribution.
See the distributions
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 rng.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 rng = urandom::new();
let fizzbuzz = rng.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,
buffer: &mut [I::Item]
) -> usize
pub fn multiple<I: IntoIterator>(
&mut self,
collection: I,
buffer: &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 rng = urandom::new();
for len in 1..12345 {
let index = rng.index(len);
assert!(index < len, "len:{} index:{} was not inbounds", len, index);
}
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 choose_iter<'a, T>(
&'a mut self,
slice: &'a [T]
) -> impl 'a + Iterator<Item = &'a T>
pub fn choose_iter<'a, T>(
&'a mut self,
slice: &'a [T]
) -> impl 'a + Iterator<Item = &'a T>
Returns an iterator over random chosen elements of the slice with repetition.
Produces None
values 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 rng = urandom::new();
let mut array = [1, 2, 3, 4, 5];
println!("Unshuffled: {:?}", array);
rng.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
sourceimpl<R: Rng> Read for Random<R>
impl<R: Rng> Read for Random<R>
sourcefn read(&mut self, buf: &mut [u8]) -> Result<usize>
fn read(&mut self, buf: &mut [u8]) -> Result<usize>
sourcefn 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 moresourcefn read_to_string(&mut self, _buf: &mut String) -> Result<usize>
fn read_to_string(&mut self, _buf: &mut String) -> Result<usize>
buf
. Read moresourcefn read_exact(&mut self, buf: &mut [u8]) -> Result<()>
fn read_exact(&mut self, buf: &mut [u8]) -> Result<()>
buf
. Read more1.36.0 · sourcefn 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 moresourcefn is_read_vectored(&self) -> bool
fn is_read_vectored(&self) -> bool
can_vector
)sourcefn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<(), Error>
fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<(), Error>
read_buf
)sourcefn 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 · sourcefn by_ref(&mut self) -> &mut Selfwhere
Self: Sized,
fn by_ref(&mut self) -> &mut Selfwhere
Self: Sized,
Read
. Read more