168 lines
12 KiB
Markdown
168 lines
12 KiB
Markdown
# Standard library API
|
||
|
||
Normative contracts: spec 16. Import rules: spec 15 §13. These modules are bundled with the compiler, with no external dependencies or grants.
|
||
|
||
All functions below declare `effects []`, allocate no heap memory and retain no borrows. Pass arrays/slices using explicit `ref` or `mut`. Names are fully qualified; no alias or short-name import exists.
|
||
|
||
| Module | Function signature | Result/failure |
|
||
|---|---|---|
|
||
| `std.math` | `min_u64(a: u64, b: u64) -> u64` | smaller operand |
|
||
| `std.math` | `max_u64(a: u64, b: u64) -> u64` | larger operand |
|
||
| `std.math` | `clamp_u64(value: u64, lower: u64, upper: u64) -> u64` | inclusive clamp; `T0002` if `lower > upper` |
|
||
| `std.bytes` | `equal(a: slice<u8>, b: slice<u8>) -> bool` | byte equality |
|
||
| `std.bytes` | `compare(a: slice<u8>, b: slice<u8>) -> i8` | unsigned lexicographic order: exactly -1/0/1 |
|
||
| `std.bytes` | `find(data: slice<u8>, byte: u8) -> usize` | first index; `data.len` if absent |
|
||
| `std.bytes` | `starts_with(data: slice<u8>, prefix: slice<u8>) -> bool` | empty prefix matches |
|
||
| `std.bytes` | `ends_with(data: slice<u8>, suffix: slice<u8>) -> bool` | empty suffix matches |
|
||
| `std.bytes` | `fill(dst: slice_mut<u8>, byte: u8) -> void` | fills caller-provided storage |
|
||
|
||
```aji
|
||
module demo.standard
|
||
import std.bytes;
|
||
import std.math;
|
||
|
||
fn main() -> u64
|
||
effects []
|
||
{
|
||
var data: [u8; 4] = zero;
|
||
std.bytes.fill(mut data, 65);
|
||
assert(std.bytes.equal(ref data, b"AAAA"));
|
||
let index = std.bytes.find(ref data, 65);
|
||
if index < data.len { assert(data[index] == 65); }
|
||
return std.math.clamp_u64(42, 0, 100);
|
||
}
|
||
```
|
||
|
||
Unknown module/member or absent import: `E7002`; duplicate import: `E7006`; malformed import or type arguments: `E7001`; wrong argument type/arity: `E7005`; conflicting borrows: `E2101`. No new diagnostic code.
|
||
|
||
The example is `tests/conformance/source/quickref/std.aji`; library boundary and algorithm tests live under `tests/conformance/source/std/`.
|
||
|
||
## Endian integers
|
||
|
||
All functions operate at slice offset zero. Pass a sub-slice to select an offset. Extra bytes are ignored on read and preserved on write. No alignment or heap allocation is required. A short destination is unchanged; a short source yields no integer payload.
|
||
|
||
| Width | Read functions (`src: slice<u8>`) | Result | Write functions (`dst: slice_mut<u8>, value: uW`) | Result |
|
||
|---|---|---|---|---|
|
||
| 16 | `std.bytes.read_u16_le`, `std.bytes.read_u16_be` | `std.bytes.ReadU16` | `std.bytes.write_u16_le`, `std.bytes.write_u16_be` | `std.bytes.WriteResult` |
|
||
| 32 | `std.bytes.read_u32_le`, `std.bytes.read_u32_be` | `std.bytes.ReadU32` | `std.bytes.write_u32_le`, `std.bytes.write_u32_be` | `std.bytes.WriteResult` |
|
||
| 64 | `std.bytes.read_u64_le`, `std.bytes.read_u64_be` | `std.bytes.ReadU64` | `std.bytes.write_u64_le`, `std.bytes.write_u64_be` | `std.bytes.WriteResult` |
|
||
|
||
Read enums have exactly `ok(uW)` and `short_input`. `WriteResult` has exactly `ok` and `short_output`. These are ordinary Copy enums, handled with qualified enum patterns; they are not intrinsic outcome matches. They can be passed or returned through user functions. No generic must-use rule is introduced.
|
||
|
||
```aji
|
||
module demo.endian
|
||
import std.bytes;
|
||
|
||
fn main() -> u32
|
||
effects []
|
||
{
|
||
var wire: [u8; 6] = zero;
|
||
match std.bytes.write_u32_be(mut wire[1..5], 0x12345678) {
|
||
std.bytes.WriteResult::ok => {}
|
||
std.bytes.WriteResult::short_output => { return 0; }
|
||
}
|
||
match std.bytes.read_u32_be(ref wire[1..5]) {
|
||
std.bytes.ReadU32::ok(value) => { return value; }
|
||
std.bytes.ReadU32::short_input => { return 0; }
|
||
}
|
||
}
|
||
```
|
||
|
||
Missing enum arm: `E7004`; duplicate/wildcard enum arm: `E7006`; unknown type/variant or missing import: `E7002`; wrong width/payload, immutable destination or variant from another enum: `E7005`; conflicting destination borrows: `E2101`. Existing `or trap` only applies to fallible built-in operations, so it is not used with these enums.
|
||
|
||
The example is checked in `source/quickref/std_endian.aji`; fixtures for every width/order and all short lengths are in `source/std/endian_u*.aji`.
|
||
|
||
## Copy and substring search
|
||
|
||
| Function | Result and contract |
|
||
|---|---|
|
||
| `std.bytes.copy(dst: slice_mut<u8>, src: slice<u8>) -> std.bytes.WriteResult` | `ok` copies the whole input into the output prefix, preserving the suffix; `short_output` leaves the whole output unchanged. Empty input succeeds. Overlap rejects (`E2101`), including on the error path. |
|
||
| `std.bytes.find_slice(data: slice<u8>, needle: slice<u8>) -> std.bytes.FindResult` | `found(index)` for the first match, or `not_found`. Empty needle is `found(0)`, including empty data. Offset is relative to the passed slice; it need not be a readable element index. |
|
||
|
||
Search allocates no heap and uses constant auxiliary storage; the reference algorithm has O(data length × needle length) worst-case comparisons. Interpreter fuel bounds execution. For splitting at the first separator, match the search result, then take `data[0..index]` and `data[index + separator.len..data.len]`, or split at the index and borrow past the separator in the right half. An empty separator leaves the whole data in the right half; repeated splitting needs an explicit progress rule. There is no split iterator or returned pair of borrowed slices.
|
||
|
||
## Recoverable arithmetic
|
||
|
||
| Operand type | Functions | Result |
|
||
|---|---|---|
|
||
| `u64` | `std.math.checked_add_u64`, `std.math.checked_sub_u64`, `std.math.checked_mul_u64` | `std.math.U64Result::ok(u64)` / `overflow` |
|
||
| `usize` | `std.math.checked_add_usize`, `std.math.checked_sub_usize`, `std.math.checked_mul_usize` | `std.math.UsizeResult::ok(usize)` / `overflow` |
|
||
|
||
Every function takes two operands of the indicated type. A representable mathematical result succeeds; unsigned subtraction underflow also returns `overflow`. Multiplication by zero always succeeds with zero. `usize` follows target pointer width. Normal arithmetic operators still trap on overflow; wrapping uses `+%`, `-%`, `*%`, with no library wrappers. These monomorphic APIs do not provide generic or signed arithmetic. Result enums use the same ordinary match rules as the endian results.
|
||
|
||
For a zero-terminated byte record, check the complete output size before copying:
|
||
|
||
```aji
|
||
fn encode(dst: slice_mut<u8>, data: slice<u8>) -> usize
|
||
effects []
|
||
{
|
||
match std.math.checked_add_usize(data.len, 1) {
|
||
std.math.UsizeResult::ok(total) => {
|
||
if total > dst.len { return 0; }
|
||
match std.bytes.copy(mut dst, ref data) {
|
||
std.bytes.WriteResult::ok => { dst[data.len] = 0; return total; }
|
||
std.bytes.WriteResult::short_output => { return 0; }
|
||
}
|
||
}
|
||
std.math.UsizeResult::overflow => { return 0; }
|
||
}
|
||
}
|
||
```
|
||
|
||
This helper returns the encoded byte count or zero on failure, and leaves the destination unchanged on failure. Import both `std.math` and `std.bytes`. Its zero sentinel is unambiguous because a successful record includes the terminator.
|
||
|
||
The checked [bounded example](../../examples/std/bounded.aji) combines overflow-aware output sizing, whole-input copy and delimiter search; it returns 10. Copy/search/split and independent arithmetic fixtures are in `source/std/bounded_*.aji`. Wrong operands/payloads are `E7005`; absent imports/types are `E7002`; missing result arms are `E7004`. No new diagnostic code, syntax, verifier state or runtime primitive is introduced.
|
||
|
||
## UTF-8 and encodings
|
||
|
||
| Function | Result and contract |
|
||
|---|---|
|
||
| `std.utf8.next(src: slice<u8>) -> std.utf8.NextResult` | `ok(scalar: u32, consumed: usize)` for the first scalar, `end` for empty input, or `invalid_input` for a bad/truncated first sequence; trailing bytes do not affect a successful first decode. |
|
||
| `std.utf8.validate(src: slice<u8>) -> std.utf8.ValidateResult` | `ok` for wholly valid bytes, including empty input; `invalid_input(offset)` at the beginning of the first bad/truncated sequence. |
|
||
| `std.encoding.hex.encode(dst: slice_mut<u8>, src: slice<u8>) -> std.encoding.hex.EncodeResult` | lowercase ASCII hex; `ok(count)` or `short_output`. |
|
||
| `std.encoding.hex.decode(dst: slice_mut<u8>, src: slice<u8>) -> std.encoding.hex.DecodeResult` | even-length ASCII digits, upper/lower/mixed case; `ok(count)`, `invalid_input` or `short_output`. |
|
||
| `std.encoding.base64.encode(dst: slice_mut<u8>, src: slice<u8>) -> std.encoding.base64.EncodeResult` | standard alphabet with canonical padding and zero unused bits; `ok(count)` or `short_output`. |
|
||
| `std.encoding.base64.decode(dst: slice_mut<u8>, src: slice<u8>) -> std.encoding.base64.DecodeResult` | canonical standard Base64 only; `ok(count)`, `invalid_input` or `short_output`. |
|
||
|
||
UTF-8 uses shortest scalar encodings, excluding surrogates and values above U+10FFFF. NUL, BOM, noncharacters and unassigned scalars are accepted; validation does not normalize or replace bytes. Iteration repeatedly calls `next(ref data[offset..data.len])` and advances offset by the returned consumed count. `next` validates its first sequence only, so validate the whole slice when that is the required contract. A malformed final prefix is `invalid_input`, not a streaming "need more" result. [UTF-8 rules: RFC 3629 §3/§4](https://www.rfc-editor.org/rfc/rfc3629.html#section-3).
|
||
|
||
Encoders check complete capacity before writing; decoders check the entire input first, then capacity. Invalid input takes precedence over short output. Every returned error preserves the whole destination. Success writes a prefix, preserves remaining output and appends no terminator. Empty encoding/decoding succeeds with `ok(0)`, including zero capacity. Mathematical lengths too large for usize/output are `short_output`, checked without overflowing an intermediate. Input/output cannot overlap; disjoint `split_at` siblings from the same allocation are allowed. These guarantees do not cover interpreter fuel interruption.
|
||
|
||
Hex decoding rejects whitespace, prefixes, separators, odd length and non-hex bytes. Base64 uses the standard `+/` alphabet; incomplete final groups require `=` padding, and complete groups omit it. Decoding rejects whitespace, URL-safe symbols, incomplete groups, misplaced/excess padding and nonzero unused bits. This is a deliberate strict policy permitted by [RFC 4648 §3.5/§4](https://www.rfc-editor.org/rfc/rfc4648.html#section-3.5); no permissive or URL-safe mode is implied.
|
||
|
||
```aji
|
||
module demo.text
|
||
import std.bytes;
|
||
import std.encoding.hex;
|
||
import std.encoding.base64;
|
||
import std.utf8;
|
||
|
||
fn main() -> u32
|
||
effects []
|
||
{
|
||
var utf8: [u8; 3] = zero;
|
||
match std.encoding.hex.decode(mut utf8, b"E282AC") {
|
||
std.encoding.hex.DecodeResult::ok(count) => { assert(count == 3); }
|
||
std.encoding.hex.DecodeResult::invalid_input => { return 0; }
|
||
std.encoding.hex.DecodeResult::short_output => { return 0; }
|
||
}
|
||
match std.utf8.validate(ref utf8) {
|
||
std.utf8.ValidateResult::ok => {}
|
||
std.utf8.ValidateResult::invalid_input(offset) => { return 0; }
|
||
}
|
||
var encoded: [u8; 4] = zero;
|
||
match std.encoding.base64.encode(mut encoded, ref utf8) {
|
||
std.encoding.base64.EncodeResult::ok(count) => { assert(count == 4); }
|
||
std.encoding.base64.EncodeResult::short_output => { return 0; }
|
||
}
|
||
assert(std.bytes.equal(ref encoded, b"4oKs"));
|
||
match std.utf8.next(ref utf8) {
|
||
std.utf8.NextResult::ok(scalar, count) => { assert(count == 3); return scalar; }
|
||
std.utf8.NextResult::end => { return 0; }
|
||
std.utf8.NextResult::invalid_input => { return 0; }
|
||
}
|
||
}
|
||
```
|
||
|
||
The [text example](../../examples/std/text.aji) is checked by `source/std/text_example.aji` and returns 8364 (U+20AC). Independent byte/scalar vectors, capacities, invalid-input precedence, namespace collisions, alias rejects and disjoint buffers are under `source/std/text_*.aji`. UTF-8/encoding algorithms allocate no heap and declare `effects []`; fixed local tables are constant auxiliary storage. Wrong operands/payloads: `E7005`; missing result arms: `E7004`; unknown types/imports: `E7002`; conflicting borrows: `E2101`. Results are ordinary Copy enums with no new must-use rule.
|