Rng
A small, fast, seedable pseudo-random generator (SplitMix64): the same seed always gives the same sequence, on every platform.
It is meant for reproducible work (tests, procedural content, shuffling with a recorded
seed) and passed explicitly to shuffle, sample and
choose. It is not cryptographically secure: never derive a key, a
token or an identifier that must stay secret from it. Use the random-entropy feature for
that.
Import
Section titled “Import”Cargo feature random (enabled by default). To compile only this module:
or in Cargo.toml:
Definition
Section titled “Definition”Examples
Section titled “Examples”Methods
Section titled “Methods”next_u64
Section titled “next_u64”The next 64 random bits.
Returns
u64 — A u64 where every bit pattern is equally likely.
Examples
next_f64
Section titled “next_f64”A random number in [0, 1), with 53 bits of precision (every value is a multiple of
2⁻⁵³).
Returns
f64 — A value >= 0.0 and < 1.0.
Examples
A random integer in 0..bound, uniformly: values are rejected rather than folded with a
modulo, which would favor small results when bound does not divide 2⁶⁴.
Parameters
| Parameter | Type | Description |
|---|---|---|
bound | u64 | The exclusive upper bound. |
Returns
Option<u64> — A value < bound, or None when bound is 0 (there is no such value).
Examples
fill_bytes
Section titled “fill_bytes”Fills dest with random bytes.
Parameters
| Parameter | Type | Description |
|---|---|---|
dest | &mut [u8] | The buffer to fill. |
Returns
()
Examples
from_entropy
Section titled “from_entropy”Starts a generator from a seed drawn from the operating system, for work that must differ on every run but needs no secrecy (a random order, a random pick).
Needs the random-entropy feature. The generator itself is still not cryptographically
secure: for keys and tokens, use random_bytes directly.
Returns
Result<Self, super::EntropyError> — A generator with an unpredictable seed.
Errors
Returns an EntropyError when the operating system cannot provide
random bytes.
Examples
Error type: EntropyError
Section titled “Error type: EntropyError”The operating system could not provide random bytes.
Rare, but possible (no entropy source at boot, a sandbox that blocks the system call, an unsupported platform). The functions that return it never fall back to weaker randomness: a key or a token made from predictable bytes is worse than no key.
