pub struct ReseedingRng<R, Rsdr> { /* private fields */ }Expand description
A wrapper that periodically reseeds the underlying pseudorandom number generator.
This type reseeds the underlying generator every time a specified number of random bytes have
been produced. If the periodic reseeding attempt fails, ReseedingRng silently skips it and
retries after the next threshold is reached.
Unlike rand v0.9’s equivalent, this variant is built on top of TryRng instead of the
block Generator, allowing a wider choice of underlying generators, including StdRng.
§Examples
ReseedingRng is useful to replicate the reseeding behavior of ThreadRng. As of rand
v0.10.1, ThreadRng uses the same algorithm as StdRng and reseeds it via SysRng every
64KiB of output. You can emulate this behavior by configuring ReseedingRng as follows:
use rand::{RngExt as _, rngs::StdRng, rngs::SysRng};
use reseeding_rng::ReseedingRng;
let mut rng = ReseedingRng::<StdRng, _>::try_new(1024 * 64, SysRng)
.expect("couldn't initialize ReseedingRng due to SysRng failure");
println!("{:?}", rng.random::<[char; 4]>());See also [StdReseedingRng] for a convenient newtype with this configuration.
§Fork safety
The underlying generator is not automatically reseeded on process fork (contrast with
ReseedingRng from rand v0.8 and earlier). Some applications need reseeding on fork to avoid
the parent and child processes generating the same sequence of random numbers. The example
below shows a wrapper that handles this using the forkguard crate.
use rand::{Rng as _, rngs::StdRng, rngs::SysRng};
struct ForkSafeReseedingRng {
inner: reseeding_rng::ReseedingRng<StdRng, SysRng>,
guard: forkguard::Guard,
}
impl ForkSafeReseedingRng {
fn next_u32(&mut self) -> u32 {
if self.guard.detected_fork() {
// reseed ReseedingRng in child process
let _ = self.inner.try_reseed();
}
self.inner.next_u32()
}
}Implementations§
Source§impl<R, Rsdr> ReseedingRng<R, Rsdr>where
R: SeedableRng,
Rsdr: TryRng,
impl<R, Rsdr> ReseedingRng<R, Rsdr>where
R: SeedableRng,
Rsdr: TryRng,
Trait Implementations§
Source§impl<R, Rsdr> Clone for ReseedingRng<R, Rsdr>
This implementation reseeds the underlying generator upon clone().
impl<R, Rsdr> Clone for ReseedingRng<R, Rsdr>
This implementation reseeds the underlying generator upon clone().