Trait SeedableRng
trait SeedableRng: Sized
A random number generator that can be explicitly seeded.
This trait encapsulates the low-level functionality common to all pseudo-random number generators (PRNGs, or algorithmic generators).
Associated Types
type Seed: TraitBound { trait_: Path { path: "Clone", id: Id(58), args: None }, generic_params: [], modifier: None } + TraitBound { trait_: Path { path: "Default", id: Id(5), args: None }, generic_params: [], modifier: None } + TraitBound { trait_: Path { path: "AsRef", id: Id(2), args: Some(AngleBracketed { args: [Type(Slice(Primitive("u8")))], constraints: [] }) }, generic_params: [], modifier: None } + TraitBound { trait_: Path { path: "AsMut", id: Id(4), args: Some(AngleBracketed { args: [Type(Slice(Primitive("u8")))], constraints: [] }) }, generic_params: [], modifier: None }Seed type, which is restricted to types mutably-dereferenceable as
u8arrays (we recommend[u8; N]for someN).It is recommended to seed PRNGs with a seed of at least circa 100 bits, which means an array of
[u8; 12]or greater to avoid picking RNGs with partially overlapping periods.For cryptographic RNG's a seed of 256 bits is recommended,
[u8; 32].Implementing
SeedableRngfor RNGs with large seedsNote that
Defaultis not implemented for large arrays[u8; N]withN> 32. To be able to implement the traits required bySeedableRngfor RNGs with such large seeds, the newtype pattern can be used:use SeedableRng; const N: usize = 64; ; # ;
Required Methods
fn from_seed(seed: <Self as >::Seed) -> SelfCreate a new PRNG using the given seed.
PRNG implementations are allowed to assume that bits in the seed are well distributed. That means usually that the number of one and zero bits are roughly equal, and values like 0, 1 and (size - 1) are unlikely. Note that many non-cryptographic PRNGs will show poor quality output if this is not adhered to. If you wish to seed from simple numbers, use
seed_from_u64instead.All PRNG implementations should be reproducible unless otherwise noted: given a fixed
seed, the same sequence of output should be produced on all runs, library versions and architectures (e.g. check endianness). Any "value-breaking" changes to the generator should require bumping at least the minor version and documentation of the change.It is not required that this function yield the same state as a reference implementation of the PRNG given equivalent seed; if necessary another constructor replicating behaviour from a reference implementation can be added.
PRNG implementations should make sure
from_seednever panics. In the case that some special values (like an all zero seed) are not viable seeds it is preferable to map these to alternative constant value(s), for example0xBAD5EEDu32or0x0DDB1A5E5BAD5EEDu64("odd biases? bad seed"). This is assuming only a small number of values must be rejected.
Provided Methods
fn seed_from_u64(state: u64) -> SelfCreate a new PRNG using a
u64seed.This is a convenience-wrapper around
from_seedto allow construction of anySeedableRngfrom a simpleu64value. It is designed such that low Hamming Weight numbers like 0 and 1 can be used and should still result in good, independent seeds to the PRNG which is returned.This is not suitable for cryptography, as should be clear given that the input size is only 64 bits.
Implementations for PRNGs may provide their own implementations of this function, but the default implementation should be good enough for all purposes. Changing the implementation of this function should be considered a value-breaking change.
fn from_rng<impl RngCore: RngCore>(rng: &mut impl RngCore) -> SelfCreate a new PRNG seeded from an infallible
Rng.This may be useful when needing to rapidly seed many PRNGs from a master PRNG, and to allow forking of PRNGs. It may be considered deterministic.
The master PRNG should be at least as high quality as the child PRNGs. When seeding non-cryptographic child PRNGs, we recommend using a different algorithm for the master PRNG (ideally a CSPRNG) to avoid correlations between the child PRNGs. If this is not possible (e.g. forking using small non-crypto PRNGs) ensure that your PRNG has a good mixing function on the output or consider use of a hash function with
from_seed.Note that seeding
XorShiftRngfrom anotherXorShiftRngprovides an extreme example of what can go wrong: the new PRNG will be a clone of the parent.PRNG implementations are allowed to assume that a good RNG is provided for seeding, and that it is cryptographically secure when appropriate. As of
rand0.7 /rand_core0.5, implementations overriding this method should ensure the implementation satisfies reproducibility (in prior versions this was not required).fn try_from_rng<R: TryRngCore>(rng: &mut R) -> Result<Self, <R as >::Error>Create a new PRNG seeded from a potentially fallible
Rng.See [
from_rng][SeedableRng::from_rng] docs for more information.fn from_os_rng() -> SelfCreates a new instance of the RNG seeded via
getrandom.This method is the recommended way to construct non-deterministic PRNGs since it is convenient and secure.
Note that this method may panic on (extremely unlikely)
getrandomerrors. If it's not desirable, use thetry_from_os_rngmethod instead.In case the overhead of using
getrandomto seed many PRNGs is an issue, one may prefer to seed from a local PRNG, e.g.from_rng(rand::rng()).unwrap().Panics
If
getrandomis unable to provide secure entropy this method will panic.fn try_from_os_rng() -> Result<Self, Error>Creates a new instance of the RNG seeded via
getrandomwithout unwrapping potentialgetrandomerrors.In case the overhead of using
getrandomto seed many PRNGs is an issue, one may prefer to seed from a local PRNG, e.g.from_rng(&mut rand::rng()).unwrap().
Implementors
impl<R: BlockRngCore + SeedableRng> SeedableRng for BlockRng<R>impl<R: BlockRngCore + SeedableRng> SeedableRng for BlockRng64<R>