Files
blackwriter-server/doc/rand.md
PIVODEVAT 059fbda921 init
2025-12-13 22:28:05 +03:00

61 KiB

Crate Documentation

Version: 0.9.2

Format Version: 54

Module rand

Utilities for random number generation

Rand provides utilities to generate random numbers, to convert them to useful types and distributions, and some randomness-related algorithms.

Quick Start

// The prelude import enables methods we use below, specifically
// Rng::random, Rng::sample, SliceRandom::shuffle and IndexedRandom::choose.
use rand::prelude::*;

// Get an RNG:
let mut rng = rand::rng();

// Try printing a random unicode code point (probably a bad idea)!
println!("char: '{}'", rng.random::<char>());
// Try printing a random alphanumeric value instead!
println!("alpha: '{}'", rng.sample(rand::distr::Alphanumeric) as char);

// Generate and shuffle a sequence:
let mut nums: Vec<i32> = (1..100).collect();
nums.shuffle(&mut rng);
// And take a random pick (yes, we didn't need to shuffle first!):
let _ = nums.choose(&mut rng);

The Book

For the user guide and further documentation, please read The Rust Rand Book.

Modules

Module distr

Generating random samples from probability distributions

This module is the home of the [Distribution] trait and several of its implementations. It is the workhorse behind some of the convenient functionality of the Rng trait, e.g. [Rng::random] and of course [Rng::sample].

Abstractly, a probability distribution describes the probability of occurrence of each value in its sample space.

More concretely, an implementation of Distribution<T> for type X is an algorithm for choosing values from the sample space (a subset of T) according to the distribution X represents, using an external source of randomness (an RNG supplied to the sample function).

A type X may implement Distribution<T> for multiple types T. Any type implementing [Distribution] is stateless (i.e. immutable), but it may have internal parameters set at construction time (for example, Uniform allows specification of its sample space as a range within T).

The Standard Uniform distribution

The StandardUniform distribution is important to mention. This is the distribution used by [Rng::random] and represents the "default" way to produce a random value for many different types, including most primitive types, tuples, arrays, and a few derived types. See the documentation of StandardUniform for more details.

Implementing [Distribution<T>] for StandardUniform for user types T makes it possible to generate type T with [Rng::random], and by extension also with the random function.

Other standard uniform distributions

[Alphanumeric] is a simple distribution to sample random letters and numbers of the char type; in contrast StandardUniform may sample any valid char.

There's also an [Alphabetic] distribution which acts similarly to [Alphanumeric] but doesn't include digits.

For floats (f32, f64), StandardUniform samples from [0, 1). Also provided are [Open01] (samples from (0, 1)) and [OpenClosed01] (samples from (0, 1]). No option is provided to sample from [0, 1]; it is suggested to use one of the above half-open ranges since the failure to sample a value which would have a low chance of being sampled anyway is rarely an issue in practice.

Parameterized Uniform distributions

The Uniform distribution provides uniform sampling over a specified range on a subset of the types supported by the above distributions.

Implementations support single-value-sampling via Rng::random_range(Range). Where a fixed (non-const) range will be sampled many times, it is likely faster to pre-construct a [Distribution] object using [Uniform::new], [Uniform::new_inclusive] or From<Range>.

Non-uniform sampling

Sampling a simple true/false outcome with a given probability has a name: the Bernoulli distribution (this is used by [Rng::random_bool]).

For weighted sampling of discrete values see the [weighted] module.

This crate no longer includes other non-uniform distributions; instead it is recommended that you use either rand_distr or statrs.

pub mod distr { /* ... */ }

Modules

Module slice

Distributions over slices

pub mod slice { /* ... */ }

Types

Struct Choose

A distribution to uniformly sample elements of a slice

Like IndexedRandom::choose, this uniformly samples elements of a slice without modification of the slice (so called "sampling with replacement"). This distribution object may be a little faster for repeated sampling (but slower for small numbers of samples).

Examples

Since this is a distribution, Rng::sample_iter and [Distribution::sample_iter] may be used, for example:

use rand::distr::{Distribution, slice::Choose};

let vowels = ['a', 'e', 'i', 'o', 'u'];
let vowels_dist = Choose::new(&vowels).unwrap();

// build a string of 10 vowels
let vowel_string: String = vowels_dist
    .sample_iter(&mut rand::rng())
    .take(10)
    .collect();

println!("{}", vowel_string);
assert_eq!(vowel_string.len(), 10);
assert!(vowel_string.chars().all(|c| vowels.contains(&c)));

For a single sample, IndexedRandom::choose may be preferred:

use rand::seq::IndexedRandom;

let vowels = ['a', 'e', 'i', 'o', 'u'];
let mut rng = rand::rng();

println!("{}", vowels.choose(&mut rng).unwrap());
pub struct Choose<''a, T> {
    // Some fields omitted
}
Fields
Name Type Documentation
private fields ... Some fields have been omitted
Implementations
Methods
  • pub fn new(slice: &''a [T]) -> Result<Self, Empty> { /* ... */ }
    

    Create a new Choose instance which samples uniformly from the slice.

  • pub fn num_choices(self: &Self) -> NonZeroUsize { /* ... */ }
    

    Returns the count of choices in this distribution

Trait Implementations
  • Any

    • fn type_id(self: &Self) -> TypeId { /* ... */ }
      
  • Borrow

    • fn borrow(self: &Self) -> &T { /* ... */ }
      
  • BorrowMut

    • fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ }
      
  • Clone

    • fn clone(self: &Self) -> Choose<''a, T> { /* ... */ }
      
  • CloneToUninit

    • unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ }
      
  • Copy

  • Debug

    • fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ }
      
  • Distribution

    • fn sample<R: crate::Rng + ?Sized>(self: &Self, rng: &mut R) -> &''a T { /* ... */ }
      
  • Freeze

  • From

    • fn from(t: T) -> T { /* ... */ }
      
      Returns the argument unchanged.
  • Into

    • fn into(self: Self) -> U { /* ... */ }
      
      Calls U::from(self).
  • RefUnwindSafe

  • SampleString

    • fn append_string<R: crate::Rng + ?Sized>(self: &Self, rng: &mut R, string: &mut String, len: usize) { /* ... */ }
      
  • Send

  • Sync

  • ToOwned

    • fn to_owned(self: &Self) -> T { /* ... */ }
      
    • fn clone_into(self: &Self, target: &mut T) { /* ... */ }
      
  • TryFrom

    • fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> { /* ... */ }
      
  • TryInto

    • fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error> { /* ... */ }
      
  • Unpin

  • UnwindSafe

  • VZip

    • fn vzip(self: Self) -> V { /* ... */ }
      

