Skip to content

random

Randomness without a hidden global generator.

Rng is a small seedable generator for work that must be reproducible and testable: shuffle, sample and choose take it as an argument, so the same seed always gives the same result. It is not for secrets: a 64-bit seed can be guessed.

Keys, tokens and anything an attacker must not predict come from the operating system, with the random-entropy feature (not in default, it pulls the getrandom crate): random_bytes, random_hex, random_alphanumeric and Rng::from_entropy. They return an EntropyError when the system cannot provide bytes, and never fall back to weaker randomness. They are not built for wasm32-unknown-unknown, which has no default entropy source: pass bytes from the host (crypto.getRandomValues) to the pure constructors of the id module instead.

Cargo feature random (enabled by default). To compile only this module:

cargo add helpers4 --no-default-features --features random

or in Cargo.toml:

[dependencies]
helpers4 = { version = "0.0.9", default-features = false, features = ["random"] }

Opt-in sub-feature random-entropy (adds the getrandom dependency): .

Import path: helpers4::random.

ItemWhat it does
choosePicks one element at random, each with the same probability.
random_alphanumericA random string of letters and digits (A-Za-z0-9) from the operating system’s random source, with every character equally likely.
random_bytesRandom bytes from the operating system, suitable for keys, tokens and salts.
random_hexRandom bytes from the operating system, written as lowercase hexadecimal: the usual form of a master key or a session token (random_hex(32) is a 256-bit key in 64 characters).
RngA small, fast, seedable pseudo-random generator (SplitMix64): the same seed always gives the same sequence, on every platform.
samplePicks count different elements at random (without replacement), in random order.
shuffleReturns the elements in a random order (Fisher–Yates: every permutation is equally likely), leaving items as it is.

Documented on the page of the helper that returns them.

TypeReturned by
EntropyErrorrandom_alphanumeric, random_bytes, random_hex, Rng