Add pinned std.io.reader and std.io.writer using safe source, explicit fixed allocation and file transfer. Finish/discard return complete resources; writer failures preserve pending data and prohibit unsound partial retries. Specify cursor, acceptance, failure and cleanup contracts in spec 16, RFC 0034, the API reference and source bundle. Add standalone conformance, independent byte oracles, task/GC stress, CLI/package/profile checks and hosted partial-write tests with a raised child quota to detect retries. Validation: 1061 conformance cases; 34 buffered cases with per-step GC and 12 schedule seeds; unit/Quick Reference, formatting, hosted smoke, 89 CLI checks, 115 source coverage constructs and reference generation.
62 KiB
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.fmt, std.hash, std.hashmap, std.hashset, std.heap, std.io, std.io.reader, std.io.writer, std.map, std.math, std.option, std.result, std.utf8, std.vec and std.deque. They are implemented in safe .aji; their stable source paths are std/bytes.aji, std/encoding/base64.aji, std/encoding/hex.aji, std/fmt.aji, std/hash.aji, std/hashmap.aji, std/hashset.aji, std/heap.aji, std/io.aji, std/io/reader.aji, std/io/writer.aji, std/map.aji, std/math.aji, std/option.aji, std/result.aji, std/utf8.aji, std/vec.aji and std/deque.aji, respectively. Spec 15 §13 defines imports; the reference API tables are in reference/std.md. Modules other than std.io/std.io.reader/std.io.writer implement deterministic algorithms in every profile and have no concurrency effects; std.io/std.io.reader/std.io.writer follow the profile I/O/blocking rules in §2.17–§2.18 and spec 11. Modules other than std.vec/std.deque/std.map/std.hashmap/std.hashset/std.heap and std.io/std.io.reader/std.io.writer declare effects [] and allocate no heap memory. std.io declares only the concrete I/O effects in §2.17 and allocates no heap storage. std.io.reader/std.io.writer declare mem.alloc only on new and the concrete file effects in §2.18 on read/write/flush/finish; their other operations allocate no heap. std.vec/std.deque/std.map/std.hashmap/std.hashset/std.heap new/reserve declare mem.alloc and require explicit allocation authority (§2.10–§2.11, §2.13–§2.16); their other functions allocate no heap. Ordinary interpreter fuel limits apply.
2.1 std.math
min_u64(a: u64, b: u64) -> u64returns the smaller operand.max_u64(a: u64, b: u64) -> u64returns the larger operand.clamp_u64(value: u64, lower: u64, upper: u64) -> u64returnslowerbelow the range,upperabove it, orvalueinside it. The inclusive range MUST satisfylower <= upper; violation trapsT0002before 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:
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<u8>.
equal(a, b) -> bool: true exactly when lengths and all bytes agree.compare(a, b) -> i8: unsigned-byte lexicographic comparison; returns exactly-1,0or1. The shorter of two matching prefixes sorts first.find(data, byte: u8) -> usize: index of the first occurrence;data.lenwhen 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 (T0008for 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 thandata.fill(dst: slice_mut<u8>, byte: u8) -> void: writes every byte ofdst, 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:
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<u8>) -> std.bytes.ReadUWMUST returnshort_inputwhensrc.len < N, without reading elements. Otherwise it MUST returnok(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, for0 <= i < N.write_uW_ORDER(dst: slice_mut<u8>, value: uW) -> std.bytes.WriteResultMUST returnshort_outputwhendst.len < Nand leave every destination byte unchanged. Otherwise it MUST write exactly the first N bytes in the selected order, leave the remaining bytes unchanged and returnok.
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<u8>, src: slice<u8>) -> 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<u8>, needle: slice<u8>) -> std.bytes.FindResult returns an ordinary Copy enum:
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.
enum NextResult { ok(u32, usize), end, invalid_input }
enum ValidateResult { ok, invalid_input(usize) }
next(src: slice<u8>) -> std.utf8.NextResultMUST returnendexactly when src is empty. Otherwise it MUST decode only the first scalar:ok(value, byte_count)with 1..4 consumed bytes, orinvalid_inputif 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<u8>) -> std.utf8.ValidateResultMUST returnokfor a wholly valid sequence, including empty input. Otherwise it MUST returninvalid_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:
enum EncodeResult { ok(usize), short_output }
enum DecodeResult { ok(usize), invalid_input, short_output }
Each module provides encode(dst: slice_mut<u8>, src: slice<u8>) -> EncodeResult and decode(dst: slice_mut<u8>, src: slice<u8>) -> 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.
2.8 Supplied-buffer integer formatting
std.fmt provides write_u64, write_i64, write_usize and write_isize. Each takes (dst: slice_mut<u8>, value: T) with the named integer type T, and returns std.fmt.WriteResult, an ordinary Copy enum:
enum WriteResult { ok(usize), short_output }
The functions MUST produce the exact ASCII decimal representation of value: 0 for zero, no leading zeroes otherwise, and a leading - exactly for negative signed values. No plus sign, whitespace, padding, locale transformation or terminator is written. usize/isize use the target pointer width (spec 09 §9); all values, including signed minima and unsigned maxima, MUST be supported.
When dst can hold the complete representation, the function MUST write exactly that prefix, preserve every remaining byte and return ok(count) with its length, including any sign. Otherwise it MUST return short_output and leave the entire destination unchanged. Empty output always fails, including for zero. Capacity MUST be checked before any write. To append, the caller passes a sub-slice at an explicit offset and advances it only after success; no implicit cursor, returned borrow, growable string or format-string language is introduced. Text copying uses std.bytes.copy; byte-to-hex encoding remains std.encoding.hex.
The preserved invariant is exclusive writes only within the supplied initialized slice, no escaping borrow, and no partial mutation on returned failure. Functions declare effects [], allocate no heap, use constant scalar auxiliary storage and O(decimal digit count) work. Existing call, initialization, alias, lifetime, bounds and enum verifier rules apply; conflicting live borrows MUST reject even on short output. No new verifier state, runtime rule, diagnostic, AIR feature or authority is added. Valid slices and every scalar value MUST NOT produce arithmetic, cast or bounds traps; interpreter fuel exhaustion remains an environment outcome and is outside the returned-error preservation guarantee. Behavior is identical in deterministic and hosted profiles. Existing APIs, source syntax and AIR format 0 retain their contracts.
2.9 Option and result
The compiler registry MUST also include std.option and std.result. They declare ordinary generic enums:
enum Option<T> { some(T), none }
enum Result<T, E> { ok(T), err(E) }
std.option.is_some<T: Copy>(value: Option<T>) -> bool and std.result.is_ok<T: Copy, E: Copy>(value: Result<T, E>) -> bool declare effects [], allocate no heap and classify the active variant. They neither extract nor implicitly consume any payload. Call them using spec 15 §15's explicit expression arguments, e.g. std.option.is_some::<u64>(value). Types/constructors/patterns are fully qualified and require a direct import; exhaustive matches extract payloads through ordinary enum rules. none still requires a type argument. err(E) is an ordinary enum variant, not the intrinsic outcome shorthand.
Option/Result accept ordinary complete value payloads, including owners/resources/endpoints under linear_aggregates (spec 03 §25, source §16). Their class is structural: an owning specialization is linear even when the active variant is none or a Copy error. It MUST be explicitly moved and exhaustively consumed; unused linear payloads reject E3002. Borrow/storage/function-bound payloads remain forbidden by ordinary member/type rules. is_some/is_ok retain Copy constraints and MUST reject E7005 for linear arguments; they do not consume a resource merely to classify it. Match an owning value explicitly instead. Existing Copy specializations retain behavior. No implicit unwrap/default/conversion or cleanup is added.
2.10 Explicit owning vectors
Compiler-pinned std.vec MUST provide Vec<T> { storage: buffer<T> } and ordinary result enums: NewResult { ok(Vec), err(alloc_error) }, PushResult { ok, full(T) }, ReserveResult { ok, err(alloc_error) }, FreeResult { ok, not_empty(Vec) }, ReplaceResult { ok(T), out_of_bounds(T) }. All payloads follow ordinary complete-value/linearity rules; no implicit destruction occurs. Fields are ordinary visible source fields, not an opaque trusted container.
Public functions use explicit ::<T> specialization: new(capacity:usize,heap:cap<mem.alloc>)→NewResult; len(value:ref<Vec>)→usize; capacity(value:ref<Vec>)→usize; reserve(value:mut<Vec>,capacity:usize,heap:cap<mem.alloc>)→ReserveResult; push(value:mut<Vec>,item:T)→PushResult; pop(value:mut<Vec>)→std.option.Option; free(value:Vec)→FreeResult; get<T:Copy>(value:ref<Vec>,index:usize)→std.option.Option; replace(value:mut<Vec>,index:usize,item:T)→ReplaceResult. Only new/reserve declare effects [mem.alloc]; all other functions declare effects [].
These are safe .aji wrappers over spec 03 §26. new chooses exact initial capacity, reserve chooses a minimum capacity without shrinking, and push never grows implicitly. len/capacity observe initialized length/backing capacity. pop removes the last complete value, returning none for empty. A full push returns the original item. get copies an in-bounds Copy item or returns none. replace exchanges an in-bounds initialized element and returns the previous item; out_of_bounds returns the original supplied item and preserves the vector. free releases only an empty vector; otherwise it returns the same vector. Returned owning result specializations need exhaustive match move; Copy results use ordinary matching. Callers drain and explicitly consume resource payloads before freeing.
Capacity/allocation failure, alias/task exclusion, deterministic profiles and diagnostics are those of buffer primitives and ordinary enum/call rules. Valid complete values include owners/files/endpoints; no collection bypasses Send/Share or channel_transfer gates. Imports grant no authority. HashMap/HashSet/BinaryHeap, owning strings and general borrowed function returns remain separate increments of STD-6.
2.11 Explicit owning deques
The compiler-pinned registry MUST include safe std.deque (std/deque.aji). Its ordinary type is Deque<T> { storage: buffer<std.option.Option<T>>, head: usize, length: usize }, always linear. It exports NewResult<T> { ok(Deque<T>), err(alloc_error) }, PushResult<T> { ok, full(T) }, ReserveResult { ok, err(alloc_error) }, FreeResult<T> { ok, not_empty(Deque<T>) } and ReplaceResult<T> { ok(T), out_of_bounds(T) }.
For a valid deque of capacity C, the backing buffer MUST have C initialized Option slots. For C=0, head=length=0; otherwise head<C and length≤C, with head=0 when empty. Logical element i (0≤i<length) occupies (head+i) mod C; precisely those slots contain some(T), every other slot contains none. Each linear element is owned exactly once. Algorithms MUST compute indices without intermediate usize overflow. Fields follow ordinary source visibility: callers constructing or modifying the representation MUST preserve this invariant. Library operations preserve it; ordinary traps/bounds/ownership checks still apply to invalid caller representations, with no unsafe exemption or promise to validate the entire invariant on every call.
Every function supplies explicit ::<T> specialization:
| Function | Parameters | Result / contract |
|---|---|---|
| new | capacity: usize, heap: cap<mem.alloc> | NewResult; exact capacity, empty queue |
| len / capacity | value: ref<Deque> | usize; logical length / capacity |
| reserve | value: mut<Deque>, capacity: usize, heap: cap<mem.alloc> | ReserveResult; no shrink; successful growth preserves logical order and sets head=0 |
| push_front / push_back | value: mut<Deque>, item: T | PushResult; insert at selected end, or full(original_item) with entire deque unchanged |
| pop_front / pop_back | value: mut<Deque> | std.option.Option; remove/move selected end, or none with empty deque unchanged |
| free | value: Deque | FreeResult; empty frees all backing storage; nonempty returns same deque unchanged |
| get<T: Copy> | value: ref<Deque>, index: usize | std.option.Option; copy logical element, or none out of bounds |
| replace | value: mut<Deque>, index: usize, item: T | ReplaceResult; return old logical element after complete exchange, or out_of_bounds(original_item) without mutation |
Only new/reserve declare effects [mem.alloc] and require cap<mem.alloc>. Each slot charges accounted_size(Option) (the enum tag plus its largest payload), including free none slots. Growth uses buffer.reserve's old+new allocation peak; an allocation error MUST preserve head, length, capacity, every slot and ownership. After successful allocation the library initializes new slots to none and rotates the old ring using complete value.swap operations, with no second allocation. Requests≤C succeed without mutation. New/growth perform O(capacity) slot work; end operations, get/replace and metadata use constant slot work; freeing an empty deque drains its none slots in O(capacity). These are library slot-operation counts; the reference interpreter currently copies the initialized prefix in buffer.push, so construction/growth can have higher host cost. No native backend performance guarantee is added. Fuel exhaustion/traps are abnormal execution outcomes, outside returned-error preservation guarantees.
A full push and out-of-bounds replace return the exact original item. Callers MUST consume returned linear payloads. A nonempty free MUST NOT pop, close or destroy user elements; callers pop/consume all elements first. Empty free explicitly consumes only internal none slots before freeing its buffer. Ownership never escapes through a borrowed result. Valid calls add no program trap beyond the environment's execution limits. Existing linear availability, borrow/task-loan, bounds, generic Copy/Send/Share, effects and allocation rules verify the library as ordinary source; no new verifier state, AIR feature/opcode, runtime primitive, diagnostic, effect or authority is added. AIR format 0 and existing APIs retain meaning. Owners, files and channel endpoints follow the same rules as Vec; map/set/heap collections remain separate work.
2.12 std.hash: non-cryptographic bytes and checksums
The compiler registry MUST include std.hash, implemented in ordinary safe source. It exports exactly four monomorphic functions, all effects []:
| Function | Contract |
|---|---|
fnv1a64(data: slice<u8>) -> u64 |
FNV-1a 64, initial state 0xcbf29ce484222325 |
fnv1a64_extend(state: u64, data: slice<u8>) -> u64 |
continue from the supplied FNV state |
crc32c(data: slice<u8>) -> u32 |
reflected CRC-32C (Castagnoli), initial/final XOR 0xffffffff |
crc32c_extend(checksum: u32, data: slice<u8>) -> u32 |
continue from a finalized checksum, undoing and reapplying the final XOR |
FNV MUST process each byte in slice order by XOR with its zero-extended value, then multiplication by 0x100000001b3 modulo 2^64. CRC results MUST equal this recurrence: start with checksum XOR 0xffffffff, XOR each zero-extended byte into the low bits, and perform eight steps: shift right once, XOR 0x82f63b78 exactly when the previous low bit was one. Return the state XOR 0xffffffff. crc32c(data) is crc32c_extend(0, data). These numeric results do not depend on target byte order or pointer width; serialization uses explicit std.bytes endian operations. CRC-32C is distinct from IEEE CRC-32. FNV and CRC definitions follow RFC 9923 §§2,5 and RFC 3720 Appendix B.4, respectively; the rules above specify the API's numeric convention.
Empty input returns the supplied state/checksum; a fresh empty hash is the FNV offset basis or zero CRC. For any bytes A/B, extending hash(A) with B MUST equal hashing their concatenation. Any u64/u32 continuation value is valid; it need not come from a previous call. Input bytes including zero MUST all participate. No UTF-8 validation, terminator, implicit padding or field separator is introduced. The caller MUST encode field boundaries and scalar byte order when hashing structured data.
These operations MUST NOT allocate heap memory, mutate input, retain a borrow, obtain authority or consume an owner. They use ordinary slice bounds, immutable borrows and explicit wrapping arithmetic; no new verifier/runtime rule, diagnostic, AIR feature or unsafe boundary is introduced. Conflicting mutable access rejects under existing E2101; argument type errors use E7005 and missing imports/members E7002. Valid calls do not trap except ordinary execution limits. Time is O(data.len), auxiliary state O(1); the initial CRC implementation MAY use eight bit steps per byte rather than a lookup table. Deterministic and hosted profiles MUST return the same values, and existing APIs/AIR retain meaning. Hashes/checksums provide neither cryptographic authentication nor adversarial collision resistance and MUST NOT be used as key equality in a map.
2.13 std.map: bounded owning numeric-key map
The registry MUST include std.map, ordinary safe source. U64Map stores exact u64 keys and complete V values; V MAY be Copy, an owner, file or endpoint subject to existing member/Send/Share rules. It does not implement general HashMap<K,V> hashing/equality (Q-037). Entry has key: u64 and value: V. Ten operations use explicit ::<V> specialization:
| Function | Result |
|---|---|
new<V>(capacity: usize, heap: cap<mem.alloc>) |
NewResult: ok(U64Map), err(alloc_error) |
len<V>(map: ref<U64Map<V>>) -> usize |
live entries |
capacity<V>(map: ref<U64Map<V>>) -> usize |
maximum live entries |
reserve<V>(map: mut<U64Map<V>>, capacity: usize, heap: cap<mem.alloc>) |
ReserveResult: ok, err(alloc_error) |
insert<V>(map: mut<U64Map<V>>, key: u64, value: V) |
InsertResult: inserted, replaced(V), full(V) |
contains<V>(map: ref<U64Map<V>>, key: u64) -> bool |
exact presence |
get<V: Copy>(map: ref<U64Map<V>>, key: u64) -> std.option.Option<V> |
copy of value, or none |
remove<V>(map: mut<U64Map<V>>, key: u64) -> std.option.Option<V> |
moving extraction, or none |
pop<V>(map: mut<U64Map<V>>) -> std.option.Option<Entry<V>> |
first occupied physical slot, or none |
free<V>(map: U64Map<V>) |
FreeResult: ok, not_empty(U64Map) |
Representation: U64Map has storage: buffer<Slot> and length: usize. Slot has key: u64, state: SlotState and value: std.option.Option; SlotState is the Copy enum empty/deleted/occupied. A logical capacity N uses exactly 2N initialized physical slots. buffer.len(storage) equals buffer.capacity(storage); length≤N equals occupied count; occupied slots contain some(V), other slots none; occupied keys are unique and reachable by the probing rule. Copy key/state fields are observable through ref without copying V. Ordinary visible fields have no special access protection; manual construction/mutation MUST preserve this invariant. Invalid representations retain ordinary ownership/bounds safety but need not preserve map behavior.
New creates all-empty slots. Only new/reserve declare effects [mem.alloc] and require cap<mem.alloc>; every other operation is effects [] and allocates no heap. Multiplication/charge overflow MUST return alloc_error.budget_exceeded before mutation. Each slot charges the key, SlotState tag and Option tag plus maximum payload, including vacancies/tombstones; separately allocated V owners retain their own charges. Zero capacity succeeds with zero slots, no modulo; new-key insertion returns full(value). A key's hash is FNV-1a of exactly eight little-endian key bytes; the starting slot is that u64 hash modulo physical count. Probing visits at most the physical count and wraps without overflowing. Lookup passes deleted and stops at empty/end. Hash equality MUST NOT substitute for exact u64 equality; 0 and maximum u64 are valid keys.
Insert searches for an existing key before choosing its first deleted/empty slot. Existing-key replacement MUST succeed even at full logical capacity, returning the old complete V. A new key when full MUST return the exact input V without mutation. Deletion/pop exchange a complete Option for none, mark deleted and return ownership; missing removal preserves all state. Tombstones need no implicit compaction. Tables with no empty slots MUST still terminate probes and reuse deleted slots without duplicate keys. pop order is physical-index order, deterministic for the complete history; successful rehash MAY change that order. No borrowed value or cursor escapes.
Reserve≤N is an unchanged no-op, retaining its explicit effect/capability/mut contract. Growth MUST allocate/initialize the entire new table before changing the original. Returned failure MUST preserve every old slot, metadata, key/value association and pop order. Peak quota includes both whole tables and existing user-owned allocations; old storage is refunded to its recorded authority even if a different capability funds growth. After successful allocation, transfer complete entries in old physical-index order, clear tombstones and explicitly free old internal vacant storage. No subsequent recoverable error is permitted; fuel/traps are abnormal outcomes outside returned-error preservation. Nonempty free MUST return the entire map; empty free MUST consume all internal none values and free the storage, never normally discarding an occupied/owning payload, including with corrupted caller metadata. Callers MUST consume returned linear replacements/full/remove/pop/not_empty results; no hidden destructor closes user resources.
Existing aggregate/enum moves, value.swap, slice bounds, borrow/task-loan exclusion, Copy/Send/Share, effects and allocation accounting verify this library without map-specific rules, diagnostics, AIR instructions/features or runtime behavior. Preflight size failures construct alloc_error values through error_values (spec 05 §14); map adds no further semantic feature. Bad moves/leaks/aliases/tasks/Copy uses retain E7003/E2002/E3002/E2101/E4101/E7005 and Share restrictions E4002. Valid operations do not trap except execution limits. Deterministic/hosted profiles agree; existing source/AIR/API meanings remain unchanged. Lookup/insert/remove are O(N) worst-case slot work, pop/free O(N), growth O(N²) worst-case collision work. Initialized-prefix copying may increase interpreter host cost; no native throughput guarantee or adversarial collision bound is added.
2.14 std.hashmap: bounded owning general-key map
The registry MUST include std.hashmap at std/hashmap.aji, ordinary safe source. HashMap<K,V,H,E> binds explicit static H: fn(ref<K>) -> u64 effects [] and E: fn(ref<K>,ref<K>) -> bool effects [] (spec 15 §18). K/V MAY be Copy, owners, files or endpoints under ordinary member/Send/Share rules. An applied type uses HashMap<K,V,fn hash,fn equal>; functions use ::<K,V,fn hash,fn equal>. Distinct operation identities are distinct nominal map types. Entry<K,V> has key: K and value: V; both are returned/transferred completely, never implicitly destroyed.
The caller MUST supply deterministic, stable hashing and equality for live keys: E is an equivalence relation, and E(a,b) implies H(a)=H(b). Equality decides identity even when hashes collide. A stored key MUST NOT be modified in a way that changes its hash/equality; normal exclusive access rules still apply. These algebraic laws are explicit library preconditions, not compiler-proved properties. Hash/equality receive only shared key borrows, no capability or hidden state. User callback traps and fuel exhaustion are abnormal outcomes, outside returned-error preservation.
Ten operations are specialized by the four ordered arguments above (get additionally requires V: Copy):
| Operation | Result / transfer |
|---|---|
| new(capacity: usize, heap: cap<mem.alloc>) | NewResult<K,V,H,E>: ok(HashMap<K,V,H,E>), err(alloc_error) |
| len(map: ref<HashMap<K,V,H,E>>) -> usize | live entry count |
| capacity(map: ref<HashMap<K,V,H,E>>) -> usize | maximum live entries |
| reserve(map: mut<HashMap<K,V,H,E>>, capacity: usize, heap: cap<mem.alloc>) | ReserveResult: ok, err(alloc_error) |
| insert(map: mut<HashMap<K,V,H,E>>, key: K, value: V) | InsertResult<K,V>: inserted, replaced(Entry<K,V>), full(Entry<K,V>) |
| contains(map: ref<HashMap<K,V,H,E>>, key: ref) -> bool | presence by actual key equality |
| get(map: ref<HashMap<K,V,H,E>>, key: ref) -> std.option.Option | copied value; no K: Copy requirement |
| remove(map: mut<HashMap<K,V,H,E>>, key: ref) -> std.option.Option<Entry<K,V>> | moves complete stored key/value out |
| pop(map: mut<HashMap<K,V,H,E>>) -> std.option.Option<Entry<K,V>> | moves the last dense entry out |
| free(map: HashMap<K,V,H,E>) | FreeResult<K,V,H,E>: ok, not_empty(HashMap<K,V,H,E>) |
Only new/reserve declare effects [mem.alloc] and require explicit heap authority; all other functions declare effects [] and perform no heap allocation. Insert is bounded, never grows. Replacement succeeds at full capacity and returns the previous complete key/value; the supplied equivalent key becomes the stored key. A new key when full returns the exact supplied key/value with all storage unchanged. Missing removal leaves storage unchanged. Callers MUST consume owning replaced/full/remove/pop/not_empty payloads explicitly. No borrowed value/cursor escapes.
Representation: HashMap has entries: buffer<StoredEntry<K,V>>, buckets: buffer. StoredEntry has hash: u64, key: K, value: V. Bucket has hash: u64, index: usize, state: BucketState (empty/deleted/occupied). For capacity N, entries.capacity=N, entries.len=L≤N; buckets.capacity=buckets.len=2N. Every dense entry [0,L) has one occupied bucket whose hash/index agree; no other bucket owns or refers to a live entry. Cached hash equals H(key); live keys are pairwise unequal by E. Each occupied bucket is reachable by the probing rule. Keys/values have no vacancy sentinel or default value. Manual representation construction/mutation MUST preserve this invariant; invalid representations retain ordinary memory/ownership safety but may trap or violate map behavior.
Probe start is the unsigned u64 hash modulo the bucket count. Advance wraps without overflow, and at most bucket count probes occur. Lookup skips deleted and stops at empty/end; occupied hash equality is only a filter before E. Insert remembers the first deleted/empty slot but searches for an existing equal key before choosing it, including when full. Zero capacity never performs modulo and returns full on insert. Deleted-only tables remain bounded and reusable.
Removal exchanges the last dense entry into the removed entry's position when needed and repairs that moved entry's occupied bucket by its cached hash/index. Thus the initialized prefix always contains complete values; no uninitialized hole or partial move is introduced. pop consumes the last dense entry and marks its bucket deleted without invoking H/E. Pop order is reverse current dense order (insertion appends; replacement retains position; removal may exchange the last entry into a hole). This is deterministic for the history, not sorted order. Successful reserve preserves dense/pop order and clears tombstones. Nonempty free returns the entire map unchanged, based on actual entries.len, not forgeable length metadata. Empty free explicitly drains only Copy bucket metadata and frees both buffers; it cannot normally discard a key/value, even with invalid bucket metadata.
New checks 2N overflow, allocates the empty entry buffer, then the fully initialized bucket buffer. A returned second-allocation failure MUST free the temporary empty entry buffer and refund its recorded authority. Reserve≤N is an unchanged no-op with its declared mut/effect/capability requirements. Growth MUST allocate/initialize a new bucket buffer before calling ownership-preserving buffer.reserve on the dense entries. Any returned failure MUST free temporary metadata, preserve both original buffers, every key/value/hash/index/state and pop order, and refund all temporary charges. After entries reserve succeeds, only cached hashes are used to rebuild the new buckets; no further recoverable allocation or callback occurs. Swap in the new buckets and explicitly free the old Copy metadata buffer. Peak quota includes old/new entry buffers, old/new bucket buffers and separately charged user owners. All old storage refunds go to their recorded authorities, even when growth uses another capability. Arithmetic/allocation-size overflow returns alloc_error.budget_exceeded; no shrink occurs.
Each StoredEntry slot charges hash plus full K/V slot sizes, including uninitialized capacity; each Bucket charges hash, usize and state tag. Unused capacity reserves bytes but contains no live K/V. There is no tag/default key allocation and no implicit destruction. Existing initialized buffers, aggregate transfer/exchange, borrows/task loans, bounds, effects, Copy/Send/Share and quota verification suffice; no new AIR instruction/feature, source form, verifier/runtime state or diagnostic is added. Generic callback contracts are RFC 0029. Valid bookkeeping does not trap with a valid representation and successful callbacks. Existing API/AIR meanings remain unchanged, including std.map.U64Map. Deterministic/hosted behavior agrees. Probe operations are O(N) worst-case plus callback work, pop/removal repair O(N), reserve O(N²) worst-case collision work; buffer-prefix interpreter copying may add host cost. No adversarial collision or native throughput promise is made.
2.15 std.hashset: bounded owning general-key set
The registry MUST include std.hashset at std/hashset.aji, ordinary safe source. HashSet<K,H,E> binds the same exact pure ref-key hash/equality contracts and stable algebraic laws as std.hashmap (§2.14), with explicit type/application arguments K,fn hash,fn equal. It owns complete arbitrary K, including owning byte buffers, structs, resources and endpoints subject to existing member/Send/Share rules. Its representation is one field map: std.hashmap.HashMap<K,bool,H,E>, with every live value true; all underlying dense/probe invariants apply. No default key, implicit destruction or library access privilege is added.
Nine operations use the three ordered arguments above:
| Operation | Result / transfer |
|---|---|
| new(capacity: usize, heap: cap<mem.alloc>) | NewResult<K,H,E>: ok(HashSet<K,H,E>), err(alloc_error) |
| len(set: ref<HashSet<K,H,E>>) -> usize | live count |
| capacity(set: ref<HashSet<K,H,E>>) -> usize | maximum live keys |
| reserve(set: mut<HashSet<K,H,E>>, capacity: usize, heap: cap<mem.alloc>) | ReserveResult: ok, err(alloc_error) |
| insert(set: mut<HashSet<K,H,E>>, key: K) | InsertResult: inserted, present(original_input_K), full(original_input_K) |
| contains(set: ref<HashSet<K,H,E>>, key: ref) -> bool | exact membership |
| remove(set: mut<HashSet<K,H,E>>, key: ref) -> std.option.Option | moving extraction of the stored key |
| pop(set: mut<HashSet<K,H,E>>) -> std.option.Option | moving extraction of last dense key |
| free(set: HashSet<K,H,E>) | FreeResult<K,H,E>: ok, not_empty(HashSet<K,H,E>) |
Only new/reserve declare mem.alloc and take explicit heap authority. Insert checks membership before transferring to the underlying map: duplicate insertion MUST preserve the existing stored key and every entry/bucket, returning the exact input key as present, even when full. New-key full also preserves the set and returns its exact input. This gives one canonical insert contract; replacement requires explicit remove/insert by the caller. No automatic growth occurs. Owning present/full/remove/pop/not_empty results MUST be consumed. contains returns no borrow. Missing remove and nonempty free preserve all state. Pop order is the underlying reverse current dense order; removal may move the last key to a hole, and reserve preserves the order.
New/reserve failure, peak quota/refund, zero capacity, probing, collision equality, callback/fuel traps and visible representation invariants are exactly §2.14's rules. Each capacity slot charges hash plus complete K plus bool, and two buckets: for K=u64, N charges 51N bytes; separately owned K allocations remain separately charged. insert MAY evaluate H/E for membership and again for bounded map insertion; these pure stable operations grant no authority and cannot be inferred away. Once membership says absent, map replacement is unreachable under the valid representation/hash/equality laws; invalid laws may trap under ordinary abnormal-path semantics.
Existing buffers/aggregates/borrows, static callable identity, effects, Copy/Send/Share and ownership verification suffice. No new syntax, diagnostic, feature/opcode, verifier/runtime state, implicit allocation/destructor or trusted boundary is added. Deterministic/hosted behavior agrees and existing APIs/AIR meanings remain unchanged. Worst-case insertion/membership/removal/pop is O(N) plus callback work; growth is O(N²) worst-case collision work with existing interpreter prefix-copy costs. No sorted output, adversarial collision bound or native throughput promise is added.
2.16 std.heap: bounded owning binary heap
The registry MUST include std.heap at std/heap.aji, ordinary safe source. BinaryHeap<T,B> binds an explicit static B: fn(ref<T>,ref<T>) -> bool effects [] (spec 15 §18), applied as BinaryHeap<T,fn before> and ::<T,fn before>. T MAY contain owners, files or endpoints under ordinary member/Send/Share rules. Distinct bound operations give distinct nominal heap types. No default T, captured environment, runtime dispatch or implicit cleanup is added.
B(a,b) means a MUST precede b. B MUST be a stable strict weak order on live values: irreflexive and transitive, with transitive incomparability. Equivalent values have neither B(a,b) nor B(b,a); their extraction order is deterministic for a fixed operation sequence but MUST NOT be assumed stable. Changing a live value's relative order violates the representation precondition. Pure callbacks grant no authority; callback traps/fuel exhaustion are abnormal outcomes, with no returned-state preservation promise.
Eight operations use the two ordered arguments above; peek additionally requires T: Copy:
| Operation | Result / transfer |
|---|---|
| new(capacity: usize, heap: cap<mem.alloc>) | NewResult<T,B>: ok(BinaryHeap<T,B>), err(alloc_error) |
| len(value: ref<BinaryHeap<T,B>>) -> usize | live count |
| capacity(value: ref<BinaryHeap<T,B>>) -> usize | maximum live count |
| reserve(value: mut<BinaryHeap<T,B>>, capacity: usize, heap: cap<mem.alloc>) | ReserveResult: ok, err(alloc_error) |
| push(value: mut<BinaryHeap<T,B>>, item: T) | PushResult: ok, full(original_input_T) |
| peek(value: ref<BinaryHeap<T,B>>) -> std.option.Option | Copy root value, or none |
| pop(value: mut<BinaryHeap<T,B>>) -> std.option.Option | moving extraction of root, or none |
| free(value: BinaryHeap<T,B>) | FreeResult<T,B>: ok, not_empty(BinaryHeap<T,B>) |
Only new/reserve declare mem.alloc and take explicit allocation authority. Push is bounded: full MUST preserve all state, return the exact input and evaluate no ordering callback; it never grows. Successful push/pop MUST restore the heap invariant; pop returns the root that preceded the operation, or none without mutation when empty. Peek copies only Copy T and retains no borrow. Nonempty free MUST return the complete unchanged heap. Every owning full/pop/not_empty result MUST be explicitly consumed.
The visible representation is BinaryHeap<T,B> { entries: buffer<Entry<T>>, indices: buffer<usize> }, Entry<T> { position: usize, value: T }. Both initialized lengths are L and capacities N, with L≤N. Indices form a permutation of 0..L; entries[indices[p]].position MUST equal p. For every nonroot p, B(value_at(p),value_at((p-1)/2)) MUST be false. Values are owned exactly once in the initialized dense prefix; unused capacity contains no live T. Copy indices permit sifting without copying owners, holes, temporary default values or borrowed enum payloads. Caller construction/mutation MUST preserve the complete invariant.
Push appends a complete entry and its Copy index, then sifts upward by swapping Copy indices and repairing positions. Pop removes the final Copy index, installs it at the root when nonempty, then sifts downward: compare the children, choose right only when it strictly precedes left, and swap only when the chosen child strictly precedes its parent. After ordering, pop the last dense entry; if it is not the removed root, exchange it into that dense hole and repair its Copy heap index using its recorded position. Return the complete removed T. Bounds and parent/child arithmetic MUST be checked before accesses; the nonleaf condition p<L/2 permits 2p+1 without overflow. No retained view escapes.
New allocates empty entries then empty indices; a returned second-allocation failure MUST free the temporary empty entries and refund its recorded authority. Zero capacity is valid. Reserve≤N is an unchanged no-op with its declared mut/effect/capability requirements. Growth MUST allocate a new index buffer and copy the old live indices before ownership-preserving buffer.reserve on entries. Any returned failure MUST drain/free temporary Copy indices, preserve both original buffers, all values/positions/indices and extraction order, and refund temporary charges. After entries reserve succeeds, exchange the new indices into place and explicitly drain/free the old Copy indices; no callback or further recoverable allocation occurs. Growth preserves the heap layout and never shrinks.
Each capacity slot charges usize + complete T for Entry and usize for the index. On air64, T=u64 or own reserves 24N bytes, with separately owned payloads charged independently. Peak growth includes old/new entries, old/new indices and all user-owned allocations. Refunds follow each buffer's recorded authority, including growth through a different capability. Arithmetic/allocation-size overflow returns alloc_error.budget_exceeded.
Existing buffer/aggregate transfer/exchange, static contracts, borrow/task-loan exclusion, bounds, effects, Copy/Send/Share and resource verification suffice. Valid representations/successful callbacks do not trap during bookkeeping. Existing source/AIR meanings are unchanged; no new syntax, diagnostic, AIR feature/instruction, verifier/runtime state or trusted boundary is added. Deterministic/hosted behavior agrees. Abstract push/pop perform O(log L) comparisons and index swaps, peek is O(1), reserve copies O(L); interpreter prefix-copy/GC costs may add host work. No native-throughput or stable tie-order promise is made.
2.17 std.io: bounded I/O foundation
The registry MUST include std.io at std/io.aji, ordinary safe source. Six concrete functions compose existing borrowed-resource/capability I/O with caller-supplied slices. They MUST NOT allocate heap storage, open/close resources, retain borrows, infer effects or gain authority through import. Existing primitive writes already report all bytes written on success; no redundant write alias is added.
ReadError has completed: usize / error: io_error. ReadExactResult has ok, eof(usize), err(ReadError). ReadToEndResult has eof(usize), full(usize), err(ReadError). CopyError has read: usize / confirmed_written: usize / error: io_error; CopyResult has eof(usize), limit(usize), err(CopyError). All are ordinary Copy data, never authority.
| Function arguments | Result | Effects |
|---|---|---|
| read_exact_stdin(input: cap<io.read>, destination: slice_mut) | ReadExactResult | io.read |
| read_exact_file(input: mut<file>, destination: slice_mut) | ReadExactResult | fs.read |
| read_exact_stream(input: mut, destination: slice_mut) | ReadExactResult | net.read |
| read_to_end_file(input: mut<file>, destination: slice_mut) | ReadToEndResult | fs.read |
| copy_file(input: mut<file>, output: mut<file>, scratch: slice_mut, limit: usize) | CopyResult | fs.read, fs.write |
| copy_file_append(input: mut<file>, output: mut<file>, scratch: slice_mut, limit: usize) | CopyResult | fs.read, fs.write |
Exact reads loop over the unfilled suffix until destination.len successful bytes have been read (ok), an intrinsic reports zero (eof(completed)), or a read errors (err with the previous successful byte count and unchanged error). Empty exact destination returns ok without an intrinsic. EOF leaves the remaining destination unchanged. On a returned read error, only the completed successful prefix is guaranteed; contents of the attempted suffix follow the primitive and are not additionally promised by this wrapper. Bytes outside the destination MUST remain unchanged. Every count increment MUST be bounded by the remaining capacity.
read_to_end_file loops until zero (eof(completed)), destination capacity is reached (full(destination.len)), or a read errors (same prefix/error contract). Empty destination returns full(0) without I/O. Full does not establish that unread bytes remain or that EOF was reached: the function MUST NOT read/discard an extra byte to distinguish those states. Neither reader changes or retains caller resource ownership.
Copies use scratch chunks bounded by min(scratch.len, limit-completed). Successful reads are followed by fs.write_all; reaching zero returns eof(completed), reaching limit returns limit(completed) without probing EOF. Thus exact EOF at limit returns limit, not eof. A read error returns both counts equal to the previously confirmed completed chunks. A write error returns read including the just-read chunk and confirmed_written counting only earlier successful writes. The failed write MAY have externally written a prefix; confirmed_written is a lower bound, not an exact failed-output count or rollback promise. The input has advanced through confirmed successful reads. Counts MUST NOT exceed limit or overflow. EOF/error retain both borrowed resources for explicit caller cleanup.
limit=0 MUST return limit(0) without I/O, including with empty scratch. Empty scratch with positive limit MUST return err(CopyError{read:0,confirmed_written:0,error:io_error.invalid_input}) without I/O. Scratch contents after the call are unspecified; bytes outside its slice MUST remain unchanged. Functions do not allocate, grow, sync or close; the caller explicitly supplies all grants, slices, limits and final resource consumption. Effects/mut/task-loan requirements apply even to no-op paths. Append copies use the existing append resource semantics.
Existing type, effect/capability, borrow/task-loan, resource availability, bounds and outcome checks apply without new diagnostics or verifier/runtime state. Operations use ordinary AIR and spec 11 profile behavior; no unsafe/trusted boundary, syntax/opcode/feature, implicit cleanup, timeout or existing semantic change is introduced. Blocking/fuel remain environment outcomes. Returned failures are explicit ordinary enums, never exceptions. Successful work is linear in read bytes plus intrinsic calls; caller capacities/limits and fuel bound work. Buffered adapters are specified in §2.18; lexical paths remain a subsequent STD-7 increment.
2.18 std.io.reader / std.io.writer: owning bounded file adapters
The registry MUST include std.io.reader at std/io/reader.aji and std.io.writer at std/io/writer.aji, ordinary safe source with concrete file modes. They MUST NOT open/close files, sync, retain caller borrows, grow implicitly, infer effects or acquire authority through import. Each owns one file and one fixed-capacity initialized buffer. Only new declares mem.alloc and accepts explicit allocation authority; byte storage charges capacity bytes, including unused capacity. Capacity zero is valid and uses direct primitive reads/writes. Constructor failure MUST return the exact original file with alloc_error, without I/O or resource consumption.
Reader is { file: file<read>, storage: buffer<u8>, begin: usize, end: usize }, with fully initialized length=capacity=N and 0≤begin≤end≤N. Bytes begin..end are unread prefetched data; the underlying file cursor has advanced through those bytes. Writer is { file: file<write>, storage: buffer<u8>, used: usize, failed: std.option.Option<io_error> }, with fully initialized length=capacity=N and 0≤used≤N. Bytes 0..used are pending accepted data; failed is none or the first failed external-write error. Neither adapter's file/storage may be independently used, consumed or mutated in a way that violates these logical invariants. Ordinary visible fields grant no representation privilege.
Reader types: NewError{file:file,error:alloc_error}; NewResult{ok(Reader),err(NewError)}; ReadResult{ok(usize),err(io_error)}; FinishResult{ok(file),unread(Reader)}; Discarded{file:file,unread:usize}. Writer types: NewError{file:file,error:alloc_error}; NewResult{ok(Writer),err(NewError)}; WriteError{accepted:usize,error:io_error}; WriteResult{ok,err(WriteError)}; FlushResult{ok,err(io_error)}; FinishError{writer:Writer,error:io_error}; FinishResult{ok(file),err(FinishError)}; Discarded{file:file,pending:usize,failed:std.option.Option<io_error>}. Every file/adapter-bearing result is linear and MUST be explicitly consumed.
| Module operation | Result | Effects |
|---|---|---|
| reader.new(input: file, capacity: usize, heap: cap<mem.alloc>) | NewResult | mem.alloc |
| reader.read(input: mut, destination: slice_mut) | ReadResult | fs.read |
| reader.read_exact(input: mut, destination: slice_mut) | std.io.ReadExactResult | fs.read |
| reader.finish(input: Reader) | FinishResult | none |
| reader.discard(input: Reader) | Discarded | none |
| writer.new(output: file, capacity: usize, heap: cap<mem.alloc>) | NewResult | mem.alloc |
| writer.write(output: mut, bytes: slice) | WriteResult | fs.write |
| writer.flush(output: mut) | FlushResult | fs.write |
| writer.finish(output: Writer) | FinishResult | fs.write |
| writer.discard(output: Writer) | Discarded | none |
Reader.read returns at most destination.len bytes. Empty destination returns ok(0) without I/O or consuming cached data; it does not establish EOF. If cached bytes exist, copy min(unread,destination.len) and advance begin, without refilling during that call. Otherwise, for N>0, refill the whole storage using fs.read, then return one cached prefix; a successful zero refill returns ok(0) as EOF. With N=0 delegate one primitive read directly to the destination. Refill errors retain the file/storage and existing offsets, returning the original io_error with no guessed external cursor rollback. Bytes outside the destination remain unchanged. read_exact composes read over destination suffixes and uses §2.17's completed-prefix/EOF/error contract, with no borrow escaping.
Reader.finish MUST return unread(the complete unchanged Reader) when begin<end. Otherwise drain/free Copy storage and return the original file at its current cursor. It does not require a confirmed EOF and does not read or close. Reader.discard explicitly abandons end-begin prefetched bytes, drains/frees storage and returns the file plus unread count. No rewind is promised; the underlying cursor remains advanced through prefetch. Storage refunds follow its recorded allocation authority.
Writer.write accepts the complete input into buffered storage or successful writes, returning ok; accepted is not a durability/external-write count. With N>0, copy as much as fits, flushing a full buffer only to make room for further input. If a call ends with a full buffer, retain it until a later write/flush/finish. On a room-making flush error, return WriteError with the number of this call's input bytes already accepted and the original error; the unaccepted suffix remains caller-owned. Buffered pending bytes remain in Writer, including accepted bytes from earlier calls. With N=0, delegate fs.write_all directly: failure has accepted=0, though an external prefix MAY have been written. No count exceeds input.len or overflows.
Writer.flush on a healthy empty buffer returns ok without I/O. On a successful external write, used becomes zero. On any external write failure, used/data remain unchanged and failed becomes some(the first error); no automatic retry/reset is allowed. Once failed is some(error), every write (including empty) MUST return err with accepted=0 and that error, and every flush MUST return err(error), without I/O or buffer mutation. Unknown partial external writes make retrying pending data unsound. Writer.finish first flushes: success drains/frees storage and returns the file; error returns FinishError with the complete unchanged failed Writer and original error. Finish does not sync or close. Writer.discard explicitly abandons buffered pending bytes, drains/frees storage and returns the file, used count and failure state; pending on failure MAY overlap an already externally written prefix and is not an exact loss count.
Effects, moves and mut/task-loan requirements apply on no-op/cached/failure paths. Existing aggregate/buffer moves, resource borrowing, alias exclusion, bounds/arithmetic, effect/capability and Copy/Send/Share rules verify all safe code; files make adapters non-Share and ordinary Send checks govern task transfer. Deterministic/hosted behavior follows existing profile primitives. No new AIR meaning, instruction/feature, syntax, diagnostic, verifier/runtime state, unsafe boundary, implicit destructor or cancellation policy is introduced. Invalid representation may trap through existing checked operations, preserving memory safety. Valid bookkeeping does not trap for a valid invariant/conforming primitives. Work is linear in initialized/copy/drained bytes plus I/O calls, with existing interpreter prefix-copy/GC costs. Lexical paths and Std 0.1 remain unfinished.