Struct Empty

Error: empty slice

This error is returned when [Choose::new] is given an empty slice.

pub struct Empty;
Implementations
Trait Implementations
  • Any

    • fn type_id(self: &Self) -> TypeId { /* ... */ }
      
  • Borrow

    • fn borrow(self: &Self) -> &T { /* ... */ }
      
  • BorrowMut

    • fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ }
      
  • Clone

    • fn clone(self: &Self) -> Empty { /* ... */ }
      
  • CloneToUninit

    • unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ }
      
  • Copy

  • Debug

    • fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ }
      
  • Display

    • fn fmt(self: &Self, f: &mut core::fmt::Formatter<''_>) -> core::fmt::Result { /* ... */ }
      
  • Error

  • Freeze

  • From

    • fn from(t: T) -> T { /* ... */ }
      
      Returns the argument unchanged.
  • Into

    • fn into(self: Self) -> U { /* ... */ }
      
      Calls U::from(self).
  • RefUnwindSafe

  • Send

  • Sync

  • ToOwned

    • fn to_owned(self: &Self) -> T { /* ... */ }
      
    • fn clone_into(self: &Self, target: &mut T) { /* ... */ }
      
  • ToString

    • fn to_string(self: &Self) -> String { /* ... */ }
      
  • TryFrom

    • fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> { /* ... */ }
      
  • TryInto

    • fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error> { /* ... */ }
      
  • Unpin

  • UnwindSafe

  • VZip

    • fn vzip(self: Self) -> V { /* ... */ }
      

Module uniform

A distribution uniformly sampling numbers within a given range.

Uniform is the standard distribution to sample uniformly from a range; e.g. Uniform::new_inclusive(1, 6).unwrap() can sample integers from 1 to 6, like a standard die. Rng::random_range is implemented over Uniform.

Example usage

use rand::Rng;
use rand::distr::Uniform;

let mut rng = rand::rng();
let side = Uniform::new(-10.0, 10.0).unwrap();

// sample between 1 and 10 points
for _ in 0..rng.random_range(1..=10) {
    // sample a point from the square with sides -10 - 10 in two dimensions
    let (x, y) = (rng.sample(side), rng.sample(side));
    println!("Point: {}, {}", x, y);
}

Extending Uniform to support a custom type

To extend Uniform to support your own types, write a back-end which implements the UniformSampler trait, then implement the SampleUniform helper trait to "register" your back-end. See the MyF32 example below.

At a minimum, the back-end needs to store any parameters needed for sampling (e.g. the target range) and implement new, new_inclusive and sample. Those methods should include an assertion to check the range is valid (i.e. low < high). The example below merely wraps another back-end.

The new, new_inclusive, sample_single and sample_single_inclusive functions use arguments of type SampleBorrow<X> to support passing in values by reference or by value. In the implementation of these functions, you can choose to simply use the reference returned by SampleBorrow::borrow, or you can choose to copy or clone the value, whatever is appropriate for your type.

use rand::prelude::*;
use rand::distr::uniform::{Uniform, SampleUniform,
        UniformSampler, UniformFloat, SampleBorrow, Error};

struct MyF32(f32);

#[derive(Clone, Copy, Debug)]
struct UniformMyF32(UniformFloat<f32>);

impl UniformSampler for UniformMyF32 {
    type X = MyF32;

    fn new<B1, B2>(low: B1, high: B2) -> Result<Self, Error>
        where B1: SampleBorrow<Self::X> + Sized,
              B2: SampleBorrow<Self::X> + Sized
    {
        UniformFloat::<f32>::new(low.borrow().0, high.borrow().0).map(UniformMyF32)
    }
    fn new_inclusive<B1, B2>(low: B1, high: B2) -> Result<Self, Error>
        where B1: SampleBorrow<Self::X> + Sized,
              B2: SampleBorrow<Self::X> + Sized
    {
        UniformFloat::<f32>::new_inclusive(low.borrow().0, high.borrow().0).map(UniformMyF32)
    }
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X {
        MyF32(self.0.sample(rng))
    }
}

impl SampleUniform for MyF32 {
    type Sampler = UniformMyF32;
}

let (low, high) = (MyF32(17.0f32), MyF32(22.0f32));
let uniform = Uniform::new(low, high).unwrap();
let x = uniform.sample(&mut rand::rng());
pub mod uniform { /* ... */ }

Types

Enum Error

Error type returned from [Uniform::new] and new_inclusive.

pub enum Error {
    EmptyRange,
    NonFinite,
}
Variants
EmptyRange

low > high, or equal in case of exclusive range.

NonFinite

Input or range high - low is non-finite. Not relevant to integer types.

Implementations
Trait Implementations
  • Any

    • fn type_id(self: &Self) -> TypeId { /* ... */ }
      
  • Borrow

    • fn borrow(self: &Self) -> &T { /* ... */ }
      
  • BorrowMut

    • fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ }
      
  • Clone

    • fn clone(self: &Self) -> Error { /* ... */ }
      
  • CloneToUninit

    • unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ }
      
  • Copy

  • Debug

    • fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ }
      
  • Display

    • fn fmt(self: &Self, f: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ }
      
  • Eq

  • Error

  • Freeze

  • From

    • fn from(t: T) -> T { /* ... */ }
      
      Returns the argument unchanged.
  • Into

    • fn into(self: Self) -> U { /* ... */ }
      
      Calls U::from(self).
  • PartialEq

    • fn eq(self: &Self, other: &Error) -> bool { /* ... */ }
      
  • RefUnwindSafe

  • Send

  • StructuralPartialEq

  • Sync

  • ToOwned

    • fn to_owned(self: &Self) -> T { /* ... */ }
      
    • fn clone_into(self: &Self, target: &mut T) { /* ... */ }
      
  • ToString

    • fn to_string(self: &Self) -> String { /* ... */ }
      
  • TryFrom

    • fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> { /* ... */ }
      
  • TryInto

    • fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error> { /* ... */ }
      
  • Unpin

  • UnwindSafe

  • VZip

    • fn vzip(self: Self) -> V { /* ... */ }
      

