Standard Library

Standard Library

The Sun standard library is distributed as a precompiled stdlib.moon file. Include it in your manifest and import the std namespace:

using std;
 
function main() void {
  // Use stdlib types...
}
 
manifest {
  libraries: ["stdlib.moon"]
}

An installed compiler finds stdlib.moon on its own — the Homebrew and Debian packages put it where the compiler already looks. SUN_PATH is only needed when you built from source, where it points at the build/ directory: export SUN_PATH=/path/to/sun/build. See Path Resolution for every place that is searched.

The library's own tests are Sun code: each stdlib/<area>_tests.sun sits next to the file it tests, listed under test_files: in the manifest (see Testing). They compile only into the test binary, never into stdlib.moon.

Modules

Import the module for the API you use. using std; provides core types such as String, Vec, Option, and Error; it does not import child modules.

ModuleAPIs
std.ioPrinting, files, streams, and readiness polling
std.netIPv4, TCP, UDP, and socket configuration
std.httpHTTP requests, responses, and servers
std.jsonJSON values, parsing, and serialization
std.xmlXML documents, parsing, and serialization
std.linalgMatrices, matrix views, and linear algebra

For example, printing now needs using std.io;, and TCP sockets need using std.net;. Qualified calls use names such as std.io.println and std.net.TcpStream. Tests for each API use that same module.

Memory allocation (std.mem)

Import std.mem for allocator types, typed allocation functions, and Unique. IAllocator exposes only alloc_raw(size, alignment) and dealloc_raw(pointer, size, alignment), so a const ref IAllocator can select any implementation at runtime.

HeapAllocator

global_allocator is the immutable system heap allocator. Pass it explicitly to allocating APIs; it can be shared across functions and modules without constructing an allocator in each function. HeapAllocator() and make_heap_allocator() remain available and do not allocate.

function build_values() Vec<i32> throws {
  var values = Vec<i32>(std.mem.global_allocator, 4);
  values.push(42);
  return values;
}

Allocation returns storage directly and may throw AllocationError, InvalidArgumentError, or OverflowError. Negative sizes are rejected before calling the system allocator; typed size multiplication is checked. Zero-sized requests own at least one physical byte and are freed normally.

FunctionReturn typeBehavior
alloc<T>(allocator, count)raw_ptr<T> throwsAllocate aligned, uninitialized element storage
dealloc<T>(allocator, pointer, count)voidRelease storage after destroying initialized values
create<T>(allocator, args...)raw_ptr<T> throwsAllocate and construct a value
create_unique<T>(allocator, args...)Unique<T, const ref IAllocator> throwsConstruct an automatically owned value
create_interface<I>(allocator, value)I throwsMove a concrete value into an owning interface

These functions take const ref IAllocator. Owners retain that borrow until cleanup completes, including when the allocator is a local HeapAllocator. Use global_allocator when the result must escape the current function. create_interface consumes an already constructed value even if allocation fails. It makes one aligned allocation containing both the allocator reference and the concrete value. Dropping the owner destroys the value and releases the box through that allocator.

ArenaAllocator

ArenaAllocator(capacity: i64) throws allocates a fixed-capacity heap buffer and private allocation state. Negative capacities are rejected. It does not grow implicitly. create_interface<I>(arena, value) reserves aligned storage, throwing AllocationError when capacity is exhausted; zero-sized values still reserve storage. Allocation cursor updates are synchronized.

Arena owners borrow the arena. Dropping an owner destroys its concrete value and owned fields, but does not reclaim its slot. reset() reclaims all slots and requires that all owners and views borrowing the arena have left scope. The arena cannot be moved, replaced, or destroyed while those borrows remain live. Collections retain the lifetime restrictions of their elements conservatively until they die.

create and create_unique propagate supported constructor errors. A failed allocation never runs the constructor. Failed construction releases raw storage and drops initialized fields without calling the incomplete object's destructor. Unsupported constructor error payloads are rejected during compilation.

String and container construction, growth, cloning, and serialization also return results when they can allocate. Use try in a function with a compatible result return type, or match to handle failure locally. Failed vector or map growth preserves existing contents and capacity. Arguments passed by value are still consumed according to the usual ownership rules.

function make_point() std.mem.Unique<Point, const ref std.mem.IAllocator> throws {
  return std.mem.create_unique<Point>(std.mem.global_allocator, 3, 4);
}

Unique<T, A>

An owner that destroys its value and returns the allocation through its allocator binding when it leaves scope. Both type arguments are required. Use Unique<T, HeapAllocator> for an owned stateless heap allocator, or Unique<T, const ref A> to borrow a stateful allocator. The latter cannot outlive its allocator and prevents mutation such as arena reset while it remains live. Unique<T, const ref IAllocator> accepts any allocator implementation through runtime dispatch; this is the type returned by create_unique<T>.

Unique<T, A>(value, allocator) allocates storage and consumes the value and any owned allocator argument. Raw-pointer adoption uses an unsafe constructor and requires exclusive ownership of initialized storage compatible with the allocator. get() panics on an empty owner.

var p = std.mem.create_unique<Point>(std.mem.global_allocator, 3, 4);
p.get().x;  // Safe access - returns ref T
p.get_raw();  // Get raw pointer for low-level operations
p.is_null();  // Check if null
// p.deinit() called automatically at scope exit
MethodSignatureDescription
get()() ref TSafe dereference - returns a reference to the value
get_raw()() raw_ptr<T>Get the underlying raw pointer
is_null()() boolCheck if pointer is null
deinit()() voidFree memory (called automatically)

Shared<T>

The shared-ownership counterpart to Unique<T, A>: Unique has one owner, Shared has as many as you like, and it is safe to hand to several threads. The value lives in a heap box next to a std.thread.Mutex and an atomic count of the live handles. clone() adds an owner, and the last handle to go drops the value and frees the box.

Since Sun never copies implicitly, every extra owner is a visible clone(). The value is reachable only through lock(), which waits for the lock and returns a guard that releases it when dropped.

var s = Shared<Counter>(std.mem.global_allocator, Counter());
 
var c = s.clone();  // two owners now
s.count();  // 2
 
if (true) {
  var g = s.lock();  // g holds the lock
  g.get().n = 42;  // the value, as a reference
}  // g is dropped here, which unlocks
MethodSignatureDescription
clone()() Shared<T>Another owner of the same value
lock()() SharedGuard<T>Wait for the lock, return a guard that holds it
count()() i32How many owners there are right now
is_null()() boolWhether the handle has been moved out of
deinit()() voidDrop one owner (called automatically)
SharedGuard<T> methodSignatureDescription
get()() ref TThe shared value, as a reference
deinit()() voidRelease the lock (called automatically)

See Threads for sharing one value between several threads.

Vec<T>

A generic growable array backed by contiguous memory. Implements IIterable<T, Vec<T>> for use with for-in loops.

