2.3 KiB
default-rng
Purpose
defaultRng is the canonical CSPRNG-backed Rng factory used by NetworkSimulator and any other deterministic-when-asked, random-by-default primitive in @suaveplan/bitpacker-network. It exists so callers don't have to reach into @suaveplan/random directly to obtain the standard random source — and so that swapping the simulator to a seeded RNG in tests is a single keyword argument away.
The factory delegates to cryptoRng() from @suaveplan/random, which uses globalThis.crypto.getRandomValues underneath. In environments without a CSPRNG (some embedded runtimes) the underlying call throws a RANDOM.SOURCE.UNAVAILABLE error. We surface that directly: the policy is "if you don't have a CSPRNG, you must inject a seeded Rng yourself" — never silently downgrade to Math.random().
Features
- Zero-config default for production — call
defaultRng()and you get aRnginstance backed by Web Crypto. - Errors surface immediately when the host lacks a CSPRNG.
- Trivially overridable in tests by passing a
Mulberry32Rng(or anyRng) into the simulator constructor. - No module-scope state; each call returns a fresh
Rnginstance.
Usage: Basic Example
import { defaultRng } from "@suaveplan/bitpacker-network";
const rng = defaultRng();
const value = rng.nextFloat(); // [0, 1)
Usage: Advanced Example
import { Mulberry32Rng } from "@suaveplan/pseudo-random";
import { NetworkSimulator } from "@suaveplan/bitpacker-network";
// Deterministic test: seed a Mulberry32 PRNG instead of using defaultRng().
const sim = new NetworkSimulator({ rng: new Mulberry32Rng(42), clock: testClock });
API Reference
defaultRng(): Rng
- Returns: A new
Rnginstance backed bycryptoRng()from@suaveplan/random. - Throws: Re-throws
RANDOM.SOURCE.UNAVAILABLEfromcryptoRng()ifglobalThis.crypto.getRandomValuesis unavailable.
Implementation Notes
Rnginterface from@suaveplan/typesis the canonical contract;cryptoRng()andMulberry32Rngboth implement it.- We surface
cryptoRng()directly rather than wrapping in a try/catch because callers should know if their environment lacks a CSPRNG — silent fallback would defeat determinism guarantees elsewhere in the simulator. - This factory is used as the default for
NetworkSimulator'srngconstructor option.