Struct Uniform

Attributes:

  • Other("#[<cfg_attr>(feature = \"serde\", derive(Serialize, Deserialize))]")
  • Other("#[<cfg_attr>(feature = \"serde\",\nserde(bound(serialize = \"X::Sampler: Serialize\")))]")
  • Other("#[serde(bound(serialize = \"X::Sampler: Serialize\"))]")
  • Other("#[<cfg_attr>(feature = \"serde\",\nserde(bound(deserialize = \"X::Sampler: Deserialize<'de>\")))]")
  • Other("#[serde(bound(deserialize = \"X::Sampler: Deserialize<'de>\"))]")

Sample values uniformly between two bounds.

Construction

[Uniform::new] and [Uniform::new_inclusive] construct a uniform distribution sampling from the given low and high limits. Uniform may also be constructed via [TryFrom] as in Uniform::try_from(1..=6).unwrap().

Constructors may do extra work up front to allow faster sampling of multiple values. Where only a single sample is required it is suggested to use Rng::random_range or one of the sample_single methods instead.

When sampling from a constant range, many calculations can happen at compile-time and all methods should be fast; for floating-point ranges and the full range of integer types, this should have comparable performance to the StandardUniform distribution.

Provided implementations

  • char ([UniformChar]): samples a range over the implementation for u32
  • f32, f64 (UniformFloat): samples approximately uniformly within a range; bias may be present in the least-significant bit of the significand and the limits of the input range may be sampled even when an open (exclusive) range is used
  • Integer types (UniformInt) may show a small bias relative to the expected uniform distribution of output. In the worst case, bias affects 1 in 2^n samples where n is 56 (i8 and u8), 48 (i16 and u16), 96 (i32 and u32), 64 (i64 and u64), 128 (i128 and u128). The unbiased feature flag fixes this bias.
  • usize ([UniformUsize]) is handled specially, using the u32 implementation where possible to enable portable results across 32-bit and 64-bit CPU architectures.
  • Duration (UniformDuration): samples a range over the implementation for u32 or u64
  • SIMD types (requires simd_support feature) like x86's __m128i and std::simd's u32x4, f32x4 and mask32x4 types are effectively arrays of integer or floating-point types. Each lane is sampled independently from its own range, potentially with more efficient random-bit-usage than would be achieved with sequential sampling.

Example

use rand::distr::{Distribution, Uniform};

let between = Uniform::try_from(10..10000).unwrap();
let mut rng = rand::rng();
let mut sum = 0;
for _ in 0..1000 {
    sum += between.sample(&mut rng);
}
println!("{}", sum);

For a single sample, Rng::random_range may be preferred:

use rand::Rng;

let mut rng = rand::rng();
println!("{}", rng.random_range(0..10));
pub struct Uniform<X: SampleUniform>(/* private field */);
Fields
Index Type Documentation
0 private Private field
Implementations
Methods
  • pub fn new<B1, B2>(low: B1, high: B2) -> Result<Uniform<X>, Error>
    

where B1: SampleBorrow + Sized, B2: SampleBorrow + Sized { /* ... */ }

Create a new `Uniform` instance, which samples uniformly from the half

- ```rust
pub fn new_inclusive<B1, B2>(low: B1, high: B2) -> Result<Uniform<X>, Error>
where
  B1: SampleBorrow<X> + Sized,
  B2: SampleBorrow<X> + Sized { /* ... */ }

Create a new Uniform instance, which samples uniformly from the closed

Trait Implementations
  • Any

    • fn type_id(self: &Self) -> TypeId { /* ... */ }
      
  • Borrow

    • fn borrow(self: &Self) -> &T { /* ... */ }
      
  • BorrowMut

    • fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ }
      
  • Clone

    • fn clone(self: &Self) -> Uniform<X> { /* ... */ }
      
  • CloneToUninit

    • unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ }
      
  • Copy

  • Debug

    • fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ }
      
  • Deserialize

    • fn deserialize<__D>(__deserializer: __D) -> _serde::__private::Result<Self, <__D as >::Error>
      

where __D: _serde::Deserializer<''de> { /* ... */ } ```

  • DeserializeOwned

  • Distribution

    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> X { /* ... */ }
      
  • Eq

  • Freeze

  • From

    • fn from(t: T) -> T { /* ... */ }
      
      Returns the argument unchanged.
  • Into

    • fn into(self: Self) -> U { /* ... */ }
      
      Calls U::from(self).
  • PartialEq

    • fn eq(self: &Self, other: &Uniform<X>) -> bool { /* ... */ }
      
  • RefUnwindSafe

  • SampleString

    • fn append_string<R: Rng + ?Sized>(self: &Self, rng: &mut R, string: &mut alloc::string::String, len: usize) { /* ... */ }
      
  • Send

  • Serialize

    • fn serialize<__S>(self: &Self, __serializer: __S) -> _serde::__private::Result<<__S as >::Ok, <__S as >::Error>
      

