Docs/Toolchain

Toolchain

Standard library

GitHub

In-tree std packages, public API contracts, and prelude resolution.

Aura’s core stdlib is intentionally small (RFC-007, RFC-000 batteries-included-but-modular). In this repository, packages live under std/.

Packages today

PackagePathRole
std.iostd/ioConsole, file I/O, argv, stdin, exit
std.assertstd/assertAssert helpers for tests
std.collectionsstd/collectionsMap/Set/List, generic hash collections, snapshot and live iterators, Iterable, HOFs, join
std.errorstd/errorShared error categories, owned errors, and generic outcomes
std.bytesstd/bytesValidated Byte, binary Buffer operations, and network-order integer helpers
std.encodingstd/encodingUTF-8, hexadecimal, base64, and percent encoding
std.jsonstd/jsonBounded JSON validation, parsing, escaping, root classification, and typed generic decoding
std.mimestd/mimeMedia-type validation and upload filename sanitization
std.fsstd/fsPortable path and filesystem metadata helpers
std.osstd/osEnvironment, process, platform, and working-directory helpers
std.netstd/netNonblocking endpoint-aware TCP listeners, connections, streams, and typed failures
std.dnsstd/dnsBounded numeric host resolution
std.urlstd/urlOrigin-form and absolute URI parsing plus component encoding
std.httpstd/httpBounded HTTP/1.1 client/server request and response values
std.streamstd/streamAsync reader/writer adapters over owned network streams
std.timestd/timeMonotonic durations, deadlines, and async sleep
std.taskstd/taskTask join, cancellation, and cancellation linking
std.syncstd/syncNonblocking atomics, mutexes, reader/writer locks, and one-shot gates
std.signalstd/signalGraceful SIGINT/SIGTERM shutdown state
std.logstd/logBounded level-based and structured text logging
std.metricsstd/metricsSequentially consistent counters and Prometheus samples
std.teststd/testDeterministic assertion helpers for native and corpus tests
std.cryptostd/cryptoRuntime-backed MD5/SHA-256, HMAC, PBKDF2, secure randomness, and TLS foundations
std.reflectstd/reflectBounded compiler-backed type/member metadata
std.tlsstd/tlsOpenSSL-backed verified TLS client with String and binary stream adapters
std.udpstd/udpRuntime-backed bounded endpoint/datagram transport on POSIX
std.websocketstd/websocketRuntime-backed bounded WebSocket client framing
std.compressstd/compressBounded gzip/deflate text round-trip with hex-safe compressed output
std.multipartstd/multipartBounded multipart parser/encoder with line-delimited boundaries, escaped quoted parameters, and header-injection rejection

Builtins such as Array<T> and core scalars are part of the language, not a separate import. String methods (indexOf, split, trim, toInt, …) are language surface — see Types and the cheatsheet.

std.io

Console, process, and file helpers (runtime aura_* intrinsics). Strict file APIs throw a String message on failure (missing path, I/O error, oversized file, embedded NUL). Soft tryReadFile returns null instead. Text is treated as a regular-file UTF-8 byte sequence (no embedded NUL); max size 256 MiB.

Console

APIRole
print / printlnstdout (no newline / with newline)
eprint / eprintlnstderr

Process (C12b–e)

APIRole
args(): Array<String>Process argv; [0] = program name; user flags from index 1 (C12b)
readLine(): String?One line without trailing \n / \r\n; null on EOF; empty line is "" (C12d)
readLineResult()Result<String?, String>; Ok(null) is EOF and Err is an I/O failure
readAllStdin(): StringRemainder of stdin (throws on oversize / I/O / embedded NUL)
readAllStdinResult()Result<String, String> with an owned stdin failure message
exit(code: Int)Terminate with status; flushes stdout/stderr first; does not return (C12e)

Task outcomes

join returns Result<T, TaskError>. taskErrorTypeName exposes the typed failure name when available; taskErrorSpanStart and taskErrorSpanEnd expose the retained source span, and taskErrorSourceId exposes its stable throw-origin identity without borrowing the child task frame.

