std/format
std/format
Section titled “std/format”std/format — human-readable formatting helpers. format(fmt, args) — runtime template substitution with {} placeholders. format_bytes(n) / format_duration_ms(ms) — pre-canned shapes for byte sizes and elapsed durations. Migrated from the auto-injected prelude per docs/PRELUDE-TO-MODULES.md. The auto-prelude declares import "std/format"; so existing bare-name callers keep working unchanged.
format
Section titled “format”pub function format(fmt: string, args: string[]): stringformat(fmt, args) — runtime template substitution. Walks
fmt byte-by-byte, replacing each {} placeholder with the
next element of args. Extra args (more args than {}s) are
silently dropped; missing args (more {}s than args) emit
the placeholder unchanged. Mirrors Python’s str.format() /
Rust’s format!() minimal subset.
Use cases the f-string sugar doesn’t cover:
- Dynamic templates (read from a config file, locale table, error catalogue, etc.).
- Programs that build their own diagnostic strings — a checker emitting “expected {}, got {}” where the template lives in a const-table rather than at every call site.
Caller pre-stringifies args (to_string() for i32 / i64 /
f32 / f64 / boolean). A typed-overload story would need
trait dispatch which lang doesn’t have yet; the string[]
signature keeps the type story trivial.
format_bytes
Section titled “format_bytes”pub function format_bytes(n: i32): stringformat_bytes(n) — render an i32 byte count as “N B” /
“N KiB” / “N MiB” / “N GiB” using binary (1024-based)
prefixes. Integer truncation only — for “1.5 KiB” the
caller can divide by 1024 themselves and apply
to_string_padded. Negative input is rendered with a
leading ”-” before the unit (“-512 B”). i32 caps the
representable range at ~2 GiB which covers the common
CLI / log use case; callers needing larger sizes can
drop down to manual i64 div + to_string.
format_duration_ms
Section titled “format_duration_ms”pub function format_duration_ms(ms: i32): stringformat_duration_ms(ms) — human-readable duration like
“1h 23m 45s” / “500ms”. Components are emitted only when
non-zero, separated by spaces; “0” alone returns “0ms”.
Negative ms gets a leading ”-” before the magnitude.