where __S: _serde::Serializer { /* ... */ } ```

  • StructuralPartialEq

  • Sync

  • ToOwned

    • fn to_owned(self: &Self) -> T { /* ... */ }
      
    • fn clone_into(self: &Self, target: &mut T) { /* ... */ }
      
  • TryFrom

    • fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> { /* ... */ }
      
    • fn try_from(r: Range<X>) -> Result<Uniform<X>, Error> { /* ... */ }
      
    • fn try_from(r: ::core::ops::RangeInclusive<X>) -> Result<Uniform<X>, Error> { /* ... */ }
      
  • TryInto

    • fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error> { /* ... */ }
      
  • Unpin

  • UnwindSafe

  • VZip

    • fn vzip(self: Self) -> V { /* ... */ }
      

Traits

Trait SampleUniform

Helper trait for creating objects using the correct implementation of UniformSampler for the sampling type.

See the module documentation on how to implement Uniform range sampling for a custom type.

pub trait SampleUniform: Sized {
    /* Associated items */
}

This trait is not object-safe and cannot be used in dynamic trait objects.

Required Items
Associated Types
  • Sampler: The UniformSampler implementation supporting type X.
Implementations

This trait is implemented for the following types:

  • f32
  • f64
  • f32x2
  • f32x4
  • f32x8
  • f32x16
  • f64x2
  • f64x4
  • f64x8
  • i8
  • i16
  • i32
  • i64
  • i128
  • u8
  • u16
  • u32
  • u64
  • u128
  • Simd<u8, LANES> with
  • Simd<i8, LANES> with
  • Simd<u16, LANES> with
  • Simd<i16, LANES> with
  • Simd<u32, LANES> with
  • Simd<i32, LANES> with
  • Simd<u64, LANES> with
  • Simd<i64, LANES> with
  • usize
  • char
  • core::time::Duration

Trait UniformSampler

Helper trait handling actual uniform sampling.

See the module documentation on how to implement Uniform range sampling for a custom type.

Implementation of sample_single is optional, and is only useful when the implementation can be faster than Self::new(low, high).sample(rng).

pub trait UniformSampler: Sized {
    /* Associated items */
}

This trait is not object-safe and cannot be used in dynamic trait objects.

Required Items
Associated Types
  • X: The type sampled by this implementation.
Required Methods
  • new: Construct self, with inclusive lower bound and exclusive upper bound [low, high).
  • new_inclusive: Construct self, with inclusive bounds [low, high].
  • sample: Sample a value.
Provided Methods
  • fn sample_single<R: Rng + ?Sized, B1, B2>(low: B1, high: B2, rng: &mut R) -> Result<<Self as >::X, Error>
    

where B1: SampleBorrow<::X> + Sized, B2: SampleBorrow<::X> + Sized { /* ... */ }

Sample a single value uniformly from a range with inclusive lower bound

- ```rust
fn sample_single_inclusive<R: Rng + ?Sized, B1, B2>(low: B1, high: B2, rng: &mut R) -> Result<<Self as >::X, Error>
where
  B1: SampleBorrow<<Self as >::X> + Sized,
  B2: SampleBorrow<<Self as >::X> + Sized { /* ... */ }

Sample a single value uniformly from a range with inclusive lower bound

Implementations

This trait is implemented for the following types:

  • UniformFloat<f32>
  • UniformFloat<f64>
  • UniformFloat<f32x2>
  • UniformFloat<f32x4>
  • UniformFloat<f32x8>
  • UniformFloat<f32x16>
  • UniformFloat<f64x2>
  • UniformFloat<f64x4>
  • UniformFloat<f64x8>
  • UniformInt<i8>
  • UniformInt<i16>
  • UniformInt<i32>
  • UniformInt<i64>
  • UniformInt<i128>
  • UniformInt<u8>
  • UniformInt<u16>
  • UniformInt<u32>
  • UniformInt<u64>
  • UniformInt<u128>
  • UniformInt<Simd<u8, LANES>> with
  • UniformInt<Simd<i8, LANES>> with
  • UniformInt<Simd<u16, LANES>> with
  • UniformInt<Simd<i16, LANES>> with
  • UniformInt<Simd<u32, LANES>> with
  • UniformInt<Simd<i32, LANES>> with
  • UniformInt<Simd<u64, LANES>> with
  • UniformInt<Simd<i64, LANES>> with
  • UniformUsize
  • UniformChar
  • UniformDuration

Trait SampleBorrow

Helper trait similar to Borrow but implemented only for SampleUniform and references to SampleUniform in order to resolve ambiguity issues.

pub trait SampleBorrow<Borrowed> {
    /* Associated items */
}
Required Items
Required Methods
  • borrow: Immutably borrows from an owned value. See [Borrow::borrow]
Implementations

This trait is implemented for the following types:

  • Borrowed with
  • &Borrowed with

Trait SampleRange

Range that supports generating a single sample efficiently.

Any type implementing this trait can be used to specify the sampled range for Rng::random_range.

pub trait SampleRange<T> {
    /* Associated items */
}

This trait is not object-safe and cannot be used in dynamic trait objects.

Required Items
Required Methods
  • sample_single: Generate a sample from the given range.
  • is_empty: Check whether the range is empty.
Implementations

This trait is implemented for the following types:

  • core::ops::Range<T> with <T: SampleUniform + PartialOrd>
  • core::ops::RangeInclusive<T> with <T: SampleUniform + PartialOrd>
  • RangeTo<u8>
  • RangeToInclusive<u8>
  • RangeTo<u16>
  • RangeToInclusive<u16>
  • RangeTo<u32>
  • RangeToInclusive<u32>
  • RangeTo<u64>
  • RangeToInclusive<u64>
  • RangeTo<u128>
  • RangeToInclusive<u128>
  • RangeTo<usize>
  • RangeToInclusive<usize>

Re-exports

Re-export UniformFloat

Attributes:

  • Other("#[doc(inline)]")
pub use float::UniformFloat;

Re-export UniformInt

Attributes:

  • Other("#[doc(inline)]")
pub use int::UniformInt;

Re-export UniformUsize

Attributes:

  • Other("#[doc(inline)]")
pub use int::UniformUsize;

Re-export UniformChar

Attributes:

  • Other("#[doc(inline)]")
pub use other::UniformChar;

Re-export UniformDuration

Attributes:

  • Other("#[doc(inline)]")
pub use other::UniformDuration;

Module weighted

Attributes:

  • Other("#[<cfg>(feature = \"alloc\")]")

Weighted (index) sampling

Primarily, this module houses the [WeightedIndex] distribution. See also rand_distr::weighted for alternative implementations supporting potentially-faster sampling or a more easily modifiable tree structure.

pub mod weighted { /* ... */ }

Types

Enum Error

Attributes:

  • NonExhaustive

Invalid weight errors

This type represents errors from [WeightedIndex::new], [WeightedIndex::update_weights] and other weighted distributions.

pub enum Error {
    InvalidInput,
    InvalidWeight,
    InsufficientNonZero,
    Overflow,
}
Variants
InvalidInput

The input weight sequence is empty, too long, or wrongly ordered

InvalidWeight

A weight is negative, too large for the distribution, or not a valid number

InsufficientNonZero

Not enough non-zero weights are available to sample values

When attempting to sample a single value this implies that all weights are zero. When attempting to sample amount values this implies that less than amount weights are greater than zero.

Overflow

Overflow when calculating the sum of weights

