first commit

This commit is contained in:
2026-05-29 08:20:56 +01:00
commit 949299f58d
6368 changed files with 527176 additions and 0 deletions

View File

@@ -0,0 +1,45 @@
# 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 a `Rng` instance backed by Web Crypto.
- Errors surface immediately when the host lacks a CSPRNG.
- Trivially overridable in tests by passing a `Mulberry32Rng` (or any `Rng`) into the simulator constructor.
- No module-scope state; each call returns a fresh `Rng` instance.
## Usage: Basic Example
```ts
import { defaultRng } from "@suaveplan/bitpacker-network";
const rng = defaultRng();
const value = rng.nextFloat(); // [0, 1)
```
## Usage: Advanced Example
```ts
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 `Rng` instance backed by `cryptoRng()` from `@suaveplan/random`.
- **Throws:** Re-throws `RANDOM.SOURCE.UNAVAILABLE` from `cryptoRng()` if `globalThis.crypto.getRandomValues` is unavailable.
## Implementation Notes
- `Rng` interface from `@suaveplan/types` is the canonical contract; `cryptoRng()` and `Mulberry32Rng` both 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`'s `rng` constructor option.