Struct ThreadRng

pub struct ThreadRng { /* private fields */ }

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:

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

Forks and interrupts

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.

Panics

Implementations of TryRng and Rng panic in case of SysRng failure during reseeding (highly unlikely).

Implementations

impl ThreadRng

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

Immediately reseed the generator

This discards any remaining random data in the cache.

Trait Implementations

impl Clone for ThreadRng

fn clone(&self) -> Self

impl Debug for ThreadRng

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

impl Default for ThreadRng

fn default() -> ThreadRng

impl TryCryptoRng for ThreadRng

impl TryRng for ThreadRng

type Error = never;
fn try_next_u32(&mut self) -> Result<u32, Infallible>
fn try_next_u64(&mut self) -> Result<u64, Infallible>
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Infallible>

Auto Trait Implementations

impl !RefUnwindSafe for ThreadRng

impl !Send for ThreadRng

impl !Sync for ThreadRng

impl !UnwindSafe for ThreadRng

impl Freeze for ThreadRng

impl Unpin for ThreadRng

impl UnsafeUnpin for ThreadRng

Blanket Implementations

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

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

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

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

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

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

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

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

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

impl<T> From<T> for ThreadRng

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

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

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

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