packages / fmt
package

fmt

import "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 18

pub fn n_digits(n i64) i64

n_digits returns the number of bytes itoa(n) would write, including the leading '-' for negatives.

fmt.bos:30 #n_digits
pub fn n_udigits(n u64) i64

n_udigits returns the number of bytes utoa(n) would write.

fmt.bos:59 #n_udigits
pub fn n_hex_digits(n u64) i64

n_hex_digits returns the number of bytes htoa(n) would write (no 0x).

fmt.bos:70 #n_hex_digits
pub fn itoa(out []mut byte, n i64) []byte

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).

fmt.bos:87 #itoa
pub fn utoa(out []mut byte, n u64) []byte

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)).

fmt.bos:146 #utoa
pub fn htoa(out []mut byte, n u64) []byte

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)).

fmt.bos:181 #htoa
pub fn ftoa(out []mut byte, f f64, prec i64) []byte

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.

fmt.bos:264 #ftoa
pub fn str(w io.writer, s []byte) i64, ?io.error
fmt.bos:360 #str
pub fn int(w io.writer, n i64) i64, ?io.error

int formats n as signed decimal into a stack buffer and writes it once.

fmt.bos:366 #int
pub fn uint(w io.writer, n u64) i64, ?io.error

uint formats n as unsigned decimal and writes it once.

fmt.bos:374 #uint
pub fn hex(w io.writer, n u64) i64, ?io.error

hex formats n as "0x"-prefixed lowercase hex and writes it once.

fmt.bos:382 #hex
pub fn char(w io.writer, c byte) i64, ?io.error

char writes the single byte c.

fmt.bos:393 #char
pub fn bool(w io.writer, b bool) i64, ?io.error

bool writes "true" or "false".

fmt.bos:401 #bool
pub fn float(w io.writer, f f64, prec i64) i64, ?io.error

float writes f in fixed-point notation with `prec` digits after the point.

fmt.bos:411 #float
pub fn float_trim(w io.writer, f f64) i64, ?io.error

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.

fmt.bos:422 #float_trim
pub fn nl(w io.writer) i64, ?io.error

nl writes a single newline.

fmt.bos:445 #nl
pub fn print(format []byte, args ...any) i64, ?io.error

print formats to stdout. See printf for directive semantics.

fmt.bos:662 #print
pub fn printf(w io.writer, format []byte, args ...any) i64, ?io.error

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.

fmt.bos:685 #printf

Types 4

pub type Builder struct { ... }
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.)

fmt.bos:471 #Builder
Methods
str(b *mut Builder, s []byte)

str appends s, truncating nothing — if it would not fit, the latched error is set and nothing is written.

fmt.bos:478 #Builder.str
int(b *mut Builder, n i64)
fmt.bos:492 #Builder.int
uint(b *mut Builder, n u64)
fmt.bos:504 #Builder.uint
hex(b *mut Builder, n u64)
fmt.bos:516 #Builder.hex
char(b *mut Builder, c byte)
fmt.bos:530 #Builder.char
bool(b *mut Builder, v bool)
fmt.bos:540 #Builder.bool
nl(b *mut Builder)
fmt.bos:548 #Builder.nl
bytes(b *Builder) []byte

bytes returns the accumulated bytes as a borrowed view buf[0:pos].

fmt.bos:553 #Builder.bytes
space(b *Builder) i64

space returns the remaining unwritten capacity.

fmt.bos:558 #Builder.space
error(b *Builder) ?io.error

error returns the latched error (nil while clean).

fmt.bos:563 #Builder.error
reset(b *mut Builder)

reset rewinds the cursor and clears the latched error; buf is untouched.

fmt.bos:568 #Builder.reset
pub type BuilderWriter struct { ... }
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)

fmt.bos:579 #BuilderWriter
Methods
write(self *BuilderWriter, bs []byte) i64, ?io.error

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.

fmt.bos:585 #BuilderWriter.write
pub type strerr struct { msg owned []byte }
struct { msg owned []byte }

strerr is an error type useful for constructing error messages at runtime.

fmt.bos:622 #strerr
Methods
new(format []byte, args ...any) owned *mut strerr
fmt.bos:623 #strerr.new
format(e *strerr, w io.writer) ?io.error
fmt.bos:628 #strerr.format
destroy(e owned *mut strerr)
fmt.bos:632 #strerr.destroy
pub type StringBuilder struct { ... }
struct {
	buf owned []mut byte
	pos i64
}
string_builder.bos:5 #StringBuilder
Methods
new() owned *owned mut StringBuilder
string_builder.bos:9 #StringBuilder.new
expand(b *mut StringBuilder, at_least i64)
string_builder.bos:13 #StringBuilder.expand
str(b *mut StringBuilder, s []byte)
string_builder.bos:29 #StringBuilder.str
int(b *mut StringBuilder, n i64)
string_builder.bos:41 #StringBuilder.int
uint(b *mut StringBuilder, n u64)
string_builder.bos:51 #StringBuilder.uint
hex(b *mut StringBuilder, n u64)
string_builder.bos:61 #StringBuilder.hex
char(b *mut StringBuilder, c byte)
string_builder.bos:73 #StringBuilder.char
bool(b *mut StringBuilder, v bool)
string_builder.bos:81 #StringBuilder.bool
write(b *mut StringBuilder, bs []byte) i64, ?io.error
string_builder.bos:89 #StringBuilder.write
borrow(b *StringBuilder) []byte

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.

string_builder.bos:100 #StringBuilder.borrow
string(b *mut StringBuilder) owned []byte
string_builder.bos:104 #StringBuilder.string
to_string(b owned *owned mut StringBuilder) owned []byte
string_builder.bos:110 #StringBuilder.to_string
destroy(b owned *owned mut StringBuilder)
string_builder.bos:116 #StringBuilder.destroy

Interfaces 2

pub interface stringer

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.

fmt.bos:610 #stringer
Methods
string(self *self) []byte from(self)
pub interface Formatter

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).

fmt.bos:617 #Formatter
Methods
format(self *self, w io.writer) ?io.error