Record the owner-requested STD-0..7 merge boundary and adoption of implemented RFCs 0016-0035, whose normative rules and vertical implementations land together. Update repository and std status; keep remaining Std 0.1 and service milestones in the backlog. Track Q-034/P6-11 as the next source-language task and retain the existing P7/P8 gate. Implementation checks are recorded in RFC 0035 and the std plan; this change updates adoption metadata and planning only.
14 KiB
RFC 0019: UTF-8 and supplied-buffer hex/Base64
Status: Implemented Scope: STD-2a, safe standard modules; existing source syntax and AIR format 0 unchanged Language version: 0.1 Supersedes: — Adoption: owner-requested intermediate std merge, 2026-10-07; normative rules and reference implementation are integrated together.
This work branch contains the proposed specification, implementation and tests for review. Only the owner changes the RFC to Accepted. Formatting is a separate STD-2b increment.
Motivation
CLI, protocol and storage code needs to validate text and transform arbitrary bytes without hidden allocation. UTF-8 iteration can use existing scalar/offset values, while caller-provided encoding buffers make capacity and mutation explicit. A bad trailing byte must not leave a partially decoded record that the caller needs to reason about.
The increment improves semantic explicitness, deterministic behavior, memory safety and implementation simplicity. Its Model Capability Compression benefit is a hypothesis, not inferred from fixtures. Three modules add six functions and six ordinary Copy enums; no runtime codec or new language mechanism is needed.
Precise invariant
UTF-8 only reads shared input and returns scalar/count or validation offset values. Encoding operations only access initialized supplied slices; successful writes modify exactly an output prefix. Returned invalid-input/short-output errors leave the entire destination unchanged. No borrow escapes, heap allocation occurs, owner/resource is consumed, authority is created or task starts. Fixed local tables are frame storage. Ordinary shared/exclusive alias rules apply on every path.
Normative rule changes
Complete proposed contracts are integrated in spec 16 §2.5–§2.7; the closed registry/source-path table in §2 now lists five modules. Spec 15 §13 references that table without changing resolution rules.
std.utf8.next(src)MUST returnok(scalar, consumed),endfor empty input orinvalid_inputfor a malformed/truncated first sequence. It checks only that sequence; caller offsets/sub-slices express iteration.validate(src)MUST validate all input and returninvalid_input(offset)at the leading byte of the first bad/truncated sequence, orok. Empty input succeeds. The scalar domain excludes surrogates and values above U+10FFFF; no normalization or replacement is performed.- Hex encode MUST emit lowercase ASCII digits; decode MUST accept even-length ASCII hex in either letter case, with no prefixes, separators or whitespace.
- Base64 encode/decode MUST use canonical padded standard encoding. Decode rejects incomplete groups, nonalphabet bytes, misplaced/extra padding and nonzero unused bits. URL-safe/permissive modes are not part of the contract.
- Encoding MUST precheck the full output size without intermediate overflow. Decode MUST validate all input before checking capacity or writing. Invalid input MUST win over short output; both returned errors MUST preserve the entire destination.
ok(count)identifies the written prefix; remaining output stays unchanged, no terminator is appended, and empty input succeeds with count zero even with empty output. A mathematical encoded size exceeding usize/capacity isshort_output.
Unicode scalar/byte rules were checked against RFC 3629 §3/§4. Base64 alphabet/padding and the deliberate strict unused-bit policy follow RFC 4648 §3.5/§4. Hex lowercase output is an explicit Aji choice; decode also accepts uppercase public vectors.
Verifier implications
No new abstract state, transfer function, diagnostic code or trusted exemption. Existing call, slice initialization/lifetime, bounds, shared/exclusive alias and enum payload/match rules apply. Size guards do not discharge alias checks. Overlap rejects; proven disjoint split_at siblings from one allocation work. All results are ordinary Copy values, with existing qualified type/constructor/pattern syntax and no must-use rule.
Interpreter / runtime implications
No runtime primitive or profile change. Ordinary source branches, shifts/masks, fixed frame arrays, slice accesses and enums implement the algorithms. UTF-8 checks remaining capacity before continuation accesses and restricted second-byte ranges before scalar assembly. Validation advances only by a successful 1..4-byte count bounded by the remaining slice.
Hex encode checks src.len <= dst.len / 2 before multiplying. Base64 encode checks whole groups against dst.len / 4, then tail capacity before summing. This avoids overflow in src.len + 2, group multiplication or output offsets. Decode first validates digits/groups/padding/unused bits, computes the bounded decoded count, then checks capacity before writing. Padding is never interpreted as a data symbol.
Reference work is O(input length), with constant auxiliary storage: a 16- or 64-byte alphabet and/or 256-byte inverse map. Frame storage is explicit source; no heap or hidden cursor exists. All functions declare effects [], are deterministic in both profiles and do not produce bounds/arithmetic/cast/shift traps for valid slices. Malformed/truncated input and capacity failure are ordinary results. Fuel exhaustion remains an environment outcome; destination preservation covers returned errors, not interruption mid-operation.
AIR changes
None. Algorithms use existing calls, arithmetic, arrays, ownership/borrows and enum.make/enum.switch; the normal combined feature closure is emitted. There is no opcode, type kind, instruction contract, feature registry entry or altered format-0 meaning. Three new registry entries embed safe source through the existing frontend and verifier.
Valid example
module example
import std.utf8;
fn first(src: slice<u8>) -> u32
effects []
{
match std.utf8.next(ref src) {
std.utf8.NextResult::ok(scalar, count) => { return scalar; }
std.utf8.NextResult::end => { return 0; }
std.utf8.NextResult::invalid_input => { return 0; }
}
}
examples/std/text.aji combines hex decoding, UTF-8 validation, Base64 encoding and scalar decoding, returning 8364 (U+20AC). Its conformance copy is text_example.aji, and the API reference includes that checked program. text_utf8_iteration.aji demonstrates explicit offsets and four scalar widths. text_disjoint.aji encodes/decodes between disjoint halves of one allocation.
Rejected example
module example
import std.encoding.hex;
fn main() -> u8
effects []
{
var buf: [u8; 4] = zero;
let result = std.encoding.hex.decode(mut buf, ref buf);
return 0;
}
Existing E2101 reports the conflicting borrow and call argument conflict; text_hex_alias.aji captures both. Base64 encode has the same negative test. Wrong result payloads and passing the hex result as a Base64 result reject with E7005; imported modules keep distinct enum identities.
Diagnostics impact
No new codes. Wrong operands/payloads use E7005 (AIR payload test E1001); missing/unknown imports use E7002; incomplete result matches use E7004; conflicting input/output borrows use E2101. Source diagnostic types and provenance retain public paths. Invalid byte sequences are returned variants, not compiler diagnostics or traps. Existing enum wildcard/duplicate rules continue unchanged.
Spec integration
- Spec 16 §2: five-module registry and stable bundled source paths.
- Spec 16 §2.5–§2.7: UTF-8 scalar/offset rules, codec signatures, capacity/validation/mutation, complexity, safety and compatibility.
- Spec 15 §13: provenance refers to the registry table; no new syntax/lowering rule.
- Reference/Quick Reference/bundle navigation: on-demand API contracts and checked example, with existing result handling.
- Plan STD-2a/2b and Q-030: this scope is complete only after checks; supplied-buffer formatting remains pending.
Compatibility and migration
AIR format 0, source syntax, existing APIs, verifier/runtime rules and capability/effect contracts retain their meanings. Unknown imports now recognize three additional compiler-pinned modules; no filesystem/network/package resolution or dependencies are introduced. Each module is self-contained and uses full standard type paths. Lexicographic composition, collision suffixes and stable diagnostics work at four-component paths; unit tests cover all five imports in different orders and directory names. No migration is required. Q-027's empty byte literal gap remains; empty fixtures use zero-length slices.
Agent complexity impact
- New concepts: scalar-level UTF-8 with explicit consumed count/validation offset; caller-output codec operations; strict canonical Base64 acceptance. No owning string/iterator or borrowed aggregate.
- New verifier state: none. No additional lifetime, alias, allocation, capability, cleanup or concurrency obligation.
- New syntax/instructions: none. Six function names and six ordinary Copy enum names are read on demand; nested standard paths use the existing parser/linker.
- Interactions: existing enum payloads/exhaustiveness, slices/sub-slices/disjoint splits, frame arrays, checked arithmetic/short-circuit guards, compiler-pinned imports and fuel.
- Repairability: a returned decode failure has no partial output state; empty input and valid zero-length output are explicit; UTF-8 error offsets identify a sequence start. Callers must still handle/check Copy results under existing rules. No measured model capability reduction is claimed.
- Existing primitives suffice; pure source avoids a runtime codec trusted boundary. Scalar/offset iteration and fixed tables avoid adding iterator machinery, generics or allocation contracts.
- New source diagnostics: zero. Quick Reference adds a routing paragraph; complete signatures, malformed-input/capacity policy and a checked example stay in on-demand
library/std.md.
Measured against STD-1b (6397a31) with zig build agent-reference and HF_HUB_OFFLINE=1 uv run --with tiktoken --with tokenizers tools/agent_bundle_tokens.py --source:
| Group | cl100k before → after | o200k before → after | Qwen2.5 before → after |
|---|---|---|---|
Quick Reference (QUICK.md, includes navigation) |
6,082 → 6,163 (+1.3%) | 6,102 → 6,184 (+1.3%) | 6,272 → 6,356 (+1.3%) |
| Other source docs | 33,628 → 36,042 (+7.2%) | 33,718 → 36,159 (+7.2%) | 34,572 → 37,048 (+7.2%) |
| Full source docs without AIR | 39,710 → 42,205 (+6.3%) | 39,820 → 42,343 (+6.3%) | 40,844 → 43,404 (+6.3%) |
| AIR docs in the source bundle | 42,454 → 42,454 | 42,602 → 42,602 | 43,827 → 43,827 |
Standalone AIR stays 160,797 bytes, 48 sections and 19 files. Incremental source growth is below the 10% warning threshold. The on-demand library page grows from 4,223/4,229/4,367 to 6,644/6,677/6,849 tokens: six APIs require scalar validity, first-sequence versus whole-input handling, exact error offsets, canonical byte acceptance, capacity priority and unchanged-output contracts, plus one checked composition example. Quick Reference only adds a routing paragraph and changes the navigation row; catalogs remain on demand.
Cumulatively since the pre-stdlib source baseline in RFC 0016, source docs excluding AIR grow from 33,981 to 42,205 cl100k tokens (+24.2%), crossing the 20% review line. This growth is explicit for owner review: the five-module library has 35 functions and 13 result enums, all algorithm contracts live on demand, and there is no new verifier state, syntax or AIR documentation. The Quick Reference grows from 5,511 to 6,163 (+11.8%); future increments should split/selectively expose library references instead of extending its catalog. Documentation growth is not evidence of model capability compression; API/read/repair costs still need empirical review.
Branch checks: build, unit/Quick Reference checks, full conformance (529 passed, zero failed/pending), formatting, source coverage (72/72), agent-reference and hosted file/stdin/TCP smoke pass. The executable text example returns 8364 without grants. Twenty-four new tests cover all 256 single bytes for UTF-8, 139 fixed valid and 608 malformed/prefixed scalar-sequence cases, four-width explicit iteration, 276 independent valid vectors per encoding (including empty and every single byte), 242 malformed hex and 296 malformed Base64 vectors, every relevant capacity, untouched suffixes, invalid-input precedence, noncanonical pad bits, proven disjoint same-allocation operations, alias rejection and module/type collision rules. Source runs compare with hand-written AIR scalar/encoded-byte fixtures; AIR payload typing rejects with E1001. All run tests execute twice for determinism. Unit checks compare canonical lowering for all five imports in different orders/directories and preserve all bundled source paths without heap/capability/intrinsic instructions.
Alternatives considered
Replacement decoding hides malformed input; streaming recovery needs a separate explicit state contract. Silent partial output makes post-failure byte validity caller-dependent. Permissive Base64, URL-safe switches and optional padding multiply accepted forms; they can be separate independently justified APIs later. Hidden growing strings/iterators need allocation and lifetime features beyond this step. Returning a borrow or aggregate iterator is unnecessary when a scalar and consumed count suffice. Runtime intrinsics add trusted code for operations safe source can already express.
Unresolved questions
Q-030 records the codec policy as resolved on this branch. Streaming UTF-8/codecs, URL-safe Base64, Unicode normalization/properties, owning strings, generic results and must-use values remain separate work. STD-2b still needs a minimal formatting contract; this RFC does not claim formatting is implemented.