Pass user args after -- with the CLI (CLI):

bash
aura run my_pkg -- --flag value
cargo run -p aura-cli -- run corpus/std_io/args -- hello
printf 'line\n' | cargo run -p aura-cli -- run corpus/std_io/stdin

Files (C11a / C12p)

APIRole
readFile(path): Stringread entire regular file (throws on error)
tryReadFile(path): String?soft read; null on missing/error (C12p)
writeFile(path, content)create/truncate and write
tryWriteFile(path, content): Boolsoft write; false on failure
readFileResult(path): Result<String, String>non-throwing read with error payload
writeFileResult(path, content): Result<Bool, String>non-throwing write with error payload
appendFile(path, content)append (create if needed)
fileExists(path): Boolregular file present
fileExistsResult(path): Result<Bool, String>non-throwing regular-file existence check
fileSize(path): Intbyte size (throws if missing)
fileSizeResult(path): Result<Int, String>non-throwing regular-file size query
openFile(path, mode): ForeignHandle<Int>owned handle; mode 0 read, 1 truncate, 2 read/write, 3 append
readFd(fd, capacity): Stringasync bounded descriptor read
readFdResult(fd, capacity): Result<String, String>async descriptor read with an owned failure message
writeFd(fd, content): Intasync descriptor write; returns bytes
writeFdResult(fd, content): Result<Int, String>async descriptor write with an owned failure message

Typical use (explicit import or auto-prelude on package builds):

aura
package main

import std.io as Io

fun main() {
  Io.println("Hello, Aura")
  val argv = Io.args()
  if (argv.len > 1) {
    Io.println(argv.get(1))
  }
  Io.writeFile("out.txt", "hi")
  val s = Io.tryReadFile("out.txt")
  if (s != null) {
    Io.println(s)
  }
}

Corpus:

bash
aura run corpus/std_io/app
aura run corpus/std_io/prelude
aura run corpus/std_io/files
aura run corpus/std_io/try_read_file
aura run corpus/std_io/args -- hello
aura run corpus/std_io/stdin
aura run corpus/std_io/exit
# monorepo: cargo run -p aura-cli -- run corpus/std_io/files

Dogfood CLI that ties args + soft read + String tools: examples/wc (README).

std.assert

std.assert.assert(condition) is the runtime assertion primitive. Use it with aura test and @test functions:

bash
aura run corpus/std_assert/app

The RFC-011 names are assertTrue, generic assertEqual, generic assertNotNull, and assertFails. The typed assertEqInt, assertEqString, and assertEqBool helpers remain alpha compatibility aliases; the language-level assert_eq helpers are separate builtins.

benchmark, snapshot, and property provide deterministic advanced testing hooks. Benchmarks use AURA_BENCH_ITERATIONS; snapshots read from AURA_SNAPSHOT_DIR and can be created or updated with AURA_UPDATE_SNAPSHOTS=1; property checks execute the requested number of cases. The CLI runner and richer generator/report protocols remain separate follow-up work.

std.collections

