Embed std.hash with four ordinary safe byte functions: FNV-1a 64 and Castagnoli CRC-32C, each with fresh and numeric continuation forms. Specify exact constants, empty/chunk semantics, arbitrary continuation states, target-independent numeric results and explicit serialization. No heap allocation, authority, AIR, verifier or runtime change. Propose the next U64Map<V> contract: exact key equality, bounded insert, returned replacement/full ownership, tombstones, moving drain and failure-preserving peak-charged rehash. Keep general HashMap<K,V> key hash/equality policy open as Q-037. A checked slot prerequisite confirms read-only Copy key/state fields over Option<V>, with explicit accounting for both tags and owning payload cleanup; no map module is registered. Validation: unit tests, 797 full conformance cases, 12 new fixtures; all 11 hash cases with per-instruction collection and 12 schedule seeds across four quanta, plus owning slot collection; 84 source/AIR, package and hosted CLI checks; independent forward-polynomial CRC and arbitrary precision FNV oracles for 286 inputs / 1144 results; 95/95 source coverage; Zig formatting, whitespace and reference generation. Published vectors come from RFC 9923 and RFC 3720, with explicit numeric/wire conventions. Reference cost: source excluding AIR 53,993 -> 55,281 cl100k (+2.4%); Quick Reference 7,747 -> 7,806 (+0.8%); AIR remains 175,736 bytes. Map design remains outside both bundles. No empirical MCC or native throughput claim; CRC initially uses eight bit steps per byte.
29 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.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/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. All operations are deterministic in every profile and have no concurrency effects. Modules other than std.vec/std.deque declare effects [] and allocate no heap memory. std.vec/std.deque new/reserve declare mem.alloc and require explicit allocation authority (§2.10–§2.11); 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.