Implementations
Trait Implementations
  • Any

    • fn type_id(self: &Self) -> TypeId { /* ... */ }
      
  • Borrow

    • fn borrow(self: &Self) -> &T { /* ... */ }
      
  • BorrowMut

    • fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ }
      
  • Clone

    • fn clone(self: &Self) -> Error { /* ... */ }
      
  • CloneToUninit

    • unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ }
      
  • Copy

  • Debug

    • fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ }
      
  • Display

    • fn fmt(self: &Self, f: &mut fmt::Formatter<''_>) -> fmt::Result { /* ... */ }
      
  • Eq

  • Error

  • Freeze

  • From

    • fn from(t: T) -> T { /* ... */ }
      
      Returns the argument unchanged.
  • Into

    • fn into(self: Self) -> U { /* ... */ }
      
      Calls U::from(self).
  • PartialEq

    • fn eq(self: &Self, other: &Error) -> bool { /* ... */ }
      
  • RefUnwindSafe

  • Send

  • StructuralPartialEq

  • Sync

  • ToOwned

    • fn to_owned(self: &Self) -> T { /* ... */ }
      
    • fn clone_into(self: &Self, target: &mut T) { /* ... */ }
      
  • ToString

    • fn to_string(self: &Self) -> String { /* ... */ }
      
  • TryFrom

    • fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> { /* ... */ }
      
  • TryInto

    • fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error> { /* ... */ }
      
  • Unpin

  • UnwindSafe

  • VZip

    • fn vzip(self: Self) -> V { /* ... */ }
      

Traits

Trait Weight

Bounds on a weight

See usage in [WeightedIndex].

pub trait Weight: Clone {
    /* Associated items */
}

This trait is not object-safe and cannot be used in dynamic trait objects.

Required Items
Associated Constants
  • ZERO: Representation of 0
Required Methods
  • checked_add_assign: Checked addition
Implementations

This trait is implemented for the following types:

  • i8
  • i16
  • i32
  • i64
  • i128
  • isize
  • u8
  • u16
  • u32
  • u64
  • u128
  • usize
  • f32
  • f64

Re-exports

Re-export WeightedIndex

pub use weighted_index::WeightedIndex;

Types

Struct StandardUniform

Attributes:

  • Other("#[<cfg_attr>(feature = \"serde\", derive(serde::Serialize, serde::Deserialize))]")

The Standard Uniform distribution

This [Distribution] is the standard parameterization of Uniform. Bounds are selected according to the output type.

Assuming the provided Rng is well-behaved, these implementations generate values with the following ranges and distributions:

  • Integers (i8, i32, u64, etc.) are uniformly distributed over the whole range of the type (thus each possible value may be sampled with equal probability).
  • char is uniformly distributed over all Unicode scalar values, i.e. all code points in the range 0...0x10_FFFF, except for the range 0xD800...0xDFFF (the surrogate code points). This includes unassigned/reserved code points. For some uses, the [Alphanumeric] or [Alphabetic] distribution will be more appropriate.
  • bool samples false or true, each with probability 0.5.
  • Floating point types (f32 and f64) are uniformly distributed in the half-open range [0, 1). See also the notes below.
  • Wrapping integers (Wrapping<T>), besides the type identical to their normal integer variants.
  • Non-zero integers (NonZeroU8), which are like their normal integer variants but cannot sample zero.

The StandardUniform distribution also supports generation of the following compound types where all component types are supported:

  • Tuples (up to 12 elements): each element is sampled sequentially and independently (thus, assuming a well-behaved RNG, there is no correlation between elements).
  • Arrays [T; n] where T is supported. Each element is sampled sequentially and independently. Note that for small T this usually results in the RNG discarding random bits; see also [Rng::fill] which offers a more efficient approach to filling an array of integer types with random data.
  • SIMD types (requires simd_support feature) like x86's __m128i and std::simd's u32x4, f32x4 and mask32x4 types are effectively arrays of integer or floating-point types. Each lane is sampled independently, potentially with more efficient random-bit-usage (and a different resulting value) than would be achieved with sequential sampling (as with the array types above).

Custom implementations

The StandardUniform distribution may be implemented for user types as follows:

# #![allow(dead_code)]
use rand::Rng;
use rand::distr::{Distribution, StandardUniform};

struct MyF32 {
    x: f32,
}

impl Distribution<MyF32> for StandardUniform {
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> MyF32 {
        MyF32 { x: rng.random() }
    }
}

Example usage

use rand::prelude::*;
use rand::distr::StandardUniform;

let val: f32 = rand::rng().sample(StandardUniform);
println!("f32 from [0, 1): {}", val);

Floating point implementation

The floating point implementations for StandardUniform generate a random value in the half-open interval [0, 1), i.e. including 0 but not 1.

All values that can be generated are of the form n * ε/2. For f32 the 24 most significant random bits of a u32 are used and for f64 the 53 most significant bits of a u64 are used. The conversion uses the multiplicative method: (rng.gen::<$uty>() >> N) as $ty * (ε/2).

See also: [Open01] which samples from (0, 1), [OpenClosed01] which samples from (0, 1] and Rng::random_range(0..1) which also samples from [0, 1). Note that Open01 uses transmute-based methods which yield 1 bit less precision but may perform faster on some architectures (on modern Intel CPUs all methods have approximately equal performance).

pub struct StandardUniform;
Implementations
Trait Implementations
  • Any

    • fn type_id(self: &Self) -> TypeId { /* ... */ }
      
  • Borrow

    • fn borrow(self: &Self) -> &T { /* ... */ }
      
  • BorrowMut

    • fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ }
      
  • Clone

    • fn clone(self: &Self) -> StandardUniform { /* ... */ }
      
  • CloneToUninit

    • unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ }
      
  • Copy

  • Debug

    • fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ }
      
  • Default

    • fn default() -> StandardUniform { /* ... */ }
      
  • Deserialize

    • fn deserialize<__D>(__deserializer: __D) -> _serde::__private::Result<Self, <__D as >::Error>
      