Type / helperNotes
Map<K, V>Linear map; getV?; put / remove / clear
Set<T>Generic set (linear)
map_string_int() / set()Empty concrete compatibility factories
HashMap<K,V>Generic open addressing with K: Hashable; containsValue (C19a)
hashMap<K,V>()Generic factory for typed named-parameter maps (compatibility factories remain)
hash_map() / hash_map_str() / hash_set()Empty generic collection factories
HashSet<T>Generic open addressing backed by HashMap<T,Bool>; containsAll(Array<T>) (C19a)
HashMapEntryHandle / HashMapLiveEntryKey-based mutation handle and epoch-checked live entry view
get / getOr / contains / replaceNullable lookup, default lookup, membership, and existing-value replacement
grow / capacity / len / isEmpty / clearTable sizing and collection state operations
Hashablehash(): Int; built-in for Int and String (C14)
keyArray() / valueArray()HashMap snapshots in logical table order (C18)
HashMapEntry<K,V> / entries()Key/value snapshot pairs in logical table order (C19b)
toArray()HashSet snapshots in logical table order (C18)
map_hash_map_valuesGeneric (K,V) -> R map-entry HOF (C18)
filter_hash_set / map_hash_setGeneric set HOFs returning arrays (C18)
Iterable<E>len + get protocol for for-in, including entry snapshots (C19c)
keyIterator() / entryIterator() / iterator()Read-only deterministic snapshots for HashMap/HashSet (C20g)
liveKeyIterator() / liveEntryIterator() / liveIterator()Invalidation-checked live HashMap/HashSet cursors (C20j)
HashMapKeyIterator / HashMapEntryIterator / HashSetIteratorSnapshot values exposing len() and get(i)
HashMapLiveKeyIterator / HashMapLiveIterator / HashSetLiveIteratorLive cursors exposing isValid(), hasNext(), and next()
map<T,R> / filter<T> / fold<T,A>Generic array HOFs; verified for Int and String (C16)
map_ints / filter_ints / fold_intsInt compatibility wrappers
map_strings / filter_strings / fold_stringsString compatibility wrappers (C12o)
join(parts, sep)Array<String>String with separator (C12j)

List<T>, List.of(...), listOf(...), and list<T>() provide the growable list API backed by owning Array<T> storage. map<R> supports element-type transforms. iterator() and toArray() return independent snapshots, so later list mutation cannot invalidate or alias the returned values.

See Arrays for HOF usage and capture limits.

bash
aura run corpus/std_collections/app
aura run corpus/std_collections/hashmap
aura run corpus/std_collections/hashmap_str
aura run corpus/std_collections/hashmap_int
aura run corpus/std_collections/hashset_int
aura run corpus/std_collections/hof
aura run corpus/std_collections/hof_str
aura run corpus/std_collections/join

Hash collection HOFs are free functions because methods cannot declare their own type parameters yet (C2b). They return arrays in logical table order and skip empty/tombstone slots; they do not mutate the source collection.

HashMap.entries() likewise returns a fresh, shallow structural snapshot of HashMapEntry<K,V> pairs. It preserves key/value pairing and can be consumed directly with for-in, but it is not a live iterator or entry view: changing an entry cannot mutate the source map.

HashMap.entry(key) returns a key-based mutation handle when the key exists. Calling handle.set(value) replaces only that existing value and returns false if it was removed. The handle retains the map and re-resolves its key on every update, so rehash and GC cannot make it stale.

HashMap.liveEntry(key) returns an invalidation-checked live view when the key exists. Its get() and set(value) operate only while isValid() is true; inserting, removing, clearing, or growing/rehashing the map invalidates the view. Updating its own value preserves validity.

Snapshot iterators are safe across source mutation, rehash, and clear. Live iterators retain their source and become terminal after structural mutation; isValid() reports the epoch check and next() returns null once invalid. Value replacement remains visible while a cursor is valid. Map live entry iterators yield HashMapLiveEntry views, whose get() and set(value) are also invalidation-checked.

std.error

Shared non-throwing error surface used by filesystem, OS, DNS, network, and HTTP adapters.

APIContract
ErrorKindRFC names: InvalidInput, Unsupported, NotFound, PermissionDenied, WouldBlock, TimedOut, Cancelled, Disconnected, LimitExceeded, Protocol, System plus legacy alpha variants
Error(kind, message, code)Owned error payload; isRetryable() identifies transient I/O/network/timeout failures
protocol / network / transport / invalidInput / notFoundError constructors; transport classifies timeout, cancellation, and peer-close diagnostics
kindCode(code)Map a native status code to the stable category number
Outcome<T,E>OutcomeOk(value) or OutcomeErr(error)
success / failure / isSuccessImport-safe outcome constructors and inspection

std.bytes

