Random

Struct Random 

Source
pub struct Random<R: ?Sized> { /* private fields */ }
Expand description

Rich interface for consuming random number generators.

Implementations§

Source§

impl<R: Rng + ?Sized> Random<R>

Source

pub fn next_u32(&mut self) -> u32

Returns the next u32 in the sequence.

§Examples
let value = urandom::new().next_u32();
Source

pub fn next_u64(&mut self) -> u64

Returns the next u64 in the sequence.

§Examples
let value = urandom::new().next_u64();
Source

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);
Source

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);
Source

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]);
Source

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]]);
Source

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]);
Source

pub fn jump(&mut self)

Advances the internal state significantly.

Useful to produce deterministic independent random number generators for parallel computation.

Source

pub fn split(&mut self) -> Self
where 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());
}
Source

pub fn next<T>(&mut self) -> T

Returns a sample from the StandardUniform distribution.

§Examples
let int: i8 = urandom::new().next();
Source

pub fn fill<T>(&mut self, buf: &mut [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);
Source

pub fn range<T, I>(&mut self, interval: I) -> T
where 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 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;
	}
}
Source

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.

Source

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.

Source

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.

Source

pub fn chance(&mut self, p: f64) -> bool

Returns true if a random number (0.0, 1.0) is less than the given probability.

This is known as the Bernoulli distribution.

§Precision

For p >= 1.0, the resulting distribution will always generate true.
For p <= 0.0, the resulting distribution will always generate false.

Source

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.

Source

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}!");
Source

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.

Source

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");
}
Source

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.

Source

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.

Source

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:?}");
Source

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: Clone + ?Sized> Clone for Random<R>

Source§

fn clone(&self) -> Random<R>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<R: Rng + ?Sized> Debug for Random<R>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<R: Rng + ?Sized> Read for Random<R>

Source§

fn read(&mut self, buf: &mut [u8]) -> Result<usize>

Pull some bytes from this source into the specified buffer, returning how many bytes were read. Read more
Source§

fn read_to_end(&mut self, _buf: &mut Vec<u8>) -> Result<usize>

Reads all bytes until EOF in this source, placing them into buf. Read more
Source§

fn read_to_string(&mut self, _buf: &mut String) -> Result<usize>

Reads all bytes until EOF in this source, appending them to buf. Read more
Source§

fn read_exact(&mut self, buf: &mut [u8]) -> Result<()>

Reads the exact number of bytes required to fill buf. Read more
1.36.0 · Source§

fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>

Like read, except that it reads into a slice of buffers. Read more
Source§

fn is_read_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Reader has an efficient read_vectored implementation. Read more
Source§

fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Pull some bytes from this source into the specified buffer. Read more
Source§

fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Reads the exact number of bytes required to fill cursor. Read more
1.0.0 · Source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adaptor for this instance of Read. Read more
1.0.0 · Source§

fn bytes(self) -> Bytes<Self>
where Self: Sized,

Transforms this Read instance to an Iterator over its bytes. Read more
1.0.0 · Source§

fn chain<R>(self, next: R) -> Chain<Self, R>
where R: Read, Self: Sized,

Creates an adapter which will chain this stream with another. Read more
1.0.0 · Source§

fn take(self, limit: u64) -> Take<Self>
where Self: Sized,

Creates an adapter which will read at most limit bytes from it. Read more

Auto Trait Implementations§

§

impl<R> Freeze for Random<R>
where R: Freeze + ?Sized,

§

impl<R> RefUnwindSafe for Random<R>
where R: RefUnwindSafe + ?Sized,

§

impl<R> Send for Random<R>
where R: Send + ?Sized,

§

impl<R> Sync for Random<R>
where R: Sync + ?Sized,

§

impl<R> Unpin for Random<R>
where R: Unpin + ?Sized,

§

impl<R> UnwindSafe for Random<R>
where R: UnwindSafe + ?Sized,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.