Skip to content

std/random ​

Random numbers from the platform CSPRNG: arc4random on macOS, getentropy on Linux, BCryptGenRandom on Windows. Nothing to seed, and nothing to replay: for a reproducible stream (simulations, property tests), use std/rng.

milo
from "std/random" import { Random }

For key material (secrets, salts, nonces, tokens) use Random.bytes(n): n bytes as a byte string, the form Hex.encode, Base64.urlEncode and std/crypto take.

milo
from "std/random" import { Random }
from "std/hex" import { Hex }

fn main() {
    let token = Hex.encode(Random.bytes(16))   // 32 hex digits
    print(token.len)
}

API reference ​

std/random has one implementation per target (darwin, linux, windows); the resolver picks the one for the target you build for.

Random ​

milo
pub struct Random

Random namespace — Random.int/range/float/bool/bytes/... (platform RNG).

Random.bool ​

milo
fn Random.bool(): bool

true or false with equal probability.

Random.bytes ​

milo
fn Random.bytes(n: i64): string

n cryptographically secure random bytes (the OS CSPRNG), as a byte string: the representation std's crypto APIs take keys, salts and nonces in (Hex.encode, Base64.urlEncode, Crypto.aesGcmEncrypt). Never fails; if the OS entropy source is unavailable the process exits rather than return predictable bytes.

Random.fillRaw ​

milo
fn Random.fillRaw(buf: *u8, n: i64): void

Fill buf with n random bytes, as bytes does: the raw form for a fixed array a caller already holds. buf must point at n writable bytes.

Random.float ​

milo
fn Random.float(): f64

A random float in [0.0, 1.0).

Random.floatRange ​

milo
fn Random.floatRange(min: f64, max: f64): f64

A random float in [min, max).

Random.int ​

milo
fn Random.int(max: i64): i64

A random integer in [0, max). max must be positive.

Random.range ​

milo
fn Random.range(min: i64, max: i64): i64

A random integer in [min, max], both ends inclusive.

Random.shuffleI64 ​

milo
fn Random.shuffleI64(v: &mut Vec<i64>, n: i64): void

Shuffle the first n elements of v in place (Fisher-Yates). Pass v.len() for all.

Random.u32 ​

milo
fn Random.u32(): u32

A random u32 in [0, 2^32).