APIContract
Byte / byte(value)Nominal unsigned byte; construction rejects values outside 0..255
copy / concat / equalsOwned byte-string copy, concatenation, and exact comparison
slice(value, start, length)Bounded owned slice; returns null for invalid bounds
Buffer / newBuffer()Mutable owned binary buffer and empty-buffer factory
Buffer.length / get / cloneLength, nullable integer inspection, and deep copy
Buffer.appendByte / readByteAppend/read validated Byte values without UTF-8 conversion
Buffer.writeByte / slice / concatIn-place write, independent bounded slice, and owned concatenation
readInt16BE / readInt32BERead unsigned network-order integers; return null for invalid bounds
writeInt16BE / writeInt32BEWrite network-order integers; return false for invalid value or bounds

The legacy Buffer.push and Buffer.get integer operations remain available for compatibility. Binary protocol code should use Byte and the explicit buffer methods so payloads never pass through UTF-8 String conversion.

std.encoding

APIContract
isValidUtf8Validate a complete UTF-8 byte sequence
hexEncode / hexDecodeLowercase hexadecimal encoding and bounded decoding
base64Encode / base64DecodeRFC 4648 base64 without line wrapping
percentEncode / percentDecodeRFC 3986 component escaping; malformed escapes return null

std.json

APIContract
isValidValidate one complete bounded JSON value
errorOffsetFirst invalid byte offset, or -1 for valid input
escapeStringEncode a JSON string literal including quotes
parseReturn a validated Value, or null
Value.raw / serializeReturn the preserved validated JSON text
Value.kindReturn object, array, string, number, bool, null, or invalid
Value.isObject / isArray / isString / isNumber / isBool / isNullRoot-kind predicates
Value.get / at / asString / keysBounded source-backed traversal and string access
ParseOptions / DuplicateKeyPolicy / ParseErrorLocked bounds, duplicate-key, and typed-failure contract
parseWithOptions / parseResult / decode<T>Bounded parser outcomes plus primitive, nested primitive-array, and recursive generic class decoding
Value.clone / byteLength / depthIndependent clone and bounded source/tree metadata

Value exposes bounded object-member and array traversal. ParseOptions supports maxBytes, maxDepth, and explicit duplicate-key behavior (Reject, FirstWins, LastWins). Typed decoding supports primitives, Array<Int>, Array<Bool>, Array<String>, recursively nested primitive arrays, and recursive application classes with generic, nullable, nested-class, struct, unit-enum, and primitive/class-array fields. Payload-bearing enum mapping remains outside this bounded contract.

std.mime

APIContract
isValidTypeValidate a media type and semicolon-delimited parameters
sanitizeFilenameRemove path separators and reject unsafe or empty names
dispositionFilenameExtract and sanitize a filename parameter

std.fs

APIContract
join / basename / dirname / extensionPortable path composition and components
isAbsoluteCheck host-specific absolute path syntax
isDirectory / isSymlinkInspect filesystem node kind without throwing
fileMode0 missing/error, 1 regular file, 2 directory, 3 other node
permissionsLow nine POSIX permission bits, or 0 when unavailable
modifiedMillisUnix epoch modification time, or -1 on error
listNamesBounded newline-delimited directory-entry snapshot
readTextResult / writeTextResultShared std.error.Outcome wrappers over text file I/O

std.os

APIContract
getEnv / setEnv / unsetEnvRead, update, or remove environment variables
cwd / pid / platformCurrent directory, process ID, and platform identifier
getEnvResult / setEnvResult / unsetEnvResultNon-throwing shared error wrappers

std.net

std.net accepts endpoint strings on POSIX targets. A numeric endpoint such as "8080" binds/connects to loopback; use "0.0.0.0:8080" for all IPv4 interfaces or "[::]:8080" for IPv6. Handles are owned ForeignHandle<Int> resources and async operations preserve them across suspension.

APIContract
listen(endpoint) / connect(endpoint, timeoutMs)Legacy throwing handles; endpoint is PORT, HOST:PORT, or [IPv6]:PORT
listenResult / connectResultTyped Outcome wrappers returning owned handles or NetError
accept(listener)Async accepted-stream operation
closeListener / closeStreamIdempotent terminal close operations
closeListenerResult / closeStreamResultTyped Outcome<Bool, NetError> compatibility wrappers
readStream(stream, capacity)Async single-chunk read; empty string means EOF
readAllStream(stream, capacity)Async read-until-EOF bounded by aggregate capacity
writeStream(stream, content)Async complete write; returns transferred byte count
readExactly(stream, length)Async exact binary read into std.bytes.Buffer; distinguishes EOF and partial EOF
readExactlyWithTimeout / writeAllWithTimeoutBinary exact read/write with an operation deadline in milliseconds
writeAll(stream, bytes)Async complete binary write from std.bytes.Buffer; returns byte count
readStreamResult / writeStreamResultShared std.error.Outcome wrappers