where __D: _serde::Deserializer<''de> { /* ... */ } ```

  • DeserializeOwned

  • Distribution

    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> f32 { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> f64 { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> f32x2 { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> f32x4 { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> f32x8 { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> f32x16 { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> f64x2 { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> f64x4 { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> f64x8 { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> u8 { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> u16 { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> u32 { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> u64 { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> u128 { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> i8 { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> i16 { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> i32 { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> i64 { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> i128 { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> NonZeroU8 { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> NonZeroU16 { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> NonZeroU32 { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> NonZeroU64 { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> NonZeroU128 { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> NonZeroI8 { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> NonZeroI16 { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> NonZeroI32 { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> NonZeroI64 { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> NonZeroI128 { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> __m128i { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> __m256i { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> __m512i { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> Simd<u8, LANES> { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> Simd<i8, LANES> { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> Simd<u16, LANES> { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> Simd<i16, LANES> { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> Simd<u32, LANES> { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> Simd<i32, LANES> { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> Simd<u64, LANES> { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> Simd<i64, LANES> { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> char { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> bool { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> Mask<T, LANES> { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> (A) { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> (A, B) { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> (A, B, C) { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> (A, B, C, D) { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> (A, B, C, D, E) { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> (A, B, C, D, E, F) { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> (A, B, C, D, E, F, G) { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> (A, B, C, D, E, F, G, H) { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> (A, B, C, D, E, F, G, H, I) { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> (A, B, C, D, E, F, G, H, I, J) { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> (A, B, C, D, E, F, G, H, I, J, K) { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> (A, B, C, D, E, F, G, H, I, J, K, L) { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> [T; N] { /* ... */ }
      
    • fn sample<R: Rng + ?Sized>(self: &Self, rng: &mut R) -> Wrapping<T> { /* ... */ }
      
  • Freeze

  • From

    • fn from(t: T) -> T { /* ... */ }
      
      Returns the argument unchanged.
  • Into

    • fn into(self: Self) -> U { /* ... */ }
      
      Calls U::from(self).
  • RefUnwindSafe

  • SampleString

    • fn append_string<R: Rng + ?Sized>(self: &Self, rng: &mut R, s: &mut String, len: usize) { /* ... */ }
      
  • Send

  • Serialize

    • fn serialize<__S>(self: &Self, __serializer: __S) -> _serde::__private::Result<<__S as >::Ok, <__S as >::Error>
      

where __S: _serde::Serializer { /* ... */ } ```

  • Sync

  • ToOwned

    • fn to_owned(self: &Self) -> T { /* ... */ }
      
    • fn clone_into(self: &Self, target: &mut T) { /* ... */ }
      
  • TryFrom

    • fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> { /* ... */ }
      
  • TryInto

    • fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error> { /* ... */ }
      
  • Unpin

  • UnwindSafe

  • VZip

    • fn vzip(self: Self) -> V { /* ... */ }
      

Re-exports

Re-export Bernoulli

pub use self::bernoulli::Bernoulli;

Re-export BernoulliError

pub use self::bernoulli::BernoulliError;

Re-export SampleString

Attributes:

  • Other("#[<cfg>(feature = \"alloc\")]")
pub use self::distribution::SampleString;

Re-export Distribution

pub use self::distribution::Distribution;

Re-export Iter

pub use self::distribution::Iter;

Re-export Map

pub use self::distribution::Map;

Re-export Open01

pub use self::float::Open01;

Re-export OpenClosed01

pub use self::float::OpenClosed01;

Re-export Alphabetic

pub use self::other::Alphabetic;

Re-export Alphanumeric

pub use self::other::Alphanumeric;

Re-export Uniform

Attributes:

  • Other("#[doc(inline)]")
pub use self::uniform::Uniform;

Module prelude

Convenience re-export of common members

Like the standard library's prelude, this module simplifies importing of common items. Unlike the standard prelude, the contents of this module must be imported manually:

use rand::prelude::*;
# let mut r = StdRng::from_rng(&mut rand::rng());
# let _: f32 = r.random();
pub mod prelude { /* ... */ }

Re-exports

Re-export Distribution

Attributes:

  • Other("#[doc(no_inline)]")
pub use crate::distr::Distribution;

Re-export SmallRng

Attributes:

  • Other("#[<cfg>(feature = \"small_rng\")]")
  • Other("#[doc(no_inline)]")
pub use crate::rngs::SmallRng;

Re-export StdRng

Attributes:

  • Other("#[<cfg>(feature = \"std_rng\")]")
  • Other("#[doc(no_inline)]")
pub use crate::rngs::StdRng;

Re-export ThreadRng

Attributes:

  • Other("#[doc(no_inline)]")
  • Other("#[<cfg>(feature = \"thread_rng\")]")
pub use crate::rngs::ThreadRng;

Re-export IndexedMutRandom

Attributes:

  • Other("#[doc(no_inline)]")
pub use crate::seq::IndexedMutRandom;

Re-export IndexedRandom

Attributes:

  • Other("#[doc(no_inline)]")
pub use crate::seq::IndexedRandom;

Re-export IteratorRandom

Attributes:

  • Other("#[doc(no_inline)]")
pub use crate::seq::IteratorRandom;

Re-export SliceRandom

Attributes:

  • Other("#[doc(no_inline)]")
pub use crate::seq::SliceRandom;

Re-export CryptoRng

Attributes:

  • Other("#[doc(no_inline)]")
pub use crate::CryptoRng;

Re-export Rng

Attributes:

  • Other("#[doc(no_inline)]")
pub use crate::Rng;

Re-export RngCore

Attributes:

  • Other("#[doc(no_inline)]")
pub use crate::RngCore;

Re-export SeedableRng

Attributes:

  • Other("#[doc(no_inline)]")
pub use crate::SeedableRng;

Module rngs

Random number generators and adapters

This crate provides a small selection of non-portable generators. See also Types of generators and Our RNGs in the book.

Generators

This crate provides a small selection of non-portable random number generators:

  • [OsRng] is a stateless interface over the operating system's random number source. This is typically secure with some form of periodic re-seeding.
  • ThreadRng, provided by [crate::rng()], is a handle to a thread-local generator with periodic seeding from [OsRng]. Because this is local, it is typically much faster than [OsRng]. It should be secure, but see documentation on ThreadRng.
  • [StdRng] is a CSPRNG chosen for good performance and trust of security (based on reviews, maturity and usage). The current algorithm is ChaCha12, which is well established and rigorously analysed. [StdRng] is the deterministic generator used by ThreadRng but without the periodic reseeding or thread-local management.
  • [SmallRng] is a relatively simple, insecure generator designed to be fast, use little memory, and pass various statistical tests of randomness quality.

The algorithms selected for [StdRng] and [SmallRng] may change in any release and may be platform-dependent, therefore they are not reproducible.

