fmt
Package fmt provides string formatting shaped to Boson's constraints: no GC, immutable []byte strings, and value-shape interface-coercion limits.
Five layers, smallest first:
1. Raw conversions (itoa/utoa/htoa) write a single typed value into the head of a caller-provided []mut byte. No allocation, no I/O. 2. Writer helpers (str/int/uint/hex/char/bool/nl) format one value into a stack scratch buffer and emit it through an io.writer in one write. 3. Builder is a bring-your-own-memory accumulator over a caller-supplied []mut byte, with append methods and a borrowed []byte view. 4. stringer and Formatter are the two user-extension "render me" hooks, discovered at runtime via interface assertion. 5. print/printf are printf-style variadic helpers backed by per-arg type assertion.
All storage is caller-owned. The only heap traffic is the lazy itab cache built by interface assertion inside %v dispatch; in steady state it is zero.
Index
Functions
- pub fn n_digits(n i64) i64
- pub fn n_udigits(n u64) i64
- pub fn n_hex_digits(n u64) i64
- pub fn itoa(out []mut byte, n i64) []byte
- pub fn utoa(out []mut byte, n u64) []byte
- pub fn htoa(out []mut byte, n u64) []byte
- pub fn ftoa(out []mut byte, f f64, prec i64) []byte
- pub fn str(w io.writer, s []byte) i64, ?io.error
- pub fn int(w io.writer, n i64) i64, ?io.error
- pub fn uint(w io.writer, n u64) i64, ?io.error
- pub fn hex(w io.writer, n u64) i64, ?io.error
- pub fn char(w io.writer, c byte) i64, ?io.error
- pub fn bool(w io.writer, b bool) i64, ?io.error
- pub fn float(w io.writer, f f64, prec i64) i64, ?io.error
- pub fn float_trim(w io.writer, f f64) i64, ?io.error
- pub fn nl(w io.writer) i64, ?io.error
- pub fn print(format []byte, args ...any) i64, ?io.error
- pub fn printf(w io.writer, format []byte, args ...any) i64, ?io.error
Types
- pub type Builder struct { ... }
- str(b *mut Builder, s []byte)
- int(b *mut Builder, n i64)
- uint(b *mut Builder, n u64)
- hex(b *mut Builder, n u64)
- char(b *mut Builder, c byte)
- bool(b *mut Builder, v bool)
- nl(b *mut Builder)
- bytes(b *Builder) []byte
- space(b *Builder) i64
- error(b *Builder) ?io.error
- reset(b *mut Builder)
- pub type BuilderWriter struct { ... }
- write(self *BuilderWriter, bs []byte) i64, ?io.error
- pub type strerr struct { msg owned []byte }
- new(format []byte, args ...any) owned *mut strerr
- format(e *strerr, w io.writer) ?io.error
- destroy(e owned *mut strerr)
- pub type StringBuilder struct { ... }
- new() owned *owned mut StringBuilder
- expand(b *mut StringBuilder, at_least i64)
- str(b *mut StringBuilder, s []byte)
- int(b *mut StringBuilder, n i64)
- uint(b *mut StringBuilder, n u64)
- hex(b *mut StringBuilder, n u64)
- char(b *mut StringBuilder, c byte)
- bool(b *mut StringBuilder, v bool)
- write(b *mut StringBuilder, bs []byte) i64, ?io.error
- borrow(b *StringBuilder) []byte
- string(b *mut StringBuilder) owned []byte
- to_string(b owned *owned mut StringBuilder) owned []byte
- destroy(b owned *owned mut StringBuilder)
Functions 18
n_digits returns the number of bytes itoa(n) would write, including the leading '-' for negatives.
n_udigits returns the number of bytes utoa(n) would write.
n_hex_digits returns the number of bytes htoa(n) would write (no 0x).
itoa writes the canonical signed-decimal form of n into the head of out and returns the rendered bytes as a sub-slice of out (`out[0:k]`). No NUL terminator; a leading '-' is emitted for negatives. If out is too small the longest prefix that fits is written and the returned slice is the whole of out (len == len(out)) — compare len against n_digits(n) to detect truncation. The result borrows out, so it stays valid as long as the caller's buffer does (the return-alias inference records this).
utoa writes the canonical unsigned-decimal form of n and returns the rendered bytes as a sub-slice of out. Same truncation contract as itoa (compare len against n_udigits(n)).
htoa writes the canonical lowercase-hex form of n with no "0x" prefix and returns the rendered bytes as a sub-slice of out. (The "0x" prefix is added by the Layer 2 hex writer.) Same truncation contract as itoa (compare len against n_hex_digits(n)).
ftoa renders f in fixed-point notation with exactly `prec` digits after the decimal point, and returns the rendered bytes as a sub-slice of out.
Truncation follows the same contract as itoa: if the rendering does not fit in out, the leading len(out) bytes are written and returned.
This is deliberately not a shortest-round-trip conversion — that is a substantial sub-project of its own, and a fixed-precision result is deterministic, which matters because the test suite diffs exact strings. The digits are exact for values whose integer part is below 2^53; beyond that the repeated division used to extract digits is itself rounded, so far-out digits of very large magnitudes are approximate. They are still deterministic.
Specials render as NaN, +Inf and -Inf. Negative zero keeps its sign, which is why the sign is taken from 1.0/f rather than from a comparison: -0.0 is not less than zero.
int formats n as signed decimal into a stack buffer and writes it once.
uint formats n as unsigned decimal and writes it once.
hex formats n as "0x"-prefixed lowercase hex and writes it once.
char writes the single byte c.
bool writes "true" or "false".
float writes f in fixed-point notation with `prec` digits after the point.
float_trim writes f with trailing fraction zeros removed, keeping at least one digit so the result still reads as a float: 1.5 prints "1.5", 1.0 prints "1.0". This is what %v uses — a natural rendering rather than a fixed column width. Specials have no fraction to trim.
nl writes a single newline.
print formats to stdout. See printf for directive semantics.
printf renders format into w, consuming one arg per directive. Directives:
A verb names a rendering; the argument's own type (carried by the `any`) decides correctness — there is no verb whose job is to announce the type.
%d decimal — any integer type, signed or unsigned by its own type %x "0x"-prefixed hex — any integer type %s a []byte or []mut byte (string), written verbatim %c an integer as a character (its low byte) %v natural: integers in decimal, bool as true/false, byte slices as text, else stringer/Formatter, else a %!v(...) placeholder %% literal '%' (consumes no arg)
Returns (written, err): written is total bytes successfully written; err is the first non-OK condition (write failure, type mismatch, missing/surplus arg). A write failure stops immediately; mismatch and missing-arg write an inline marker, latch the error, and continue. Surplus args are appended %v-style and latch a surplus error.
Types 4
struct { buf []mut byte pos i64 err_ ?io.error }
Builder is a bring-your-own-memory accumulator. The caller supplies the backing buffer; the lifetime of bytes() is the lifetime of buf. Construct inline with a struct literal — there is no constructor:
var backing [256]byte var b fmt.Builder = fmt.Builder{ buf: backing[:], pos: 0, err_: nil }
Append methods are statement-shaped (they return nothing) and follow a latched-error pattern: the first append that would overflow the buffer sets err_ to io.io_err.ENOSPC, and every subsequent append becomes a no-op. Inspect error() once at the end.
(DEVIATION from the proposal: the append methods return nothing rather than *mut Builder. Boson forbids returning a borrowed pointer — including the *mut Builder receiver — so the proposed `b.str(..).int(..)` chaining is not expressible. Sequential statement calls are the sound equivalent.)
str appends s, truncating nothing — if it would not fit, the latched error is set and nothing is written.
bytes returns the accumulated bytes as a borrowed view buf[0:pos].
space returns the remaining unwritten capacity.
error returns the latched error (nil while clean).
reset rewinds the cursor and clears the latched error; buf is untouched.
struct { b *mut Builder }
BuilderWriter adapts a *mut Builder to the *self-shaped io.writer interface, so a Builder can be a printf/Formatter sink. Construct inline:
var bw fmt.BuilderWriter = fmt.BuilderWriter{b: &b} fmt.printf(bw, "x=%d\n", x)
write appends bs to the underlying Builder. Reading self.b yields the *mut Builder and the *mut str method is callable through it; the adapter struct itself is not mutated.
struct { msg owned []byte }
strerr is an error type useful for constructing error messages at runtime.
struct { buf owned []mut byte pos i64 }
borrow returns a view without copying. Use it before passing the builder to a mutable method such as write, str, or expand, or before destroy. A mutable call invalidates existing views even when it does not grow. Call borrow again afterward for a fresh view of the current contents.
Interfaces 2
stringer is implemented by types that can render themselves as a byte slice without constructing new storage. The result may be a borrowed view of the receiver — `from(self)` — so `return self.buf` is allowed: the canonical render-yourself pattern, with no allocation. Storage that outlives the receiver (a static .rodata slice like `return "Point"`) also satisfies the contract, since borrowing nothing is ⊆ borrowing self.
The cost of the `from(self)` declaration is borne by callers: a `%v` / string() result is assumed to borrow the formatted value and may not outlive it. In the dominant format-and-write-now path that window is a single statement, so the cost is invisible; render_v writes the result immediately. Preferred over Formatter when both are available; Formatter remains the path for rendering that must stream into a writer.
Formatter is implemented by types whose rendering must be constructed at call time. format writes self into w and returns the first write error (or nil).