# 16. Standard Library ## 1. Contract The standard library SHOULD make CLI programs, storage components, network services and structured concurrent programs possible without external source dependencies. Scope and sequencing are tracked in `docs/plan/standard-library.md`; that roadmap does not imply that unimplemented APIs are available. Standard APIs MUST expose allocation, authority, effects, ownership transfer and recoverable failure in their public contracts. Safe library source MUST pass the ordinary verifier. Unsafe or foreign implementations MUST use an explicit audited trusted boundary under spec 13; they MUST NOT masquerade as verified source. The library MUST NOT obtain ambient host authority. APIs SHOULD offer one canonical operation for a common need, small documentation requirements, bounded memory behavior and stable repair guidance (spec 14 §8). Resource cleanup remains explicit. Pure byte/path transformations do not grant authority over files or sockets. ## 2. Bootstrap module registry The built-in registry contains `std.bytes`, `std.encoding.base64`, `std.encoding.hex`, `std.math` and `std.utf8`. They are implemented in safe `.aji` with `effects []`; their stable source paths are `std/bytes.aji`, `std/encoding/base64.aji`, `std/encoding/hex.aji`, `std/math.aji` and `std/utf8.aji`, respectively. Spec 15 §13 defines imports; the reference API tables are in `reference/std.md`. All operations are deterministic in every profile, have no concurrency effects and allocate no heap memory. Ordinary interpreter fuel limits apply. ### 2.1 `std.math` - `min_u64(a: u64, b: u64) -> u64` returns the smaller operand. - `max_u64(a: u64, b: u64) -> u64` returns the larger operand. - `clamp_u64(value: u64, lower: u64, upper: u64) -> u64` returns `lower` below the range, `upper` above it, or `value` inside it. The inclusive range MUST satisfy `lower <= upper`; violation traps `T0002` before returning a value. These are monomorphic functions, not a generic arithmetic facility. Checked/wrapping operators retain their existing semantics (spec 02); importing this module does not alter them. #### 2.1.1 Recoverable unsigned arithmetic For `T` equal to `u64` or `usize`, `checked_add_T(a: T, b: T)`, `checked_sub_T(a: T, b: T)` and `checked_mul_T(a: T, b: T)` return `std.math.U64Result` or `std.math.UsizeResult`, respectively: ```aji enum U64Result { ok(u64), overflow } enum UsizeResult { ok(usize), overflow } ``` Each operation MUST return `ok(value)` exactly when its mathematical result is representable in T, and `overflow` otherwise. Unsigned subtraction underflow is `overflow`. A successful zero is distinct from overflow. `usize` uses the target pointer width (spec 02); no fixed-width maximum or implicit cast is allowed. These functions MUST NOT trap for any scalar operands, apart from the execution environment's fuel limit, including multiplication by zero. They allocate no heap and declare `effects []`. The functions use ordinary Copy enums and the existing integer and enum rules, with no new verifier/runtime primitive. Failure is handled by an exhaustive qualified enum match; no must-use rule or intrinsic outcome shorthand is added. Normal `+`, `-`, `*` still trap on overflow; wrapping uses `+%`, `-%`, `*%`. The library MUST NOT add synonymous wrapping wrappers for these operators. Signed arithmetic and other widths are outside this monomorphic increment; general numeric APIs require separate contracts. ### 2.2 `std.bytes` Inputs are byte slices, not encoded text. No UTF-8 validation or locale interpretation occurs. Read-only parameters are `slice`. - `equal(a, b) -> bool`: true exactly when lengths and all bytes agree. - `compare(a, b) -> i8`: unsigned-byte lexicographic comparison; returns exactly `-1`, `0` or `1`. The shorter of two matching prefixes sorts first. - `find(data, byte: u8) -> usize`: index of the first occurrence; `data.len` when absent. A found index is valid only for the searched slice and exactly when the result is less than its length. Indexing retains the ordinary bounds-check rules (`T0008` for an absent result used as an index). - `starts_with(data, prefix) -> bool`, `ends_with(data, suffix) -> bool`: true for matching prefixes/suffixes, including empty ones; false when the candidate is longer than `data`. - `fill(dst: slice_mut, byte: u8) -> void`: writes every byte of `dst`, including zero writes for an empty slice. The library MUST NOT read or write outside a passed slice and MUST NOT retain or return any borrow. The verifier enforces existing shared/exclusive borrowing, lifetime and bounds rules; there is no library privilege or new transfer function. Read-only functions only read their slices; `fill` writes only its exclusive slice. None consumes an owner or resource. These operations MUST NOT trap for valid byte slices and scalar operands, apart from the execution environment's fuel limit. ### 2.3 Endian reads and writes in `std.bytes` The library provides `read_u16_le`, `read_u16_be`, `read_u32_le`, `read_u32_be`, `read_u64_le`, `read_u64_be`, and the corresponding `write_` functions. Width/order are part of the function name; no native-endian default exists. `le` is least-significant byte first; `be` is most-significant byte first. These functions operate on the beginning of the passed slice. To use an offset, pass an explicit sub-slice. There is no cursor state or alignment requirement. Public result enums: ```aji enum ReadU16 { ok(u16), short_input } enum ReadU32 { ok(u32), short_input } enum ReadU64 { ok(u64), short_input } enum WriteResult { ok, short_output } ``` These declarations belong to `std.bytes` and are named with that prefix (spec 15 §13). For width `W` and byte count `N = W / 8`: - `read_uW_ORDER(src: slice) -> std.bytes.ReadUW` MUST return `short_input` when `src.len < N`, without reading elements. Otherwise it MUST return `ok(value)` decoded from exactly the first N bytes. Extra bytes MUST NOT affect the result. `value = Σ src[i] × 2^(8i)` for LE and `Σ src[i] × 2^(8(N-1-i))` for BE, for `0 <= i < N`. - `write_uW_ORDER(dst: slice_mut, value: uW) -> std.bytes.WriteResult` MUST return `short_output` when `dst.len < N` and leave every destination byte unchanged. Otherwise it MUST write exactly the first N bytes in the selected order, leave the remaining bytes unchanged and return `ok`. Short slices are recoverable enum results, not traps. A successful zero value is distinct from a short input. These APIs declare `effects []`, allocate no heap, retain no borrow and consume no owner/resource. They have no concurrency or authority requirements beyond the ordinary slice borrow contract. All capacity checks precede all accesses/mutations. Valid slices and values MUST NOT produce bounds, arithmetic, cast or shift traps; interpreter fuel exhaustion remains an environment outcome. The verifier uses the existing enum payload, call, shared/exclusive borrow, lifetime and bounds rules. There is no new transfer function, runtime primitive or AIR feature. Ordinary enum construction and exhaustive `enum.switch` lower the result handling. Existing `E7002`, `E7004`, `E7005`, `E7006`, `E2101` cover invalid names/matches/calls and aliasing. The behavior is identical in deterministic and hosted profiles. Existing AIR and the existing nine library operations retain their semantics; imported source receives additional declarations pinned to the compiler version. ### 2.4 Bounded copy, substring search and splitting `std.bytes.copy(dst: slice_mut, src: slice) -> std.bytes.WriteResult` MUST return `short_output` when `dst.len < src.len`, leaving every destination byte unchanged and reading no source elements. Otherwise it MUST copy exactly `src.len` bytes into the beginning of `dst`, preserve remaining destination bytes and return `ok`. Empty input succeeds, including with an empty output. Capacity is checked before any copy. Source/destination overlap MUST be rejected by the existing shared/exclusive alias rules (`E2101`), even if the output is short or the slices are empty. This operation is not an overlap-safe move. `std.bytes.find_slice(data: slice, needle: slice) -> std.bytes.FindResult` returns an ordinary Copy enum: ```aji enum FindResult { found(usize), not_found } ``` It MUST return `found(index)` for the least index at which all needle bytes match, or `not_found` if there is no match. A found index satisfies `index <= data.len` and `needle.len <= data.len - index`. An empty needle MUST return `found(0)` for any data, including empty data, without reading elements. A needle longer than the data MUST return `not_found` without reading elements. Offsets are relative to the passed slice; a found index is an offset, not necessarily an index of a readable element. Search only reads shared slices, retains no borrow and never mutates its input. The reference implementation uses constant auxiliary storage and at most O(data.len × needle.len) byte comparisons; interpreter fuel still bounds execution. Splitting at the first byte-string separator uses `find_slice`, then the existing explicit sub-slice or `split_at` forms (spec 15 §6). On `found(index)`, the left part is `data[0..index]`, the separator `data[index..index + separator.len]` and the right part `data[index + separator.len..data.len]`. On `not_found` the caller chooses how to handle an absent separator. An empty separator yields an empty left part and the whole data as the right part; repeated splitting with an empty separator needs a caller-defined progress rule. There is no standard split iterator, returned aggregate of borrows or hidden cursor. Single-byte splitting MAY use the existing `find` length sentinel, checked before slicing. Both functions declare `effects []`, allocate no heap, retain no borrow and consume no owner/resource. Valid slices MUST NOT produce bounds or integer traps; fuel exhaustion remains an environment outcome. The invariant is existing shared-read/exclusive-write access within the supplied slices, with no partial mutation on a short-output result. Existing call, alias, lifetime, initialization, capacity/bounds and enum transfer functions apply, with no new privilege, diagnostic code, AIR feature or runtime rule. Deterministic and hosted profiles behave identically. Existing APIs and AIR format 0 retain their contracts. ### 2.5 UTF-8 `std.utf8` interprets UTF-8 as the shortest encoding of Unicode scalar values 0..0x10FFFF excluding 0xD800..0xDFFF, following RFC 3629 §3/§4. Unassigned scalar values, noncharacters, NUL and U+FEFF are valid. No normalization, replacement decoding, locale handling or BOM removal occurs. ```aji enum NextResult { ok(u32, usize), end, invalid_input } enum ValidateResult { ok, invalid_input(usize) } ``` - `next(src: slice) -> std.utf8.NextResult` MUST return `end` exactly when src is empty. Otherwise it MUST decode only the first scalar: `ok(value, byte_count)` with 1..4 consumed bytes, or `invalid_input` if the first sequence is malformed or truncated. Trailing bytes after a successful first sequence MUST NOT affect that result. Iteration uses an explicit caller offset and a sub-slice, without retained cursor state or borrows. - `validate(src: slice) -> std.utf8.ValidateResult` MUST return `ok` for a wholly valid sequence, including empty input. Otherwise it MUST return `invalid_input(offset)` at the beginning of the first malformed or truncated sequence, relative to src, after the maximal valid prefix. The offset identifies the sequence's leading byte, not necessarily the bad continuation byte. ASCII bytes 00..7F are single-byte scalars. Multi-byte leading bytes are C2..DF, E0..EF and F0..F4 with two, three or four total bytes, respectively. Continuations MUST be 80..BF; the second byte MUST be A0..BF after E0, 80..9F after ED, 90..BF after F0 and 80..8F after F4. These conditions reject overlong forms, surrogates and out-of-range scalars. Invalid input is a result, never replacement text or a trap. Validation and explicit iteration use O(src.len) work and constant auxiliary storage. ### 2.6 Supplied-buffer encodings Both `std.encoding.hex` and `std.encoding.base64` export these ordinary Copy enums, distinct between modules: ```aji enum EncodeResult { ok(usize), short_output } enum DecodeResult { ok(usize), invalid_input, short_output } ``` Each module provides `encode(dst: slice_mut, src: slice) -> EncodeResult` and `decode(dst: slice_mut, src: slice) -> DecodeResult`, with fully qualified result types. `ok(count)` MUST report the number of output bytes. Successful operations MUST write exactly the output prefix and leave remaining destination bytes unchanged; no terminator is appended. Empty input MUST succeed with `ok(0)` for any capacity, including zero. Encoding MUST check full output capacity before writing. If the mathematical encoded length exceeds either usize or output capacity, it MUST return `short_output`, leaving the entire destination unchanged; guards MUST avoid intermediate overflow. Decoding MUST validate the entire input before any destination write. Malformed input MUST return `invalid_input`, even with insufficient output capacity. Valid input with insufficient capacity MUST return `short_output`. Both error results MUST leave the entire destination unchanged. Ordinary shared/exclusive alias rules (`E2101`) apply even on failure paths; overlapping input/output is not allowed. Guarantees about unchanged output apply to returned errors, not interpreter fuel exhaustion mid-operation. #### 2.6.1 Hex `std.encoding.hex.encode` MUST produce two lowercase ASCII hexadecimal digits per byte, most-significant nibble first, with mathematical length 2 × src.len. `decode` MUST accept exactly even-length sequences of ASCII digits 0..9, a..f or A..F, interpreting each pair as one byte. Mixed case is accepted. Odd lengths, separators, prefixes, whitespace and other bytes are `invalid_input`. There is no padding. #### 2.6.2 Base64 `std.encoding.base64` uses RFC 4648 §4's standard alphabet `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`, with `=` padding, no line breaks and zero unused bits. Encoded length is 4 × ceil(src.len / 3). Implementations MUST check that this length fits without overflowing an intermediate such as an unconditional `src.len + 2`. Decoding MUST accept only canonical standard Base64: input length divisible by four; alphabet symbols in every unpadded position; zero, one or two padding symbols only at the end; and zero unused low bits (four low bits in the second symbol for `==`, two low bits in the third for `=`). Padding is required for incomplete final groups, and omitted for complete groups. Whitespace, URL-safe `-`/`_`, extra/misplaced padding, incomplete groups and nonzero unused bits are `invalid_input`. Empty input is canonical. Invalid-input precedence and unchanged-output guarantees are those of §2.6. ### 2.7 Text/encoding safety and compatibility Sections 2.5/2.6 use safe source, ordinary calls, integer operations, slices, local fixed-size tables and enums. They declare `effects []`, allocate no heap, retain no borrow and consume no owner/resource. Work is O(input length) with constant auxiliary storage. The preserved invariant is shared-read/exclusive-write access within supplied initialized slices, no escaping borrow and no mutation on returned encoding errors. Existing verifier call/alias/lifetime/bounds/initialization/enum rules and deterministic interpreter behavior apply without a privilege, new transfer function, diagnostic, AIR feature or runtime primitive. Valid slices MUST NOT produce bounds, arithmetic, cast or shift traps; malformed bytes and capacity failure are results. Deterministic and hosted profiles behave identically. Existing APIs, source syntax and AIR format 0 retain their contracts.