Additional generators

  • The rdrand crate provides an interface to the RDRAND and RDSEED instructions available in modern Intel and AMD CPUs.
  • The rand_jitter crate provides a user-space implementation of entropy harvesting from CPU timer jitter, but is very slow and has security issues.
  • The rand_chacha crate provides portable implementations of generators derived from the ChaCha family of stream ciphers
  • The rand_pcg crate provides portable implementations of a subset of the PCG family of small, insecure generators
  • The rand_xoshiro crate provides portable implementations of the xoshiro family of small, insecure generators

For more, search crates with the rng tag.

Traits and functionality

All generators implement RngCore and thus also [Rng][crate::Rng]. See also the Random Values chapter in the book.

Secure RNGs may additionally implement the CryptoRng trait.

Use the [rand_core] crate when implementing your own RNGs.

pub mod rngs { /* ... */ }

Modules

Module mock

Attributes:

  • Other("#[allow(deprecated)]")

⚠️ Deprecated since 0.9.2

Mock random number generator

pub mod mock { /* ... */ }

Types

Struct StepRng

Attributes:

  • Other("#[<cfg_attr>(feature = \"serde\", derive(Serialize, Deserialize))]")

⚠️ Deprecated since 0.9.2: Deprecated without replacement

A mock generator yielding very predictable output

This generates an arithmetic sequence (i.e. adds a constant each step) over a u64 number, using wrapping arithmetic. If the increment is 0 the generator yields a constant.

Other integer types (64-bit and smaller) are produced via cast from u64.

Other types are produced via their implementation of Rng or Distribution. Output values may not be intuitive and may change in future releases but are considered portable. (bool output is true when bit 1u64 << 31 is set.)

Example

# #![allow(deprecated)]
use rand::Rng;
use rand::rngs::mock::StepRng;

let mut my_rng = StepRng::new(2, 1);
let sample: [u64; 3] = my_rng.random();
assert_eq!(sample, [2, 3, 4]);
pub struct StepRng {
    // Some fields omitted
}
Fields
Name Type Documentation
private fields ... Some fields have been omitted
Implementations
Methods
  • pub fn new(initial: u64, increment: u64) -> Self { /* ... */ }
    
    Create a StepRng, yielding an arithmetic sequence starting with
Trait Implementations
  • Any

    • fn type_id(self: &Self) -> TypeId { /* ... */ }
      
  • Borrow

    • fn borrow(self: &Self) -> &T { /* ... */ }
      
  • BorrowMut

    • fn borrow_mut(self: &mut Self) -> &mut T { /* ... */ }
      
  • Clone

    • fn clone(self: &Self) -> StepRng { /* ... */ }
      
  • CloneToUninit

    • unsafe fn clone_to_uninit(self: &Self, dest: *mut u8) { /* ... */ }
      
  • Debug

    • fn fmt(self: &Self, f: &mut $crate::fmt::Formatter<''_>) -> $crate::fmt::Result { /* ... */ }
      
  • Deserialize

    • fn deserialize<__D>(__deserializer: __D) -> _serde::__private::Result<Self, <__D as >::Error>
      

where __D: _serde::Deserializer<''de> { /* ... */ } ```

  • DeserializeOwned

  • Eq

  • Freeze

  • From

    • fn from(t: T) -> T { /* ... */ }
      
      Returns the argument unchanged.
  • Into

    • fn into(self: Self) -> U { /* ... */ }
      
      Calls U::from(self).
  • PartialEq

    • fn eq(self: &Self, other: &StepRng) -> bool { /* ... */ }
      
  • RefUnwindSafe

  • Rng

  • RngCore

    • fn next_u32(self: &mut Self) -> u32 { /* ... */ }
      
    • fn next_u64(self: &mut Self) -> u64 { /* ... */ }
      
    • fn fill_bytes(self: &mut Self, dst: &mut [u8]) { /* ... */ }
      
  • Send

  • Serialize

    • fn serialize<__S>(self: &Self, __serializer: __S) -> _serde::__private::Result<<__S as >::Ok, <__S as >::Error>
      

where __S: _serde::Serializer { /* ... */ } ```

  • StructuralPartialEq

  • Sync

  • ToOwned

    • fn to_owned(self: &Self) -> T { /* ... */ }
      
    • fn clone_into(self: &Self, target: &mut T) { /* ... */ }
      
  • TryFrom

    • fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error> { /* ... */ }
      
  • TryInto

    • fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error> { /* ... */ }
      
  • TryRngCore

    • fn try_next_u32(self: &mut Self) -> Result<u32, <R as TryRngCore>::Error> { /* ... */ }
      
    • fn try_next_u64(self: &mut Self) -> Result<u64, <R as TryRngCore>::Error> { /* ... */ }
      
    • fn try_fill_bytes(self: &mut Self, dst: &mut [u8]) -> Result<(), <R as TryRngCore>::Error> { /* ... */ }
      
  • Unpin

  • UnwindSafe

  • VZip

    • fn vzip(self: Self) -> V { /* ... */ }
      

Re-exports

Re-export ReseedingRng

pub use reseeding::ReseedingRng;

Re-export SmallRng

Attributes:

  • Other("#[<cfg>(feature = \"small_rng\")]")
pub use self::small::SmallRng;

Re-export StdRng

Attributes:

  • Other("#[<cfg>(feature = \"std_rng\")]")
pub use self::std::StdRng;

Re-export ThreadRng

Attributes:

  • Other("#[<cfg>(feature = \"thread_rng\")]")
pub use self::thread::ThreadRng;

Re-export OsRng

Attributes:

  • Other("#[<cfg>(feature = \"os_rng\")]")
pub use rand_core::OsRng;

Module seq

Sequence-related functionality

This module provides:

  • [IndexedRandom] for sampling slices and other indexable lists
  • [IndexedMutRandom] for sampling slices and other mutably indexable lists
  • [SliceRandom] for mutating slices
  • [IteratorRandom] for sampling iterators
  • [index::sample] low-level API to choose multiple indices from 0..length

Also see:

  • [crate::distr::weighted::WeightedIndex] distribution which provides weighted index sampling.

In order to make results reproducible across 32-64 bit architectures, all usize indices are sampled as a u32 where possible (also providing a small performance boost in some cases).

pub mod seq { /* ... */ }

Modules

Module index

Low-level API for sampling indices

pub mod index { /* ... */ }

Functions

Function sample_array

