Skip to main content

ThreadRng

Struct ThreadRng 

pub struct ThreadRng { /* private fields */ }
Expand description

A reference to the thread-local generator

This type is a reference to a lazily-initialized thread-local generator. An instance can be obtained via [rand::rng()][crate::rng()] or via ThreadRng::default(). The handle cannot be passed between threads (is not Send or Sync).

§Security

Security must be considered relative to a threat model and validation requirements. The Rand project can provide no guarantee of fitness for purpose. The design criteria for ThreadRng are as follows:

  • Automatic seeding via [SysRng] and after every 64 kB of output. Limitation: there is no automatic reseeding on process fork (see below).
  • A rigorusly analyzed, unpredictable (cryptographic) pseudo-random generator (see the book on security). The currently selected algorithm is ChaCha (12-rounds). See also StdRng documentation.
  • Not to leak internal state through Debug or serialization implementations.
  • No further protections exist to in-memory state. In particular, the implementation is not required to zero memory on exit (of the process or thread). (This may change in the future.)
  • Be fast enough for general-purpose usage. Note in particular that ThreadRng is designed to be a “fast, reasonably secure generator” (where “reasonably secure” implies the above criteria).

We leave it to the user to determine whether this generator meets their security requirements. For an alternative, see [SysRng].

§Fork

ThreadRng is not automatically reseeded on fork. It is recommended to explicitly call ThreadRng::reseed immediately after a fork, for example:

fn do_fork() {
    let pid = unsafe { libc::fork() };
    if pid == 0 {
        // Reseed ThreadRng in child processes:
        rand::rng().reseed();
    }
}

Methods on ThreadRng are not reentrant-safe and thus should not be called from an interrupt (e.g. a fork handler) unless it can be guaranteed that no other method on the same ThreadRng is currently executing.

Implementations§

§

impl ThreadRng

pub fn reseed(&mut self) -> Result<(), Error>

Immediately reseed the generator

This discards any remaining random data in the cache.

Trait Implementations§

§

impl Clone for ThreadRng

§

fn clone(&self) -> ThreadRng

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
§

impl Debug for ThreadRng

Debug implementation does not leak internal state

§

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

Formats the value using the given formatter. Read more
§

impl Default for ThreadRng

§

fn default() -> ThreadRng

Returns the “default value” for a type. Read more
§

impl TryRng for ThreadRng

§

type Error = Infallible

The type returned in the event of a RNG error. Read more
§

fn try_next_u32(&mut self) -> Result<u32, Infallible>

Return the next random u32.
§

fn try_next_u64(&mut self) -> Result<u64, Infallible>

Return the next random u64.
§

fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Infallible>

Fill dst entirely with random data.
§

impl TryCryptoRng for ThreadRng

Auto Trait Implementations§

Blanket Implementations§

§

impl<R> TryRngCore for R
where R: TryRng,

§

type Error = <R as TryRng>::Error

👎Deprecated since 0.10.0: use TryRng instead
Error type.
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.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

impl<R> Rng for R
where R: TryRng<Error = Infallible> + ?Sized,

§

fn next_u32(&mut self) -> u32

Return the next random u32.
§

fn next_u64(&mut self) -> u64

Return the next random u64.
§

fn fill_bytes(&mut self, dst: &mut [u8])

Fill dest with random data. Read more
§

impl<R> RngExt for R
where R: Rng + ?Sized,

§

fn random<T>(&mut self) -> T
where StandardUniform: Distribution<T>,

Return a random value via the StandardUniform distribution. Read more
§

fn random_iter<T>(self) -> Iter<StandardUniform, Self, T>
where Self: Sized, StandardUniform: Distribution<T>,

Return an iterator over random variates Read more
§

fn random_range<T, R>(&mut self, range: R) -> T
where T: SampleUniform, R: SampleRange<T>,

Generate a random value in the given range. Read more
§

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

Return a bool with a probability p of being true. Read more
§

fn random_ratio(&mut self, numerator: u32, denominator: u32) -> bool

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

fn sample<T, D>(&mut self, distr: D) -> T
where D: Distribution<T>,

Sample a new value, using the given distribution. Read more
§

fn sample_iter<T, D>(self, distr: D) -> Iter<D, Self, T>
where D: Distribution<T>, Self: Sized,

Create an iterator that generates values using the given distribution. Read more
§

fn fill<T>(&mut self, dest: &mut [T])
where T: Fill,

Fill any type implementing [Fill] with random data Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
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.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

impl<R> CryptoRng for R
where R: TryCryptoRng<Error = Infallible> + ?Sized,

§

impl<R> RngCore for R
where R: Rng,