std.dns

APIContract
resolveHost(host, preferIpv6)One numeric IPv4/IPv6 address, or null
resolveHostList(host, preferIpv6)Preference-ordered newline-delimited address list
resolveHostResultShared network error outcome for lookup failure

std.url

APIContract
isOriginForm / path / normalizePathValidate and process HTTP origin-form targets
query / queryValueRead raw query text or one exact key value
isAbsolute / authorityValidate and extract absolute-URI authority
authorityHost / authorityPortExtract host and explicit decimal port
encodeComponent / decodeComponentRFC 3986 component encoding and bounded decoding

std.http

Bounded HTTP/1.1 values and loopback client/server helpers built on std.net. Server handlers receive scoped Request and Response objects; raw foreign handles remain package-private.

The bounded server accepts origin-form GET, HEAD, POST, PUT, PATCH, DELETE, and OPTIONS requests. Other methods receive a bounded 405 response.

APIContract
Handler(Request, Response) -> Task<Unit> handler type
serveConnection / serveAsync bounded HTTP server entry points
get / postAsync raw response helpers for loopback servers
ClientResponse(status, body)Parsed bounded response value
getResponse / postResponseRaw client helpers returning ClientResponse
getResponseResult / postResponseResultTyped response helpers returning std.error.Outcome, including transport failures
Request.method / target / versionRequest-line fields
Request.headerCount / headerName / headerValueBounded header snapshot access
Request.body / bodyReaderBody snapshot or single-reader body adapter
RequestBody.readChunkAsync bounded single-reader chunk read; claim is held across suspension and empty string means EOF
RequestBody.readChunkResultTyped Outcome<String, HttpError> body-read boundary
Response.status / keepAliveInspect response state
Response.setStatus / setKeepAlive / setBody / addHeaderConfigure response before commit
Response.writeChunkAsync chunked response write; commits on first call
Response.writeChunkResultTyped Outcome<Bool, HttpError> response-write boundary

std.stream

APIContract
Reader(stream)Handler-scoped async reader over an owned network stream
Reader.read(capacity)Read one bounded String chunk
Reader.readBytes / readExactlyExact binary reads into std.bytes.Buffer
Writer.writeBytes / writeAllComplete binary writes from std.bytes.Buffer
Reader.close()Idempotently close the underlying stream
Writer(stream)Handler-scoped async writer over an owned network stream
Writer.write(content)Write all content and return transferred bytes
Writer.close()Idempotently close the underlying stream

std.time

All clocks and deadlines are monotonic; wall-clock changes do not affect them.

APIContract
Duration(milliseconds) / millisecondsTyped duration; negative values are representable but invalid
Duration.isValidCheck for a non-negative duration
nowMillisCurrent monotonic timestamp
Deadline(atMillis)Absolute monotonic expiry point
Deadline.isExpired / remainingInspect expiry and get a non-negative remainder
after(duration)Create a deadline relative to now
sleep / sleepFor / sleepUntilAsync monotonic suspension helpers

std.task

APIContract
joinTask(task)Observe completion as std.io.Result<T, TaskError>
cancelTask(task)Request cooperative cancellation; idempotent
cancelAfter(task, milliseconds)Arm delayed cancellation; false for invalid/terminal tasks
linkCancellation(parent, child)Propagate cancellation between live tasks
isCancelled()Inspect cancellation of the current async task
taskScope(body)Structured scope with child adoption and cancellation drain
Select<T> / select<T>()Scheduler-backed channel selection with fair wakeups
spawnBlocking<T>(body)OS-worker execution with cooperative cancellation

