Crate rand [−] [src]
Utilities for random number generation
Example
// Rng is the main trait and needs to be imported: use rand::{Rng, thread_rng}; // thread_rng is often the most convenient source of randomness: let mut rng = rand::thread_rng(); if rng.gen() { // random bool let x: f64 = rng.gen(); // random number in range (0, 1) println!("x is: {}", x); println!("Number from 0 to 9: {}", rng.gen_range(0, 10)); }
The key function is Rng::gen()
. It is polymorphic and so can be used to
generate many types; the Uniform
distribution carries the
implementations. In some cases type annotation is required, e.g.
rng.gen::<f64>()
.
Getting random values
The most convenient source of randomness is likely thread_rng
, which
automatically initialises a fast algorithmic generator on first use per
thread with thread-local storage.
If one wants to obtain random data directly from an external source it is
recommended to use EntropyRng
which manages multiple available sources
or OsRng
which retrieves random data directly from the OS. It should be
noted that this is significantly slower than using a local generator like
thread_rng
and potentially much slower if EntropyRng
must fall back to
JitterRng
as a source.
It is also common to use an algorithmic generator in local memory; this may
be faster than thread_rng
and provides more control. In this case
StdRng
— the generator behind thread_rng
— and SmallRng
— a
small, fast, weak generator — are good choices; more options can be found in
the prng
module as well as in other crates.
Local generators need to be seeded. It is recommended to use NewRng
or
to seed from a strong parent generator with from_rng
:
// seed with fresh entropy: use rand::{StdRng, NewRng}; let mut rng = StdRng::new(); // seed from thread_rng: use rand::{SmallRng, SeedableRng, thread_rng}; let mut rng = SmallRng::from_rng(thread_rng());
In case you specifically want to have a reproducible stream of "random"
data (e.g. to procedurally generate a game world), select a named algorithm
(i.e. not StdRng
/SmallRng
which may be adjusted in the future), and
use SeedableRng::from_seed
or a constructor specific to the generator
(e.g. IsaacRng::new_from_u64
).
Applying / converting random data
The RngCore
trait allows generators to implement a common interface for
retrieving random data, but how should you use this? Typically users should
use the Rng
trait not RngCore
; this provides more flexible ways to
access the same data (e.g. gen()
can output many more types than
next_u32()
and next_u64()
; Rust's optimiser should eliminate any
overhead). It also provides several useful algorithms,
e.g. gen_bool(p)
to generate events with weighted probability and
shuffle(&mut v[..])
to randomly-order a vector.
The distributions
module provides several more ways to convert random
data to useful values, e.g. time of decay is often modelled with an
exponential distribution, and the log-normal distribution provides a good
model of many natural phenomona.
The seq
module has a few tools applicable to sliceable or iterable data.
Cryptographic security
Security analysis requires a threat model and expert review; we can provide
neither, but can provide some guidance. We assume that the goal is to
obtain secret random data and that some source of secrets ("entropy") is
available; that is, EntropyRng
is functional.
Potential threat: is the entropy source secure? The primary entropy source
is OsRng
which is simply a wrapper around the platform's native "secure
entropy source"; usually this is available (outside of embedded platforms)
and usually you can trust this (some caveats may apply; see OsRng
doc).
The fallback source used by EntropyRng
is JitterRng
which runs extensive
tests on the quality of the CPU timer and is conservative in its estimates
of the entropy harvested from each time sample; this makes it slow but very
strong. Using EntropyRng
directly should therefore be secure; the main
reason not to is performance, which is why many applications use local
algorithmic generators.
Potential threat: are algorithmic generators predictable? Certainly some
are; algorithmic generators fall broadly into two categories: those using a
small amount of state (e.g. one to four 32- or 64-bit words) designed for
non-security applications and those designed to be secure, typically with
much larger state space and complex initialisation. The former should not be
trusted to be secure, the latter may or may not have known weaknesses or
may even have been proven secure under a specified adversarial model. We
provide some notes on the security of the cryptographic algorithmic
generators provided by this crate, Hc128Rng
and ChaChaRng
. Note that
previously IsaacRng
and Isaac64Rng
were used as "reasonably strong
generators"; these have no known weaknesses but also have no proofs of
security, thus are not recommended for cryptographic uses.
Potential threat: could the internal state of a cryptographic generator be
leaked? This falls under the topic of "side channel attacks", and multiple
variants are possible: the state of the generators being accidentally
printed in log files or some other application output, the process's memory
being copied somehow, the process being forked and both sub-processes
outputting the same random sequence but such that one of those can be read;
likely some other side-channel attacks are possible in some circumstances.
It is typically impossible to prove immunity to all side-channel attacks,
however some mitigation of known threats is usually possible, for example
all generators implemented in this crate have a custom Debug
implementation omitting all internal state, and ReseedingRng
allows
periodic reseeding such that a long-running process with leaked generator
state should eventually recover to an unknown state. In the future we plan
to add further mitigations; see issue #314.
We provide the CryptoRng
marker trait as an indication of which random
generators/sources may be used for cryptographic applications; this should
be considered advisory only does not imply any protection against
side-channel attacks.
Examples
For some inspiration, see the examples:
Re-exports
pub use jitter::JitterRng; |
pub use os::OsRng; |
pub use chacha::ChaChaRng; |
pub use prng::Hc128Rng; |
Modules
chacha |
The ChaCha random number generator. |
distributions |
Sampling from random distributions. |
isaac |
The ISAAC random number generator. |
jitter |
Non-physical true random number generator based on timing jitter. |
mock |
Mock random number generator |
os |
Interfaces to the operating system provided random number generators. |
prng |
Pseudo random number generators are algorithms to produce apparently random numbers deterministically, and usually fairly quickly. |
read |
A wrapper around any Read to treat it as an RNG. |
reseeding |
A wrapper around another PRNG that reseeds it after it generates a certain number of random bytes. |
seq |
Functions for randomly accessing and sampling sequences. |
Structs
AsciiGenerator |
[ Deprecated ] Iterator which will continuously generate random ascii characters. |
EntropyRng |
A generator provided specifically for securely seeding algorithmic generators (PRNGs). |
Error |
Error type of random number generators |
Generator |
[ Deprecated ] Iterator which will generate a stream of random items. |
Isaac64Rng |
A random number generator that uses ISAAC-64, the 64-bit variant of the ISAAC algorithm. |
IsaacRng |
A random number generator that uses the ISAAC algorithm. |
SmallRng |
An RNG recommended when small state, cheap initialization and good
performance are required. The PRNG algorithm in |
StdRng |
The standard RNG. The PRNG algorithm in |
ThreadRng |
The type returned by |
XorShiftRng |
An Xorshift[1] random number generator. |
Enums
ErrorKind |
Error kind which can be matched over. |
Traits
AsByteSliceMut |
Trait for casting types to byte slices |
BlockRngCore |
A trait for RNGs which do not generate random numbers individually, but in
blocks (typically |
CryptoRng |
A marker trait used to indicate that an |
NewRng |
A convenient way to seed new algorithmic generators with fresh entropy from
|
Rand |
[ Deprecated ] A type that can be randomly generated using an |
Rng |
An automatically-implemented extension trait on |
RngCore |
The core of a random number generator. |
SeedableRng |
A random number generator that can be explicitly seeded. |
Functions
random |
[ Deprecated ] DEPRECATED: use |
sample |
[ Deprecated ] DEPRECATED: use |
thread_rng |
Retrieve the lazily-initialized thread-local random number
generator, seeded by the system. Intended to be used in method
chaining style, e.g. |
weak_rng |
[ Deprecated ] DEPRECATED: use |