Skip to content

std/math

std/math — random integers, integer ranges, numeric-width constants, packed-RGB helper. Migrated from the auto-injected prelude per docs/PRELUDE-TO-MODULES.md.

pub function random_int(lo: i32, hi: i32): i32

random_int(lo, hi) — random i32 in [lo, hi). Returns lo when hi <= lo (empty range fallback). Pulls 3 bytes from random_bytes (kernel CSPRNG on natives, wasi_random on wasm), combines into a 24-bit value, and modulo-maps to the range width. 24 bits caps the maximum bias-free range at ~16M which covers the common short-range use cases (port pick, ID generation, jitter).

The range local intentionally shares its name with the module-level range() function below — a deliberate regression guard for the self-host module loader, which previously mangled such a shadowing local into the function reference on import (see flatten.fern + TestSelfHostLocalShadowsImportedDecl). The earlier rng rename worked around that; the loader now resolves the shadow correctly, so the natural name is restored.

pub function range(start: i32, end: i32): i32[]

range(start, end) — i32[] of [start, end). Empty if start >= end. Standard half-open range.

pub function range_step(start: i32, end: i32, step: i32): i32[]

range_step(start, end, step) — same as range but with arbitrary positive step. Step <= 0 returns empty (no reverse ranges — use a manual while loop for that).

pub function i32_max(): i32

Function-style accessors for the width boundaries. Plain constants would be cleaner but lang doesn’t have a const declaration syntax yet; these constant-functions inline at the call site via the IR’s constant-folding pass.

pub function i32_min(): i32
pub function i64_max(): i64
pub function i64_min(): i64
pub function pack_rgb(r: i32, g: i32, b: i32): i32

pack_rgb(r, g, b) — pack three 0..255 components into a 24-bit i32. Inverse of (n).to_rgb_hex()’s shifts. Each component is masked to its low 8 bits; values outside 0..255 silently wrap. Pairs with to_rgb_hex for the “construct then format” colour pipeline.