std.sync

These primitives are nonblocking. tryLock, tryRead, and tryWrite return false instead of blocking an async worker.

APIContract
AtomicIntSequentially consistent load, store, fetchAdd, and compareExchange
MutextryLock, unlock, and isLocked cooperative mutex state
RwLockNonblocking tryRead/tryWrite, unlockRead/unlockWrite, readerCount, and isWriteLocked
OnceOne-shot tryEnter gate and isDone inspection
Lazy<T> / lazy<T>()Exactly-once task-safe initialization cell

std.signal

APIContract
installShutdown()Install SIGINT/SIGTERM handling on supported targets
shutdownRequested()Read the in-process graceful-shutdown flag
clearShutdown()Clear the flag after the application drains work

std.log

APIContract
debug / info / warn / errorEmit level-filtered text events
setMinLevel(level)Set 0=debug, 1=info, 2=warn, 3=error threshold
minLevel()Read the current threshold
infoFields / errorFieldsEmit alternating key/value context fields; odd trailing fields are ignored

std.metrics

APIContract
CounterMutable sequentially consistent integer counter
add / increment / get / resetCounter mutation and inspection
prometheus(name)Render one Prometheus text exposition sample

std.test

APIContract
assert(condition)Fail the current test when false
assertTrue / assertEqual / assertNotNull / assertFailsRFC-011 canonical test assertions

std.crypto

The alpha contract provides Digest, TlsConfig, TlsConnection, randomBytes, randomBytesBuffer, md5Bytes, sha256, sha256Bytes, hmacSha256, hmacSha256Bytes, pbkdf2Sha256, and constantTimeEquals. Binary crypto APIs accept and return std.bytes.Buffer, so NUL bytes are preserved. PBKDF2-HMAC-SHA-256 supports SCRAM-SHA-256 key derivation; hashPassword and verifyPassword provide versioned salted password records; randomness, hashes, HMAC, PBKDF2, and constant time comparison are backed by the native runtime.

std.tls

APIContract
config(serverName, verifyPeer)Verified TLS configuration
connect(endpoint, options)Async OpenSSL client with hostname verification
wrapStream(stream, endpoint, options)Upgrade an existing std.net TCP stream without String conversion
Connection.read / writeString compatibility stream operations
Connection.readBytes / writeBytesBinary stream operations over std.bytes.Buffer
*WithTimeout methodsBinary operations with a monotonic deadline in milliseconds
Connection.close()Idempotent close; pending TLS waits are woken and resources released
loadCertificate(path)Load bounded certificate subject and issuer metadata

TLS async operations use the underlying TCP readiness scheduler. A cancelled read or write closes the TLS session and wakes the socket wait, preventing a cancelled task from retaining a blocked descriptor.

std.reflect

The package provides compiler-backed typeOf<T>, typeIdOf<T>, type-kind classification, and declaration metadata. Primitive types are always reflectable; user classes, structs, enums, and interfaces opt in with @reflect. Only public fields and methods are exposed. Closed generic class and interface metadata uses the concrete monomorph name and substitutes type parameters in exposed field and method return types.

Bounded protocol packages

std.tls, std.websocket, std.compress, and std.multipart provide runtime-backed bounded implementations with explicit size and platform limits. Unix sockets, HTTP/2/3, and QUIC remain reserved without a public package until their ownership and capability contracts are settled.

How the CLI finds std.*

  • Auto-prelude std.io for package builds
  • Path resolution for any std.* package:
    1. AURA_STD (directory that contains package directories)
    2. Walk-up from the package looking for monorepo std/<pkg>
    3. Release install: share/aura/std/<pkg> next to the toolchain
    4. Embedded copy materialized under ~/.cache/aura/<version>/std/

After a normal install (or cargo install of a recent CLI), you should not need to declare std.io = { path = "..." } in app aura.toml.

What is not in core (by design)

Application frameworks, DI containers, ORM/HTTP stacks stay out of core RFCs. Expect those as ecosystem packages later, not as stdlib defaults.

Next

All docs pages