# Standard library API Normative contracts: spec 16. Import rules: spec 15 §13. These modules are bundled with the compiler, with no external source dependencies. Allocation authority is explicit for std.vec/std.deque/std.map/std.hashmap/std.hashset/std.heap new/reserve and std.io.reader/std.io.writer new. Except std.io/std.io.reader/std.io.writer (§2.17–§2.18) and std.vec/std.deque/std.map/std.hashmap/std.hashset/std.heap new/reserve, functions below declare `effects []`, allocate no heap memory and retain no borrows. Pass arrays/slices using explicit `ref` or `mut`. Names are fully qualified; no alias or short-name import exists. | Module | Function signature | Result/failure | |---|---|---| | `std.math` | `min_u64(a: u64, b: u64) -> u64` | smaller operand | | `std.math` | `max_u64(a: u64, b: u64) -> u64` | larger operand | | `std.math` | `clamp_u64(value: u64, lower: u64, upper: u64) -> u64` | inclusive clamp; `T0002` if `lower > upper` | | `std.bytes` | `equal(a: slice, b: slice) -> bool` | byte equality | | `std.bytes` | `compare(a: slice, b: slice) -> i8` | unsigned lexicographic order: exactly -1/0/1 | | `std.bytes` | `find(data: slice, byte: u8) -> usize` | first index; `data.len` if absent | | `std.bytes` | `starts_with(data: slice, prefix: slice) -> bool` | empty prefix matches | | `std.bytes` | `ends_with(data: slice, suffix: slice) -> bool` | empty suffix matches | | `std.bytes` | `fill(dst: slice_mut, byte: u8) -> void` | fills caller-provided storage | ```aji module demo.standard import std.bytes; import std.math; fn main() -> u64 effects [] { var data: [u8; 4] = zero; std.bytes.fill(mut data, 65); assert(std.bytes.equal(ref data, b"AAAA")); let index = std.bytes.find(ref data, 65); if index < data.len { assert(data[index] == 65); } return std.math.clamp_u64(42, 0, 100); } ``` Unknown module/member or absent import: `E7002`; duplicate import: `E7006`; malformed import or type arguments: `E7001`; wrong argument type/arity: `E7005`; conflicting borrows: `E2101`. No new diagnostic code. The example is `tests/conformance/source/quickref/std.aji`; library boundary and algorithm tests live under `tests/conformance/source/std/`. ## Endian integers All functions operate at slice offset zero. Pass a sub-slice to select an offset. Extra bytes are ignored on read and preserved on write. No alignment or heap allocation is required. A short destination is unchanged; a short source yields no integer payload. | Width | Read functions (`src: slice`) | Result | Write functions (`dst: slice_mut, value: uW`) | Result | |---|---|---|---|---| | 16 | `std.bytes.read_u16_le`, `std.bytes.read_u16_be` | `std.bytes.ReadU16` | `std.bytes.write_u16_le`, `std.bytes.write_u16_be` | `std.bytes.WriteResult` | | 32 | `std.bytes.read_u32_le`, `std.bytes.read_u32_be` | `std.bytes.ReadU32` | `std.bytes.write_u32_le`, `std.bytes.write_u32_be` | `std.bytes.WriteResult` | | 64 | `std.bytes.read_u64_le`, `std.bytes.read_u64_be` | `std.bytes.ReadU64` | `std.bytes.write_u64_le`, `std.bytes.write_u64_be` | `std.bytes.WriteResult` | Read enums have exactly `ok(uW)` and `short_input`. `WriteResult` has exactly `ok` and `short_output`. These are ordinary Copy enums, handled with qualified enum patterns; they are not intrinsic outcome matches. They can be passed or returned through user functions. No generic must-use rule is introduced. ```aji module demo.endian import std.bytes; fn main() -> u32 effects [] { var wire: [u8; 6] = zero; match std.bytes.write_u32_be(mut wire[1..5], 0x12345678) { std.bytes.WriteResult::ok => {} std.bytes.WriteResult::short_output => { return 0; } } match std.bytes.read_u32_be(ref wire[1..5]) { std.bytes.ReadU32::ok(value) => { return value; } std.bytes.ReadU32::short_input => { return 0; } } } ``` Missing enum arm: `E7004`; duplicate/wildcard enum arm: `E7006`; unknown type/variant or missing import: `E7002`; wrong width/payload, immutable destination or variant from another enum: `E7005`; conflicting destination borrows: `E2101`. Existing `or trap` only applies to fallible built-in operations, so it is not used with these enums. The example is checked in `source/quickref/std_endian.aji`; fixtures for every width/order and all short lengths are in `source/std/endian_u*.aji`. ## Non-cryptographic hashing and CRC-32C Directly import `std.hash`. All four functions are ordinary safe source, `effects []`, with no heap allocation, mutation, retained borrow or capability requirement. | Function | Result | |---|---| | `std.hash.fnv1a64(data: slice) -> u64` | FNV-1a 64, offset basis `0xcbf29ce484222325` | | `std.hash.fnv1a64_extend(state: u64, data: slice) -> u64` | continue from the supplied state | | `std.hash.crc32c(data: slice) -> u32` | finalized Castagnoli CRC; empty input gives zero | | `std.hash.crc32c_extend(checksum: u32, data: slice) -> u32` | continue from a finalized checksum, undo/reapply final XOR | Extend with the previous result and the next bytes: `crc32c_extend(crc32c(prefix), suffix)` equals CRC of their concatenation. Empty input preserves any supplied continuation value. FNV wraps multiplication modulo 2^64; CRC uses reflected polynomial `0x82f63b78` and initial/final XOR `0xffffffff`. Every byte participates, including zero; there are no implicit separators or padding. Numeric results are target-independent; serialize explicitly with `std.bytes.write_u32/u64_le/be`. These are not cryptographic functions, and CRC-32C is not IEEE CRC-32. A hash collision never establishes key equality. Structured fields need explicit byte encoding and boundaries. The [checked example](../../examples/std/hash.aji) computes CRC-32C of `123456789` (`0xe3069283`) in two chunks, hashes `foobar` and serializes the CRC little-endian. Empty slices use an existing array's `ref data[0..0]`; an empty byte literal has no array type. Calls cost O(bytes) work and O(1) auxiliary state; CRC initially uses eight bit steps per byte. Borrow/type/import errors keep E2101/E7005/E7002, and these monomorphic functions take no generic arguments. Definition/constants: [FNV RFC 9923](https://www.rfc-editor.org/rfc/rfc9923.html#section-2); independent published CRC vectors: [RFC 3720 B.4](https://www.rfc-editor.org/rfc/rfc3720.html#appendix-B.4). Exact recurrence is spec 16 §2.12. ## Copy and substring search | Function | Result and contract | |---|---| | `std.bytes.copy(dst: slice_mut, src: slice) -> std.bytes.WriteResult` | `ok` copies the whole input into the output prefix, preserving the suffix; `short_output` leaves the whole output unchanged. Empty input succeeds. Overlap rejects (`E2101`), including on the error path. | | `std.bytes.find_slice(data: slice, needle: slice) -> std.bytes.FindResult` | `found(index)` for the first match, or `not_found`. Empty needle is `found(0)`, including empty data. Offset is relative to the passed slice; it need not be a readable element index. | Search allocates no heap and uses constant auxiliary storage; the reference algorithm has O(data length × needle length) worst-case comparisons. Interpreter fuel bounds execution. For splitting at the first separator, match the search result, then take `data[0..index]` and `data[index + separator.len..data.len]`, or split at the index and borrow past the separator in the right half. An empty separator leaves the whole data in the right half; repeated splitting needs an explicit progress rule. There is no split iterator or returned pair of borrowed slices. ## Recoverable arithmetic | Operand type | Functions | Result | |---|---|---| | `u64` | `std.math.checked_add_u64`, `std.math.checked_sub_u64`, `std.math.checked_mul_u64` | `std.math.U64Result::ok(u64)` / `overflow` | | `usize` | `std.math.checked_add_usize`, `std.math.checked_sub_usize`, `std.math.checked_mul_usize` | `std.math.UsizeResult::ok(usize)` / `overflow` | Every function takes two operands of the indicated type. A representable mathematical result succeeds; unsigned subtraction underflow also returns `overflow`. Multiplication by zero always succeeds with zero. `usize` follows target pointer width. Normal arithmetic operators still trap on overflow; wrapping uses `+%`, `-%`, `*%`, with no library wrappers. These monomorphic APIs do not provide generic or signed arithmetic. Result enums use the same ordinary match rules as the endian results. For a zero-terminated byte record, check the complete output size before copying: ```aji fn encode(dst: slice_mut, data: slice) -> usize effects [] { match std.math.checked_add_usize(data.len, 1) { std.math.UsizeResult::ok(total) => { if total > dst.len { return 0; } match std.bytes.copy(mut dst, ref data) { std.bytes.WriteResult::ok => { dst[data.len] = 0; return total; } std.bytes.WriteResult::short_output => { return 0; } } } std.math.UsizeResult::overflow => { return 0; } } } ``` This helper returns the encoded byte count or zero on failure, and leaves the destination unchanged on failure. Import both `std.math` and `std.bytes`. Its zero sentinel is unambiguous because a successful record includes the terminator. The checked [bounded example](../../examples/std/bounded.aji) combines overflow-aware output sizing, whole-input copy and delimiter search; it returns 10. Copy/search/split and independent arithmetic fixtures are in `source/std/bounded_*.aji`. Wrong operands/payloads are `E7005`; absent imports/types are `E7002`; missing result arms are `E7004`. No new diagnostic code, syntax, verifier state or runtime primitive is introduced. ## UTF-8 and encodings | Function | Result and contract | |---|---| | `std.utf8.next(src: slice) -> std.utf8.NextResult` | `ok(scalar: u32, consumed: usize)` for the first scalar, `end` for empty input, or `invalid_input` for a bad/truncated first sequence; trailing bytes do not affect a successful first decode. | | `std.utf8.validate(src: slice) -> std.utf8.ValidateResult` | `ok` for wholly valid bytes, including empty input; `invalid_input(offset)` at the beginning of the first bad/truncated sequence. | | `std.encoding.hex.encode(dst: slice_mut, src: slice) -> std.encoding.hex.EncodeResult` | lowercase ASCII hex; `ok(count)` or `short_output`. | | `std.encoding.hex.decode(dst: slice_mut, src: slice) -> std.encoding.hex.DecodeResult` | even-length ASCII digits, upper/lower/mixed case; `ok(count)`, `invalid_input` or `short_output`. | | `std.encoding.base64.encode(dst: slice_mut, src: slice) -> std.encoding.base64.EncodeResult` | standard alphabet with canonical padding and zero unused bits; `ok(count)` or `short_output`. | | `std.encoding.base64.decode(dst: slice_mut, src: slice) -> std.encoding.base64.DecodeResult` | canonical standard Base64 only; `ok(count)`, `invalid_input` or `short_output`. | UTF-8 uses shortest scalar encodings, excluding surrogates and values above U+10FFFF. NUL, BOM, noncharacters and unassigned scalars are accepted; validation does not normalize or replace bytes. Iteration repeatedly calls `next(ref data[offset..data.len])` and advances offset by the returned consumed count. `next` validates its first sequence only, so validate the whole slice when that is the required contract. A malformed final prefix is `invalid_input`, not a streaming "need more" result. [UTF-8 rules: RFC 3629 §3/§4](https://www.rfc-editor.org/rfc/rfc3629.html#section-3). Encoders check complete capacity before writing; decoders check the entire input first, then capacity. Invalid input takes precedence over short output. Every returned error preserves the whole destination. Success writes a prefix, preserves remaining output and appends no terminator. Empty encoding/decoding succeeds with `ok(0)`, including zero capacity. Mathematical lengths too large for usize/output are `short_output`, checked without overflowing an intermediate. Input/output cannot overlap; disjoint `split_at` siblings from the same allocation are allowed. These guarantees do not cover interpreter fuel interruption. Hex decoding rejects whitespace, prefixes, separators, odd length and non-hex bytes. Base64 uses the standard `+/` alphabet; incomplete final groups require `=` padding, and complete groups omit it. Decoding rejects whitespace, URL-safe symbols, incomplete groups, misplaced/excess padding and nonzero unused bits. This is a deliberate strict policy permitted by [RFC 4648 §3.5/§4](https://www.rfc-editor.org/rfc/rfc4648.html#section-3.5); no permissive or URL-safe mode is implied. ```aji module demo.text import std.bytes; import std.encoding.hex; import std.encoding.base64; import std.utf8; fn main() -> u32 effects [] { var utf8: [u8; 3] = zero; match std.encoding.hex.decode(mut utf8, b"E282AC") { std.encoding.hex.DecodeResult::ok(count) => { assert(count == 3); } std.encoding.hex.DecodeResult::invalid_input => { return 0; } std.encoding.hex.DecodeResult::short_output => { return 0; } } match std.utf8.validate(ref utf8) { std.utf8.ValidateResult::ok => {} std.utf8.ValidateResult::invalid_input(offset) => { return 0; } } var encoded: [u8; 4] = zero; match std.encoding.base64.encode(mut encoded, ref utf8) { std.encoding.base64.EncodeResult::ok(count) => { assert(count == 4); } std.encoding.base64.EncodeResult::short_output => { return 0; } } assert(std.bytes.equal(ref encoded, b"4oKs")); match std.utf8.next(ref utf8) { std.utf8.NextResult::ok(scalar, count) => { assert(count == 3); return scalar; } std.utf8.NextResult::end => { return 0; } std.utf8.NextResult::invalid_input => { return 0; } } } ``` The [text example](../../examples/std/text.aji) is checked by `source/std/text_example.aji` and returns 8364 (U+20AC). Independent byte/scalar vectors, capacities, invalid-input precedence, namespace collisions, alias rejects and disjoint buffers are under `source/std/text_*.aji`. UTF-8/encoding algorithms allocate no heap and declare `effects []`; fixed local tables are constant auxiliary storage. Wrong operands/payloads: `E7005`; missing result arms: `E7004`; unknown types/imports: `E7002`; conflicting borrows: `E2101`. Results are ordinary Copy enums with no new must-use rule. ## Integer formatting (`std.fmt`) Import `std.fmt`. Its four functions share `std.fmt.WriteResult::ok(count: usize)` / `short_output`: | Function | Value type | |---|---| | `write_u64(dst: slice_mut, value: u64)` | unsigned 64-bit | | `write_i64(dst: slice_mut, value: i64)` | signed 64-bit | | `write_usize(dst: slice_mut, value: usize)` | unsigned target pointer width | | `write_isize(dst: slice_mut, value: isize)` | signed target pointer width | Output is decimal ASCII with no leading zeroes, plus sign, padding or terminator; negative values begin with `-` and zero is `0`. Every scalar value is supported, including signed minima. Success writes the prefix and preserves the suffix; short capacity preserves the entire output. Empty output is short even for zero. No heap allocation, cursor or format string exists. Full contracts are in spec 16 §2.8. Compose byte literals and integers using explicit offsets, advancing only after a successful operation: ```aji module demo.format import std.bytes; import std.fmt; fn main() -> usize effects [] { var record: [u8; 24] = [165; 24]; match std.bytes.copy(mut record, b"value=") { std.bytes.WriteResult::ok => {} std.bytes.WriteResult::short_output => { return 0; } } var offset: usize = 6; match std.fmt.write_i64(mut record[offset..record.len], -42) { std.fmt.WriteResult::ok(count) => { offset = offset + count; } std.fmt.WriteResult::short_output => { return 0; } } match std.bytes.copy(mut record[offset..record.len], b" count=") { std.bytes.WriteResult::ok => { offset = offset + 7; } std.bytes.WriteResult::short_output => { return 0; } } match std.fmt.write_usize(mut record[offset..record.len], 7) { std.fmt.WriteResult::ok(count) => { offset = offset + count; } std.fmt.WriteResult::short_output => { return 0; } } assert(std.bytes.equal(ref record[0..offset], b"value=-42 count=7")); for i in offset..record.len { assert(record[i] == 165); } return offset; } ``` This checked program is `examples/std/format.aji` and `tests/conformance/source/std/fmt_example.aji`. It returns 17 without grants. Each operation preserves its own destination on short output; a sequence is not transactional across earlier successful calls. Existing alias checks apply even when a write would return short output. Smaller scalar widths require an explicit widening conversion to an appropriate writer; wider integers, float formatting and parsing are outside this increment. ## Copy option/result templates Requires direct `import std.option;` / `import std.result;`; explicit generic spelling is spec 15 §15. | Declaration | Contract | |---|---| | `std.option.Option` | `some(T)`, `none` | | `std.option.is_some(value: Option) -> bool` | true for some; false for none; effects [] | | `std.result.Result` | `ok(T)`, `err(E)` | | `std.result.is_ok(value: Result) -> bool` | true for ok; false for err; effects [] | All are ordinary safe source/static specialization, with no allocation or authority. Generic helper calls use `is_some::(value)` / `is_ok::(value)`. Constructors and patterns use `std.option.Option::::some(value)` or `std.result.Result::::err(code)`; names and variant matches remain explicit even for none. Extract values by exhaustive match; an err variant is not intrinsic outcome syntax. Owners/resources/endpoints make these enums linear under spec 03 §25 and require exhaustive `match move`. Borrows remain invalid members; Copy classification helpers reject linear arguments with E7005. No must-use or implicit unwrap/default/conversion is introduced. [Checked example](../../examples/std/generics.aji) returns 42 without grants. ## Owning vectors Import std.vec; every function supplies explicit `::`. Vec contains a buffer and is always linear. No implicit growth or cleanup occurs. The storage field follows ordinary aggregate visibility/borrow rules. New/reserve require cap and effects [mem.alloc]; all other functions declare effects []. | Function | Parameters | Result | |---|---|---| | new | capacity: usize, heap: cap | NewResult: ok(Vec) / err(alloc_error) | | len / capacity | value: ref> | usize | | reserve | value: mut>, capacity: usize, heap: cap | ReserveResult: ok / err(alloc_error) | | push | value: mut>, item: T | PushResult: ok / full(T) | | pop | value: mut> | std.option.Option: some(T) / none | | free | value: Vec | FreeResult: ok / not_empty(Vec) | | get | value: ref>, index: usize | std.option.Option: some(T) / none | | replace | value: mut>, index: usize, item: T | ReplaceResult: ok(old_value: T) / out_of_bounds(original_item: T) | Growth has an old+new capacity allocation peak. Failure preserves capacity/length/elements; full push and out-of-bounds replacement return the exact input. Nonempty free returns the vector; pop/consume all elements before retrying. get returns none out of bounds, replace returns the old complete element on success. Generic moves compose Copy and linear types. Qualified variants require direct imports (including std.option for pop/get). [Executable owning vector](../../examples/std/vector.aji) returns 42 with heap=mem.alloc:256. Views and nested element borrows cannot escape or overlap shape changes. Normative contracts: spec 16 §2.10 and spec 03 §26. ## Owning deques Import std.deque; every operation supplies `::`. Deque is always linear and has bounded ring capacity. Pop transfers complete values. No operation grows except explicit reserve. New/reserve declare mem.alloc and take explicit authority; all others declare effects []. | Function | Parameters | Result | |---|---|---| | new | capacity: usize, heap: cap | NewResult: ok(Deque) / err(alloc_error) | | len / capacity | value: ref> | usize | | reserve | value: mut>, capacity: usize, heap: cap | ReserveResult: ok / err(alloc_error) | | push_front / push_back | value: mut>, item: T | PushResult: ok / full(original_item: T) | | pop_front / pop_back | value: mut> | std.option.Option: some(T) / none | | free | value: Deque | FreeResult: ok / not_empty(Deque) | | get | value: ref>, index: usize | std.option.Option: some(T) / none | | replace | value: mut>, index: usize, item: T | ReplaceResult: ok(old_item: T) / out_of_bounds(original_item: T) | Indices count from the front. Full pushes, out-of-bounds replaces and nonempty free preserve the queue and return ownership. Allocation failure also preserves physical slots/head/length. Successful growth preserves logical order, resets head and charges the old+new capacities at the peak; no shrink occurs. Every slot is an Option (tag plus payload), including free slots: capacity 3 of own charges 27 bytes. Empty free explicitly drains internal none slots; it never destroys a user's T. Callers pop and consume resources before freeing; match move on linear result values and import std.option to name pop/get variants. End operations and indexing use constant slot work; construction/growth/free use O(capacity) work. Interpreter representation costs remain those of buffer primitives. Deque fields are ordinarily visible; direct representation writes/construction must preserve spec 16 §2.11's ring invariant. Library calls maintain it. [Executable owning deque](../../examples/std/deque.aji) returns 42 with heap=mem.alloc:1024. There is no iterator, returned borrow, trait hierarchy or implicit allocation/cleanup. Existing alias, task-loan and Copy/Send/Share checks apply. ## Owning numeric-key maps Import `std.map`; each generic operation supplies `::`. `U64Map` is always linear, uses exact u64 key equality and supports Copy values, owners, files and sender endpoints. Hashes select probe positions; they never establish key equality. General keys use `std.hashmap` with explicit hash/equality (§2.14). | Operation | Return / ownership | |---|---| | `new(capacity: usize, heap: cap)` | `NewResult::ok(U64Map)` / `err(alloc_error)` | | `len(map: ref>) -> usize` | entry count | | `capacity(map: ref>) -> usize` | maximum live entries before a new key returns full | | `reserve(map: mut>, capacity: usize, heap: cap)` | `ReserveResult::ok` / `err(alloc_error)`; grow explicitly, preserve every slot on returned failure | | `insert(map: mut>, key: u64, value: V)` | `InsertResult::inserted` / `replaced(V)` / `full(V)` | | `contains(map: ref>, key: u64) -> bool` | presence without copying V | | `get(map: ref>, key: u64)` | `std.option.Option` copied lookup | | `remove(map: mut>, key: u64)` | `std.option.Option` moved removal | | `pop(map: mut>)` | `std.option.Option>`; Entry has key: u64, value: V | | `free(map: U64Map)` | `FreeResult::ok` / `not_empty(U64Map)` | Only new/reserve declare `effects [mem.alloc]` and take allocation authority. No operation implicitly grows. Full insertion returns the exact input; replacement works even when full and returns the old value. Callers must explicitly consume owning results and drain before free. Use `ref map` for reads and `mut map` for mutation, including explicit shared reborrows from mut parameters. Representation: `U64Map { storage: buffer>, length: usize }`, `Slot { key: u64, state: SlotState, value: std.option.Option }`, `SlotState { empty, deleted, occupied }`. Occupied implies some(V), vacancies imply none, keys are unique and reachable, and length equals occupied count. Direct representation writes must preserve spec 16 §2.13's invariant. Capacity N allocates and initializes 2N physical slots, with both enum tags charged. N=0 allocates no bytes. Both whole tables and user allocations count toward growth's peak quota; old storage is refunded to its original authority. Overflowing size returns budget_exceeded. Lookup traverses deleted slots, compares original keys and terminates after bounded probes, even with no empty slots. Pop drains physical-index order; successful rehash may change this deterministic order. Worst-case probe work is O(N); collision-heavy growth is O(N²). Existing borrow, task-loan, Copy/Send/Share and resource diagnostics apply. The [owning example](../../examples/std/map.aji) returns 42 with heap=mem.alloc:256. ## Owning general-key maps Import `std.hashmap` and `std.option` for lookup/extraction results. `HashMap` stores complete keys and values, including owning byte buffers, structs, owners, files and channel endpoints. The two declared functions have exactly `fn(ref) -> u64 effects []` / `fn(ref,ref) -> bool effects []`. Equality is stable equivalence and equal keys must hash equally; hash equality alone never identifies a key. Do not change a live key's hash/equality. Different bound functions produce distinct nominal map types. Operations never capture state or gain authority from selection. Every call supplies `::` (get additionally requires V: Copy, without requiring K: Copy): | Function arguments | Result | |---|---| | new(capacity: usize, heap: cap) | NewResult: ok(HashMap), err(alloc_error) | | len(map: ref) | usize live count | | capacity(map: ref) | usize maximum live entries | | reserve(map: mut, capacity: usize, heap: cap) | ReserveResult: ok, err(alloc_error) | | insert(map: mut, key: K, value: V) | InsertResult: inserted, replaced(Entry), full(Entry) | | contains(map: ref, key: ref) | bool | | get(map: ref, key: ref) | std.option.Option copied value | | remove(map: mut, key: ref) | std.option.Option> moving extraction | | pop(map: mut) | std.option.Option> moving extraction | | free(map: HashMap) | FreeResult: ok, not_empty(HashMap) | Here HashMap abbreviates the fully applied type, and Entry has key: K/value: V. Pass `ref q` when querying through mut q; ownership transfer of named linear K/V requires move. Replacement returns both old resources and retains the new equivalent key. Full insert returns both original inputs. Explicitly consume every owning result; free returns the nonempty map. get cannot copy an owned V, while contains/remove work without Copy requirements. No borrowed value/cursor escapes. Only new/reserve allocate and declare mem.alloc with explicit authority. Growth has no implicit trigger and returned failure preserves every old entry/bucket and pop order. A capacity N reserves N StoredEntry slots (hash + full K/V sizes) and 2N Copy Bucket slots (hash + usize + state tag). Live entries form an initialized dense prefix, with a separate probe-index table and cached hashes. Removing a middle entry exchanges the last into its position, repairing the index. Pop drains reverse current dense order; reserve preserves it and clears tombstones. Zero capacity is valid. Peak growth includes both entry buffers, both index buffers and external user owners; refunds follow the recorded allocation capabilities. Capacity-one Key{id:u64}/own reserves 58 bytes, plus 8 for the owned payload in the [checked example](../../examples/std/hashmap.aji), which runs with heap=mem.alloc:66. Representation fields are ordinary visible source; manual construction/mutation must preserve the full invariant in spec 16 §2.14. Hash/equality traps and fuel exhaustion are abnormal outcomes. Existing moves, alias/task-loan and Copy/Send/Share rules apply without unsafe or map-specific runtime semantics. Worst-case lookup/insert/remove/pop is O(N) plus callback work, rehash O(N²); no adversarial collision/native-throughput guarantee is made. `std.map.U64Map` retains its existing API for numeric keys. ## Owning general-key sets Import `std.hashset` and `std.option` for extraction results. `HashSet` uses the map's exact pure `fn(ref) -> u64 effects []` / `fn(ref,ref) -> bool effects []` contracts and stable equality/hash laws. Complete owning keys, including byte buffers and resource-bearing structs, need no Copy constraint. Every operation supplies `::`: | Function arguments | Result | |---|---| | new(capacity: usize, heap: cap) | NewResult: ok(HashSet), err(alloc_error) | | len(set: ref) | usize live count | | capacity(set: ref) | usize maximum live keys | | reserve(set: mut, capacity: usize, heap: cap) | ReserveResult: ok, err(alloc_error) | | insert(set: mut, key: K) | InsertResult: inserted, present(K), full(K) | | contains(set: ref, key: ref) | bool | | remove(set: mut, key: ref) | std.option.Option moving extraction | | pop(set: mut) | std.option.Option moving extraction | | free(set: HashSet) | FreeResult: ok, not_empty(HashSet) | Here HashSet abbreviates the applied type. Duplicate insertion preserves the stored representative and every entry/bucket, returning the original incoming K as present, even at capacity. Full returns the original new key. Remove/pop return stored keys; free returns a nonempty set. Explicitly consume all owning results. Use `move` for named linear inputs and `ref q` for queries through mut q; contains retains no borrow. Replacement requires explicit remove followed by insert. Only new/reserve allocate with mem.alloc and explicit authority. There is no automatic growth or cleanup. The visible representation is `map: std.hashmap.HashMap` with every live value true; callers must preserve spec 16 §2.15's complete invariant. Dense extraction/pop order, failure preservation, peak accounting and refunds follow the map. Each capacity slot charges hash + K + bool and two buckets: 51 bytes for u64, or 59 for Key{id:u64,owner:own}, plus the separately allocated payload. The [owning example](../../examples/std/hashset.aji) returns 42 with heap=mem.alloc:67. Policies may run for membership and again for insertion, with no runtime dispatch or gained authority. Existing moves/aliases/task loans and Copy/Send/Share checks apply. Callback traps/fuel exhaustion are abnormal outcomes. Worst-case membership/insert/remove/pop is O(N) plus callbacks; growth is O(N²) under collisions. No sorted iteration or native-throughput guarantee is made. ## Owning binary heaps Import `std.heap` and `std.option`. `BinaryHeap` stores complete T with an explicit exact `fn(ref,ref) -> bool effects []` operation. before(a,b) means a has higher extraction priority. It must remain a stable strict weak order: irreflexive/transitive, with transitive incomparability. Equivalent items have deterministic extraction for a fixed operation sequence, without a stable tie-order promise. Use `<` for numeric minimum first or `>` for maximum first. Distinct bound operations give distinct nominal types; selection grants no authority. Every call supplies `::`; peek additionally requires T: Copy: | Function arguments | Result | |---|---| | new(capacity: usize, heap: cap) | NewResult: ok(BinaryHeap), err(alloc_error) | | len(value: ref) | usize live count | | capacity(value: ref) | usize maximum live count | | reserve(value: mut, capacity: usize, heap: cap) | ReserveResult: ok, err(alloc_error) | | push(value: mut, item: T) | PushResult: ok, full(T) | | peek(value: ref) | std.option.Option copied root | | pop(value: mut) | std.option.Option moving root extraction | | free(value: BinaryHeap) | FreeResult: ok, not_empty(BinaryHeap) | Here BinaryHeap abbreviates the applied type. Use move for named linear inputs, mut for push/pop/reserve and ref for queries (ref q through a mut parameter). Full push preserves all state, returns the original input and calls no comparator. Empty pop/peek returns none; nonempty free returns the whole heap. Explicitly consume owning full/pop/not_empty results. Peek retains no borrow and cannot copy an owner; complete owning records, files and sender endpoints use pop. Only new/reserve allocate with mem.alloc and explicit authority; growth is never automatic. The visible representation is entries: buffer> / indices: buffer, Entry{position:usize,value:T}. Both initialized lengths/capacities agree. Indices are a permutation of dense positions; each entry points back to its index position, and no child precedes its parent. Callers must preserve spec 16 §2.16's complete invariant. Sifting swaps Copy indices and inverse positions; pop repairs the dense hole through complete exchange. No default T or implicit destruction is needed. New allocates empty entries then indices, refunding entries on second-allocation failure. Reserve allocates/copies new indices before growing entries; returned failure preserves both old buffers, values/positions/indices and extraction order, and refunds temporaries. Success preserves the layout and frees old indices explicitly. Peak quota includes both entry/index buffers and all external user allocations; refunds go to recorded authorities. Zero capacity is valid; size overflow returns budget_exceeded. On air64 each capacity slot costs sizeof(T)+16 bytes. The [owning example](../../examples/std/heap.aji) needs 32 bytes for one Item slot plus 8 for its payload: heap=mem.alloc:40. Existing ownership/alias/task-loan/Send/Share rules apply with no unsafe boundary or new runtime semantics. Callback/fuel traps are abnormal. Abstract push/pop need O(log L) comparisons/swaps, peek O(1), reserve O(L) copies; interpreter prefix-copy/GC costs may add host work. There is no native-throughput guarantee. ## Bounded I/O composition Import `std.io`. Six concrete functions compose existing primitives with caller-provided slices. They never allocate, open/close resources or retain borrows. Effects and authority remain explicit even for empty/no-op paths. File/stream resources are mutably lent and remain owned by the caller on every normal return. | Function | Result | Effects | |---|---|---| | read_exact_stdin(input: cap, destination: slice_mut) | ReadExactResult | io.read | | read_exact_file(input: mut>, destination: slice_mut) | ReadExactResult | fs.read | | read_exact_stream(input: mut, destination: slice_mut) | ReadExactResult | net.read | | read_to_end_file(input: mut>, destination: slice_mut) | ReadToEndResult | fs.read | | copy_file(input: mut>, output: mut>, scratch: slice_mut, limit: usize) | CopyResult | fs.read, fs.write | | copy_file_append(input: mut>, output: mut>, scratch: slice_mut, limit: usize) | CopyResult | fs.read, fs.write | ReadExactResult is ok / eof(completed:usize) / err(ReadError{completed:usize,error:io_error}). Exact reads fill the destination, looping over short reads. Empty destination is ok without I/O. EOF leaves the remaining suffix unchanged. A read error guarantees only the successful prefix; the attempted suffix follows the primitive's failure contract. Bytes outside the supplied destination remain unchanged. ReadToEndResult is eof(completed:usize) / full(completed:usize) / err(ReadError). Full means the supplied buffer was filled; it does not establish whether EOF was reached or unread data remains. Empty destination is full(0), and no extra byte is read/discarded to probe EOF. Growing/owning read-to-end is separate work; fixed-capacity adapters are below. CopyResult is eof(completed:usize) / limit(completed:usize) / err(CopyError{read:usize,confirmed_written:usize,error:io_error}). Copies bound every scratch chunk by remaining limit and stop without probing past it. Exact EOF at the limit reports limit. A read error has both counts equal to earlier completed chunks. A write error includes its consumed input chunk in read; confirmed_written includes only prior successful writes. The failed write may have externally written a prefix: there is no rollback promise or exact failed-output count. Resources remain borrowed for explicit caller cleanup. Zero limit returns limit(0) without I/O, even with empty scratch. Empty scratch with positive limit returns invalid_input with both error counts zero without I/O. No counter exceeds the limit or overflows. Scratch contents after a call are unspecified; bytes outside its slice remain unchanged. The [copy example](../../examples/std/io.aji) uses only fs.read/fs.write entry grants and a fixed frame scratch array, handling results and closing both resources explicitly. Existing fs.write_all/net.send_all/console writes already write all bytes on success, so this increment adds no duplicate write alias. Ordinary alias/task-loan, type/mode, capability and effect checks apply; imports grant nothing. Blocking/fuel/profile errors remain spec 11 behavior, with no hidden timeout, task or unsafe boundary. std.io's concrete contracts are spec 16 §2.17; owning buffered adapters and lexical paths remain forthcoming. ## Owning buffered files Import `std.io.reader` for Reader/file and `std.io.writer` for Writer/file. Import `std.io` directly when spelling read_exact's result, and `std.option` when matching the writer failure state; dependency imports do not expose names to callers. Each adapter owns a fixed initialized buffer and its file. Only new allocates, with an explicit mem.alloc capability, charging N bytes. Zero capacity delegates directly to primitive I/O. Files are never implicitly closed or synced. All file/adapter-bearing results are linear: consume every normal branch explicitly. | Function arguments | Result | Effects | |---|---|---| | std.io.reader.new(input: file, capacity: usize, heap: cap) | NewResult: ok(Reader), err(NewError{file:file,error:alloc_error}) | mem.alloc | | std.io.reader.read(input: mut, destination: slice_mut) | ReadResult: ok(usize), err(io_error) | fs.read | | std.io.reader.read_exact(input: mut, destination: slice_mut) | std.io.ReadExactResult | fs.read | | std.io.reader.finish(input: Reader) | FinishResult: ok(file), unread(Reader) | none | | std.io.reader.discard(input: Reader) | Discarded{file:file,unread:usize} | none | | std.io.writer.new(output: file, capacity: usize, heap: cap) | NewResult: ok(Writer), err(NewError{file:file,error:alloc_error}) | mem.alloc | | std.io.writer.write(output: mut, bytes: slice) | WriteResult: ok, err(WriteError{accepted:usize,error:io_error}) | fs.write | | std.io.writer.flush(output: mut) | FlushResult: ok, err(io_error) | fs.write | | std.io.writer.finish(output: Writer) | FinishResult: ok(file), err(FinishError{writer:Writer,error:io_error}) | fs.write | | std.io.writer.discard(output: Writer) | Discarded{file:file,pending:usize,failed:std.option.Option} | none | Move named files into new and named adapters into finish/discard. Constructor failure returns the exact original file before I/O; it can be closed or reused. Successful finish/discard drains/frees storage and refunds its recorded authority, returning the file for explicit use/close. No implicit growth, cleanup, retained caller borrow or extra authority is introduced. Reader.read copies one cached prefix without refilling; when empty it refills the storage once, then returns a prefix. Thus read can return short even with more data available. Empty destination returns ok(0) without consuming/refilling and does not establish EOF. read_exact loops to fill the destination, using the std.io prefix/EOF/error contract. Reader.finish returns the complete unchanged Reader if cached unread bytes remain. Empty cache permits finish without probing EOF. Discard explicitly abandons unread prefetched bytes and returns their count: the file cursor remains advanced through prefetch, with no rewind. A read error retains ownership/offsets but promises no external cursor rollback or untouched attempted destination suffix. Writer.write fills available storage and flushes a full buffer only when more input needs room. Ending with a full buffer keeps it pending. Empty input on a healthy writer does nothing. A write error reports bytes accepted from that call; accepted includes buffered data and is not an externally written/durable count. Pending data may include earlier calls. At capacity zero a direct failed write reports accepted=0 even if an external prefix was written. Healthy flush of empty storage performs no I/O; successful flush resets used to zero. Any failed external write preserves pending bytes/used and records its first io_error. Every subsequent write, including empty, returns that error with accepted=0; every flush returns it, with no I/O or mutation. Finish returns the complete failed Writer plus error. There is no retry/reset because the failed operation may already have externally written an unknown prefix. Discard returns the file, pending count and failure state; pending can overlap that prefix and is not an exact loss count. Callers can explicitly handle the returned file according to their application protocol. The visible representations are Reader{file,storage,begin,end}, 0≤begin≤end≤N, and Writer{file,storage,used,failed}, 0≤used≤N. Both buffers have initialized length=capacity=N. Caller field access/construction must preserve spec 16 §2.18's complete data/cursor/first-error invariant and must not independently consume/use the internal file/storage. Existing ownership, alias/task-loan, effects and Send/Share checks apply. Adapters can transfer to workers but cannot be shared immutably across tasks because files are non-Share. No unsafe/trusted boundary or new runtime/verifier state is needed. The [copy example](../../examples/std/buffered_io.aji) uses two three-byte buffers (heap=mem.alloc:6), explicitly handles constructor/finish failure and returns the copied byte count, or zero after normal error cleanup. Conformance fixtures include capacities zero/full, unread finish/discard, exact EOF, allocation failure/refunds, worker transfer and rejected ownership/effect/alias cases. Hosted tests exercise read errors and real partial external writes; Linux raises the child file quota after failure to detect forbidden retry. ## Lexical paths Import `std.path`. Six pure operations use byte `/` separators in every profile. They never allocate heap, retain/return a borrow, inspect the filesystem/current directory or grant authority. Backslash, colon and non-UTF-8 bytes are ordinary component bytes; there is no drive/UNC or symlink resolution. Range{start:usize,end:usize} is Copy; callers explicitly borrow ref path[range.start..range.end]. A range is data, and bounds are still checked if it is reused for a different path. | Function arguments | Result | |---|---| | is_absolute(path: slice) | bool: first byte is `/` | | basename(path: slice) | Range of final nonempty raw component, ignoring trailing separators; 0..0 for empty/root-only | | parent(path: slice) | Range of raw prefix before basename, trimming the separator run before it; rooted input retains first `/`; 0..0 for empty/relative leaf | | extension(path: slice) | Range after basename's last dot, excluding dot; empty at basename.end for absent/leading-only/trailing dot or `.`/`..` | | normalize(destination: slice_mut, path: slice) | WriteResult: ok(usize), invalid_input, size_overflow, short_output | | join(destination: slice_mut, base: slice, child: slice) | WriteResult | Queries accept arbitrary bytes, including NUL, and return offsets into the original input, without normalizing it. For a//b///, basename selects b and parent selects a; parent(a/../b) selects `a/..`. Root-only parent selects the first slash; root-only basename is empty. Extension(.profile) is empty, extension(.profile.json) selects json, extension(a..b) selects b, extension(a.) is empty. Empty extension deliberately makes no distinction between no dot and empty suffix. Normalize collapses separator runs and leading slashes, removes `.` and trailing slashes, and cancels each ordinary component followed by `..`. Relative unmatched parents remain leading `..`; parents above root are dropped. Empty/reduced-empty relative input becomes `.`; empty rooted output becomes `/`. Examples: a//b/../c/ → a/c; a/../../b → ../b; /../../a → /a; a/.. → . . Normalization is idempotent. Exactly two leading slashes have no special meaning. Join normalizes absolute child alone, replacing base. Otherwise it normalizes base followed by child as components separated by a slash; an empty base does not introduce a root. Empty child normalizes base, both empty become `.`, and child parents can cancel base components. Examples: /data/a + ../b → /data/b; a + /b → /b; empty + a → a. These transformations give no capability-containment proof. Filesystem primitives still reject normalized relative paths and enforce their granted scopes on absolute ones. Both writers first validate all input bytes: NUL yields invalid_input, including in base when an absolute child replaces it. Invalid input precedes size_overflow, which precedes short_output. Every returned error leaves the entire destination unchanged. Success writes exactly the reported prefix, preserves the suffix and writes no NUL terminator. Only final normalized size must fit: a long component followed by `..` can normalize into one byte of output. Reverse measurement/emission needs fixed frame state and no intermediate buffer or allocation. Work is linear in supplied input/output bytes. Input borrows can overlap each other; destination must be disjoint. Explicit split_at permits source/output in one allocation. Existing type/borrow/task-loan/Send/Share checks apply, including no-op/short-output paths. No unsafe boundary, new language/AIR semantics or hidden effects are needed. Ordinary source functions can return retained views under spec 15 §19; path queries retain their Copy range API. The [pure example](../../examples/std/path.aji) joins into a caller buffer and borrows basename/parent/extension from the returned prefix. The independent Python forward-stack oracle covers normalization/join/query/capacity/idempotence; hosted fixtures confirm filesystem authority remains independent.