var v = Vec<i32>(std.mem.global_allocator, 8);  // Initial capacity 8
v.push(10);
v.push(20);
v.push(30);
v.set(1, 25);  // Update index 1
var last = v.pop();  // Option.Some(30) (removes last element)
var len = v.size();  // 2
var val = v.get(0);  // Borrows 10; keep the Vec unchanged while using val
MethodSignatureDescription
push(value)(T) void throwsAppend element (grows if needed)
pop()() Option<T>Remove and return last element; None when empty (ownership moves to the caller)
get(index)(i64) ref T throwsBorrow an element or report an invalid index
set(index, value)(i64, T) void throwsReplace an element or report an invalid index
size()() i64Current number of elements
capacity()() i64Current allocated capacity
is_empty()() boolCheck if empty
reserve(n)(i64) void throwsEnsure capacity for at least n elements
clear()() voidRemove all elements (doesn't deallocate)
first()() Option<ref T>Borrow the first element; None when empty
last()() Option<ref T>Borrow the last element; None when empty
iter()() VecIterator<T>Get iterator for for-in loops

Indexing

Vec<T> supports bracket indexing syntax:

v[0] = 42;  // Calls __setindex__
var x = v[0];  // Calls __index__

Iteration

using std.io;
 
var v = Vec<i32>(allocator, 4);
v.push(1);
v.push(2);
v.push(3);
 
for (var x: i32 in v) {
  println(x);
}

Map<K, V>

A generic hash map using open addressing with linear probing. Implements IIterable<V, Map<K, V>> for iterating over values. Supports i32, i64, and String keys.

var m = Map<i64, i32>(std.mem.global_allocator, 16);  // Initial capacity 16
m.insert(42, 100);
var fallback: i32 = 0;
var val: i32 = m.get_or_default(42, fallback);  // 100
try { m.remove(42); } catch (error: NotFoundError) {}
MethodSignatureDescription
insert(key, value)(K, V) void throwsInsert or update a key-value pair
get(key)(K) ref V throwsBorrow the value or throw NotFoundError
find(key)(K) Option<ref V>Get value by key; None if not present
get_or_default(key, default)(K, ref V) ref VGet value or return default
remove(key)(K) V throwsRemove the value or throw NotFoundError
contains(key)(K) boolCheck if key exists
size()() i64Number of entries
capacity()() i64Number of buckets
is_empty()() boolCheck if empty
clear()() voidRemove all entries
iter()() MapIterator<K, V>Get iterator over values

Handle get and remove with try/catch, or propagate their exceptions from a function declared throws.

Iteration

using std.io;
 
var m = Map<i64, i32>(allocator, 16);
m.insert(1, 10);
m.insert(2, 20);
 
for (var v: i32 in m) {
  println(v);  // Iterates over values
}
⚠️

The map automatically grows when load factor exceeds 70%. Initial capacity should be chosen based on expected size for best performance.

String

A heap-allocated mutable string backed by Matrix<u8>. Supports slicing via the [start:end] syntax which returns a StringView.

using std.io;
var s = String(std.mem.global_allocator, "Hello");
var t = String("literal only");  // uses global_allocator
println(s.length());  // 5
var ch = s.at(0);  // b'H'
s.append_char(b'!');  // Append a byte
s.push('😀');  // Append a char, UTF-8 encoded

A String holds UTF-8 and is indexed by byte: at, length and the *_char methods all work in bytes, so they pair with byte literals (b'!'). The methods that speak in Unicode scalar values — push, iterate_chars, count_chars, and the char overloads of find / rfind / contains — take and yield char. See Characters and Bytes.

MethodSignatureDescription
length()() i64Current string length
capacity()() i64Allocated capacity
is_empty()() boolTrue when the string has no bytes
at(i)(i64) u8 throwsRead a byte; reject indices outside length()
set_at(i, val)(i64, u8) void throwsWrite a byte; reject indices outside length()
unsafe_at(i)(i64) u8Unchecked read; requires an unsafe block
unsafe_set_at(i, val)(i64, u8) voidUnchecked write; requires an unsafe block
append_char(ch)(u8) void throwsAppend a single byte
append(other)(const ref String) void throwsAppend another String
append_literal(s)(static_ptr<u8>) void throwsAppend a string literal
equals_literal(s)(static_ptr<u8>) boolCompare with a string literal
find_char(ch)(u8) Option<i64>Index of first occurrence; None if absent
rfind_char(ch)(u8) Option<i64>Index of last occurrence; None if absent
contains_char(ch)(u8) boolCheck if the byte occurs
push(c)(char) void throwsAppend the UTF-8 encoding of a char (1 to 4 bytes)
iterate_chars()() CharsIterate the string as Unicode scalar values
count_chars()() i64Number of scalar values, which is length() only for ASCII
find(c)(char) Option<i64>Byte index of the first occurrence of a char; None if absent
rfind(c)(char) Option<i64>Byte index of the last occurrence of a char; None if absent
contains(c)(char) boolCheck if the char occurs
find(needle)(static_ptr<u8>) Option<i64>, (const ref String) Option<i64>Index of first occurrence of a substring; None if absent
contains(needle)(static_ptr<u8>) bool, (const ref String) boolCheck if the substring occurs
starts_with(s) / ends_with(s)(static_ptr<u8>) bool, (const ref String) boolPrefix / suffix check
append_i64(n) / append_u64(n)(i64) void throwsAppend an integer in decimal
append_f64(x)(f64) void throwsAppend a float in its shortest round-trip form (0.1, 1e+21)
append(x)(f64) void throws, (f32) void throws, ...Overloads used by ${x} interpolation for every primitive
parse_i64()() Option<i64>Whole string as a decimal integer; None if malformed or out of range
parse_f64()() Option<f64>Whole string as a decimal float; None if malformed
bytes()() raw_ptr<u8> (const method)Borrow the bytes without allocating or adding a NUL terminator
c_str()() raw_ptr<u8>NUL-terminated pointer for C, valid until the next mutation

bytes() works on a const ref String. Read only length() bytes and do not write through the pointer. The pointer remains valid until the next mutation or until the string is destroyed. Pass it with the length to C functions that accept a byte buffer.

The terminator c_str() writes sits past the length, so the string itself is unchanged. from_c_str(alloc, p) is the other direction — it copies a NUL-terminated C string into an owned String, which is how Env and read_dir keep text returned by libc.

var path = String(alloc, "/tmp/");
path.append_literal("out.txt");
write_string(path.c_str(), body);

Text Manipulation

Methods that keep the same bytes, or fewer, edit the string in place. Methods that produce new strings take the allocator to build them with.

var line = String(allocator, "  name = Ada  ");
line.trim();  // "name = Ada"
line.replace(" = ", "=");  // "name=Ada"
line.to_upper();  // "NAME=ADA"
var fields = line.split(allocator, 61);  // ['=' is 61] -> ["NAME", "ADA"]
var again = join(allocator, fields, "=");  // "NAME=ADA"
MethodSignatureDescription
to_lower() / to_upper()() voidConvert ASCII letters in place
trim()() voidDrop leading and trailing ASCII whitespace in place
trim_start() / trim_end()() voidDrop whitespace from one end in place
reverse()() voidReverse the bytes in place
replace(from, to)(static_ptr<u8>, static_ptr<u8>) void throws, (const ref String, const ref String) void throwsReplace every occurrence in place; an empty from does nothing
clone(alloc)(const ref HeapAllocator) String throwsCopy into a new String
substr(alloc, start, count)(const ref HeapAllocator, i64, i64) String throwsCopy a byte range or return OutOfBounds
split(alloc, sep)(const ref HeapAllocator, u8) Vec<String> throws, (const ref HeapAllocator, static_ptr<u8>) Vec<String> throwsSplit into owned pieces; always yields one piece more than there are separators
split_nonempty(alloc, sep)(const ref HeapAllocator, u8) Vec<String> throws, (const ref HeapAllocator, static_ptr<u8>) Vec<String> throwsLike split, but empty pieces are dropped: adjacent, leading, and trailing separators yield nothing
split_whitespace(alloc)(const ref HeapAllocator) Vec<String> throwsSplit on runs of ASCII whitespace; never yields an empty piece
join(alloc, parts, sep)(const ref HeapAllocator, const ref Vec<String>, static_ptr<u8>) String throwsFree function: concatenate pieces with a separator between them

Slicing

String slicing returns a StringView (non-owning view, no copy):

using std.io;
 
var s = String(allocator, "Hello, World!");
var view = s[0:5];  // StringView of "Hello"
println(view.length());  // 5

Character helpers

Free functions in std for moving between char and code points.

FunctionSignatureDescription
char_of(code)(i64) Option<char>A char from a code point; None for a surrogate or anything above U+10FFFF
code_of(c)(char) i64The code point of a char
compute_utf8_len(code)(i64) i64Bytes the UTF-8 encoding of a code point occupies
encode_utf8_byte(code, j)(i64, i64) u8Byte j of that encoding

char_of is the checked counterpart to _convert<char>(n), which does not verify that n is a Unicode scalar value.

Chars

Iterates a String as Unicode scalar values, decoding UTF-8 as it goes. Obtained from String.iterate_chars().

using std.io;
 
var s = String(alloc, "héllo😀");
s.length();  // 10 bytes
s.count_chars();  // 6 scalar values
 
var it = s.iterate_chars();
for (var c: char in it) {
  print(c);
}
MethodSignatureDescription
next(self)(ref Chars) Option<char>Next scalar value; None at the end
offset()() i64Byte offset of the scalar value next will return

Bytes that are not well-formed UTF-8 decode as U+FFFD and advance one byte, so iteration always terminates and always covers the whole string.

A Chars borrows the string's bytes: it must not outlive the String, and any mutation of that String invalidates it.

StringView

A non-owning view into a String. Provides read-only access to a substring without copying.

MethodSignatureDescription
length()() i64View length
at(i)(i64) u8 throwsRead a byte; reject indices outside the view
unsafe_at(i)(i64) u8Unchecked read relative to the view; requires an unsafe block
equals_literal(s)(static_ptr<u8>) boolCompare with a string literal
find_char(ch)(u8) Option<i64>Index of first occurrence; None if absent
rfind_char(ch)(u8) Option<i64>Index of last occurrence; None if absent
contains_char(ch)(u8) boolCheck if the byte occurs
append_i64(n) / append_u64(n)(i64) void throwsAppend an integer in decimal
append_f64(x)(f64) void throwsAppend a float in its shortest round-trip form (0.1, 1e+21)
append(x)(f64) void throws, (f32) void throws, ...Overloads used by ${x} interpolation for every primitive
parse_i64()() Option<i64>Whole string as a decimal integer; None if malformed or out of range
parse_f64()() Option<f64>Whole string as a decimal float; None if malformed
⚠️

A StringView must not outlive the parent String. The view holds a reference to the String's internal memory.

Matrix<T>

N-dimensional matrices backed by contiguous heap memory. Supports bracket indexing and slicing.

using std.linalg;
var m = Matrix<i32>(std.mem.global_allocator, [3, 3]);  // 3x3 matrix
m[0, 0] = 1;
m[1, 1] = 5;
var val = m[1, 1];  // 5
MethodSignatureDescription
get(indices)(ref array<i64>) TGet element at indices
set(indices, value)(ref array<i64>, T) voidSet element at indices
dim(i)(i64) i64Size of dimension i
size()() i64Total number of elements
ndims()() i64Number of dimensions

See Matrices for detailed documentation.

Threads

stdlib/std/thread/thread.sun (module std.thread). spawn starts an OS thread and hands back a handle that joins when it is dropped, so a thread never outlives the scope that started it.

using std.thread;
var t = spawn((n: i32) => i32 { return n * 2; }, 21);
var answer = t.join();  // 42
FunctionSignatureDescription
spawn()<F: _Callable>(fn: F, args...: _params_of<F>) Thread<_return_type_of<F>> throwsRun fn on a new thread with args, which move into it
Thread<T> methodSignatureDescription
join()() TBlock until the thread finishes, and take its result

Online CPU count

std.thread.online_cpu_count() returns i64 throws with the number of online logical CPUs on each call. It does not report process affinity, container quotas, or a recommended worker count. Failure is explicit; callers choose their own fallback if needed.

Atomic Boolean

std.thread.AtomicBool() starts false; AtomicBool(true) starts true. It stores its value inline and allocates nothing. On supported x86-64 and AArch64 targets, its naturally aligned 32-bit operations are lock-free, with no lock fallback.

MethodOrderingResult
load()AcquireCurrent Boolean
store(value)ReleaseSets the Boolean
compare_exchange(expected, desired)Acquire-release on success; acquire on failureWhether the value was replaced

A release store followed by an acquire load that observes it publishes preceding writes to the reader. These operations are not sequentially consistent. Keep the flag at a stable address while shared: initialization, moves, and destruction require exclusive access. Sun does not implicitly copy the flag. Only these atomic operations are signal-safe on the named targets; this is not a signal-safety promise for arbitrary calling code or generic atomic implementations.

Mutex

Mutual exclusion, using an atomic compare-and-swap for the uncontended case and futex blocking under contention.

var m = Mutex();
m.lock();
// Critical section
m.unlock();
MethodSignatureDescription
lock()() voidAcquire the lock (blocks if contended)
unlock()() voidRelease the lock

See Threads for the whole picture.

File I/O

stdlib/std/io/io.sun (module std.io). Every path is taken two ways: as a static_ptr<u8> — what a string literal is — and as a ref String for a path put together at runtime. Fallible calls throw Error with a bounded Error. The examples use try inside a function returning a compatible result.

using std;
using std.io;
 
var f = File();
f.open("notes.txt", FileMode.Write);
f.write("Hello, World!");
f.close();
 
// Or in one step
var text = read_to_string(alloc, "notes.txt");
 
// A runtime path
var path = String(alloc, "/tmp/");
path.append_literal("report.csv");
write_string(path, text);

FileMode is Read (must exist), Write (create or truncate) or Append. Whence is Start, Current or End.

MethodSignatureDescription
open(path: Path, mode: FileMode) void throwsOpen a file
adopt(fd: i32) voidTake ownership of an open descriptor
write(data: static_ptr<u8>) i64 / (data: ref String) i64Bytes written
write_all(bytes: const ref ByteSlice) WriteResultWrite a bounded slice, retrying short writes and interruptions
write_bytesunsafe (buf: raw_ptr<u8>, len: i64) i64Write caller-validated raw storage
read_all(alloc: const ref HeapAllocator) String throwsRead to end of file
read(bytes: ref MutableByteSlice) ReadResultRead into a bounded slice, retrying interruptions
read_intounsafe (buf: raw_ptr<u8>, len: i64) i64Read into caller-validated raw storage
seek(offset: i64, whence: Whence) i64New offset from the start
tell / size() i64Current position / total length
sync / truncate() void throws / (length: i64) void throwsFlush / resize
close / is_open / get_fdClose (idempotent), query, borrow the fd

A File closes itself at scope exit. The descriptor it holds is 0 when it holds nothing, so a moved-from File — which is zeroed — closes nothing rather than closing stdin.

Borrowed streams and bounded bytes

std.io.stdin(), stdout(), and stderr() return BorrowedStream handles. Dropping a handle never closes the descriptor. BorrowedStream(fd) also borrows an existing descriptor; its owner must keep it open during use.

ByteSlice(buffer) borrows a ContiguousBuffer<u8> read-only, while MutableByteSlice(buffer) borrows it mutably. Neither allocates or copies bytes. The (buffer, start, count) constructors throw IndexOutOfBoundsError for negative, overflowing, or out-of-bounds ranges. The backing buffer remains borrowed while the slice is in use. Slices expose size() and checked get(index).

using std.io;
using std;
 
/** Reads a bounded chunk from standard input. */
function read_chunk(alloc: const ref std.mem.HeapAllocator) void throws {
  var buffer = ContiguousBuffer<u8>(alloc, 4096);
  var bytes = MutableByteSlice(buffer);
  var input = std.io.stdin();
  match input.read(bytes) {
    std.io.ReadResult.Data(count) => println(count),
    std.io.ReadResult.Eof => println("end of input"),
    std.io.ReadResult.WouldBlock => println("try again when readable")
  };
  return;
}

Both File and BorrowedStream provide read and write_all:

  • read returns Data(count) as soon as bytes arrive, Eof for end of input, or WouldBlock for a nonblocking descriptor with no available bytes. Failures throw Error. An empty slice returns Data(0) without a system call.
  • write_all retries short writes until complete. It returns Complete(count), or WouldBlock(count). Failures throw WriteError, whose transferred() method reports the number of bytes already written. To resume, pass a new slice starting after that prefix; do not resend the whole original slice. An empty slice returns Complete(0) without I/O.
  • Both retry interrupted calls. A zero-progress write is an error. Descriptor flags and process signal handling are unchanged, including native SIGPIPE behavior for writes to closed pipes.

std.byte_order.read_native_u16/u32/u64 and read_native_i16/i32/i64 take a const ref ByteSlice and a byte offset, returning integer throws. They accept unaligned offsets and check against the slice's bounds before copying the integer in the target's native byte order. No allocation is needed.

Free functions:

FunctionSignature
read_to_string(alloc: const ref HeapAllocator, path: Path) String throws
write_string(path: Path, contents: ref String) void throws
remove_file / remove_dir(path: Path) void throws
rename_file(old_path: Path, new_path: Path) void throws
make_dir(path: Path, mode: i32) void throws
exists / is_dir / is_file(path: Path) bool
get_file_size(path: Path) i64 throws
read_line(alloc: const ref HeapAllocator) Option<String> throws

Path stands for the two overloads each of these has: static_ptr<u8> (a string literal) and ref String (a path built at runtime). rename_file has all four combinations.

read_line reads stdin one byte at a time and strips the newline, returning None only at end of input with nothing read. It is deliberately unbuffered: a buffered reader would swallow bytes a child process spawned later expects to find on the descriptor.

Open-file metadata

File.metadata() returns FileMetadata throws for the same open object that subsequent reads use, including after rename or unlink. It does not resolve the path again or change the seek position. A closed file throws an exception.

FieldTypeMeaning
kindFileKindRegular file, directory, symlink, or another native file kind
sizei64Byte size; interpretation for nonregular files is OS-specific
modified.secondsi64Unix seconds, including negative values before the epoch
modified.nanosecondsi64Subsecond remainder, from zero through 999,999,999

Metadata is a snapshot, not a lock against concurrent writes. Filesystem timestamp precision varies. Normally opened symlinks describe their targets. The private stdlib boundary handles Linux x86-64/AArch64 and macOS Intel/Apple Silicon stat layouts; applications need neither raw pointers nor native declarations.

Bounded file lines

LineReader(alloc, file, max_line_length, buffer_size) borrows an open File and returns LineReader throws. The maximum is measured in bytes, excluding LF. A zero maximum allows empty lines; negative limits and nonpositive buffer sizes are rejected. Do not close, seek, or read the file separately while the reader is in use.

using std.io;
 
var file = File();
file.open("recording.jsonl", FileMode.Read);
var reader = LineReader(alloc, file, 65536, 4096);
match reader.next() {
  LineReadResult.Complete => println(reader.line()),
  LineReadResult.Incomplete => println("unterminated final record"),
  LineReadResult.TooLong => println("record exceeds the byte limit"),
  LineReadResult.Eof => {},
  LineReadResult.WouldBlock => {}
};

Call next() for each record. line() borrows the bytes until the next call; clone the string explicitly to retain it. LF is removed, while CR and other bytes are preserved. Incomplete reports nonempty final data without LF separately from Eof. TooLong takes precedence for an overlong final record, retains only the bounded prefix, and drains through LF or EOF so the following call can continue with the next record. EOF remains EOF on subsequent calls.

The reader retries interrupted reads and accumulates short reads. WouldBlock and Error preserve partial data for a later retry, including progress while skipping an overlong line. Storage consists of the fixed read buffer and a string that grows on demand up to the line limit (with spare capacity) and is reused; it does not grow with the total file size.

Reading a directory

read_dir returns the entries with their kind attached, taken from the directory record itself — no second syscall per entry, and no application-level parsing of getdents64 output.

using std.io;
 
var entries = read_dir(alloc, "/etc");
for (var e: DirEntry in entries) {
  if (e.is_dir()) {
    print("dir  ");
  } else {
    print("file ");
  }
  println(e.name());
}
ItemSignatureDescription
read_dir(alloc: const ref HeapAllocator, path: Path) Vec<DirEntry> throws. and .. excluded, filesystem order
DirEntry.name() ref StringBorrowed — the entry keeps it
DirEntry.kind() FileKindFile, Dir, Symlink, Other or Unknown
DirEntry.is_dir / is_file() bool

Some filesystems do not report a kind, giving FileKind.Unknown; is_dir(path) answers it with a syscall when that matters.

Waiting on descriptors

EventLoop uses epoll on Linux and kqueue on macOS. It watches descriptors without scanning every registration on each wait. Call open() before adding borrowed descriptors, and remove them before closing or reusing them. The loop owns its queue and closes it on destruction. Registration changes can allocate through the supplied allocator; waits reuse storage reserved by the constructor.

var loop = EventLoop(alloc, 64);  // maximum native events per batch
loop.open();
loop.add(sock_fd, POLLIN, 42u64);
var count = loop.wait(std.time.create_duration_millis(250));
for (var i: i64 = 0; i < count; i = i + 1) {
  var event = loop.event_at(i);
  if (event.is_readable()) { /* read from event.fd(); identify it by event.token() */ }
  if (event.is_hup()) { /* drain buffered input before closing */ }
}
loop.modify(sock_fd, POLLIN | POLLOUT, 42u64);
loop.remove(sock_fd);

Interest accepts POLLIN, POLLOUT, both, or zero to suspend normal readiness. Errors and hangups are reported through is_error() and is_hup(); their reporting for suspended descriptors depends on the OS. Tokens are full-width u64 values and need not be unique. Duplicate adds and missing modify/remove operations throw exceptions. Failed changes preserve registrations; if macOS cannot roll back a partial filter change, the loop closes and reports that failure.

Readiness is level-triggered: data remains ready until consumed. An integer wait timeout of zero polls, -1 waits indefinitely, and other negative values are rejected. Duration waits round up fractional milliseconds. Signals return an interrupted system error recognized by is_interrupted(error.code()) rather than an OS-specific constant. A timeout returns zero. Each wait replaces the previous batch, including on failure. event_at() checks bounds and returns an independent snapshot without allocating. macOS may return separate read and write events for one descriptor; event order is unspecified. A full batch does not discard remaining readiness. Use a loop from one thread at a time. Read interest reports peer write-half-close through is_hup() on both backends; drain buffered input before acting on EOF.

Modifying or removing a registration invalidates only its cached events, even if its descriptor and application token are reused. event_at() returns IndexOutOfBoundsError for these stale slots; skip them and continue dispatch. Already returned snapshots remain historical values after registration changes.

Poller wraps portable poll(2). Removal preserves the remaining registration order and readiness flags in linear time. Its integer timeout overload keeps descriptors in registration order, so is_readable(i) answers for the i-th one. Nothing here needs a struct pollfd assembled by hand.

var poller = Poller(alloc);
poller.add_read(sock_fd);
poller.add_read(pipe_fd);
 
var ready = poller.wait(1000);  // -1 blocks forever
if (poller.is_readable(0)) { /* sock_fd has data */ }
if (poller.is_hup(1)) { /* pipe_fd's writer closed */ }

For a finite wait, pass a Duration to receive only the descriptors that reported an event. Positive fractions of a millisecond round up, and very long durations clamp to the largest i32 timeout.

using std.time;
 
var events = poller.wait(create_duration_millis(250));
for (var event: ref Event in events) {
  if (event.is_readable()) { /* event.fd() has data */ }
  if (event.is_hup()) { /* event.fd() reached end of stream */ }
}
 
poller.modify(sock_fd, POLLOUT);  // replaces interest in every matching registration
poller.remove(sock_fd);  // removes every registration for sock_fd
MethodSignatureDescription
add_read / add_write / add_read_write(fd: i32) voidWatch a descriptor
add(fd: i32, events: i16) voidWatch with an explicit POLL* mask
modify(fd: i32, events: i16) boolReplace interest and clear readiness for every matching registration
remove(fd: i32) boolRemove every matching registration; report whether one existed
wait(timeout_ms: i32) i32 throwsNumber ready; -1 blocks
wait(timeout: const ref Duration) Vec<Event> throwsReady descriptors in registration order
is_readable / is_writable / is_hup / is_error(i: i64) bool
fd_at / revents(i: i64) i32 / (i: i64) i16
clear / countReset, or how many are watched

The bits are POLLIN, POLLPRI, POLLOUT, POLLERR, POLLHUP and POLLNVAL. Do not call add while a wait is in flight: growing the set reallocates it.

An Event exposes fd() and the raw mask through events(). Its is_readable(), is_priority(), is_writable(), is_error(), is_hup() and is_invalid() helpers test the corresponding bit without exposing platform details.

Cross-thread wakeups

std.io.Wakeup(allocator) returns Wakeup throws owning a nonblocking, close-on-exec pipe on either OS. Explicit clone() calls share ownership without duplicating descriptors. Every clone keeps both endpoints alive. Register fd() for read readiness with Poller or EventLoop, then call drain() before inspecting the application's synchronized work queue.

notify() and drain() return void throws. Repeated notifications coalesce, including saturation; notification counts and ordering are not preserved. A mutex orders notification against draining, so a concurrent notify is either consumed by that drain or leaves readiness for a future wait. Operations on separate clones may run concurrently. They never wait for pipe capacity, but may briefly wait for the mutex, and are not signal-handler-safe.

Construction uses the supplied allocator; cloning and successful notify/drain operations do not allocate. Errors own diagnostic messages. Remove the registration before dropping the last clone. Do not close, read, or change flags on the borrowed descriptor. Pipe flag setup is not atomic with a concurrent fork/exec; coordinate process spawning during creation.

Signal events

std.signal.SignalSubscription explicitly installs handlers for SIGINT and SIGTERM on Linux and macOS (x86-64 and AArch64). It owns a nonblocking, close-on-exec pipe; register fd() for read readiness with Poller or EventLoop. take_pending() drains wakeups and returns a SignalEvents snapshot with interrupted(), terminated(), and any() queries. Repeated signals coalesce; counts and order are not preserved. Both signal kinds remain pending even when the pipe is full. A wakeup can occasionally have an empty snapshot when another handler finishes writing after its pending bit was consumed.

using std.net;
using std;
 
/** Wait for an interrupt or termination request, then restore both handlers. */
function wait_for_shutdown() void throws {
  var signals = std.signal.SignalSubscription();
  var loop = std.io.EventLoop(std.mem.global_allocator, 4);
  loop.open();
  loop.add(signals.fd(), std.io.POLLIN, 1u64);
  var stopping = false;
  while (not stopping) {
    try {
      var count = loop.wait(-1);
    } catch (error: Error) {
      if (not is_interrupted(error.code())) { throw error; }
      // EINTR: the signal may have interrupted the waiting thread.
    }
    var events = signals.take_pending();
    stopping = events.any();
  }
  loop.remove(signals.fd());
  signals.restore();
  return;
}

restore() is idempotent and restores the previous callbacks, masks, and flags. Scope exit also attempts restoration, including after error propagation. Remove the descriptor from pollers before restoration or destruction; fd() returns -1 after restoration. An explicit restoration error retains the resources for a retry; a destructor cannot report that error and leaves those resources alive. Only one subscription can be active in a library instance; an overlapping subscription throws an exception without changing either disposition.

Signals may arrive on any thread. The native handler preserves errno, records pending bits using lock-free atomics, and writes a byte without blocking. It allocates nothing, takes no locks, and calls no user callback. Restoration waits for active pipe writes before closing either end. Use subscription methods on one thread at a time. Do not independently change these signal dispositions or fork while subscribed. Do not unload the compiled handler code while a callback could still be returning. Signals delivered during installation or restoration may use either disposition; blocked signals remain blocked until the application unblocks them. No work is scheduled implicitly, and no thread is created.

Terminal

stdlib/std/terminal/terminal.sun (module std.terminal). Scoped raw and cbreak modes, terminal size queries and single-key reads with a timeout, on Linux and macOS. Nothing here needs termios or ioctl bound by hand: the struct mirror and the per-OS flag values live in target_linux.sun / target_darwin.sun.

Inside a function declared throws, calls propagate failures:

using std.io;
using std.terminal;
using std.time;
 
if (is_terminal(STDIN_FD)) {
  var mode = TerminalMode(STDIN_FD, Mode.Raw, SignalPolicy.AsInput);
  var size = get_size(STDOUT_FD);
  while (true) {
    match read_key(STDIN_FD, create_duration_millis(250)) {
      Option.Some(key) => { if (key == 3 or key == b'q') { break; } },
      Option.None => { size = get_size(STDOUT_FD); }  // maybe resized
    };
  }
}  // `mode` leaves scope here and the terminal is restored

TerminalMode saves the descriptor's settings when it is constructed and puts them back when it leaves scope, whether by reaching the end of the block, by return, or by an exception unwinding the stack. Call restore() to put them back early; a second call does nothing. A moved-from guard is all zeros and restores nothing, so handing a guard to another owner moves the duty with it. Constructing one on a descriptor that is not a terminal throws an exception with ENOTTY and changes nothing.

ModeClearsKeeps
Rawecho, line editing, CR/NL translation, Ctrl-S/Ctrl-Q flow control, output processing
Cbreakecho, line editingoutput processing and CR/NL translation

In Raw mode a "\n" no longer returns to column 0; write "\r\n". Both modes set VMIN=1, VTIME=0, so a read returns as soon as one byte arrives, and both the change and the restore use TCSANOW, so input typed around the switch is never discarded.

Signal policy

The terminal library never installs a signal handler. Signal subscriptions are an explicit, separate operation through std.signal. What the interrupt keys do is a choice the caller makes when constructing the terminal guard:

SignalPolicyMeaning
PassthroughISIG stays on. Ctrl-C, Ctrl-\ and Ctrl-Z raise SIGINT, SIGQUIT and SIGTSTP for the foreground process group and never arrive as bytes.
AsInputISIG is off. The same keys arrive as bytes 3, 28 and 26, and the program decides what they mean.

A process killed by a signal runs no destructors, so under Passthrough a Ctrl-C leaves the terminal in raw mode; the shell's reset or stty sane repairs it. To avoid that, use AsInput and exit normally when byte 3 arrives, as the example above does. Cbreak with Passthrough is the gentler combination when signals must keep working: output processing stays on, so a terminal left behind is still usable.

SIGWINCH is not used. A resize is observed by calling get_size again, for example whenever read_key returns None.

FunctionSignatureDescription
is_terminal(fd: i32) boolisatty; false for pipes, files and invalid descriptors
get_size(fd: i32) Size throwsrows and cols; returns ENOTTY on a non-terminal
read_key(fd: i32, timeout: const ref Duration) Option<u8> throwsOne byte, None on timeout; throws an exception once input has closed
try_read_key(fd: i32) Option<u8> throwsread_key with a zero timeout
read_attributes(fd: i32) Termios throwsSnapshot of the line-discipline settings
has_echo / is_canonical / delivers_signals(const ref Termios) boolRead the ECHO / ICANON / ISIG bits of a snapshot
TerminalModeSignatureDescription
init(fd: i32, mode: Mode, signals: SignalPolicy) throwsSave and switch
restore() void throwsPut the saved settings back now; idempotent
is_active() boolWhether the terminal is still in the applied mode

read_key allocates nothing and never touches a descriptor the caller did not pass, so it is safe to use on stdin alongside a child process. A multi-byte key (an arrow key is ESC [ A) arrives as several calls: after a 27, drain the rest with try_read_key. Termios is opaque; equals(const ref Termios) compares two snapshots. The native request codes TIOCGWINSZ, TIOCSWINSZ and TIOCSCTTY are public for programs that drive ioctl themselves.

Terminal operations and TerminalMode construction can throw exceptions. Handle them with try/catch or propagate them from a caller declared throws.

Environment

Env in module std.env owns a snapshot of the process environment. It copies entries in native order, preserves duplicate names, splits each entry at its first =, and is directly iterable as borrowed EnvEntry values.

The fallible calls below use try inside a function returning T throws with a throws declaration.

using std.io;
using std;
using std.env;
 
var environment = Env(alloc);
match environment.get("HOME") {
  Option.Some(value) => { println(value); },
  Option.None => {}
};
 
for (var entry: ref EnvEntry in environment) {
  println(entry.name());
}
 
environment.set("LANG", "C");
var here = environment.cwd();
MethodSignatureDescription
get(name: Name) Option<ref String>First matching entry, or None
has(name: Name) boolWhether the snapshot contains the name
set(name: Name, value: Name) void throwsMutate libc, then refresh
remove(name: Name) void throwsMutate libc, then refresh
refresh() voidObserve changes made outside this Env
size / is_empty() i64 / () boolSnapshot size
iter() EnvIteratorBorrow entries in native order
cwd() String throwsWorking directory
set_cwd(path: Name) void throwsChange it process-wide
args(argc, argv) Vec<String> throwsCopy argv, with argv[0] first

Name means either static_ptr<u8> or ref String; set provides all four combinations. A snapshot is not automatically live: external changes appear after refresh(), while its own set and remove refresh automatically.

using std.io;
 
function main(argc: i32, argv: raw_ptr<raw_ptr<i8>>) i32 throws {
  var environment = std.env.Env(std.mem.global_allocator);
  var cli = environment.args(argc, argv);
  for (var s: ref String in cli) { println(s); }
  return 0;
}

Processes

stdlib/std/process/process.sun (module std.process). Command covers running a program; the raw POSIX calls are there for programs that drive the fork themselves. Fallible operations return T throws with an owned Error; try propagates its code and message to a compatible caller result.

using std.io;
using std.process;
 
var cmd = Command(alloc, "/bin/sh");
cmd.add_arg("-c");
cmd.add_arg("printf hello");
var out = cmd.output();
 
println(out.status());  // 0
println(out.stdout());  // hello

Command

MethodSignatureDescription
init(alloc: const ref HeapAllocator, program: static_ptr<u8> | ref String)The program is argv[0]
arg(value: static_ptr<u8>) void throws / (value: ref String) void throwsAppend one argument
stdin / stdout / stderr(mode: Stdio) voidInherit, Piped or Null
start() Child throwsRun it, return immediately
status() i32 throwsRun to completion, inheriting the streams
output() Output throwsRun to completion, capturing both streams

Arguments are passed to the program as they are given — a space inside one argument stays inside it, with no shell reparsing.

The child starts with SIGPIPE at its default disposition even when the parent ignores it. An ignored signal would otherwise survive exec, and a child whose reader goes away would then see EPIPE and complain instead of exiting quietly.

Child

MethodSignatureDescription
id() i32Process id
wait() i32 throwsExit code; a killed child reports 128 + signal
try_wait() Option<i32> throwsNone while it is still running
kill(sig: i32) void throws
write_stdin / close_stdin(data: ref String) i64 / () voidNeeds stdin(Stdio.Piped)
take_stdout / take_stderr() i32Hand the pipe over
collect(alloc: const ref HeapAllocator) Output throwsDrain both pipes and wait

collect polls the two pipes rather than draining one and then the other: a child that fills the stderr pipe while the parent is stuck reading stdout would deadlock. Output gives status() i32 and borrowed stdout() / stderr().

A Child releases any pipes it still holds when it goes out of scope. It never waits and never signals there — a moved-from Child is all zeroes, and reaping or killing on that would touch a process the object no longer stands for. Call wait to reap.

Process inspection and identity-bound handles

Inspection runs with the caller's existing credentials. Pass an allocator to process_ids(alloc), process_identity(alloc, pid), and inspect_process(alloc, pid); all may throw on failure. Enumeration returns Vec<i32> and can race with process creation and exit. Inspect each PID separately and handle failures.

ProcessIdentity contains pid: i32 and start_marker: u64, with equals(other) comparing both. The marker is opaque and valid only on the same host and boot: Linux uses start ticks, macOS uses the start timeval. Markers have OS-defined resolution; they are not globally unique identifiers.

ProcessSnapshot owns these public fields:

FieldTypeMeaning
identityProcessIdentityIdentity checked again after collecting the fields
cpu_time_nsu64Cumulative user plus system CPU time in nanoseconds, excluding children; Linux precision is clock ticks
rss_bytesu64Resident memory in bytes
executableStringExecutable path, if visible
argumentsVec<String>Arguments including argv[0], preserving spaces and empty arguments

Inspection returns a complete snapshot or throws. Unavailable data, a failed identity read, or a changed identity fails the whole inspection; unavailable fields are not silently represented by zero or empty values. Fields are collected at different times: this is not an atomic snapshot, and a concurrent exec may change the executable and arguments without changing the start marker. Arguments may have been modified by the target. On macOS the OS argument record's padding makes an empty argv[0] indistinguishable from padding.

page_size_bytes() and physical_memory_bytes() return u64 throws. Physical memory is the system total, not a container or cgroup limit.

using std.io;
 
var observed = process_identity(alloc, target_pid);
var handle = ProcessHandle(alloc);
handle.open(observed);
println(handle.protection() == ProcessProtection.Atomic);
handle.terminate();  // SIGTERM; kill() sends SIGKILL
handle.close();

ProcessHandle owns its native reference and is moved, never implicitly copied. open(identity) first closes any previous reference and leaves the handle closed on failure. close() is idempotent; destruction closes automatically. Neither operation signals nor reaps the process. Closed handles reject signaling with EBADF. The allocator passed to the constructor is retained for identity queries.

Platformprotection()Guarantee
LinuxProcessProtection.AtomicUses pidfd_open and pidfd_send_signal; after opening, PID reuse cannot redirect a signal. Missing kernel facilities return ENOSYS; there is no fallback to POSIX kill.
macOSProcessProtection.CheckedChecks the saved identity immediately before POSIX kill. A process can exit and its PID can be reused between these calls; signaling is not atomically protected.

Opening validates the caller's observed start marker. Linux also checks that the pidfd still refers to a live process after reading its identity. The kernel still enforces signaling permissions; errors such as EPERM remain visible. Handles to arbitrary processes do not provide the child-specific waiting behavior of Child.

Identity, signals and raw control

FunctionSignatureDescription
pid / parent_pid() i32
uid / euid() u32
kill(target: i32, sig: i32) void throws
set_pgid(target: i32, pgid: i32) void throws0 means "this one"
create_new_session() i32 throwssetsid
exit / exit_now(code: i32) voidWith / without atexit handlers
fork() i32 throws0 in the child, the child's pid in the parent
exec(cmd: ref Command) void throwsOnly returns on failure
wait_pid(target: i32, options: i32) i32 throwsRaw wait status; -1 = any child
exited / exit_status / signaled / get_term_signal(status: i32)Read a wait status
open_pipe(alloc: const ref HeapAllocator) Pipe throwsread_fd() / write_fd()
dup_fd(old_fd: i32, new_fd: i32) void throwsdup2

Signal numbers are SIGHUP, SIGINT, SIGQUIT, SIGKILL, SIGSEGV, SIGPIPE, SIGALRM, SIGTERM, SIGCHLD, SIGCONT, SIGSTOP; wait_pid takes WNOHANG.

Between fork and exec a child may only call things that are safe inside a signal handler — no allocation, no method that might allocate. Command is written to that rule; hand-rolled forks have to be too.

Time

stdlib/std/time/time.sun (module std.time).

using std.io;
using std.time;
 
var start = now();
sleep(create_duration_millis(50));
println(start.elapsed().as_millis());
 
println(format(alloc, convert_to_utc(read_unix_time()), "%Y-%m-%d %H:%M:%S"));
ItemSignatureDescription
nanos / micros / millis / seconds(n: i64) DurationBuild a Duration
Duration.as_secs / as_millis / as_micros / as_nanos() i64
Duration.as_secs_f64() f64
Duration.subsec_nanos() i64Remainder on top of as_secs
now() InstantMonotonic clock
Instant.elapsed() DurationTime since it was taken
Instant.since(earlier: const ref Instant) DurationZero if this is the earlier
read_unix_time / read_unix_time_millis() i64Wall clock, since the epoch
sleep(d: const ref Duration) voidA signal can cut it short
utc / local(unix_secs: i64) DateTimeBreak into calendar fields
to_unix_utc / to_unix_local(dt: const ref DateTime) i64And back
format(alloc, dt: const ref DateTime, fmt: raw_ptr<u8>) String throwsstrftime

Only differences between Instants mean anything: the zero point is arbitrary, and the clock never jumps backwards when the system time is adjusted.

DateTime uses human units — year is the full year and month is 1-12, not C's tm_year/tm_mon offsets. It also carries day, hour, minute, second, weekday (Sunday = 0), yearday and utc_offset.

Networking

TCP and UDP sockets and hostname resolution, from networking.sun. For TLS and HTTPS see TLS & HTTPS. Fallible networking and HTTP operations return T throws. These examples use try inside a function returning a throws declaration.

using std.net;
using std;
 
// Client
var stream = TcpStream();
var host = String(alloc, "example.com");
stream.connect_host(host, 80);  // resolve a name, then connect
stream.connect_ip(ip, 80);  // or an address already in hand
stream.connect_local(8080);  // or 127.0.0.1
stream.set_nonblocking(true);  // configure the chosen connection
 
stream.send_str("ping");
stream.send_string(message);
var buf = ContiguousBuffer<u8>(alloc, 4096);
var n = stream.recv(buf);  // bytes read; 0 at end of stream
stream.close();
 
// Server
var listener = TcpListener();
listener.bind_port(8080);  // 0.0.0.0; bind_loopback for 127.0.0.1
listener.set_nonblocking(true);  // configure after binding
listener.listen(128);
var client = listener.accept();
client.set_nonblocking(true);  // accepted streams configure themselves

resolve_host_ipv4 does name resolution on its own, returning the first A record in network byte order — the form connect_ip takes:

using std.net;
 
var ip: i32 = resolve_host_ipv4(host);

Resolution throws Error when the name does not resolve or has no IPv4 address. Socket failures carry the positive libc errno value in Error.code(); they do not use -1 as an error code.

Nonblocking TCP operations

Connect a stream or bind a listener, then call set_nonblocking(true) and register get_fd() with Poller or EventLoop. Socket operations and configuration require external synchronization when sharing a socket across threads. set_nonblocking(false) restores blocking behavior without changing unrelated descriptor flags.

OperationResult
TcpListener.try_accept()AcceptResult.Accepted(TcpStream) or WouldBlock; throws on failure
TcpStream.try_read(MutableByteSlice)std.io.ReadResult.Data(count), WouldBlock, or Eof; throws on failure
TcpStream.try_write(ByteSlice)std.io.WriteResult.Complete(count) or WouldBlock(count); throws WriteError on failure

Set the listener nonblocking before calling try_accept() to avoid waiting. Accepted streams are always nonblocking and close-on-exec, regardless of native inheritance rules. Configuration failure closes the accepted descriptor. Flag setup uses checked calls and is not atomic with concurrent fork/exec on either platform; coordinate process spawning during descriptor creation.

An empty read slice returns Data(0), not EOF. Writes continue until complete, blocked, or failed; resume after the reported prefix instead of resending it. All three operations retry interruptions. Successful operations allocate no storage; exceptions carry bounded inline diagnostics. The blocking accept, recv, and send methods report would-block by throwing Error, recognized by is_would_block(error.code()).

Nonblocking connection establishment

TcpStream.start_connect(address, port) opens an unopened stream with nonblocking and close-on-exec flags. It returns ConnectResult.Connected or Pending, and throws on failure. For Pending, register the descriptor for writable/error readiness, then call finish_connect() to inspect the socket's completion status. Do not treat writable readiness alone as a successful connection. Failed attempts close the new descriptor. close() cancels a pending attempt; applications enforce deadlines using their monotonic clock and poller. Existing blocking connect methods are unchanged.

UdpSocket.set_multicast_interface(address) selects the outgoing IPv4 multicast interface after binding. This is separate from join_multicast(group, address), which selects the interface on which to receive group traffic.

Socket configuration and broken pipes

TcpListener.bind(address, port, reuse_address, reuse_port) applies checked options before binding. The listener must be unopened. Configuration or bind failure closes the new descriptor. Address and port reuse do not promise the same binding rules or connection distribution on Linux and macOS. Unsupported options retain the native error. enable_reuse_addr() now returns a checked void throws and must be handled.

TcpStream.set_nodelay(bool) configures TCP_NODELAY. Streams and listeners expose set_close_on_exec(bool). For native integrations, set_fd_close_on_exec, set_tcp_nodelay, set_socket_reuse_address, and set_socket_reuse_port accept borrowed descriptors and return checked results without taking ownership.

Sun TCP sends use Linux MSG_NOSIGNAL; macOS TCP sockets use checked SO_NOSIGPIPE, which also protects native-library writes on those sockets. An arbitrary native TLS library may use plain writes on Linux. Servers can explicitly call std.signal.ignore_broken_pipe() during startup before creating threads to ignore SIGPIPE process-wide, including native writes. This checked operation replaces the previous disposition permanently and persists across exec; it is never installed implicitly. Always handle the resulting I/O errors. SIGINT/SIGTERM subscriptions remain independent. The bundled TLS server's custom socket BIO already uses per-send protection on Linux.

IPv4 addresses

Ipv4Addr names an address by its dotted-quad octets, so nobody has to remember that 127.0.0.1 is the integer 16777343. It holds the address in network byte order — to_network_i32() returns the form connect_ip and the intrinsics take, and ipv4_from_network wraps what resolve_host_ipv4 returns.

using std.net;
using std.io;
 
var lan = Ipv4Addr(192, 168, 1, 10);  // from octets
var addr = parse_ipv4(text);  // propagate an error if malformed
var any = ipv4_any();  // 0.0.0.0
var home = ipv4_loopback();  // 127.0.0.1
println(lan.to_string(alloc));  // "192.168.1.10"
stream.connect_addr(lan, 80);  // TCP takes it too
listener.bind_addr(any, 8080);

UDP

UdpSocket sends and receives datagrams — no connection, one message per call. bind creates the socket, so it always comes first; binding port 0 lets the OS pick a free port — right for a send-only socket — and local_port() reads the pick back. Binds are exclusive by default: an occupied address returns an Error with the native EADDRINUSE code. A failed bind leaves the socket closed, so callers can retry another port. Pass true as the third argument, socket.bind(any, port, true), to enable SO_REUSEADDR for shared listeners. Each socket sharing the address must opt in; ordinary unicast listeners should keep the exclusive default.

using std.net;
using std;
 
var socket = UdpSocket();
var any = ipv4_any();
socket.bind(any, 0);
var port: i32 = socket.local_port();
 
var dest = Ipv4Addr(192, 168, 1, 20);
socket.send_str_to("ping", dest, 9000);  // a literal
socket.send_to(data, len, dest, 9000);  // raw bytes
 
var buf = ContiguousBuffer<u8>(alloc, 2048);
var datagram = socket.recv_from(buf);  // one datagram, cut to fit buf
datagram.length();  // bytes received
datagram.addr();  // sender's Ipv4Addr
datagram.port();  // sender's port
socket.close();

A blocking recv_from can be given a deadline with set_recv_timeout(duration); when it expires the call throws an exception for which is_would_block(e.code()) is true. set_nonblocking(true) and a Poller work here the same way they do for TCP.

Multicast is part of UdpSocket. Join a group on an interface (use ipv4_any() to let the OS choose one), and the socket receives datagrams sent to the group on its bound port:

using std.net;
 
var socket = UdpSocket();
socket.bind(ipv4_any(), 9000, true);
var group = Ipv4Addr(239, 255, 0, 1);
var iface = ipv4_any();
socket.join_multicast(group, iface);
socket.set_multicast_ttl(1);  // how many router hops sends may cross
socket.set_multicast_loop(true);  // hear this host's own sends
socket.leave_multicast(group, iface);

IPv4 is the only supported address family for now. TCP sockets have no socket-level receive timeout; use Poller for bounded waits there.

HTTP server

http.sun builds an HTTP/1.1 server on TcpListener. The server owns the accept loop and all framing; the handler only reads the request and fills in the response.

using std.http;
 
var server = HttpServer(std.mem.global_allocator);
server.bind_loopback(8080);
server.serve(
  (req: ref HttpRequest, resp: ref HttpResponse) => void throws {
    if (req.path.equals_literal("/")) {
      resp.set_body("<h1>Hello</h1>");
    } else {
      resp.set_status(404);
      resp.set_body("not found");
    }
    return;
  }
);

It handles one connection at a time, parses request line and headers (not bodies), and always answers Connection: close. For outgoing requests, use HttpsClient from the tls bundle.

Optional values and exceptions

Option<T>, defined in option.sun, represents a value that may be absent:

enum Option<T> { Some(T), None }

Fallible operations return their ordinary success value and declare throws. They report failures with concrete exceptions such as AllocationError, IndexOutOfBoundsError, NotFoundError, JsonError, or ProtoDecodeError. Use block-form try/catch to handle failures, or declare throws to propagate them. See Error Handling for exception families and bounded storage.

Iteration: IIterator<T, Container> and IIterable<T, Self>

The iteration protocol lives in iterator.sun and is what for-in drives:

interface IIterator<T, Container> {
  method next(container: ref Container) Option<T>;
}
interface IIterable<T, Self> {
  method iter() IIterator<T, Self>;
}

next() yields the next element or Option.None once the sequence is exhausted (and keeps returning None afterwards). for (var x: T in c) calls iter() when c has one, then loops on next() until None; the loop variable's type must match T. Iterators are separate objects that receive the container by ref on every call, so a container can be iterated more than once and iterators stay cheap:

class Countdown implements IIterator<i32, Countdown> {
  var n: i32;
  init(n: i32) { this.n = n; }
 
  method next(self: ref Countdown) Option<i32> {
    if (this.n == 0) { return Option.None; }
    this.n = this.n - 1;
    return Option.Some(this.n + 1);
  }
}
 
function main() i32 {
  var sum: i32 = 0;
  for (var x: i32 in Countdown(5)) {
    sum = sum + x;
  }
  return sum;  // 5 + 4 + 3 + 2 + 1 = 15
}

Iterators can also be driven by hand:

using std.io;
 
var it = v.iter();
var going = true;
while (going) {
  match it.next(v) {
    Option.Some(x) => { println(x); },
    Option.None => { going = false; }
  };
}

A container implements IIterable and returns its concrete iterator from iter(); the loop then passes the container to every next() call, so next must take that container type by ref (the compiler checks this — it is what keeps the container access inside next memory-safe):

class Range implements IIterable<i32, Range> {
  var start: i32;
  var end: i32;
  init(s: i32, e: i32) { this.start = s; this.end = e; }
  method iter() RangeIterator { return RangeIterator(this.start); }
}
 
class RangeIterator implements IIterator<i32, Range> {
  var cur: i32;
  init(s: i32) { this.cur = s; }
  method next(r: ref Range) Option<i32> {
    if (this.cur >= r.end) { return Option.None; }
    this.cur = this.cur + 1;
    return Option.Some(this.cur - 1);
  }
}

Because iter() returns a class rather than the IIterator<T, Self> fat pointer the interface names, an IIterable implemented this way is static-only: it drives for-in, but a Range cannot be converted to an IIterable<i32, Range> value (there is no way to dispatch iter() through it soundly).

Vec<T>, LinkedList<T>, Map<K, V> (values) and ContiguousBuffer<T> implement IIterable.

BigUint

Arbitrary-precision unsigned integer from bigint.sun: little-endian u64 limbs in a Vec, schoolbook arithmetic built on _mul_hi_u64. Values are owned (clone() to copy); the by-ref argument of a binary operation is never modified.

var n = BigUint(alloc, 1);
for (var i: u64 = 2; i <= 30; i = i + 1) { n.mul_small(i); }  // 30!
var text = String(alloc, "");
n.append_decimal(text);  // 265252859812191058636308480000000
MethodSignatureDescription
BigUint(alloc) / BigUint(alloc, v)(const ref HeapAllocator[, u64])Zero, or a machine word
clone()() BigUintIndependent copy
is_zero(), bit_length(), limb_count(), limb(i), low_u64()Inspection; limb(i) is 0 beyond the top
to_u64()() Option<u64>The value if it fits in 64 bits
set_u64(v), assign(other), clear()Replace the value
compare(other), compare_u64(v), equals(other)(const ref BigUint) i64, (u64) i64, (const ref BigUint) boolOrdering (-1/0/1)
add(other), add_small(v)(const ref BigUint) void, (u64) voidIn-place addition
sub(other)(const ref BigUint) void throwsIn-place subtraction; returns Overflow if the result would be negative
mul(other), mul_small(v), mul_pow10(n)(const ref BigUint) void, (u64) void, (i64) voidIn-place multiplication
shl(bits), shr(bits)(i64) voidIn-place shifts
divmod_small(d)(u32) u32 throwsDivide in place, returning the remainder or DivisionByZero for a zero divisor
append_decimal(out)(ref String) void throwsAppend the decimal digits
set_decimal(text)(const ref String) bool throwsParse decimal digits; false (value left at zero) if malformed

Numeric conversion

A value never narrows on its own: assigning an i64 to an i32 is a compile error. math.sun provides safe_convert<T>(x), which converts between any two numeric types and returns T, throwing a ConversionError when the value does not fit:

using std.io;
 
/** Narrows a value and lets the caller handle conversion failure. */
function narrow(value: i64) u8 throws {
  return safe_convert<u8>(value);
}
 
/** Prints the converted number or the error message. */
function show_conversion(value: i64) void throws {
  try {
    var number = narrow(value);
    println(number); } catch (error: ConversionError) { println(error.message()); }
  return;
}

Inside a function declared throws, call safe_convert<T>(x) to extract the number and propagate conversion failures. For example, converting 255.0 to u8 succeeds; 256.0, negative integers, and NaN return Error.

Checked: integer values outside T's range (including a sign change that flips the value), floats that are NaN or outside T's range, and an f64 that overflows f32. A fraction is truncated toward zero, as with _convert. Widening and integer-to-float conversions always succeed.

safe_convert takes two type parameters, <T, U>; the source type U is inferred from the argument, so only the target is written. When the value is known to fit, the _convert<T>(x) intrinsic does the same conversion with no check (see Intrinsics).

Numeric limits

math.sun also defines I64_MAX, I64_MIN, F64_MAX, F64_MIN_POSITIVE (smallest normal) and F64_EPSILON.

Byte order

A binary wire format fixes the order the bytes of a number appear in, and that order is often not the one the machine uses. stdlib/std/byte_order/byte_order.sun (module std.byte_order) converts between the two, for 16-, 32- and 64-bit unsigned integers.

swap_bytes_u16, swap_bytes_u32 and swap_bytes_u64 reverse the bytes unconditionally:

using std.byte_order;
 
var swapped: u32 = swap_bytes_u32(305419896);  // 0x12345678 -> 0x78563412

The to_/from_ pairs name the order the wire uses, and do nothing when it already matches the machine's. Big-endian is what network protocols call network byte order, so to_big_endian_u16 is the htons of C, and from_big_endian_u32 is its ntohl:

var wire: u16 = to_big_endian_u16(port);  // host -> network order
var port: u16 = from_big_endian_u16(wire);  // network -> host order
 
var little: u32 = to_little_endian_u32(n);  // for a little-endian format
var n: u32 = from_little_endian_u32(little);

There are twelve in all: to_big_endian_u16/u32/u64, from_big_endian_u16/u32/u64, and the same four for little-endian. Unlike C, the 64-bit conversions are there too.

Every processor Sun targets is little-endian, so the big-endian conversions reverse the bytes and the little-endian ones compile to nothing. Each reversal is the _bswap_u16 / _bswap_u32 / _bswap_u64 intrinsic (see Intrinsics), a single instruction.

Json

json.sun parses JSON text into an owned tree and writes it back, compact or pretty. Objects keep their members in insertion order (lookups are a linear scan), numbers are Int(i64) when the text is an integer that fits and Float(f64) otherwise, strings are UTF-8 Strings.

using std.json;
using std.io;
 
/** Parses and builds JSON while propagating concrete JSON errors. */
function json_example() void throws {
  var doc = parse_json(std.mem.global_allocator, "{\"name\": \"sun\", \"tags\": [1, 2.5]}");
  var tags = doc.get("tags");
  var second: f64 = (tags.at(1)).as_f64();
 
  var obj = create_json_object(std.mem.global_allocator);
  obj.set(String(std.mem.global_allocator, "ok"), Json(true));
  obj.set(String(std.mem.global_allocator, "tags"), create_json_array(std.mem.global_allocator));
  (obj.get("tags")).push(Json(42));
  println(obj.to_string(std.mem.global_allocator));  // {"ok":true,"tags":[42]}
  println(obj.to_pretty_string(std.mem.global_allocator, 2));
  return;
}

The tree node is class Json wrapping a public var value: JsonValue:

using std.json;
enum JsonValue { Null, Bool(bool), Int(i64), Float(f64), String(String), Array(Vec<Json>), Object(Vec<JsonMember>) }
class JsonMember { var key: String; var value: Json; }

Match on j.value directly when the accessors below are not enough.

The tree owns everything in it. Json(s), push(item) and set(key, value) take their String and Json arguments by value, which in Sun means they are moved in: the caller cannot use them afterwards, and the borrow checker rejects a later use. When a value is still needed after being placed in a document, store a copy instead. create_json_string(alloc, ref s) does that for a String:

using std.json;
 
// cfg.model is still needed later, so the document gets a copy
req.set(String(alloc, "model"), create_json_string(alloc, cfg.model));
// Equivalent to an explicit clone:
req.set(String(alloc, "model"), Json(cfg.model.clone(alloc)));
// Moves cfg.model into the document; using it again is a compile error
req.set(String(alloc, "model"), Json(cfg.model));
Function / MethodSignatureDescription
parse_json(alloc, text)(const ref HeapAllocator, ref String) Json throwsParse a complete document (also accepts a static_ptr<u8> literal). Rejects trailing text, leading zeros, control characters in strings, and nesting deeper than 256
Json(), Json(b), Json(n), Json(x), Json(s)(), (bool), (i64), (f64), (String)Build a scalar node (Json(s) moves the String into the node; see above)
create_json_array(alloc) / create_json_object(alloc)(const ref HeapAllocator) Json throwsEmpty array / object
create_json_string(alloc, text)(const ref HeapAllocator, static_ptr<u8>) Json throws, (const ref HeapAllocator, ref String) Json throwsString node from a literal, or a copy of a borrowed String (the caller keeps its own)
is_null(), is_bool(), is_int(), is_float(), is_number(), is_string(), is_array(), is_object()() boolKind checks
as_bool(), as_i64(), as_f64()() T throwsScalar readers; as_i64 accepts an integral Float, as_f64 accepts an Int
as_string()() ref String throwsBorrow the string
len()() i64Array items or object members (0 for scalars)
at(i)(i64) ref Json throwsArray item
get(key)(static_ptr<u8>) ref Json throws, (ref String) ref Json throwsObject member value
has(key)(static_ptr<u8>) boolWhether an object has the key
key_at(i) / value_at(i)(i64) ref String throws / (i64) ref Json throwsObject members by position, in insertion order
push(item)(Json) void throwsAppend to an array
set(key, value)(String, Json) void throwsSet an object member (replaces an existing key's value in place, otherwise appends)
write(out) / write_pretty(out, indent)(ref String) void throws / (ref String, i64) void throwsAppend JSON text to a String
to_string(alloc) / to_pretty_string(alloc, indent)(const ref HeapAllocator) String throws / (const ref HeapAllocator, i64) String throwsJSON text as a new String

Fallible JSON operations throw a bounded JsonError (code 60) on a kind mismatch or missing key; parse errors carry the byte offset of the problem in offset(). When writing, Float values keep a .0 or exponent so they read back as Float, and non-finite floats become null.

Testing: std.test

The assertions and runner support behind test_function — see Testing for the full feature. What user code calls directly:

FunctionSignatureDescription
assert(cond) / assert(cond, msg)(bool[, static_ptr<u8>]) void throwsThrow AssertionError when false
assert_eq(expected, actual)overloaded per primitive, plus (const ref String, const ref String)Throw an assertion error when the values differ, showing both
assert_ne(a, b)overloaded per primitiveThrow an assertion error when the values are equal
fail(msg)(static_ptr<u8>) void throwsFail unconditionally

AssertionError (code 10) implements IError. The remaining items — TestResult, run_one, report, finish, wants_sequential — exist for the compiler's synthesized test runner; --debug writes that runner's source to <input>_debug/test_runner.sun if you want to see how they fit together.

Error Types

All error types implement IError with code() i32 and message() String throws methods. message() explicitly allocates an owned copy of the description, so the text stays usable for as long as the caller keeps it, independent of the error object itself.

Error TypeCodeDescription
ErrorcustomGeneric error with custom code and message
EmptyError1Operations on empty containers
NotFoundError2Failed lookups
IndexOutOfBoundsError3Invalid array/vector indices
DivisionByZeroError4Division by zero
OverflowError5Numeric overflow
InvalidArgumentError6Invalid function arguments
IOError7I/O operations
AllocationError8Memory allocation failures
ConversionError9A value does not fit the type safe_convert targets
JsonError60JSON parse errors (with offset()) and kind mismatches
/** Returns the first value or an owned empty-container error. */
function first(v: ref Vec<i32>) i32 throws {
  try {
    var value = v.get(0);
    return value; } catch (ignored_error: IndexOutOfBoundsError) { throw EmptyError(); }
}

Error accepts either a literal or a String composed at runtime. It copies and truncates the message into inline storage without allocation, so the diagnostic survives destruction of the source string. Calling message() explicitly allocates an owned String copy.

using std.io;
 
/** Creates an owned error message from a runtime path. */
function failure(path: const ref String) void throws {
  throw Error(errno(), path);
}
 
// At the caller:
try {
  failure(path);
} catch (error: Error) {
  var message = error.message();
  eprintln(message);
}

Print Functions

Overloaded print (no newline) and println (with newline) from print.sun. Both accept any of the following argument types:

OverloadDescription
i32, i64, u32, u64Print integer value
f64Print f64
charPrint a character as UTF-8
boolPrint true or false
static_ptr<u8>Print string literal
const ref StringPrint a borrowed String
(no argument, println only)Print a bare newline

Interpolated strings can be passed directly:

using std.io;
 
var x: i32 = 42;
println(`x = ${x}`);  // prints "x = 42\n"
print("no newline");
println();

eprint and eprintln write to stderr instead, so a caller can tell diagnostics apart from the program's real output. They accept the same argument types as print and println, including numbers, characters, booleans and a const ref String. Numeric stderr output uses stack buffers without constructing a temporary String; floating-point values use the decimal formatting from String.append_f64. Calling eprintln() writes a bare newline.

using std.io;
 
eprintln("could not open the file");
eprint("error code: ");
eprintln(42);
eprintln(`giving up after ${attempts} tries`);

XML

Sun provides an in-memory UTF-8 XML reader, an editable owned tree, and a writer. The library has no native XML dependency. It supports the XML 1.0 Fifth Edition name and character rules and XML namespaces, but deliberately rejects DTDs, custom entities, XML 1.1, and encodings other than UTF-8. It is not a validating XML processor or a complete implementation of every XML encoding requirement.

Parsing and ownership

using std.xml;
using std.io;
var document = parse_xml(std.mem.global_allocator, "<p>Hello <b>Sun</b>!</p>");
var bold = (document.root().child(1)).element();
println(bold.name().local());

parse_xml(alloc, input) accepts a borrowed String or a literal and returns XmlDocument throws. The resulting document owns its names, attributes, and ordered content independently of the input. It preserves whitespace, comments, processing instructions, and the order of text around child elements. CDATA and character references become decoded text. XML line endings and attribute whitespace are normalized; the original input is never modified.

XmlReader(alloc, input) borrows a complete String. Call next() until it returns Option.None to validate the entire document. Each preceding call returns an owned XmlEvent: Start(XmlElement), End(XmlName), Text(String), Comment(String), or Instruction(XmlInstruction). Start elements have attributes and declarations but no children. Empty elements produce Start and End events. Events can outlive the reader; the reader cannot outlive its input. The first call validates input UTF-8 before returning an event. A reader retains its first error and never resumes normal parsing after failure.

All storage uses the supplied HeapAllocator. Reader events allocate their owned payloads; parsing a tree also allocates its child collections. Getters borrow rather than clone. clone(alloc) explicitly copies a name, node, element, or document. Owned arguments move into constructors and editing operations.

Names and editing

XmlName(uri, local, prefix) owns three String values. URI and local name define identity; the prefix is a serialization preference, with an empty string meaning no preference. Use empty URI and prefix strings for an unqualified name. uri(), local(), and prefix() borrow the components; equals(other) compares expanded identity. Constructors store components, while validate() and the operations consuming names check their validity.

APIBehavior
document.root()Borrow the editable root element
document.replace_root(root)Validate and move in a root, returning the old owned root
element.name() / set_name(name)Borrow or replace the expanded element name
element.attribute(name)Return Option<const ref String>; absent differs from empty
element.set_attribute(name, value)Insert or replace by expanded name, retaining insertion order
element.remove_attribute(name)Return the removed owned value, or None
element.attribute_count() / attribute_name(index)Enumerate attribute names, then look up their values
element.namespace_count() / namespace_at(index)Inspect declarations present on the parsed element
element.child_count() / child(index)Enumerate all ordered nodes, including whitespace
element.find_child(name)Borrow the first direct element matching an expanded name
element.append(node) / insert(index, node)Move in a validated child; insertion also accepts the end position
element.replace(index, node) / remove(index)Return the replaced or detached owned node
node.element() / text()Borrow the requested content or return a kind error
node.set_text(text)Replace decoded text after validation

Build nodes using XmlNode(XmlNodeValue.Element(element)), Text(text), Comment(text), or Instruction(XmlInstruction(target, data)). Comments and instructions are validated when attached or written. Processing instructions expose borrowed target_name() and content() getters. Namespace declarations expose declared_prefix() and namespace_uri() getters.

Elements recursively own their children. There are no persistent IDs or parent pointers. Detach a subtree with remove before attaching it elsewhere; ordinary Sun borrowing rules prevent using references invalidated by editing or moving storage. Names, indices, node kinds, and depth are checked before mutation. The maximum element depth is 256, including edits through borrowed descendants.

Writing

var output = String(alloc, "");
document.write(alloc, output);

document.write(alloc, output) appends an XML declaration and the complete document. Alternatively, XmlWriter(alloc, output) borrows a String for direct construction. Its operations return void throws:

OperationContract
declaration()Optional; must precede all other output
start_element(name)Open an element by expanded name
attribute(name, value)Add a unique attribute before content or another element
text(value)Escape decoded text; only whitespace is allowed outside the root
comment(value)Write validated comment content
instruction(target, data)Write a validated processing instruction
end_element()Close the innermost element
finish()Require exactly one root and no unclosed elements; stop further writes

The writer escapes text and attributes and preserves referenced carriage returns and attribute tabs/newlines. Start tags are buffered until content or closure. Every operation validates before appending its output. Failure permanently stops the writer: previously appended output may be incomplete and must be discarded. Release the writer's borrow before reading or otherwise modifying the output. There is no raw-markup insertion or automatic pretty printing.

Namespace declarations are managed automatically. Parsed declarations and preferred prefixes are retained where compatible. Conflicts generate deterministic ns1, ns2, and subsequent prefixes; namespaced attributes always use a prefix. An unqualified element beneath a default namespace gets a namespace reset. Moving subtrees preserves expanded element and attribute names. Text and attribute values are opaque: the library does not repair QName-valued content or XPath expressions.

Round trips preserve semantic names and ordered decoded content, not original prefix spelling, quote style, declaration placement, CDATA boundaries, or entity spelling. Adjacent text events may merge when serialized and parsed again.

Errors and examples

XML operations throw XmlError, whose code is 61. Its payload stores bounded inline diagnostic text, a bounded filename, and source coordinates. message() explicitly allocates an owned explanation and can throw on allocation failure. Syntax errors expose the original zero-based byte offset() and one-based line() and Unicode character column(), counting CRLF as one line ending. Errors without an input location return -1 for all three coordinates.

For source diagnostics, pass an owned filename as the third argument to parse_xml(alloc, input, filename) or XmlReader(alloc, input, filename). The filename is a label; neither API opens a file. Exceptions copy and truncate it into inline storage, so they can outlive the input and reader. XmlError.filename() returns Option<String> throws, explicitly allocating a copy when a filename is present. Unnamed errors return None.

Migrating a GIR reader

The fixtures from namo-robotics/sun_gobject are covered by stdlib/std/xml/xml_fixture_tests.sun, including valid XML, GIR metadata, selection files, malformed UTF-8, namespace errors, and external DTD rejection. To replace a local parser, use parse_xml for an owned tree, or consume XmlReader.next() to build an existing indexed model:

  • On Start, append an element and push its index onto a parent stack.
  • On End, pop the stack; empty elements emit both events.
  • On Text, append decoded content to the current element's text.
  • Handle or discard Comment and Instruction according to the model.
  • Continue through None so malformed content after the root is rejected.

Use XmlName.uri() and local() for element and attribute identity. GIR core names use http://www.gtk.org/introspection/core/1.0; C attributes use http://www.gtk.org/introspection/c/1.0. Prefix spelling may change without changing identity. Namespace declarations are available separately from ordinary attributes. Propagate XmlError to the caller and format its filename, line, column, and message at the CLI boundary. The parser never exits the process or resolves external entities.

Run the standalone SVG example from the repository root after building:

build/sun examples/105-xml/svg.sun

The SVG example generates escaped vector markup without requiring GTK. Incremental input, file adapters, XPath, schemas, and migrations of external consumers are outside this release.

ExceptionTrace

std.ExceptionTrace holds borrowed frame addresses and the original capture status. Construct it inside a catch with ExceptionTrace(_exception_trace_frames(error), _exception_trace_status(error)). The compiler rejects extraction from ordinary unthrown values and prevents the borrow from outliving the catch or surviving a rethrow that consumes the value.

std.print_exception_trace(trace) accepts a const ref ExceptionTrace and writes the original call stack to stderr without allocating or throwing. Known frames show function names and source locations; unknown frames show addresses. Incomplete or disabled traces include their capture status. Pass the borrowed view to helpers to print the original trace even inside a nested catch. See Error Handling for capture limits and lifetime examples.