Trait rand::FromEntropy
source · [−]pub trait FromEntropy: SeedableRng {
fn from_entropy() -> Self;
}
Expand description
A convenience extension to SeedableRng
allowing construction from fresh
entropy. This trait is automatically implemented for any PRNG implementing
SeedableRng
and is not intended to be implemented by users.
This is equivalent to using SeedableRng::from_rng(EntropyRng::new())
then
unwrapping the result.
Since this is convenient and secure, it is the recommended way to create PRNGs, though two alternatives may be considered:
- Deterministic creation using
SeedableRng::from_seed
with a fixed seed - Seeding from
thread_rng
:SeedableRng::from_rng(thread_rng())?
; this will usually be faster and should also be secure, but requires trusting one extra component.
Example
use rand::{Rng, FromEntropy};
use rand::rngs::StdRng;
let mut rng = StdRng::from_entropy();
println!("Random die roll: {}", rng.gen_range(1, 7));
Required methods
fn from_entropy() -> Self
fn from_entropy() -> Self
Creates a new instance, automatically seeded with fresh entropy.
Normally this will use OsRng
, but if that fails JitterRng
will be
used instead. Both should be suitable for cryptography. It is possible
that both entropy sources will fail though unlikely; failures would
almost certainly be platform limitations or build issues, i.e. most
applications targetting PC/mobile platforms should not need to worry
about this failing.
Panics
If all entropy sources fail this will panic. If you need to handle errors, use the following code, equivalent aside from error handling:
use rand::prelude::*;
use rand::rngs::EntropyRng;
// This uses StdRng, but is valid for any R: SeedableRng
let mut rng = StdRng::from_rng(EntropyRng::new())?;
println!("random number: {}", rng.gen_range(1, 10));