Randomly sample exactly N distinct indices from 0..len, and return them in random order (fully shuffled).

This is implemented via Floyd's algorithm. Time complexity is O(N^2) and memory complexity is O(N).

Returns None if (and only if) N > len.

pub fn sample_array<R, const N: usize>(rng: &mut R, len: usize) -> Option<[usize; N]>
where
    R: Rng + ?Sized { /* ... */ }

Re-exports

Re-export super::index_::*

Attributes:

  • Other("#[<cfg>(feature = \"alloc\")]")
  • Other("#[doc(inline)]")
pub use super::index_::*;

Re-exports

Re-export Error

Attributes:

  • Other("#[<cfg>(feature = \"alloc\")]")
  • Other("#[doc(no_inline)]")
pub use crate::distr::weighted::Error as WeightError;

Re-export IteratorRandom

pub use iterator::IteratorRandom;

Re-export SliceChooseIter

Attributes:

  • Other("#[<cfg>(feature = \"alloc\")]")
pub use slice::SliceChooseIter;

Re-export IndexedMutRandom

pub use slice::IndexedMutRandom;

Re-export IndexedRandom

pub use slice::IndexedRandom;

Re-export SliceRandom

pub use slice::SliceRandom;

Functions

Function thread_rng

Attributes:

  • Other("#[<cfg>(feature = \"thread_rng\")]")
  • Other("#[attr = Inline(Hint)]")

⚠️ Deprecated since 0.9.0: Renamed to rng

Access the thread-local generator

Use rand::rng() instead.

pub fn thread_rng() -> crate::rngs::ThreadRng { /* ... */ }

Function random

Attributes:

  • Other("#[<cfg>(feature = \"thread_rng\")]")
  • Other("#[attr = Inline(Hint)]")

Generate a random value using the thread-local random number generator.

This function is shorthand for [rng()].random():

  • See ThreadRng for documentation of the generator and security
  • See StandardUniform for documentation of supported types and distributions

Examples

let x = rand::random::<u8>();
println!("{}", x);

let y = rand::random::<f64>();
println!("{}", y);

if rand::random() { // generates a boolean
    println!("Better lucky than good!");
}

If you're calling random() repeatedly, consider using a local rng handle to save an initialization-check on each usage:

use rand::Rng; // provides the `random` method

let mut rng = rand::rng(); // a local handle to the generator

let mut v = vec![1, 2, 3];

for x in v.iter_mut() {
    *x = rng.random();
}
pub fn random<T>() -> T
where
    crate::distr::StandardUniform: Distribution<T> { /* ... */ }

Function random_iter

Attributes:

  • Other("#[<cfg>(feature = \"thread_rng\")]")
  • Other("#[attr = Inline(Hint)]")

Return an iterator over [random()] variates

This function is shorthand for [rng()].random_iter().

Example

let v: Vec<i32> = rand::random_iter().take(5).collect();
println!("{v:?}");
pub fn random_iter<T>() -> distr::Iter<crate::distr::StandardUniform, rngs::ThreadRng, T>
where
    crate::distr::StandardUniform: Distribution<T> { /* ... */ }

Function random_range

Attributes:

  • Other("#[<cfg>(feature = \"thread_rng\")]")
  • Other("#[attr = Inline(Hint)]")

Generate a random value in the given range using the thread-local random number generator.

This function is shorthand for [rng()].random_range(range).

Example

let y: f32 = rand::random_range(0.0..=1e9);
println!("{}", y);

let words: Vec<&str> = "Mary had a little lamb".split(' ').collect();
println!("{}", words[rand::random_range(..words.len())]);

Note that the first example can also be achieved (without collect'ing to a Vec) using [seq::IteratorRandom::choose].

pub fn random_range<T, R>(range: R) -> T
where
    T: distr::uniform::SampleUniform,
    R: distr::uniform::SampleRange<T> { /* ... */ }

Function random_bool

Attributes:

  • Other("#[<cfg>(feature = \"thread_rng\")]")
  • Other("#[attr = Inline(Hint)]")
  • Other("#[attr = TrackCaller]")

Return a bool with a probability p of being true.

This function is shorthand for [rng()].random_bool(p).

Example

println!("{}", rand::random_bool(1.0 / 3.0));

Panics

If p < 0 or p > 1.

pub fn random_bool(p: f64) -> bool { /* ... */ }

Function random_ratio

Attributes:

  • Other("#[<cfg>(feature = \"thread_rng\")]")
  • Other("#[attr = Inline(Hint)]")
  • Other("#[attr = TrackCaller]")

Return a bool with a probability of numerator/denominator of being true.

That is, random_ratio(2, 3) has chance of 2 in 3, or about 67%, of returning true. If numerator == denominator, then the returned value is guaranteed to be true. If numerator == 0, then the returned value is guaranteed to be false.

See also the Bernoulli distribution, which may be faster if sampling from the same numerator and denominator repeatedly.

This function is shorthand for [rng()].random_ratio(numerator, denominator).

Panics

If denominator == 0 or numerator > denominator.

Example

println!("{}", rand::random_ratio(2, 3));
pub fn random_ratio(numerator: u32, denominator: u32) -> bool { /* ... */ }

Function fill

Attributes:

  • Other("#[<cfg>(feature = \"thread_rng\")]")
  • Other("#[attr = Inline(Hint)]")
  • Other("#[attr = TrackCaller]")

Fill any type implementing [Fill] with random data

This function is shorthand for [rng()].fill(dest).

Example

let mut arr = [0i8; 20];
rand::fill(&mut arr[..]);

Note that you can instead use [random()] to generate an array of random data, though this is slower for small elements (smaller than the RNG word size).

pub fn fill<T: Fill + ?Sized>(dest: &mut T) { /* ... */ }

Re-exports

Re-export rand_core

pub use rand_core;

Re-export CryptoRng

pub use rand_core::CryptoRng;

Re-export RngCore

pub use rand_core::RngCore;

Re-export SeedableRng

pub use rand_core::SeedableRng;

Re-export TryCryptoRng

pub use rand_core::TryCryptoRng;

Re-export TryRngCore

pub use rand_core::TryRngCore;

Re-export rng

Attributes:

  • Other("#[<cfg>(feature = \"thread_rng\")]")
pub use crate::rngs::thread::rng;

Re-export Fill

pub use rng::Fill;

Re-export Rng

pub use rng::Rng;