Extensions to the Zig 0.17 standard library: fixed-capacity containers, strict parsers, IPv4 types, and the primitives std lacks.
The same helpers kept showing up copy-pasted across projects: strict number parsing, IPv4 and CIDR handling, fixed-capacity buffers, a bounded writer, a slab allocator. stdx is where they live. Each module is tested on its own, and the package has no dependencies.
- Modules: every export of
src/root.zig, one row each, with the reason to reach for it. - Choosing a container: which fixed-capacity type fits a need, and when to use std or
swissinstead. - Fixed-capacity containers: lists, queues, maps, sets, and comptime lookup tables. The storage lives in the value, with no allocator and no
deinit. - Probabilistic data structures:
bloom,cuckoo,count_min, andultralogloganswer membership, frequency, and distinct-count questions in fixed memory with bounded error. - Ordered maps:
btreekeeps the keys sorted for iteration and range scans, with cache-sized nodes and a stripped prefix at every node. - Strict parsing:
fmt.atoiaccepts one grammar for machine-written integers and rejects the rest.fmt.parseBoolaccepts Go's boolean spellings. - Configuration files:
dotenv.parsereads a.envfile against one documented grammar, returns borrowed slices, and reports the line that does not fit. - JSON with comments:
jsonc.parseFromSlicereads a config file with//and/* */comments and trailing commas, and keeps every byte offset sostd.jsonerrors point at the right line and column in the source. - String dispatch:
enums.Openandenums.Closedturn a byte-string list into an enum for aswitch.stringToEnummatches an existing enum with fixed-length compares. - Prefix matching:
prefix_map.Mapstores byte prefixes in a compressed radix tree and returns the longest match. - Initialize once:
once.Cellandonce.Lazyset a value at most once. TheSyncvariants share it across threads. - Sort:
sort.radixis a stable integer radix sort, andsort.nth/sort.selectfind the k-th element without sorting the rest. - Cache the recent:
lru.Stringandlru.Autokeep a fixed number of recent entries and evict the tail. - Binary encoding:
wire.Writerwrites integers, enums, slices, and varints into caller-owned bytes, with the byte order fixed at comptime and a slot for a length or checksum written later;wire.Readerreads them back and can peek without consuming. - Base64: the RFC 4648 codec at comptime: the four alphabets, exact lengths before the call, and a decode that is the validation. The kernels move a vector per instruction.
- Base32: a Crockford base32 codec for fixed-shape machine tokens. The decode itself is the validation, and every spelling outside the lowercase alphabet fails.
- IP addresses:
net.Ip4andnet.Prefix4, following Go'snet/netip: classification, ordering, canonical prefixes, and overlap checks. - UUIDs:
Uuidgenerates version 4 and version 7 values, formats them, and parses the canonical text form. - Timekeeping: clock reads with no
Iovalue, a per-tick cached clock, wall time for log lines, and a log rate limiter. - Timers: a caller-driven set of deadlines over
Io.Timestamp, with callbacks, removal by handle, and period re-arm without drift. - Logging transport:
slot_ring.Mpscmoves log lines from worker threads to one consumer. Producers never block, and a refused claim drops the new message. - Small modules: a bounded writer, rapidhash and CRC-32C, the heap pools, fixed-size byte values, secure random, and buffered stdio.
This guide explains how to choose modules and combine them. The API reference documents every symbol.
Getting started
Install
Add stdx to your project:
zig fetch --save https://baskingspot.dev/stdx/v0.6.0.tar.gz
Add the module to your build in build.zig:
const stdx = b.dependency("stdx", .{ .target = target, .optimize = optimize });
exe.root_module.addImport("stdx", stdx.module("stdx"));
stdx builds with Zig 0.17.
Import it
Import the root module once in each file. Then bind the modules that the file uses:
const stdx = @import("stdx");
const buffer = stdx.buffer;
const timex = stdx.time;
If the file uses only one module, import it directly:
const timex = @import("stdx").time;Name the bindings
Name a binding after its module. If the file already has a std module with the same name, add an x suffix.
| Binding | Why |
|---|---|
timex | std.time is in scope in most files. |
fmtx | std.fmt is in scope in most files. |
buffer | std has no buffer module. |
stdio | std has no stdio module. |
The suffix keeps both modules readable at the call site. timex.now(.awake) is stdx. time.ns_per_ms is std.
This rule is for code that uses stdx. Inside stdx, a module binding never has a suffix.
Choose std or stdx
stdx does not replace std. Use std when std has what you need. Use stdx for the cases where std is too liberal, needs an Io value that the code does not have, or has no equivalent, such as a Bloom filter.
Strict parsing is an example. Use fmt.atoi for input with a machine grammar, such as an HTTP Content-Length header or a line from /proc. It rejects bases, underscores, and trailing characters. Use std.fmt.parseInt for input that people write, such as command-line flags and config values. There, 1_000_000 is easier to read.
Read the examples
Every example in this guide is a complete file in docs/examples/. The test step compiles and runs each one, so the code in this guide builds. Run them all:
just test
The API reference has the contract for each symbol. This guide has the recipes.
Modules
A module that extends a std namespace takes its name: mem, fmt, net, posix, heap, hash. A concept std lacks gets its own: bloom, once, swiss, set. A container family follows std.array_hash_map. The module names the concept, and the constructors inside are Custom, Auto, and String.
| Module | Use it for |
|---|---|
base32 | Crockford base32 codec for fixed-shape machine tokens: lowercase-only encode and decode, where the decode is the validation. |
base64 | RFC 4648 base64: four alphabets, encode and decode over caller-owned bytes, and vector kernels on aarch64. |
bit_set | Fixed-capacity bitsets. Scratch resets without clearing the dirty backing words. |
bloom | Bloom filters with a fixed capacity. |
bounded_array_hash_map | An insertion-ordered hash map with a fixed capacity and no allocator. |
btree | An ordered map that grows: sorted iteration, and lookups by key. |
BoundedWriter | An Io.Writer over an allocated buffer with a hard byte limit. It fails at the limit instead of growing. |
buffer | Fixed-capacity buffers. Array owns its storage. Slice and Queue borrow it, and Queue consumes from the front. |
count_min | Fixed-capacity Count-Min Sketches for approximate frequency counts, with conservative updates, merging, and halving. |
cuckoo | Fixed-capacity Cuckoo filters: approximate membership with removal and SIMD bucket probes. |
dotenv | A .env parser: one grammar, borrowed key and value slices, and the line number when a line does not fit. |
enums | Switch on a byte string: generate an open or closed enum from a list, or look up an existing enum. |
fmt | Strict parsing for integers and booleans (atoi, parseBool), and comptime hex decoding. |
hash | RapidHash: rapidhash V3, plus std-style hash-map contexts. crc32c: CRC-32C, one-shot or continued from a stored digest. |
heap | SlabAllocator, SizeClassPool, and the single-threaded Bump arena. |
intern | A string pool with stable u32 ids. Names are copied into chunks, so an intern allocates only when a chunk fills. |
jsonc | JSON with // and /* */ comments and trailing commas. The scrub keeps every byte offset for std.json diagnostics. |
lru | A fixed-capacity LRU cache with no allocator and no eviction callback. |
mem | Fixed-size byte values and memory scans. |
multi_array | Struct-of-arrays types with the storage inside the value. |
net | IPv4 addresses and CIDR prefixes, after Go's net/netip: parse, classify, order, step, and test containment. Ip4Endpoint holds octets and port; HostPort splits config text. |
once | Set-once values and lazy initialization, single-threaded and thread-safe. |
pages | Release whole kernel pages back to the OS. API reference only. Linux only. |
posix | getsockname, getpeername, setsockopt, and getsockopt on raw socket handles. See Work with a raw socket fd. |
prefix_map | A compressed radix tree for exact and longest-prefix lookups. |
priority_queue | A priority queue with a fixed capacity. |
random | Secure random bytes without an Io value. |
set | A bounded set with set algebra. |
slot | A fixed-capacity pool over caller-owned entries, with intrusive links and acquisition-order iteration. |
slot_ring | A bounded MPSC ring for log lines: producers never block, and one consumer drains. Linux only. |
sort | A stable integer radix sort, and selection of the k-th element. |
static_map | Lookup tables that the compiler builds from a literal. |
stdio | Buffered stderr and stdout streams that never return an error. |
swiss | Resizable Swiss-table hash maps. |
time | Compact time values, clock reads without an Io value, a cached clock, RFC 3339 formatting, and a log rate limiter. |
timers | A caller-driven set of timers over Io.Timestamp: arm and stop entries by handle, fire callbacks, and repeat on a period. |
ultraloglog | UltraLogLog sketches for approximate distinct counts, with Optimal FGRA estimation, lossless merging, and downsizing. |
Uuid | UUID v4 and v7. Generate, parse, and format. |
wire | A forward-only writer over caller-owned bytes, with the byte order fixed at comptime. Integers, enums, packed structs, slices, backpatch slots, and LEB128 varints. |
Choosing a container
Most stdx containers have a fixed capacity. The capacity is part of the type, the storage is inside the value, and no allocator is involved. One container, swiss, grows at runtime and uses an allocator. slot.Pool takes its entries as a slice, so its capacity is runtime while its storage stays the caller's.
Find the need in the table. Then read the section for that type in Fixed-capacity containers.
| You need | Use | Notes |
|---|---|---|
| A list with a known maximum length | buffer.Array | Storage inside the value. |
| The same list over memory you already own | buffer.Slice | Same methods. The capacity is the slice length. |
| A buffer that a transport refills and a parser drains | buffer.Queue | Borrows storage. rebase compacts the consumed front. |
| One array per struct field | multi_array.Buffer | Runtime length. multi_array.Array has a fixed length. |
| The smallest item first | priority_queue.Custom | A binary heap. You supply the comparison. |
| A map that keeps insertion order | bounded_array_hash_map.Auto or .String | Fixed capacity. |
| The N most recent entries, evicting the rest | lru.Auto or .String | Fixed capacity. A hit moves to the front. |
| A set | set.Auto or .String | A map with no values, plus set algebra. |
| A set of indices in a reused workspace | bit_set.Scratch | Reset clears only a validity map. |
| A constant lookup table | static_map.Auto or .String | Built at compile time from a literal. Not the same as std.StaticStringMap: see below. |
| A cheap "have I seen this" test | bloom.Auto or .String | Can report a key that was never added. See Probabilistic data structures. |
| A cheap membership test with removal | cuckoo.Auto or .String | Can return error.FilterFull near full load. See Probabilistic data structures. |
| Approximate frequency counts in fixed memory | count_min.Auto or .String | Never undercounts. Supports addConservative, merge, and halve. |
| Approximate distinct counts in fixed memory | ultraloglog.Auto or .String | Byte-aligned registers, merge, and lossless downsize. |
| A map that grows | swiss.Auto or .String | Uses an allocator. Order is not insertion order. |
| Keys kept in sorted order | btree.Auto or .String | Uses an allocator. Iteration is in key order, not insertion order. |
Pick a fixed capacity when
- The maximum is a real limit that your program already enforces, such as a configured connection count.
- The value must copy freely, such as a configuration struct.
- The code must not allocate, such as a signal handler or an event loop that runs after startup.
Pick std or swiss when
- The size depends on input that you do not control. A fixed capacity turns a large input into
error.NoSpaceLeft. - The container is large and rarely full. A copy moves the whole capacity, used or not.
- You need
std.ArrayListfeatures that the fixed types lack.
Check std first
std.StaticStringMapalso builds a lookup table at compile time, but only for string keys. Build a table at compile time lists howstatic_mapdiffers. Usestatic_mapwhen the keys are not strings, or when you want a compile error for a duplicate key.std.EnumMapcovers dense enum keys.std.PriorityQueue,std.ArrayList, andstd.AutoArrayHashMapallocate. The stdx types of the same shape do not.
Fixed-capacity containers
A fixed-capacity container never allocates and never grows. buffer.Array stores its elements inside the value, so the capacity is a comptime parameter: buffer.Array(u8, 16) and buffer.Array(u8, 32) are different types. buffer.Slice and buffer.Queue borrow storage that the caller owns, so a copy of either copies the reference, not the storage.
Two rules hold for every type on this page except swiss, which the last section covers:
- No method takes an allocator, and no value needs a
deinit. - Nothing grows. An operation that does not fit returns
error.NoSpaceLeft, and a cursor operation that oversteps the storage panics.
Build a list
buffer.Array is the base type. append and appendSlice return error.NoSpaceLeft when the item does not fit.
const std = @import("std");
const buffer = @import("stdx").buffer;
// The capacity is part of the type. The storage lives inside the value.
const Frame = buffer.Array(u8, 16);
// A length prefix and a payload, built with no allocator. A payload that
// does not fit is an error the caller handles.
fn encode(payload: []const u8) error{NoSpaceLeft}!Frame {
var frame: Frame = .empty;
try frame.append(@intCast(payload.len));
try frame.appendSlice(payload);
return frame;
}
// When the code has already checked the size, the AssumeCapacity pair
// skips the error path.
fn encodeChecked(payload: []const u8) ?Frame {
if (payload.len + 1 > Frame.capacity) return null;
var frame: Frame = .empty;
frame.appendAssumeCapacity(@intCast(payload.len));
frame.appendSliceAssumeCapacity(payload);
return frame;
}
test "a payload that fits" {
const frame = try encode("hello");
try std.testing.expectEqualSlices(u8, "\x05hello", frame.constSlice());
}
test "a payload that does not fit" {
try std.testing.expectError(error.NoSpaceLeft, encode("this payload is too long"));
try std.testing.expectEqual(null, encodeChecked("this payload is too long"));
}
test "the checked path matches the fallible path" {
const a = try encode("abc");
const b = encodeChecked("abc").?;
try std.testing.expectEqualSlices(u8, a.constSlice(), b.constSlice());
}
Each fallible method has an AssumeCapacity form. Use it only after the code has checked the size. In Debug and ReleaseSafe builds, a wrong assumption is a safety-checked panic.
Keep it in a struct
A fixed-capacity list is a good field in a configuration struct. The struct copies by value, and nothing needs to be freed.
const std = @import("std");
const stdx = @import("stdx");
const buffer = stdx.buffer;
const Ip4 = stdx.net.Ip4;
const Backend = struct {
addr: Ip4,
port: u16,
};
// A list field that copies with its struct. No allocator, no deinit, no
// ownership to track.
const BackendList = buffer.Array(Backend, 8);
const Config = struct {
listen: Ip4 = .loopback,
backends: BackendList = .empty,
};
test "a config copies by value" {
var config: Config = .{};
try config.backends.append(.{ .addr = .parseComptime("10.0.0.1"), .port = 5432 });
// The copy owns its own list. A reload can edit one and keep the other.
var next = config;
try next.backends.append(.{ .addr = .parseComptime("10.0.0.2"), .port = 5432 });
try std.testing.expectEqual(1, config.backends.constSlice().len);
try std.testing.expectEqual(2, next.backends.constSlice().len);
}
test "the whole capacity travels with the value" {
// A copy moves every byte of the storage, used or not. Keep the
// capacity close to the real maximum.
try std.testing.expect(@sizeOf(buffer.Array(u8, 4096)) >= 4096);
}
Choose the capacity close to the real maximum. A copy moves every byte of the storage, so a large capacity makes every copy, return, and pass by value expensive. A very large value can also overflow the stack. Put such a value in a global or in a struct that you allocate.
Use one constant for the limit. The command-line check and the type then agree about the maximum.
Borrow storage
buffer.Slice has the methods of buffer.Array, but it appends into memory that the caller owns. Use it when the memory already exists, such as a stack array or a region of a larger buffer.
const std = @import("std");
const buffer = @import("stdx").buffer;
// `Slice` has the API of `Array`, but over storage the caller owns. The
// capacity is a runtime value: the length of the slice.
test "append into caller storage" {
var storage: [8]u8 = undefined;
var out: buffer.Slice(u8) = .init(&storage);
try out.appendSlice("abc");
try std.testing.expectEqualStrings("abc", out.constSlice());
// The bytes are in the caller's array, not in a copy.
try std.testing.expectEqualStrings("abc", storage[0..3]);
try std.testing.expectError(error.NoSpaceLeft, out.appendSlice("too long"));
}
The slice stores a pointer. Keep the storage alive for as long as the Slice is in use.
Refill and drain
buffer.Queue borrows storage like Slice, but it also reads from the front. Use it when a transport delivers arbitrary chunks and a parser needs complete messages.
const std = @import("std");
const buffer = @import("stdx").buffer;
// A transport delivers bytes in arbitrary chunks. The queue joins them and
// the parser takes one complete length-prefixed message.
test "join chunks into a message" {
var storage: [8]u8 = undefined;
var queue: buffer.Queue(u8) = .init(&storage);
// The first chunk: a length byte and part of the body.
const first = "\x05hel";
@memcpy(queue.unusedCapacitySlice()[0..first.len], first);
queue.advance(first.len);
// One length byte plus five body bytes: still incomplete.
try std.testing.expect(queue.bufferedLen() < 1 + queue.peek(1)[0]);
// The second chunk completes the message.
const second = "lo";
@memcpy(queue.unusedCapacitySlice()[0..second.len], second);
queue.advance(second.len);
const total = 1 + queue.peek(1)[0];
const message = queue.take(total);
try std.testing.expectEqualStrings("\x05hello", message);
// The consumed bytes are still in the backing. Rebase moves the
// unconsumed tail, which is empty here, and resets both cursors.
queue.rebase();
try std.testing.expectEqual(storage.len, queue.unusedCapacityLen());
// A stray status byte before the next message is dropped in place.
const third = "\xff\x02ok";
@memcpy(queue.unusedCapacitySlice()[0..third.len], third);
queue.advance(third.len);
queue.toss(1);
try std.testing.expectEqualStrings("\x02ok", queue.take(3));
}
buffered returns the unconsumed elements. take returns a prefix and drops it, and toss drops a prefix without returning it. unusedCapacitySlice returns the free tail, and advance commits the count written there. rebase moves the unconsumed elements to the front and invalidates every slice into the backing that an earlier call returned. Call it when the tail is too small for the next read, not after every read. The method names follow std.Io.Reader and std.Io.Writer.
Order by priority
priority_queue.Custom is the binary heap of std.PriorityQueue with a fixed capacity. The comparison function returns .lt when the first argument must pop first.
const std = @import("std");
const priority_queue = @import("stdx").priority_queue;
const Timer = struct {
deadline_ms: i64,
id: u32,
};
// The comparator returns `.lt` when `a` must pop before `b`.
fn byDeadline(_: void, a: Timer, b: Timer) std.math.Order {
return std.math.order(a.deadline_ms, b.deadline_ms);
}
// At most 64 pending timers. The queue never allocates.
const Timers = priority_queue.Custom(Timer, void, 64, byDeadline);
test "timers pop in deadline order" {
var timers: Timers = .empty;
try timers.push(.{ .deadline_ms = 300, .id = 1 });
try timers.push(.{ .deadline_ms = 100, .id = 2 });
try timers.push(.{ .deadline_ms = 200, .id = 3 });
// Peek reads the next deadline without removing it.
try std.testing.expectEqual(100, timers.peek().?.deadline_ms);
try std.testing.expectEqual(2, timers.pop().?.id);
try std.testing.expectEqual(3, timers.pop().?.id);
try std.testing.expectEqual(1, timers.pop().?.id);
try std.testing.expectEqual(null, timers.pop());
}
A queue made with .empty has an undefined context. If the comparison reads the context, make the queue with initContext.
Store key and value pairs
bounded_array_hash_map is the data structure of std.AutoArrayHashMapUnmanaged with a fixed capacity. Entries keep their insertion order. Use Auto for keys that std.hash.autoHash accepts and String for []const u8 keys.
const std = @import("std");
const bounded_array_hash_map = @import("stdx").bounded_array_hash_map;
// Keys and values live in arrays inside the value. Iteration follows
// insertion order.
const Names = bounded_array_hash_map.Auto(u32, []const u8, 2);
test "a full map refuses new keys" {
var names: Names = .init;
try names.put(10, "ten");
try names.put(20, "twenty");
// A new key does not fit.
try std.testing.expectError(error.NoSpaceLeft, names.put(30, "thirty"));
// An existing key still updates in place, and keeps its position.
try names.put(10, "TEN");
try std.testing.expectEqualStrings("TEN", names.get(10).?);
try std.testing.expectEqualSlices(u32, &.{ 10, 20 }, names.keys());
}
When the map is full, put fails for a new key. It still updates an existing key.
Store a set
set is a map with no values and the usual set operations. The operations work in place and do not allocate. add returns true for a new key and false for a key that is already present. It returns error.NoSpaceLeft when a new key does not fit, and unite does the same when the union does not fit.
const std = @import("std");
const set = @import("stdx").set;
const Ports = set.Auto(u16, 8);
test "membership and set algebra" {
var allowed: Ports = .init;
for ([_]u16{ 80, 443, 8080 }) |port| _ = try allowed.add(port);
var requested: Ports = .init;
_ = try requested.add(443);
_ = try requested.add(80);
try std.testing.expect(requested.subsetOf(&allowed));
_ = try requested.add(22);
try std.testing.expect(!requested.subsetOf(&allowed));
// Keep only what the allow list also holds.
requested.intersect(&allowed);
try std.testing.expectEqual(2, requested.count());
try std.testing.expect(!requested.contains(22));
}
// `add` has three outcomes: newly added, already present, and no room.
test "a full set refuses a new key" {
var ports: set.Auto(u16, 2) = .init;
try std.testing.expect(try ports.add(80));
try std.testing.expect(!try ports.add(80));
try std.testing.expect(try ports.add(443));
try std.testing.expectError(error.NoSpaceLeft, ports.add(8080));
}
test "unite fails when the union does not fit" {
const Small = set.Auto(u16, 3);
var a: Small = .init;
var b: Small = .init;
_ = try a.add(1);
_ = try a.add(2);
_ = try b.add(3);
_ = try b.add(4);
try std.testing.expectError(error.NoSpaceLeft, a.unite(&b));
}Reuse a bitset
bit_set.Scratch(capacity) is a fixed-capacity set of indices for a workspace that runs many requests. It has no by-value constructor: declare it undefined and call clear once, because returning or copying the value would copy the whole backing. The same call starts each later generation. A data word is zeroed the first time set touches it, so a reset costs the words a request touched, not the whole capacity.
const std = @import("std");
const bit_set = @import("stdx").bit_set;
// There is no by-value constructor: it would copy the whole backing. Declare
// the set undefined and clear it in place.
test "track touched offsets across a reuse" {
var scratch: bit_set.Scratch(1 << 10) = undefined;
scratch.clear();
scratch.set(7);
scratch.set(700);
try std.testing.expect(scratch.isSet(7));
try std.testing.expect(scratch.isSet(700));
try std.testing.expect(!scratch.isSet(8));
// Reuse for the next request. The old bits read as unset, and the data
// words are zeroed only as the new request touches them.
scratch.clear();
try std.testing.expect(!scratch.isSet(7));
try std.testing.expect(!scratch.isSet(700));
scratch.set(8);
try std.testing.expect(scratch.isSet(8));
try std.testing.expect(!scratch.isSet(7));
}
unset clears a bit. A word that was never touched reads as unset, so unset on it is a no-op.
Build a table at compile time
static_map builds a lookup table from a literal during compilation. The table is a constant. It has no startup cost, and a duplicate key is a compile error.
const std = @import("std");
const static_map = @import("stdx").static_map;
// The table is built at compile time from a literal. It has no runtime
// initialization, and a duplicate key is a compile error.
const Opcode = static_map.Auto(u8, []const u8, .{
.{ 0x01, "push" },
.{ 0x02, "pop" },
.{ 0xff, "halt" },
});
test "lookup in a comptime table" {
try std.testing.expectEqualStrings("halt", Opcode.get(0xff).?);
try std.testing.expectEqual(null, Opcode.get(0x03));
try std.testing.expect(Opcode.has(0x02));
try std.testing.expectEqual(3, Opcode.count);
}
// The keys and values keep the order of the literal.
test "iteration follows the literal" {
try std.testing.expectEqualSlices(u8, &.{ 0x01, 0x02, 0xff }, Opcode.keys);
}
std.StaticStringMap also builds a table at compile time, for string keys. static_map differs in these ways:
- Key types: std takes
[]const u8only.static_map.Autotakes key types thatstd.hash.autoHashaccepts, such asu8,u32, and enums with an explicitu8tag. A key with bits narrower than a byte, such as au2, abool, or an enum with three tags, is a compile error, because std hashes those bits differently at comptime than at runtime. Usestatic_map.Customwith your own hash for such keys.static_map.Customtakes your own hash and equality context, andstatic_map.Stringis the string-keyed form. - Lookup: std finds a key by its length, then compares it against each key of that length.
static_maphashes the key and probes a table. - Duplicates: std accepts a duplicate key, and which of its values
getreturns is unspecified.static_maprejects a duplicate key at compile time. - Order: std orders
keys()andvalues()by key length.static_mapkeeps the order of your literal. - What only std has:
getLongestPrefix, which finds the longest key that starts a string, andinit, which builds the map at runtime with an allocator.static_maphas neither.
For string keys, use std unless you want one of those properties from static_map. For a dense enum key, std.EnumMap fits. For any other key type, std has no table of this kind.
Store columns
multi_array keeps one array for each field of a struct. A loop over one field reads one contiguous array. Buffer has a runtime length. Array has a fixed length.
const std = @import("std");
const multi_array = @import("stdx").multi_array;
const Particle = struct {
x: f32,
y: f32,
alive: bool,
};
// One array per field, with fixed capacity and a runtime length.
const Particles = multi_array.Buffer(Particle, 128);
test "a field is a contiguous slice" {
var particles: Particles = .empty;
try particles.append(.{ .x = 1, .y = 10, .alive = true });
try particles.append(.{ .x = 2, .y = 20, .alive = false });
// A loop over one field touches one array, not every struct.
for (particles.items(.x)) |*x| x.* += 1;
try std.testing.expectEqualSlices(f32, &.{ 2, 3 }, particles.constItems(.x));
try std.testing.expectEqual(10, particles.get(0).y);
}Grow when you must
swiss is the exception. It is a resizable hash map, so every call that can allocate takes the allocator, and the value does not store it. The map keeps the key slices that you give it, so the keys must outlive the map.
const std = @import("std");
const swiss = @import("stdx").swiss;
// The one container here that grows. It allocates, so every call that can
// allocate takes the allocator, and the value does not store it.
const Counts = swiss.String(u32);
test "a resizable map takes the allocator per call" {
const gpa = std.testing.allocator;
var counts: Counts = .init;
defer counts.deinit(gpa);
// 1,000 keys is far past any fixed capacity. The map grows.
var key_buffer: [16]u8 = undefined;
for (0..1000) |i| {
const key = try std.mem.print(&key_buffer, "key-{d}", .{i});
// The map keeps the key slice, not a copy. A stack buffer would
// dangle, so give the map keys that outlive it.
const owned = try gpa.dupe(u8, key);
errdefer gpa.free(owned);
try counts.put(gpa, owned, @intCast(i));
}
defer {
var it = counts.keyIterator();
while (it.next()) |k| gpa.free(k.*);
}
try std.testing.expectEqual(1000, counts.count());
try std.testing.expectEqual(42, counts.get("key-42").?);
}Probabilistic data structures
Probabilistic data structures trade exactness for fixed memory and constant-time operations. None of them store the keys that you insert. Every type in this chapter lives in a flat value with no allocator and no deinit.
Use an exact container (set, bounded_array_hash_map, or swiss) when the key set fits in memory, or when a wrong answer breaks correctness. Do not use a probabilistic filter for access control, billing, or deduplication that cannot tolerate a miss or a false positive. Use these types for pre-checks, telemetry, cache admission, rate tracking, and shard-level analytics where bounded error is acceptable and memory must stay fixed.
| Question | Module | Error direction | Mutability and merge |
|---|---|---|---|
| Was this key added | bloom | False positives only | Add only. Infallible add. |
| Is this key in the active set | cuckoo | False positives only | add and remove. add returns error.FilterFull near full load. |
| How often did this key appear | count_min | Overcounts only | add, addConservative, merge, and halve. |
| How many distinct keys appeared | ultraloglog | Relative error (~0.782 / sqrt(2^p)) | add, merge, and lossless downsize. |
Test membership cheaply
Reach for bloom or cuckoo when an exact lookup is expensive, such as a disk read or a network call. A false result proves that the key is absent, so the caller skips the slow path. A true result means the caller checks the authoritative store.
Pick bloom when keys are never removed and add must never fail. bloom computes its bit count and probe count at compile time from item_count and target_rate. Its false-positive rate stays at actual_rate up to expected_items distinct keys, and degrades smoothly past that load.
const std = @import("std");
const bloom = @import("stdx").bloom;
// Sized at compile time for 10,000 keys at about a 1% false-positive rate.
const Seen = bloom.Auto(u64, 10_000, 0.01);
test "a filter has no false negatives" {
var seen: Seen = .empty;
seen.add(42);
try std.testing.expect(seen.contains(42));
}
test "the request is a target and actual_rate is the truth" {
// The filter rounds its size up to a power of two, so the rate it
// delivers can differ from the request.
try std.testing.expect(Seen.actual_rate <= 0.01);
}
Pick cuckoo when keys leave the set, or when you want faster probes at a low false-positive rate. A Cuckoo filter stores four fingerprints per bucket and probes two candidate buckets with SIMD compares. For false-positive rates below 3%, it uses less memory than a Bloom filter and touches two cache lines instead of many scattered bits.
cuckoo has two strict rules. First, add returns error.FilterFull when relocation hits max_kicks, typically above 90% load. On failure, add rolls back every relocation so no live key is lost. Second, call remove only for keys that you previously added. If you remove an absent key, cuckoo can delete a colliding fingerprint and hide a live key.
const std = @import("std");
const cuckoo = @import("stdx").cuckoo;
// Sized at compile time for 10,000 keys at a false-positive rate at or below 1%.
const Active = cuckoo.Auto(u64, .fromCapacity(10_000, 0.01));
test "cuckoo filters support removal" {
var active: Active = .empty;
try active.add(42);
try active.add(99);
try std.testing.expect(active.contains(42));
try std.testing.expect(active.remove(42));
try std.testing.expect(!active.contains(42));
try std.testing.expect(active.contains(99));
}Count frequencies in bounded memory
Use count_min when a stream has too many distinct keys to keep a counter per key, such as per-route request counts, hot-key detection, or cache admission next to lru. Every cell holds an unsigned Counter in a [depth][width]Counter grid, and additions saturate instead of wrapping around.
Size a sketch either by error bounds (Config.fromError) or by an explicit memory budget (depth, width, and Counter). Larger width shrinks the additive error epsilon = e / width. Larger depth shrinks the failure probability delta = exp(-depth).
Use addConservative for most non-negative streams. Standard add increments all depth cells for a key, while addConservative raises each cell only up to estimate(key) + amount. Conservative updates cut overestimation on skewed traffic and preserve the upper-bound guarantee across merge.
Use merge to combine per-thread or per-shard sketches into one total. Use halve on a fixed schedule or when count() reaches a threshold to decay older counts for sliding-window tracking or TinyLFU cache admission. Pair halve with a narrow Counter such as u8 or u16 to keep the table inside L1 cache.
const std = @import("std");
const count_min = @import("stdx").count_min;
// Error bounds: within 0.5% of total weight with at least 99% probability.
const Hits = count_min.String(.fromError(.{ .epsilon = 0.005, .delta = 0.01 }));
test "estimates never undercount and merge across workers" {
var worker_a: Hits = .empty;
var worker_b: Hits = .empty;
worker_a.addConservative("/health", 10);
worker_b.addConservative("/health", 4);
worker_b.addConservative("/metrics", 3);
worker_a.merge(&worker_b);
try std.testing.expect(worker_a.estimate("/health") >= 14);
try std.testing.expect(worker_a.estimate("/metrics") >= 3);
try std.testing.expectEqual(@as(u64, 17), worker_a.count());
// Halve all counters to age out older traffic.
worker_a.halve();
try std.testing.expect(worker_a.estimate("/health") >= 7);
}Count distinct keys in bounded memory
Use ultraloglog to estimate cardinality (unique users, unique IPs, distinct query hashes) when keeping an exact set is too large. UltraLogLog stores 2^precision byte registers and uses about 28% less memory than HyperLogLog for the same relative standard error. One estimator (Optimal FGRA) covers counts from zero up to 2^64.
Pick precision from the memory and error budget:
precision | Size | Relative standard error |
|---|---|---|
10 | 1 KiB | ~2.4% |
12 | 4 KiB | ~1.2% |
14 | 16 KiB | ~0.61% |
16 | 64 KiB | ~0.31% |
Each worker or shard can maintain its own sketch. merge combines those sketches into the exact register state that one sketch produces. Call downsize to reduce a sketch to a lower precision without extra error when you merge against a smaller sketch or archive history. Call asBytes and fromBytes to serialize registers over the wire. fromBytes rejects any byte that is unreachable at that precision.
const std = @import("std");
const ultraloglog = @import("stdx").ultraloglog;
// Precision 10 holds 1,024 byte registers (~2.4% relative standard error).
const Distinct = ultraloglog.String(10);
test "merge shards, downsize, and roundtrip bytes" {
var shard_a: Distinct = .empty;
var shard_b: Distinct = .empty;
shard_a.add("alice");
shard_a.add("bob");
shard_a.add("alice");
shard_b.add("bob");
shard_b.add("carol");
shard_a.merge(&shard_b);
try std.testing.expectApproxEqAbs(@as(f64, 3.0), shard_a.estimate(), 1.5);
// Serialize the raw bytes and restore with validation.
const wire = shard_a.asBytes().*;
const restored = try Distinct.fromBytes(wire);
try std.testing.expectEqual(shard_a.estimate(), restored.estimate());
// Downsize to a smaller precision without re-hashing inputs.
const compact = restored.downsize(8);
try std.testing.expectEqual(@as(usize, 256), @TypeOf(compact).register_count);
}Bring your own hash
cuckoo.Filter, count_min.Sketch, and ultraloglog.Sketch are the hash-level primitives beneath Custom, Auto, and String. They take uniform 64-bit hashes directly and perform no hashing of their own.
Use the primitives directly when you already hold a 64-bit hash, such as a hash.RapidHash digest. One digest can feed several sketches so you do not hash the key twice. The primitives also cover key types that std.hash.autoHash rejects. Never pass sequential integers or weak hashes to addHash: all three structures require uniform bits across all 64 bits.
const std = @import("std");
const stdx = @import("stdx");
const count_min = stdx.count_min;
const hash = stdx.hash;
const ultraloglog = stdx.ultraloglog;
// Hash each key once and feed both sketches through their hash-level primitives.
const Freq = count_min.Sketch(.{ .depth = 4, .width = 256 });
const Distinct = ultraloglog.Sketch(10);
test "one hash drives multiple sketches" {
var freq: Freq = .empty;
var distinct: Distinct = .empty;
const events = [_][]const u8{ "/health", "/api", "/health", "/metrics", "/health" };
for (events) |path| {
const digest = hash.RapidHash.hash(0, path);
freq.addHashConservative(digest, 1);
distinct.addHash(digest);
}
const health_hash = hash.RapidHash.hash(0, "/health");
try std.testing.expect(freq.estimateHash(health_hash) >= 3);
try std.testing.expectApproxEqAbs(@as(f64, 3.0), distinct.estimate(), 1.5);
}Ordered maps
Zig has no ordered map that owns its nodes. std.Treap orders keys, but it
takes a node from the caller for each element and chases pointers down the
tree. btree is the ordered map: it grows, it takes the allocator per call,
and it iterates in key order.
A lookup reads a few cache lines, not one per key compared. A node holds a couple of dozen keys, and the search compares one short window of every key with a single vector compare. The window starts where the keys a node routes already share their first bytes, so a common prefix costs nothing. Keys that are slices stay on the heap, and a comparison reads their bytes only when two windows tie.
Keep keys in order
Iteration is in key order. A repeated key replaces its value and keeps its
place in the order. iteratorFrom starts the walk at any key, so a range is
one iterator with a stop condition.
const std = @import("std");
const btree = @import("stdx").btree;
// An ordered map keeps the keys sorted. Iteration reads the keys in that
// order, and lookups go by key, not by an insertion position.
const Scores = btree.Auto(u32, u32);
test "an ordered map iterates in key order" {
const gpa = std.testing.allocator;
// The map grows, so every call that can allocate takes the allocator.
var scores: Scores = .empty;
defer scores.clearAndFree(gpa);
// Insertion order is 30, 10, 20. Key order is 10, 20, 30.
try scores.put(gpa, 30, 7);
try scores.put(gpa, 10, 3);
try scores.put(gpa, 20, 5);
// A repeated key replaces the value and keeps its place in the order.
try scores.put(gpa, 10, 4);
var it = scores.iterator();
var previous: ?u32 = null;
var seen: usize = 0;
while (it.next()) |entry| {
if (previous) |key| try std.testing.expect(key < entry.key_ptr.*);
previous = entry.key_ptr.*;
seen += 1;
}
try std.testing.expectEqual(3, seen);
try std.testing.expectEqual(4, scores.get(10).?);
try std.testing.expectEqual(null, scores.get(15));
try std.testing.expect(scores.remove(gpa, 30));
}
test "string keys keep their order too" {
const gpa = std.testing.allocator;
var files: btree.String(u32) = .empty;
defer files.clearAndFree(gpa);
// The map keeps the key slice, not a copy. String literals live for the
// whole program, so they outlive the map.
try files.put(gpa, "src/btree.zig", 40);
try files.put(gpa, "src/btree/map.zig", 900);
try files.put(gpa, "build.zig", 30);
var it = files.iterator();
try std.testing.expectEqualStrings("build.zig", it.next().?.key_ptr.*);
try std.testing.expectEqualStrings("src/btree.zig", it.next().?.key_ptr.*);
try std.testing.expectEqualStrings("src/btree/map.zig", it.next().?.key_ptr.*);
try std.testing.expectEqual(null, it.next());
// Start anywhere in the order: everything from "src/" upward.
var tail = files.iteratorFrom("src/", true);
try std.testing.expectEqualStrings("src/btree.zig", tail.next().?.key_ptr.*);
try std.testing.expectEqualStrings("src/btree/map.zig", tail.next().?.key_ptr.*);
try std.testing.expectEqual(null, tail.next());
}Hold a pointer safely
The map grows and owns its entries, so a value pointer or an iterator does
not survive every call: an insertion or removal in the same leaf shifts
entries, and a split or a merge frees the node. lockPointers brackets the
use of such a pointer. While a borrow is outstanding, every call that could
move or free an entry fails an assertion in Debug and ReleaseSafe, and does
nothing in ReleaseFast.
map.lockPointers();
defer map.unlockPointers();
const value = map.getPtr(key).?;
// An insertion or removal from here would invalidate `value`. While the
// lock is held, the map asserts instead of running it.Use it from one thread
The map is not thread safe. Use it from one thread at a time, and do not read it from two threads at once either. The pointer guard that catches invalidated pointers is a plain counter, and an insertion or removal moves or frees nodes.
The original also ships a concurrent map. It puts a version lock on every node, reads inner nodes optimistically, and recycles freed nodes through a free list. This one does not; that is a separate design.
Pick a key type
btree.Auto takes integer keys, ordered numerically. btree.String takes
[]const u8 keys, ordered by bytes. btree.Custom takes any key type with a
context that declares compare, and it uses inline keys when that context
also declares inlineKey.
An ordered map is the wrong choice when the order is not needed. swiss and
the fixed-capacity maps find a key without comparing keys at all, and they are
much faster for that. Reach for btree when the program reads keys in order,
looks for the nearest key on either side, or must iterate a table in a stable
sorted order.
The design is Xiangpeng Hao's, from bbtree: fastest ordered map. The Rust implementation is at XiangpengHao/bbtree. This module reimplements the ideas in Zig; none of that code is here.
Strict parsing
The std parsers accept more than one grammar. That is correct for input that people write. For input that a program writes, it hides errors. fmt.atoi accepts one grammar and rejects the rest.
Use it at a machine boundary, such as an HTTP header or a line from /proc. Use std.fmt.parseInt for values that people type, such as command-line flags.
Parse an integer
fmt.atoi accepts an optional sign (for signed types) and decimal digits. The whole string must be the number. It rejects base prefixes, underscores, spaces, and an empty string.
const std = @import("std");
const fmtx = @import("stdx").fmt;
// An HTTP Content-Length header is machine-written. It has one grammar:
// decimal digits and nothing else.
fn contentLength(value: []const u8) !u64 {
return fmtx.atoi(u64, value);
}
test "plain digits parse" {
try std.testing.expectEqual(1024, try contentLength("1024"));
}
test "everything else is an error" {
// The whole string must be the number.
try std.testing.expectError(error.InvalidCharacter, contentLength("1024 "));
try std.testing.expectError(error.InvalidCharacter, contentLength("0x400"));
try std.testing.expectError(error.InvalidCharacter, contentLength("1_000"));
try std.testing.expectError(error.InvalidCharacter, contentLength(""));
// A value too large for the type is a different error.
try std.testing.expectError(error.Overflow, contentLength("18446744073709551616"));
}
test "std.fmt.parseInt reads input that people write" {
// std accepts underscores. That suits a config value and is wrong for a
// header.
try std.testing.expectEqual(1000, try std.fmt.parseInt(u64, "1_000", 10));
}
An empty or malformed string returns error.InvalidCharacter. A number too large for the type returns error.Overflow.
Choose the grammar
fmt.atoiWith takes comptime options. Each set of options compiles to its own loop, so the choice has no runtime cost.
const std = @import("std");
const fmtx = @import("stdx").fmt;
// The options are comptime. Each configuration compiles to its own loop.
// This one is the JSON grammar for integers: no leading zeros, and no `+`.
fn jsonInt(text: []const u8) !i64 {
return fmtx.atoiWith(i64, text, .{
.leading_zeros = .reject,
.plus_sign = .reject,
});
}
// Bencode goes one step further: an optional `-`, then digits, and no
// negative zero.
fn bencodeInt(text: []const u8) !i64 {
return fmtx.atoiWith(i64, text, .{
.leading_zeros = .reject,
.plus_sign = .reject,
.negative_zero = .reject,
});
}
test "the JSON integer grammar" {
try std.testing.expectEqual(0, try jsonInt("0"));
try std.testing.expectEqual(42, try jsonInt("42"));
try std.testing.expectEqual(-1, try jsonInt("-1"));
try std.testing.expectError(error.InvalidCharacter, jsonInt("+42"));
try std.testing.expectError(error.InvalidCharacter, jsonInt("042"));
// JSON does allow negative zero, which parses as 0.
try std.testing.expectEqual(0, try jsonInt("-0"));
// The default allows both, like std.fmt.parseInt.
try std.testing.expectEqual(42, try fmtx.atoi(i64, "+042"));
}
test "the bencode integer grammar" {
try std.testing.expectEqual(-1, try bencodeInt("-1"));
try std.testing.expectError(error.InvalidCharacter, bencodeInt("-0"));
try std.testing.expectError(error.InvalidCharacter, bencodeInt("+1"));
try std.testing.expectError(error.InvalidCharacter, bencodeInt("007"));
}
.overflow = .unchecked skips the overflow check. The caller promises that the value fits. A value that does not fit is a safety-checked panic in Debug and ReleaseSafe, and undefined behavior in ReleaseFast. fmt.atoiUnchecked is the shorthand.
Three more knobs pick the sign and zero grammar. .leading_zeros = .reject refuses a 0 with digits after it. .plus_sign = .reject refuses a leading +, which only a signed type would otherwise accept. .negative_zero = .reject refuses -0, and any longer run of zeros behind a minus sign. The defaults allow all three, matching std.fmt.parseInt.
Parse a boolean
fmt.parseBool accepts the spellings of Go's strconv.ParseBool: 1, t, T, TRUE, true, True, and the same set for false. Anything else returns null.
const std = @import("std");
const fmtx = @import("stdx").fmt;
test "parse a boolean" {
try std.testing.expectEqual(true, fmtx.parseBool("TRUE").?);
try std.testing.expectEqual(false, fmtx.parseBool("0").?);
try std.testing.expectEqual(null, fmtx.parseBool("yes"));
}Configuration files
A .env file is text that a deploy step writes and a program reads. The format has no specification, and the loaders disagree about whitespace, comments, and quotes. dotenv implements one grammar, written out at the top of the module, so a file either parses or reports the line that does not fit. The parse allocates nothing.
Parse a dotenv file
dotenv.parse takes the source bytes, an array of entries, a scratch buffer for the escape bytes of double-quoted values, and ParseOptions. It returns a Doc value. On failure it returns one of Error.
Set the diagnostics field in ParseOptions to a Diagnostics value to receive the position of a failure. A successful parse does not touch that value, and a caller that wants no position passes .{}.
A key, an unquoted value, and a quoted value without escapes are slices of the source. Only an escaped value is copied, into the scratch buffer. A source of n bytes never needs more than n bytes of scratch.
The entry array bounds the file. A file with more assignments reports error.EntriesFull, and a caller that does not know the count allocates the array from an arena and retries.
Nothing expands a variable. $VAR stays four bytes, because the environment belongs to the caller.
const std = @import("std");
const dotenv = @import("stdx").dotenv;
// A configuration file: one assignment per line, an optional `export`, a
// comment, and quotes where the value needs them.
test "read a configuration file" {
const source =
\\# The service configuration.
\\PORT=8080
\\export HOST=127.0.0.1
\\GREETING="hello\nworld"
\\
;
// The entries are the caller's array, and the escapes need a scratch
// buffer. `source.len` always fits, because a decoded value is never
// longer than the text it came from.
var entries: [8]dotenv.Entry = undefined;
var scratch: [source.len]u8 = undefined;
// A failed parse writes the byte that stopped it, and the line and column
// of that byte, into the caller's struct. A successful parse leaves the
// struct alone.
var diagnostics: dotenv.Diagnostics = undefined;
const doc = dotenv.parse(source, &entries, &scratch, .{
.diagnostics = &diagnostics,
}) catch {
std.debug.print("{s} at line {d}, column {d}\n", .{
diagnostics.message(),
diagnostics.line,
diagnostics.column,
});
return error.BadConfig;
};
// `get` returns the last assignment, so a duplicate key is not an error.
try std.testing.expectEqualStrings("8080", doc.get("PORT").?);
try std.testing.expectEqualStrings("127.0.0.1", doc.get("HOST").?);
try std.testing.expectEqualStrings("hello\nworld", doc.get("GREETING").?);
try std.testing.expect(doc.get("MISSING") == null);
// Nothing is copied and nothing needs freeing: the entries point into the
// caller's bytes.
try std.testing.expectEqual(@as(usize, 3), doc.entries.len);
try std.testing.expectEqual(@as(u32, 2), doc.entries[0].line);
}Report the bad line
Diagnostics carries the byte offset, the 1-based line, the 1-based column in bytes, and the problem. The offset points into the original bytes, so a CRLF file and a byte order mark do not shift it. lineText returns the bytes of that line without the terminator, for a message or a log line.
const std = @import("std");
const dotenv = @import("stdx").dotenv;
// A line that does not fit the grammar reports where it is and what is wrong.
test "report the line that does not parse" {
const source =
\\PORT=8080
\\HOST=127.0.0.1
\\TIMEOUT.SECONDS=30
\\
;
var entries: [8]dotenv.Entry = undefined;
var scratch: [source.len]u8 = undefined;
// `parse` returns the error. The position comes back through the struct,
// so a caller that only fails fast passes no options at all.
var diagnostic: dotenv.Diagnostics = undefined;
try std.testing.expectError(
dotenv.Error.InvalidKey,
dotenv.parse(source, &entries, &scratch, .{ .diagnostics = &diagnostic }),
);
// The offset points into the original bytes, and the line and column
// count them.
try std.testing.expectEqual('.', source[diagnostic.offset]);
try std.testing.expectEqual(@as(u32, 3), diagnostic.line);
try std.testing.expectEqual(@as(u32, 8), diagnostic.column);
// `lineText` returns the offending line for a message or a log line.
try std.testing.expectEqualStrings("invalid key", diagnostic.message());
const line = dotenv.lineText(source, diagnostic.line);
try std.testing.expectEqualStrings("TIMEOUT.SECONDS=30", line);
}JSON with comments
JSONC is JSON with // and /* */ comments and a trailing comma before } or ]. jsonc does not parse JSON. It blanks the comments and the trailing commas in a copy of the source, then gives the copy to std.json. Every JSON rule and every JSON error stays with std.json.
The copy has the same length as the source. Every byte keeps its offset, so a std.json diagnostic names the same line and column in the original file.
Read a config file
jsonc.parseFromSlice scrubs the source and parses the copy. It returns a value that owns the parsed data and the scrubbed bytes. Call deinit when the value is no longer needed.
const std = @import("std");
const jsonc = @import("stdx").jsonc;
const Config = struct {
name: []const u8,
port: u16,
tags: []const []const u8,
};
// A config file is written by a person, so comments and a trailing comma
// are allowed. std.json still enforces every other rule.
test "read a config file with comments" {
const source =
\\// Name shown in logs.
\\{
\\ "name": "gateway", // the service name
\\ "port": 8080,
\\ /* An empty list is valid. */
\\ "tags": ["edge", "internal",],
\\}
;
var config = try jsonc.parseFromSlice(Config, std.testing.allocator, source, .{}, .{});
defer config.deinit();
try std.testing.expectEqualStrings("gateway", config.value.name);
try std.testing.expectEqual(@as(u16, 8080), config.value.port);
try std.testing.expectEqual(@as(usize, 2), config.value.tags.len);
try std.testing.expectEqualStrings("internal", config.value.tags[1]);
}
Both extensions are on by default. Set comments or trailing_commas to false in Options to reject that extension. With both false, the scrub still blanks a UTF-8 BOM and changes nothing else.
Keep byte offsets
jsonc.scrub returns an owned copy of the source. jsonc.scrubInPlace does the same work in a buffer that the caller owns, so a file read into mutable memory needs no second allocation.
A std.json position is available only through std.json.Diagnostics. Build a std.json.Scanner over the scrub output and call enableDiagnostics. Parse with std.json.parseFromTokenSource. The reported line, column, and byte offset refer to the original source.
const std = @import("std");
const jsonc = @import("stdx").jsonc;
// The scrub never moves a byte, so a std.json diagnostic names the same
// line and column in the file that a person wrote.
test "an error points at the source position" {
const source =
\\{
\\ // The comma after the next value is missing.
\\ "a": 1 /* the comment
\\ spans two lines */
\\ "b": 2
\\}
;
var buffer: [source.len]u8 = undefined;
@memcpy(buffer[0..], source);
try jsonc.scrubInPlace(&buffer, .{});
var diagnostics: std.json.Diagnostics = .{};
var scanner = std.json.Scanner.initCompleteInput(std.testing.allocator, &buffer);
defer scanner.deinit();
scanner.enableDiagnostics(&diagnostics);
const Config = struct { a: u8, b: u8 };
const result = std.json.parseFromTokenSource(Config, std.testing.allocator, &scanner, .{});
try std.testing.expectError(error.SyntaxError, result);
try std.testing.expectEqual(@as(u64, 5), diagnostics.getLine());
try std.testing.expectEqual(@as(u64, 5), diagnostics.getColumn());
}
error.UnterminatedBlockComment is the only syntax failure that the scrubber reports. Pass a jsonc.Diagnostics to scrubWithDiagnostics or scrubInPlaceWithDiagnostics to get the position of the opening /*.
Know the limits
The scrub handles comments, trailing commas, and a UTF-8 BOM at offset 0. Every other byte reaches std.json unchanged.
JSON5 features need a real parser and stay out: single quotes, unquoted keys, hexadecimal numbers, NaN, Infinity, and a leading or trailing decimal point. A document with one of them returns an error from std.json.
String dispatch
enums.Open turns a list of byte strings into a non-exhaustive enum. Switch on the tags, and put the miss in else:
const std = @import("std");
const enums = @import("stdx").enums;
const PoolMode = enum { transaction, session, statement, unknown };
// Open: a non-exhaustive enum. The miss is the unnamed value, so the
// switch needs an `else` arm.
const OpenModes = enums.Open(.{ "transaction", "session", "statement" });
// Closed: an exhaustive enum. The last argument names the miss tag, so the
// switch must cover every tag.
const ClosedModes = enums.Closed(.{ "transaction", "session", "statement" }, "other");
test "open: else is the miss" {
const mode: PoolMode = switch (OpenModes.match("session")) {
.transaction => .transaction,
.session => .session,
.statement => .statement,
else => .unknown,
};
try std.testing.expectEqual(PoolMode.session, mode);
try std.testing.expectEqual(OpenModes.miss, OpenModes.match("sessions"));
try std.testing.expect(OpenModes.has("statement"));
}
test "closed: every tag has an arm" {
const mode: PoolMode = switch (ClosedModes.match("statements")) {
.transaction => .transaction,
.session => .session,
.statement => .statement,
.other => .unknown,
};
try std.testing.expectEqual(PoolMode.unknown, mode);
}
const Headers = enums.Open(.{ "content-type", "content-length" });
test "a tag can be any byte string" {
const hit = switch (Headers.match("content-type")) {
.@"content-type" => true,
.@"content-length" => false,
else => false,
};
try std.testing.expect(hit);
}
test "an existing enum" {
try std.testing.expectEqual(
PoolMode.statement,
enums.stringToEnum(PoolMode, "statement").?,
);
try std.testing.expectEqual(
@as(?PoolMode, null),
enums.stringToEnum(PoolMode, "statementz"),
);
}
enums.Closed takes the name of a fallback tag and generates an exhaustive enum. The compiler then checks that every tag has an arm. Use Open when else is the simplest way to handle the miss, and Closed when the fallback deserves a name in the switch.
The compiler switches on the byte length first. A value whose length no tag has costs one test. Each arm compares only the tags of that length, with a fixed-length compare at compile time. The compare is byte-exact. The input does not have to be text.
A tag is any non-empty byte string without a null byte. Write a tag that is not an identifier as .@"content-type". For keys that cannot be tag names, use static_map.String or std.StaticStringMap.
enums.stringToEnum(E, value) matches the field names of an existing enum, like std.meta.stringToEnum. It compares each candidate with fixed-length loads.
Match a prefix
prefix_map.Map(V) is a compressed radix tree over byte strings. get is an exact lookup. getLongestPrefix returns the value of the longest stored key that is a prefix of the input.
const std = @import("std");
const prefix_map = @import("stdx").prefix_map;
// The tree is a constant. Shared prefixes are stored once.
const routes: prefix_map.Map(u8) = .initComptime(.{
.{ "api/", 1 },
.{ "api/v1/", 2 },
.{ "static/", 3 },
});
test "exact and longest-prefix lookups" {
try std.testing.expectEqual(@as(?u8, 2), routes.get("api/v1/"));
try std.testing.expectEqual(@as(?u8, null), routes.get("api/v1/users/42"));
try std.testing.expectEqual(@as(?u8, 2), routes.getLongestPrefix("api/v1/users/42"));
try std.testing.expectEqual(@as(?u8, 1), routes.getLongestPrefix("api/v2/"));
try std.testing.expectEqual(@as(?u8, 3), routes.getLongestPrefix("static/app.js"));
try std.testing.expectEqual(@as(usize, 3), routes.count());
}
test "build at runtime" {
const runtime: prefix_map.Map(u8) = try .init(.{
.{ "api/", 1 },
.{ "api/v1/", 2 },
.{ "static/", 3 },
}, std.testing.allocator);
defer runtime.deinit(std.testing.allocator);
try std.testing.expectEqual(@as(?u8, 2), runtime.getLongestPrefix("api/v1/users/42"));
}
The keys are copied into the tree, so the input slices do not need to outlive init. initComptime puts the tree in the binary. init builds the same four slices with an allocator, and deinit releases them. A duplicate key is a compile error at comptime and error.DuplicateKey at runtime.
The tree stores each shared prefix once and branches on the next byte, so a lookup walks one node per branch, not one node per byte. Children sit in a sorted range. A node with more than eight children uses a binary search.
Use it for route tables, layered configuration, or a set of byte prefixes. For exact keys at scale, use static_map.String. A hash is faster when you do not need prefix semantics. std.StaticStringMap.getLongestPrefix probes the map once per prefix length. This tree walks one node per branch, so the gap grows with the key count.
Initialize once
once.Cell(T) holds a value that is set at most once. get returns null until the value exists. getOrInit initializes it on the first call. once.Lazy(T, init) fixes the initializer at compile time, so get is the cell call.
const std = @import("std");
const once = @import("stdx").once;
var calls: u32 = 0;
fn load() u32 {
calls += 1;
return 42;
}
test "lazy" {
var lazy: once.Lazy(u32, load) = .empty;
try std.testing.expectEqual(@as(u32, 42), lazy.get().*);
try std.testing.expectEqual(@as(u32, 42), lazy.get().*);
try std.testing.expectEqual(@as(u32, 1), calls);
try std.testing.expect(lazy.isInitialized());
}
fn initWith(ctx: *u32) u32 {
ctx.* += 1;
return 7;
}
test "sync cell" {
var cell: once.SyncCell(u32) = .empty;
try std.testing.expectEqual(@as(?*u32, null), cell.get());
var init_calls: u32 = 0;
const value = try cell.getOrInit(std.testing.io, &init_calls, initWith);
try std.testing.expectEqual(@as(u32, 7), value.*);
try std.testing.expectEqual(@as(u32, 1), init_calls);
try std.testing.expectError(error.AlreadySet, cell.set(std.testing.io, 9));
}
Cell and Lazy are single-threaded. SyncCell and SyncLazy share the value across threads. The fast path is one acquire load. The first initialization takes an Io.Mutex, and threads that arrive together wait for the winner. SyncCell.get never blocks. getOrInit does.
set returns error.AlreadySet when a value exists. take moves the value out of an unsync cell. A failed getOrTryInit leaves the cell empty, so a later call can try again. Do not copy a cell after use.
Sort
std.mem.sort is the stable WikiSort/block sort, and std.mem.sortUnstable is pdqsort. sort adds the cases those do not cover.
sort.radix is a stable LSD radix sort for signed and unsigned integers. It makes one pass per digit, so its cost does not depend on comparisons. The caller supplies a scratch slice at least as long as the items, and it must not overlap them. Use it for large, unordered integer arrays. std.mem.sortUnstable wins on sorted or nearly sorted input; at small sizes the fixed passes do not pay off.
const std = @import("std");
const sort = @import("stdx").sort;
test "radix" {
var items = [_]u32{ 5, 1, 4, 2, 3 };
var scratch: [items.len]u32 = undefined;
try sort.radix(u32, &items, &scratch);
try std.testing.expectEqualSlices(u32, &.{ 1, 2, 3, 4, 5 }, &items);
}
test "select the middle" {
var items = [_]u32{ 5, 1, 4, 2, 3 };
try std.testing.expectEqual(
@as(u32, 3),
sort.select(u32, &items, 2, {}, std.sort.asc(u32)),
);
}
sort.nth partitions a slice so the value at n is the n-th smallest, in expected O(n). sort.select returns that value. Both take a comparison context, like std.mem.sort, and a depth limit falls back to std.mem.sortUnstable on the active range.
radix is ascending only. For a descending integer order, sort ascending and reverse, or use a comparison sort. radix is stable; nth and select are not.
Cache the recent
lru.String(V, capacity) and lru.Auto(K, V, capacity) keep up to capacity entries. A new key at capacity evicts the least-recently-used entry.
const std = @import("std");
const lru = @import("stdx").lru;
const Cache = lru.String(u32, 2);
test "keep the two most recent" {
var cache: Cache = .empty;
_ = cache.put("a", 1);
_ = cache.put("b", 2);
try std.testing.expectEqual(@as(u32, 1), cache.get("a").?.*);
const result = cache.put("c", 3);
try std.testing.expectEqualStrings("b", result.evicted.?.key);
try std.testing.expectEqual(@as(u32, 2), result.evicted.?.value);
try std.testing.expect(!cache.contains("b"));
var it = cache.iterator();
try std.testing.expectEqualStrings("c", it.next().?.key);
try std.testing.expectEqualStrings("a", it.next().?.key);
try std.testing.expect(it.next() == null);
}
The index is a bounded_array_hash_map from key to a node slot. The nodes form a doubly linked list with integer links, so a hit relinks and no entry data moves. get moves a hit to the front. peek leaves the order alone. put returns the displaced entry: the old value for an existing key, or the evicted entry for a new one. popLru and popMru return whole entries.
The value pointers from get and peek keep their address for the cache's lifetime. After an entry is removed, a later put can reuse its node, so an old pointer then refers to the new value.
There is no eviction callback. The caller cleans up a value that owns resources. clear drops the values. Drain with the iterator first when they need cleanup. Keys are borrowed, and the cache stores the key handle twice, once in the index and once in the node. Capacity is fixed at comptime and must be at least one.
Binary encoding
A binary format fixes the width and byte order of each field. wire.Writer writes both into storage that the caller owns. The writer moves forward only, and it never allocates.
Write a message
wire.Writer(.big) writes big-endian integers, enums, and byte slices. It writes integers of any byte width, including u24, u48, and u128. Signed values are two's complement, and an enum is written as its backing integer. buffered returns the bytes written so far. To write a range out of band, take unusedCapacitySlice, write into it, and call advance with the count.
reserve returns a slot that the caller fills later. Use it for a length or checksum that is not known until the body is written. The example reserves a 24-bit body length, writes the body, and fills the slot with std.mem.writeInt.
const std = @import("std");
const wire = @import("stdx").wire;
// A message with a 24-bit body length: reserve the slot, write the body,
// then fill the slot.
test "write a length-prefixed message" {
var storage: [32]u8 = undefined;
var writer: wire.Writer(.big) = .init(&storage);
const body_len_slot = try writer.reserve(3);
try writer.append(u8, 0x01);
try writer.append(u16, 0x0203);
try writer.appendSlice("payload");
std.mem.writeInt(u24, body_len_slot, @intCast(writer.buffered().len - 3), .big);
try std.testing.expectEqualSlices(
u8,
"\x00\x00\x0a\x01\x02\x03payload",
writer.buffered(),
);
}
// The byte order is a comptime parameter, so the other order is its own
// type with its own stores.
test "write in little-endian" {
var storage: [4]u8 = undefined;
var writer: wire.Writer(.little) = .init(&storage);
try writer.append(u16, 0x0102);
try std.testing.expectEqualSlices(u8, &.{ 0x02, 0x01 }, writer.buffered());
}Choose the byte order
The byte order is a comptime parameter, so wire.Writer(.big) and wire.Writer(.little) are different types. Each fixed-width store compiles to its own order, and the choice costs nothing at runtime. The example's second test writes a little-endian field.
Byte slices and reserved slots are order-agnostic. A protocol with a mixed byte order writes the exceptional field with std.mem.writeInt directly.
Handle a full buffer
Every fallible method has two forms. The checked form returns error.NoSpaceLeft. The AssumeCapacity form asserts the bound: it panics in Debug and ReleaseSafe, and ReleaseFast removes the check. Use the checked form when the size depends on input. Use the unchecked form when a prior check or a fixed maximum proves the fit.
A field the caller decides against comes back off the output with undo. The bytes stay in the backing, so the next write overwrites them.
Write a run of values
appendSlice copies bytes verbatim, which is wrong for an array of values wider than a byte on a host whose order differs. appendSliceEndian writes one element at a time through append, so the run has the same bytes as a loop. readSliceEndian is the inverse, and it fills a buffer the caller owns because the values only exist once the order is applied.
A packed struct writes as its backing integer in one store, since it has a defined bit layout and no padding. The fields fill that integer from its low bit, so on a big-endian writer the first declared field lands in the last byte. That is the backing integer's order, not a protocol bit order.
Write a varint
A field whose width is part of the value is a LEB128 varint. appendLeb128 takes the sign from the type, so an unsigned type writes ULEB128 and a signed type writes SLEB128. The length follows from the value, so there is no width argument and no slot.
readLeb128 is the inverse. An encoding that does not fit the type is error.Overflow, and bytes that end before the terminator are error.UnexpectedEof. A failed read leaves the cursor where it was.
Look before you read
peek, peekSlice, and peekUntil return what read, readSlice, and readUntil would return, and leave the cursor alone. A decoder uses them to route on a tag, or to check a delimiter before it commits to the field.
const std = @import("std");
const wire = @import("stdx").wire;
// A varint carries its own length, so neither call needs a width and neither
// write needs a slot. An unsigned type writes ULEB128 and a signed type writes
// SLEB128.
test "write and read a varint" {
var storage: [16]u8 = undefined;
var writer: wire.Writer(.big) = .init(&storage);
try writer.appendLeb128(u32, 624485);
try writer.appendLeb128(i32, -123456);
try std.testing.expectEqualSlices(
u8,
&.{ 0xe5, 0x8e, 0x26, 0xc0, 0xbb, 0x78 },
writer.buffered(),
);
var reader: wire.Reader(.big) = .init(writer.constBuffered());
try std.testing.expectEqual(@as(u32, 624485), try reader.readLeb128(u32));
try std.testing.expectEqual(@as(i32, -123456), try reader.readLeb128(i32));
try std.testing.expectEqual(@as(usize, 0), reader.remaining().len);
}
// A peek returns what the read would, and the read still gets it.
test "peek at a field before reading it" {
var reader: wire.Reader(.big) = .init("key=value");
// The delimiter is not consumed, so the key stays available.
try std.testing.expectEqualStrings("key", try reader.peekUntil('='));
try std.testing.expectEqual(@as(usize, 0), reader.end);
try std.testing.expectEqualStrings("key", try reader.readUntil('='));
try std.testing.expectEqualStrings("value", try reader.readSlice(5));
// A peek on a short buffer is an error, not a partial value.
try std.testing.expectError(error.UnexpectedEof, reader.peek(u32));
try std.testing.expectEqual(@as(usize, 0), reader.remaining().len);
}Know the limits
The writer writes fixed-width integers, enums, packed structs, byte slices, slots, and LEB128 varints. It does not write bits outside a packed struct, and it does not take a different byte order per field. A protocol that needs those writes the field with std.mem or its own codec.
Base64
base64 encodes and decodes RFC 4648. std has a codec for the same format. This one keeps the same four alphabets and moves a vector per instruction where std moves a byte: on aarch64 the 3-in/4-out byte interleave is an addressing mode, and the alphabet is one table permute per 16 characters.
The kernel follows the build target. A build for aarch64 uses NEON. A build for x86-64 uses AVX2 when the target CPU has it, and AVX-512 VBMI when the target has that, which means -Dcpu=x86_64_v3 or newer, or a native build. A build for the x86-64 baseline falls back to std.base64. There is no CPUID probe and no indirect call, so the binary carries one kernel and the target decides which.
The codec is a comptime value: standard, standard_no_pad, url_safe, and url_safe_no_pad. Each one carries its alphabet and its pad character into the type, so a lookup table the kernel indexes is a constant in the binary. Pass it as the first argument, or call it through the constant.
Both directions write into storage the caller owns and return the slice they wrote. encode needs encodedLen(n) bytes. decode needs decodedLen(source) bytes and writes its own length back, because padding changes it.
A decode that returns bytes has validated them. A byte outside the alphabet is error.InvalidCharacter. A length that cannot be base64, a pad character in the wrong place, and a nonzero unused low bit in a partial group are all error.InvalidPadding. A destination that is too small is error.NoSpaceLeft.
The codec does not skip whitespace or decode a stream. A format that wraps its base64 across lines unwraps it first.
const std = @import("std");
const base64 = @import("stdx").base64;
// Encode takes the codec as a comptime value, so the alphabet lookup the
// kernel indexes is a constant in the binary. `standard` is the padded
// alphabet from RFC 4648 section 4.
test "encode and decode round-trip" {
const payload = "the quick brown fox jumps over the lazy dog";
var encoded: [base64.standard.encodedLen(payload.len)]u8 = undefined;
var decoded: [payload.len]u8 = undefined;
const chars = base64.standard.encode(&encoded, payload);
try std.testing.expectEqualStrings(
"dGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZw==",
chars,
);
const bytes = try base64.standard.decode(&decoded, chars);
try std.testing.expectEqualStrings(payload, bytes);
}
// The decode is the validation. A byte outside the alphabet and a bad
// trailing group are both errors, so a decoded slice is always canonical.
test "decode rejects what is not base64" {
var decoded: [16]u8 = undefined;
// `!` is not in the alphabet.
try std.testing.expectError(
error.InvalidCharacter,
base64.standard.decode(&decoded, "dGhlIQ!!"),
);
// The unused low bits of a partial group must be zero, and the pad count
// must match: one byte takes two pads, not three.
try std.testing.expectError(
error.InvalidPadding,
base64.standard.decode(&decoded, "dGhlA==="),
);
}
// URL-safe base64 trades two alphabet characters and is unpadded when the
// format says so. Both are the same codec at a different comptime value.
test "url-safe and unpadded are the same codec" {
const payload = [_]u8{ 0xFB, 0xFF, 0xBF };
var encoded: [8]u8 = undefined;
try std.testing.expectEqualStrings("+/+/", base64.standard.encode(&encoded, &payload));
try std.testing.expectEqualStrings("-_-_", base64.url_safe.encode(&encoded, &payload));
try std.testing.expectEqualStrings("-_-_", base64.url_safe_no_pad.encode(&encoded, &payload));
}
// Sizing a destination: `encodedLen` is exact, `decodedUpperBound` fits any
// input, and `decodedLen` is exact for one already in hand.
test "the lengths are computable before the call" {
try std.testing.expectEqual(@as(usize, 4), base64.standard.encodedLen(1));
try std.testing.expectEqual(@as(usize, 2), base64.standard_no_pad.encodedLen(1));
try std.testing.expectEqual(@as(usize, 1), try base64.standard.decodedLen("Zg=="));
try std.testing.expectEqual(@as(usize, 1), try base64.standard_no_pad.decodedLen("Zg"));
try std.testing.expectEqual(@as(usize, 3), base64.standard.decodedUpperBound(4));
}Base32
base32 is a Crockford base32 codec for fixed-shape machine tokens. std has base64 and no base32. A token carries a binary key whose length is a positive multiple of 5 bytes. The token is exactly 8 * N / 5 lowercase symbols for N bytes, so it has no padding and a fixed length.
Both directions take the byte count as a comptime parameter. base32.encode(10, &key) returns a [16]u8, and base32.decode(10, &token) returns a [10]u8. base32.SymbolCount(N) names the token type for a field declaration. It rejects a count that is not a positive multiple of 5 at compile time.
The wire form is lowercase only. encode emits the lowercase Crockford alphabet, which excludes i, l, o, and u. decode rejects every byte outside that alphabet: uppercase letters fail, and the excluded letters fail in lowercase too. There is no case folding and no O/I/L alias table, so two spellings never decode to one key.
decode returns error.InvalidSymbol on the first bad byte. A token that decodes is valid by construction, so the decode itself is the validation. The caller runs no separate symbol check, and the fixed shape means the decode needs no length check either.
const std = @import("std");
const base32 = @import("stdx").base32;
// A token carries a binary key of a fixed shape. Sixteen lowercase
// Crockford symbols hold the ten bytes, with no padding.
test "a key round-trips through its token" {
const key = [_]u8{ 0xDE, 0xAD, 0xBE, 0xEF, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55 };
const token = base32.encode(10, &key);
try std.testing.expectEqual(@as(usize, 16), token.len);
try std.testing.expectEqual(key, try base32.decode(10, &token));
}
// Decode is the validation: a symbol outside the lowercase alphabet is
// the only failure, and no separate check runs before it.
test "every other spelling is rejected" {
// Uppercase is not a second spelling: no case folding, no aliases.
try std.testing.expectError(error.InvalidSymbol, base32.decode(10, &"ABCDEFGHJKMNPQRS".*));
// The excluded letters i, l, o, u are invalid in lowercase too.
try std.testing.expectError(error.InvalidSymbol, base32.decode(10, &"uuuuuuuuuuuuuuuu".*));
}IP addresses
net.Ip4 and net.Prefix4 follow Go's net/netip, with Zig names. They have the same semantics for classification, ordering, and prefix masking. They are plain values with no allocation.
Ip4 is four bytes with no port. std's Ip4Address carries a port, which a configuration field or an allow list does not need. Ip4 converts to and from the std types.
Parse an address
Ip4.parse accepts dotted-quad text and nothing else. Each error names the problem.
For a literal in code, use Ip4.parseComptime. It parses at compile time, and a typo is a compile error that quotes the string. Prefix4 has the same function. Ip4.init takes the four bytes directly, and Prefix4.init takes an address and a length.
const std = @import("std");
const Ip4 = @import("stdx").net.Ip4;
// An address has one canonical text form. Every other input is an error
// that names the problem.
test "parse accepts the canonical form" {
const ip: Ip4 = try .parse("10.1.2.3");
try std.testing.expectEqual(Ip4.init(.{ 10, 1, 2, 3 }), ip);
}
test "parse names what went wrong" {
try std.testing.expectError(error.InvalidCharacter, Ip4.parse("example.com"));
try std.testing.expectError(error.InvalidCharacter, Ip4.parse("::1"));
try std.testing.expectError(error.Incomplete, Ip4.parse(""));
try std.testing.expectError(error.NonCanonical, Ip4.parse("10.01.2.3"));
}
// A literal in code is parsed at compile time. A typo is a compile error
// that quotes the string, not a runtime failure.
test "parseComptime for literals" {
const ip: Ip4 = .parseComptime("10.1.2.3");
try std.testing.expectEqual(Ip4.init(.{ 10, 1, 2, 3 }), ip);
}
test "the well-known addresses are constants" {
try std.testing.expectEqual(Ip4.parseComptime("127.0.0.1"), Ip4.loopback);
try std.testing.expectEqual(Ip4.parseComptime("0.0.0.0"), Ip4.unspecified);
try std.testing.expectEqual(Ip4.parseComptime("255.255.255.255"), Ip4.broadcast);
}Classify an address
Ip4 has the netip predicates: isLoopback, isPrivate, isMulticast, isLinkLocalUnicast, isLinkLocalMulticast, isBroadcast, isUnspecified, and isGlobalUnicast.
isGlobalUnicast follows Go. A private or link-local address is global unicast, because it is routable. If the code means "public", it must exclude those classes.
const std = @import("std");
const Ip4 = @import("stdx").net.Ip4;
// Following Go's net/netip, a private or link-local address counts as
// global unicast: it is routable, just not on the public internet. Code
// that means "public" must say so.
fn isPublic(addr: Ip4) bool {
return addr.isGlobalUnicast() and !addr.isPrivate() and !addr.isLinkLocalUnicast();
}
test "public means more than global unicast" {
try std.testing.expect(isPublic(.parseComptime("8.8.8.8")));
const private: Ip4 = .parseComptime("10.1.2.3");
try std.testing.expect(private.isGlobalUnicast());
try std.testing.expect(!isPublic(private));
try std.testing.expect(!isPublic(.parseComptime("169.254.1.1")));
}
test "the other classes" {
try std.testing.expect(Ip4.parseComptime("127.0.0.1").isLoopback());
try std.testing.expect(Ip4.parseComptime("172.16.0.1").isPrivate());
try std.testing.expect(!Ip4.parseComptime("172.32.0.1").isPrivate());
try std.testing.expect(Ip4.broadcast.isBroadcast());
try std.testing.expect(Ip4.unspecified.isUnspecified());
}
test "multicast and its link-local block" {
const all_hosts: Ip4 = .parseComptime("224.0.0.1");
try std.testing.expect(all_hosts.isMulticast());
try std.testing.expect(all_hosts.isLinkLocalMulticast());
try std.testing.expect(!all_hosts.isGlobalUnicast());
// Multicast outside 224.0.0.0/24 is not link-local.
const other: Ip4 = .parseComptime("239.1.2.3");
try std.testing.expect(other.isMulticast());
try std.testing.expect(!other.isLinkLocalMulticast());
}Compare and step
order compares two addresses in numeric order. next and prev step by one address and return null at the ends of the space, so a loop cannot wrap.
const std = @import("std");
const Ip4 = @import("stdx").net.Ip4;
// Count the addresses from `first` to `last`, inclusive. `next` carries
// across octets and returns null past the last address, so the loop ends
// at 255.255.255.255 instead of wrapping.
fn countRange(first: Ip4, last: Ip4) u32 {
var count: u32 = 0;
var current = first;
while (current.order(last) != .gt) {
count += 1;
current = current.next() orelse break;
}
return count;
}
test "a range that crosses an octet" {
const first: Ip4 = .parseComptime("10.0.0.250");
try std.testing.expectEqual(12, countRange(first, .parseComptime("10.0.1.5")));
}
test "a range that ends at the top of the space" {
try std.testing.expectEqual(2, countRange(.parseComptime("255.255.255.254"), .broadcast));
}
test "order compares numerically" {
const two: Ip4 = .parseComptime("2.0.0.0");
try std.testing.expectEqual(.lt, two.order(.parseComptime("10.0.0.0")));
const ten: Ip4 = .parseComptime("10.0.0.2");
try std.testing.expectEqual(Ip4.parseComptime("10.0.0.1"), ten.prev());
}Work with prefixes
Prefix4 is a network address and a length in bits. parse is strict. It rejects a missing slash, a length above 32, and a length with leading zeros.
containstests an address against the prefix.maskedzeroes the host bits and returns the canonical form.overlapstests whether two prefixes cover a common address.isSingleIptests for a/32, a prefix of exactly one address.Ip4.prefixbuilds the prefix of a given length around an address.- A prefix formats with
{f}, like an address.
const std = @import("std");
const net = @import("stdx").net;
const Ip4 = net.Ip4;
const Prefix4 = net.Prefix4;
// A prefix from config text can carry host bits. `masked` returns the
// canonical form, so two spellings of one network compare equal.
test "canonical form" {
const written: Prefix4 = .parseComptime("10.1.2.3/20");
try std.testing.expectEqual(Prefix4.parseComptime("10.1.0.0/20"), written.masked());
}
test "containment works on any prefix length" {
const subnet: Prefix4 = .parseComptime("10.1.16.0/20");
try std.testing.expect(subnet.contains(.parseComptime("10.1.31.255")));
try std.testing.expect(!subnet.contains(.parseComptime("10.1.32.0")));
}
// Two rules that cover a common address are usually a config mistake.
test "overlap detection" {
const a: Prefix4 = .parseComptime("10.0.0.0/8");
const b: Prefix4 = .parseComptime("10.1.0.0/16");
const c: Prefix4 = .parseComptime("11.0.0.0/8");
try std.testing.expect(a.overlaps(b));
try std.testing.expect(b.overlaps(a));
try std.testing.expect(!a.overlaps(c));
}
test "built from parts" {
const subnet: Prefix4 = .init(.init(.{ 10, 1, 0, 0 }), 20);
try std.testing.expectEqual(Prefix4.parseComptime("10.1.0.0/20"), subnet);
}
// A /32 is one host. Config that accepts either spelling can tell them
// apart without comparing bits.
test "a single host" {
try std.testing.expect(Prefix4.parseComptime("10.1.2.3/32").isSingleIp());
try std.testing.expect(!Prefix4.parseComptime("10.1.2.0/24").isSingleIp());
}
test "an address names its own prefix" {
const addr: Ip4 = .parseComptime("10.1.2.3");
try std.testing.expectEqual(Prefix4.parseComptime("10.1.2.0/24"), try addr.prefix(24));
try std.testing.expectError(error.BitsOutOfRange, addr.prefix(33));
}
test "a prefix is parsed as strictly as an address" {
try std.testing.expectError(error.NoSlash, Prefix4.parse("10.0.0.0"));
try std.testing.expectError(error.BitsOutOfRange, Prefix4.parse("10.0.0.0/33"));
try std.testing.expectError(error.InvalidBits, Prefix4.parse("10.0.0.0/08"));
try std.testing.expectError(error.InvalidBits, Prefix4.parse("10.0.0.0/"));
}
test "a prefix formats with {f}" {
const subnet: Prefix4 = .parseComptime("10.1.0.0/20");
var text: [18]u8 = undefined;
const formatted = try std.mem.print(&text, "{f}", .{subnet});
try std.testing.expectEqualStrings("10.1.0.0/20", formatted);
}Convert from std types
Ip4.fromAny takes a std IpAddress and returns an Ip4, or null for a real IPv6 address. It also unwraps an IPv4-mapped IPv6 address. A dual-stack listener reports an IPv4 peer in that form, so fromAny gives one answer for both.
withPort makes an Ip4Address. fromIp4 drops the port. fromSlice builds an address from exactly four bytes. Ip4 formats with {f}.
const std = @import("std");
const net = @import("stdx").net;
const Ip4 = net.Ip4;
// A dual-stack listener reports an IPv4 peer as an IPv4-mapped IPv6
// address. `fromAny` gives the same `Ip4` for both spellings.
test "fromAny sees through an IPv4-mapped address" {
const ip: Ip4 = .parseComptime("10.1.2.3");
const native: net.IpAddress = .{ .ip4 = ip.withPort(5432) };
const mapped: net.IpAddress = .{ .ip6 = .fromIp4(ip.withPort(5432)) };
try std.testing.expectEqual(ip, Ip4.fromAny(native).?);
try std.testing.expectEqual(ip, Ip4.fromAny(mapped).?);
// A real IPv6 address has no IPv4 form.
try std.testing.expectEqual(null, Ip4.fromAny(.{ .ip6 = .loopback(0) }));
}
test "an address and a port make a socket address" {
const ip: Ip4 = .parseComptime("10.1.2.3");
const socket_addr = ip.withPort(8080);
try std.testing.expectEqual(8080, socket_addr.port);
try std.testing.expectEqual(ip, Ip4.fromIp4(socket_addr));
}
test "fromSlice needs exactly four bytes" {
try std.testing.expectEqual(Ip4.parseComptime("10.1.2.3"), Ip4.fromSlice(&.{ 10, 1, 2, 3 }));
try std.testing.expectEqual(null, Ip4.fromSlice(&.{ 10, 1, 2 }));
}
test "an address formats with {f}" {
const ip: Ip4 = .parseComptime("10.1.2.3");
var text: [15]u8 = undefined;
try std.testing.expectEqualStrings("10.1.2.3", try std.mem.print(&text, "{f}", .{ip}));
}Use an address as a key
An Ip4 is four bytes with no padding. It works as a key in the hash containers without a custom context.
const std = @import("std");
const stdx = @import("stdx");
const bounded_array_hash_map = stdx.bounded_array_hash_map;
const Ip4 = stdx.net.Ip4;
// An `Ip4` is four bytes with no padding, so it works as a key as it is.
const Hits = bounded_array_hash_map.Auto(Ip4, u32, 16);
fn record(hits: *Hits, client: Ip4) !u32 {
const entry = try hits.getOrPut(client);
if (!entry.found_existing) entry.value_ptr.* = 0;
entry.value_ptr.* += 1;
return entry.value_ptr.*;
}
test "count requests per client" {
var hits: Hits = .init;
const a: Ip4 = .parseComptime("10.0.0.1");
const b: Ip4 = .parseComptime("10.0.0.2");
try std.testing.expectEqual(1, try record(&hits, a));
try std.testing.expectEqual(2, try record(&hits, a));
try std.testing.expectEqual(1, try record(&hits, b));
}Carry an address and a port
net.Ip4Endpoint is four octets and a port, the same layout as std.Io.net.Ip4Address. Use it in per-connection records and in code that owns a raw fd and calls bind(2) or connect(2) directly: toSockaddrIn returns the kernel struct with the port in network order. parse takes the address text and the port separately. HostPort.parse handles config text that carries both. toStd and fromStd convert to and from Ip4Address.
Parse a host and port
net.HostPort.parse splits endpoint text such as example.com, 10.0.0.1:853, or [2001:db8::1]:853, with a caller-supplied default port. It removes the brackets from an IPv6 host. It rejects an empty host, an empty port, port 0, a port above 65535, and an unbracketed IPv6 address. The host is not validated as a name or an address; that stays caller policy.
const std = @import("std");
const net = @import("stdx").net;
// Config text carries the port when it has one and relies on the service
// default when it does not.
test "split a config endpoint" {
const cases = [_]struct { text: []const u8, host: []const u8, port: u16 }{
.{ .text = "example.com", .host = "example.com", .port = 53 },
.{ .text = "10.0.0.1:853", .host = "10.0.0.1", .port = 853 },
.{ .text = "[2001:db8::1]:853", .host = "2001:db8::1", .port = 853 },
};
for (cases) |case| {
const endpoint = try net.HostPort.parse(case.text, 53);
try std.testing.expectEqualStrings(case.host, endpoint.host);
try std.testing.expectEqual(case.port, endpoint.port);
}
// An IPv6 host without brackets is ambiguous.
try std.testing.expectError(error.UnbracketedIpv6, net.HostPort.parse("::1", 53));
}Work with a raw socket fd
posix.setsockopt and posix.getsockopt set and read a one-c_int socket option on a raw fd. Both decode errno to named errors. error.InvalidOptionValue is EINVAL. std's own posix.setsockopt maps EINVAL to unreachable, so a bad option value from configuration has no error path. The stdx wrapper returns error.InvalidOptionValue instead. posix.getsockname and posix.getpeername return the local and peer net.Ip4Address of a socket, with no caller-supplied sockaddr buffer.
Know the limits
These types are IPv4 only. Ip4.parse rejects IPv6 text, and Prefix4.parse rejects IPv6 prefixes. For dual-stack matching, keep a second set of rules for IPv6 and test both. Socket calls on raw file descriptors are in posix.
UUIDs
Uuid generates version 4 and version 7 values, formats them, and parses the canonical 36-byte text form. Version 7 values are ordered across milliseconds, but not inside one millisecond.
const std = @import("std");
const Io = std.Io;
const Uuid = @import("stdx").Uuid;
test "generate, format, parse" {
const id: Uuid = .v4();
try std.testing.expectEqual(.v4, id.version());
// The canonical form is 36 bytes.
var text: [36]u8 = undefined;
var writer: Io.Writer = .fixed(&text);
try id.format(&writer);
const parsed: Uuid = try .parse(&text);
try std.testing.expect(id.eql(parsed));
}
test "a wrong length is an error" {
try std.testing.expectError(error.InvalidLength, Uuid.parse("not-a-uuid"));
}Timekeeping
The time module reads clocks without an Io value. time.now returns std.Io.Timestamp values, so the std Duration conversions work on the result. It runs on Linux and macOS.
Choose a clock
time.now takes an Io.Clock. Two clocks cover most code.
| Clock | Use it for |
|---|---|
.awake | Elapsed time, deadlines, and timeouts. The value has meaning only inside the process. |
.real | Timestamps that people read, or that leave the process. |
Never send an .awake value to another process. It is a number with no meaning there.
Store a deadline
time.Duration and time.Timestamp store nonnegative nanoseconds in one 64-bit word. Use them when a full std timestamp wastes space in a connection record. Their range is nearly 585 years. Neither value supports a signed duration. Calling durationTo with an earlier timestamp returns error.OutOfRange.
OptionalDuration and OptionalTimestamp store an absent value in the highest u64 word. They are eight bytes each. Use .none to declare an absent value. Call get to obtain a standard optional. Constructing an occupied value with the reserved word returns error.OutOfRange.
Unit constructors distinguish nanoseconds, microseconds, milliseconds, and seconds. Arithmetic and conversion from std values reject values outside the supported range. Conversion to std values does not fail.
Use the from{unit}Comptime constructors for known values. They return plain values and report overflow at compile time. Optional forms reject the reserved sentinel then too. These constructors follow std names such as utf8EncodeComptime.
const std = @import("std");
const Io = std.Io;
const testing = std.testing;
const timex = @import("stdx").time;
const Request = struct {
deadline: timex.OptionalTimestamp,
};
test "a deadline fits in one word and expires by comparison" {
const start: timex.Timestamp = .fromMillisecondsComptime(84);
const duration: timex.Duration = .fromMillisecondsComptime(250);
const deadline = try start.add(duration);
const request: Request = .{ .deadline = try .init(deadline) };
try testing.expectEqual(@as(usize, 8), @sizeOf(Request));
try testing.expectEqual(deadline, request.deadline.get().?);
const now: Io.Timestamp = .fromNanoseconds(deadline.nanoseconds);
try testing.expect(deadline.compare(try .fromStd(now)) == .eq);
const no_deadline: timex.OptionalTimestamp = .none;
try testing.expectEqual(@as(?timex.Timestamp, null), no_deadline.get());
}
Use .awake for elapsed time and deadlines. The compact timestamp does not carry a clock identity. Do not mix values from two clocks.
Measure a deadline
A deadline must read the clock directly. A cached sample can lag by one tick, and a timeout must not fire late.
const std = @import("std");
const Io = std.Io;
const timex = @import("stdx").time;
// A deadline reads the clock directly. A cached sample can lag by
// one tick, and a timeout must not fire late.
fn expired(started: Io.Timestamp, timeout_ms: i64) bool {
const elapsed = started.durationTo(timex.now(.awake));
return elapsed.toMilliseconds() >= timeout_ms;
}
test "a zero timeout is already expired" {
try std.testing.expect(expired(timex.now(.awake), 0));
}
test "a long timeout is not" {
try std.testing.expect(!expired(timex.now(.awake), 60_000));
}Cache the clock in a loop
An event loop reads the time many times in each iteration. Each read is a system call. A CachedClock replaces all of them with one call at the top of the iteration.
const std = @import("std");
const timex = @import("stdx").time;
// One cache per thread. The thread that ticks it owns it.
threadlocal var clock: timex.CachedClock(.awake) = .init;
// The top of every loop iteration: one real clock read.
fn tick() void {
_ = clock.refresh();
}
// Everything else in the iteration reads the cache.
fn stamp() i96 {
return clock.now().nanoseconds;
}
test "every read inside a tick is the same sample" {
defer clock.clear();
tick();
try std.testing.expectEqual(stamp(), stamp());
}
Follow these rules:
- Give each thread its own cache. A
CachedClockis not thread-safe. - Call
refreshonce per iteration. Callnowfor every other read. - A cached value is never in the future. It lags true time by at most one iteration.
- A clock that was never refreshed reads the real clock directly.
Use the cache for log timestamps, metrics, and rate limits. Do not use it for deadlines.
Stamp log lines with wall time
A log line needs wall time, but the loop already holds an .awake sample. WallFromAwake converts the sample. It stores the offset between the two clocks, which the process computes once at startup.
const std = @import("std");
const Io = std.Io;
const timex = @import("stdx").time;
// The offset between the two clocks, computed once and shared.
var wall_from_awake: timex.WallFromAwake = .uninitialized;
threadlocal var clock: timex.CachedClock(.awake) = .init;
// Call once, before any thread starts.
pub fn init() void {
wall_from_awake = .compute();
}
// A log timestamp: the tick's sample, converted to wall time.
pub fn logTimestamp() Io.Timestamp {
return wall_from_awake.toWall(clock.now());
}
test "log timestamps are wall time and never go backwards" {
init();
defer clock.clear();
_ = clock.refresh();
const first = logTimestamp();
try std.testing.expect(first.toSeconds() > 1_577_836_800); // after 2020
_ = clock.refresh();
try std.testing.expect(logTimestamp().nanoseconds >= first.nanoseconds);
}
The converted time never goes backwards. A clock step from NTP cannot reorder log lines. The cost is that the converted time drifts from true wall time if the system clock steps after startup. For log lines, this is the right trade. Use .real when you need true wall time.
Write an RFC 3339 timestamp
time.writeRfc3339 writes an Io.Timestamp as UTC RFC 3339 text. The fractional width is a comptime parameter: .seconds, .milliseconds, .microseconds, or .nanoseconds. The value is truncated to that width, so the output has a fixed shape that sorts and parses without a variable fraction.
const std = @import("std");
const timex = @import("stdx").time;
// Logs want one fixed-width, sortable form. The precision is explicit.
test "format a log timestamp" {
var buffer: [32]u8 = undefined;
var writer: std.Io.Writer = .fixed(&buffer);
const timestamp = std.Io.Timestamp.fromNanoseconds(1_709_210_096_789_999_000);
try timex.writeRfc3339(&writer, timestamp, .milliseconds);
try std.testing.expectEqualStrings("2024-02-29T12:34:56.789Z", writer.buffered());
}
test "seconds only" {
var buffer: [32]u8 = undefined;
var writer: std.Io.Writer = .fixed(&buffer);
try timex.writeRfc3339(&writer, .fromNanoseconds(0), .seconds);
try std.testing.expectEqualStrings("1970-01-01T00:00:00Z", writer.buffered());
}
The full 0000-9999 year range is supported, including dates before 1970. A year outside the range returns error.TimestampOutOfRange.
Limit a repeated log line
A failure that repeats for each connection can write one line per event. RateLimit admits one line per interval. It returns the number of lines that it held back, so the one line can report them.
const std = @import("std");
const Io = std.Io;
const RateLimit = @import("stdx").time.RateLimit;
// A failure that repeats per connection logs once per interval. The
// line carries the number of failures it stands for.
fn logAcceptFailure(limit: *RateLimit, now: Io.Timestamp, out: *Io.Writer) !void {
const held_back = limit.admit(now) orelse return;
try out.print("accept failed, {d} more held back\n", .{held_back});
}
fn atMs(ms: i64) Io.Timestamp {
return .fromNanoseconds(@as(i96, ms) * std.time.ns_per_ms);
}
test "a storm logs once per interval" {
var limit: RateLimit = .default;
var buffer: [256]u8 = undefined;
var out: Io.Writer = .fixed(&buffer);
// The first failure goes out. Nine more inside the interval do not.
try logAcceptFailure(&limit, atMs(0), &out);
for (1..10) |i| try logAcceptFailure(&limit, atMs(@as(i64, @intCast(i)) * 100), &out);
try std.testing.expectEqualStrings("accept failed, 0 more held back\n", out.buffered());
// The next interval logs again and reports the nine.
try logAcceptFailure(&limit, atMs(1000), &out);
try std.testing.expectEqualStrings(
"accept failed, 0 more held back\naccept failed, 9 more held back\n",
out.buffered(),
);
}
// `default` is one second. `init` takes any `Io.Duration`.
test "a custom interval" {
var limit: RateLimit = .init(.fromMilliseconds(250));
try std.testing.expectEqual(0, limit.admit(atMs(0)));
try std.testing.expectEqual(null, limit.admit(atMs(100)));
try std.testing.expectEqual(1, limit.admit(atMs(250)));
}
admit returns null when the caller must hold the line back. Pass it a monotonic sample, such as clock.now() from a CachedClock(.awake).
RateLimit.default has a one-second interval. RateLimit.init takes any Io.Duration.
Timers
One operation does not need a set: every std wait already takes an Io.Timeout, and a .deadline in that value is the whole story. Use timers.Timers when one loop owns many deadlines. Each entry carries a calflback, removal is by handle, and a period repeats the fire.
The collection owns no clock and no wake machinery. The loop samples the clock with timex.now(.awake), calls expire(now) to fire everything due, and sleeps until next(). The entries are caller-owned: the caller constructs a Timer, standalone or embedded in a connection record, and arm links it. Nothing is allocated, and the node pointer is the handle. One loop owns the set: no method is thread-safe, and no atomics are involved.
Drive the loop
expire(now) fires every timer due at or before now, earliest first. The loop then sleeps toward next() with Io.Timeout{ .deadline = wake }. A null next() means nothing is armed, and the loop sleeps on its other events. A callback runs after the tree surgery on its own entry, so it can arm, reset, or stop any timer, including its own. After every callback, expire re-checks the minimum, so a past-due timer armed from inside a callback fires in the same drain.
stop and reset follow Go's Timer: each returns false for a timer that already fired or was stopped. Nothing is delivered outside expire, so there is no channel to drain and no stale delivery to reason about.
const std = @import("std");
const Io = std.Io;
const timers = @import("stdx").timers;
// The loop shape: expire what is due, then sleep toward next(). This
// example advances a simulated clock instead of sleeping.
test "a loop drains the timers that are due" {
var set: timers.Timers = .empty;
var connect: timers.Timer = .one_shot;
var request: timers.Timer = .one_shot;
var canceled: timers.Timer = .one_shot;
set.arm(&connect, .fromNanoseconds(100), timers.disarm);
set.arm(&request, .fromNanoseconds(200), timers.disarm);
set.arm(&canceled, .fromNanoseconds(50), timers.disarm);
// stop unlinks an armed timer and reports that it was armed.
try std.testing.expect(set.stop(&canceled));
try std.testing.expect(!set.stop(&canceled));
// next() is the earliest armed deadline: what the loop sleeps
// toward.
try std.testing.expectEqual(Io.Timestamp.fromNanoseconds(100), set.next().?);
var wakes: u32 = 0;
while (set.next()) |wake| {
wakes += 1;
set.expire(wake);
}
try std.testing.expectEqual(2, wakes);
try std.testing.expect(!connect.armed);
try std.testing.expect(!request.armed);
// Both fired: reset re-arms the entry and reports that it had
// already fired.
try std.testing.expect(!set.reset(&request, .fromNanoseconds(300)));
try std.testing.expectEqual(Io.Timestamp.fromNanoseconds(300), set.next().?);
}
// A period timer: the callback returns .rearm until the tick count,
// then .disarm. The record embeds the Timer in a field named `timer`,
// so the typed callback receives the record back.
test "a period timer stops itself after three ticks" {
const Ticker = struct {
const Self = @This();
timer: timers.Timer = .one_shot,
ticks: u32 = 0,
fn onTick(self: *Self, _: *timers.Timers, _: *timers.Timer) timers.Action {
self.ticks += 1;
return if (self.ticks < 3) .rearm else .disarm;
}
};
var set: timers.Timers = .empty;
var ticker: Ticker = .{ .timer = timers.Timer.repeat(.fromNanoseconds(10)) };
set.arm(&ticker.timer, .fromNanoseconds(100), Ticker.onTick);
// The re-arm anchors to the fired deadline: expiring late fires
// only the ticks that are due.
set.expire(.fromNanoseconds(105));
set.expire(.fromNanoseconds(1000));
try std.testing.expectEqual(3, ticker.ticks);
try std.testing.expect(!ticker.timer.armed);
try std.testing.expectEqual(@as(?Io.Timestamp, null), set.next());
}Repeat on a period
A Timer with a period is Go's Ticker: it re-arms on every fire. The next deadline is the fired deadline plus the period, never the wake time. A late expire does not shift the schedule, so drift does not accumulate.
The callback decides the next fire: return .rearm to keep the timer going, or .disarm to let it die from inside its own fire. The callback runs between the fire and the re-arm, so it sees the entry disarmed and the decision pending. A callback that re-arms its own timer wins over its returned .rearm.
Recover the record
A callback is typed. Its first parameter is a pointer to the record that embeds the Timer. The wrapper recovers the record with @fieldParentPtr, so the record's field must be named timer. A void first parameter arms a bare timer. Timer.disarm is the ready-made callback for a timer whose fire is observed through armed and next().
The wrapper inlines the typed body into the erased callback, so a fire costs one function-pointer indirection. A callback that frees its own record must return .disarm.
Logging transport
A worker thread that writes a log line cannot block on a slow consumer. slot_ring.Mpsc is a bounded, lock-free ring for that shape: many threads acquire a slot, write, and commit, and one consumer drains in order. Producers never block: a refused acquire returns null and the new message drops. The module is Linux only: it is void on other targets. slot_size is a comptime option, and it must be a multiple of the cache line. init rounds the slot count up to a power of two.
Pick the wake flavor
The consumer's shape decides the wake mechanism at compile time.
| Flavor | Consumer |
|---|---|
.none | The caller drives every drain: a test, or a loop that drains on its own schedule. |
.eventfd | A poll loop. pollFd() is the doorbell. Call ackDoorbell() when the fd reads ready, before the drain. |
.futex | A dedicated consumer thread. waitForData parks it until data or shutdown. requestShutdown ends it after the producers join. |
Pick the loss policy
.drop_new is the default and the logging choice. A full ring refuses the new message, so the loss is the newest lines. .drop_oldest displaces the oldest committed message instead, so the newest line wins. The displacing ring owns the consumer cursor, and the consumer reads through read(buf), which copies the payload into the caller's buffer. A read(buf) that loses the cursor to a displacer returns null, and the displacer ticks displacedCount.
Drain in order
The consumer stops at the first null, which marks a claim that is not committed yet. A consumer that advances past the first uncommitted claim skips the committed messages behind it. Under .drop_new, the caller owns the read position and release frees the slot. Under .drop_oldest, the ring owns the cursor and read(buf) frees the slot inside the window it claims.
Account the loss
head() counts the claims handed out. A refused acquire is the caller's drop count. Under .drop_oldest, displacedCount() counts the lines that producers displaced. Every line is delivered, displaced, or refused, so the counts close the total.
const std = @import("std");
const slot_ring = @import("stdx").slot_ring;
// Four 256-byte slots, the default wake flavor and the default drop
// policy: nothing wakes the consumer, and a full ring refuses the new
// line. Worker threads claim, write, and commit; the caller drains.
const LogRing = slot_ring.Mpsc(.{ .slot_size = 256 });
const Log = struct {
ring: *LogRing,
// The single consumer owns the read position. It advances only
// past a committed line that it released.
read_pos: u64 = 0,
dropped: u64 = 0,
// The producer path: claim, write, commit. A refused claim counts
// the drop and returns, so no path blocks.
fn write(self: *Log, line: []const u8) void {
var lease = self.ring.acquire() orelse {
self.dropped += 1;
return;
};
var w = lease.writer();
w.writeAll(line[0..@min(line.len, LogRing.payload_size)]) catch unreachable;
lease.commit(self.ring, @intCast(w.end));
}
// The consumer path: read in order from the owned position and
// stop at the first uncommitted claim, so nothing behind it is
// skipped.
fn drain(self: *Log, out: *std.Io.Writer) !void {
while (self.read_pos < self.ring.head()) : (self.read_pos += 1) {
const msg = self.ring.read(self.read_pos) orelse break;
try out.print("{s}\n", .{msg.payload});
msg.release();
}
}
};
test "a full ring drops the newest lines and the drain stays in order" {
var ring: LogRing = undefined;
try ring.init(std.testing.allocator, undefined, 4);
defer ring.deinit(std.testing.allocator);
var log: Log = .{ .ring = &ring };
// Six lines into four slots: the first four commit, the last two
// are refused.
for (0..6) |i| {
var buf: [16]u8 = undefined;
log.write(try std.mem.print(&buf, "line {d}", .{i}));
}
try std.testing.expectEqual(4, ring.head());
try std.testing.expectEqual(2, log.dropped);
// Every line is committed or counted: nothing vanishes.
try std.testing.expectEqual(6, ring.head() + log.dropped);
var buffer: [128]u8 = undefined;
var out: std.Io.Writer = .fixed(&buffer);
try log.drain(&out);
try std.testing.expectEqualStrings("line 0\nline 1\nline 2\nline 3\n", out.buffered());
// The drain released every slot. The next line lands, and the
// consumer resumes at its own position.
log.write("after");
try std.testing.expectEqual(5, ring.head());
var more: [32]u8 = undefined;
var out2: std.Io.Writer = .fixed(&more);
try log.drain(&out2);
try std.testing.expectEqualStrings("after\n", out2.buffered());
try std.testing.expectEqual(5, log.read_pos);
}Tradeoffs
The ring is not a lossless queue. Overflow drops a message under either policy: .drop_new refuses the newest, and .drop_oldest displaces the oldest committed message when it can. The loss is always accounted (head(), a refused acquire, displacedCount()) but never prevented. A caller that must not lose a message needs a blocking channel, not this ring.
One consumer thread drains by position, in order. A producer stalled mid-write stalls the drain behind its position: the cost is dropped messages, never corrupted ones. There is no out-of-order drain and no parallel drain.
Producers never block. An acquire either wins a slot or returns null, and the caller drops the message. Under .drop_oldest, a full ring displaces the oldest committed message instead, so the newest message wins. A stalled producer still refuses the claim, and so does a displacement that cannot win the cursor.
The policy decides the read shape. Under .drop_oldest, the consumer reads through read(buf) and gets a copy inside the won cursor window. .drop_new hands out a borrowed slice from read(read_pos): the single consumer owns the position, and nothing can take the slot before release.
One message costs one CAS on the head, the payload copy into the slot, and one release store of the stamp. The wake flavor adds its own cost. .none adds nothing, .eventfd writes eight bytes to the fd, and .futex bumps the wake word with one RMW. The .futex syscall runs only when a waiter is armed. A displacement adds a cursor CAS, a stamp CAS, and one atomic increment of the displaced count. It also wakes the consumer under the two waking flavors.
Linux only. The .eventfd and .futex flavors wrap Linux syscalls, and the module is void on other targets. slot_size is comptime and a cache-line multiple. Changing it instantiates a new ring type.
Small modules
These modules are small enough that the contract fits in a paragraph. The module list has the one-line summary, and the API reference has every symbol.
Assign ids to strings
intern.Pool keeps one copy of each distinct string and hands out a dense u32 id. Compare ids for the rest of the run instead of comparing bytes, and print the text through get.
intern(gpa, bytes) copies the bytes into chunk storage and returns the id, or the existing id when the bytes are already present. One allocation serves many names: the copy goes into the tail of the current chunk, and a name longer than a chunk gets a chunk of its own. lookup(bytes) finds an id without inserting, and count reports the number of distinct strings.
The pool is unmanaged, so intern and deinit take the allocator. Ids stay valid until deinit, there is no deletion, and the pool is not thread-safe.
const std = @import("std");
const intern = @import("stdx").intern;
// One pool per run. Ids are dense and stay valid until `deinit`.
test "intern a name once" {
var names: intern.Pool = .init;
defer names.deinit(std.testing.allocator);
const field = try names.intern(std.testing.allocator, "field");
const again = try names.intern(std.testing.allocator, "field");
try std.testing.expectEqual(field, again);
const value = try names.intern(std.testing.allocator, "value");
try std.testing.expectEqual(@as(u32, 1), value);
// The stored bytes come back by id, and a lookup finds them by content.
try std.testing.expectEqualStrings("field", names.get(field));
try std.testing.expectEqual(@as(?u32, field), names.lookup("field"));
try std.testing.expectEqual(@as(?u32, null), names.lookup("missing"));
}
// The pool copies the bytes, so a parser can reuse its scratch buffer.
test "the pool owns the bytes" {
var names: intern.Pool = .init;
defer names.deinit(std.testing.allocator);
var scratch: [4]u8 = undefined;
@memcpy(&scratch, "name");
const id = try names.intern(std.testing.allocator, &scratch);
@memset(&scratch, 'x');
try std.testing.expectEqualStrings("name", names.get(id));
}
// A table that compares names by id for the rest of the run.
const Symbols = struct {
pool: intern.Pool = .init,
fn declare(self: *Symbols, gpa: std.mem.Allocator, name: []const u8) !u32 {
return self.pool.intern(gpa, name);
}
fn resolve(self: *const Symbols, name: []const u8) ?u32 {
return self.pool.lookup(name);
}
fn deinit(self: *Symbols, gpa: std.mem.Allocator) void {
self.pool.deinit(gpa);
self.* = undefined;
}
};
test "compare names as integers" {
var symbols: Symbols = .{};
defer symbols.deinit(std.testing.allocator);
const field = try symbols.declare(std.testing.allocator, "field");
const value = try symbols.declare(std.testing.allocator, "value");
try std.testing.expect(field != value);
try std.testing.expectEqual(@as(?u32, value), symbols.resolve("value"));
}Bound a response
BoundedWriter is an accumulating Io.Writer over a buffer that it allocates from your allocator. It has the semantics of Io.Writer.Allocating with a ceiling: a write that would push the buffered bytes past limit returns error.WriteFailed. The bytes written before it stay, and the buffer never holds more than the limit.
Use it when input that you do not control feeds a fixed-size response, such as a JSON body. written returns the buffered bytes, and deinit frees the buffer.
const std = @import("std");
const BoundedWriter = @import("stdx").BoundedWriter;
// A response built from an unbounded row set must not outgrow its buffer.
fn render(rows: []const u32, out: *BoundedWriter) !void {
try out.writer.writeAll("[");
for (rows, 0..) |row, index| {
if (index != 0) try out.writer.writeAll(",");
try out.writer.print("{d}", .{row});
}
try out.writer.writeAll("]");
}
test "a response that fits is kept whole" {
var out: BoundedWriter = .init(std.testing.allocator, 64);
defer out.deinit();
try render(&.{ 1, 2, 3 }, &out);
try std.testing.expectEqualStrings("[1,2,3]", out.written());
}
test "a write past the limit fails and keeps the prefix" {
var out: BoundedWriter = .init(std.testing.allocator, 8);
defer out.deinit();
// "[" and the first row make 7 bytes, and the separator reaches the
// limit exactly. The next digit is the write that fails.
try std.testing.expectError(error.WriteFailed, render(&.{ 123_456, 2 }, &out));
try std.testing.expectEqualStrings("[123456,", out.written());
}Hash a key
hash.RapidHash is rapidhash V3: 64-bit, non-cryptographic, and seeded. Its output reproduces upstream's reference values on every host, so a hash is stable across builds.
hash(seed, input) is the 7-lane variant and a drop-in for std.hash.Wyhash.hash. hashMicro and hashNano are the smaller variants for short inputs. They return the same value as hash up to 80 and 48 bytes, and diverge after that.
RapidHash.StringContext and RapidHash.AutoContext(T) are std-style contexts. Pass one as the context of swiss, bounded_array_hash_map, or any std map. StringContext hashes string contents. AutoContext walks a key the way std.hash.autoHash does, and it rejects slices.
const std = @import("std");
const stdx = @import("stdx");
const bounded_array_hash_map = stdx.bounded_array_hash_map;
const rapidhash = stdx.hash.RapidHash;
// `StringContext` is a std-style hash-map context: rapidhash over the
// key bytes, with the map's equality for the rest.
const Counts = bounded_array_hash_map.Custom([]const u8, u32, rapidhash.StringContext, 16);
fn record(counts: *Counts, route: []const u8) !u32 {
const entry = try counts.getOrPut(route);
if (!entry.found_existing) entry.value_ptr.* = 0;
entry.value_ptr.* += 1;
return entry.value_ptr.*;
}
test "one seed and one input give one hash" {
try std.testing.expectEqual(rapidhash.hash(0, "GET /health"), rapidhash.hash(0, "GET /health"));
try std.testing.expect(rapidhash.hash(7, "GET /health") != rapidhash.hash(0, "GET /health"));
}
test "string keys hash with rapidhash" {
var counts: Counts = .init;
try std.testing.expectEqual(1, try record(&counts, "GET /health"));
try std.testing.expectEqual(2, try record(&counts, "GET /health"));
try std.testing.expectEqual(1, try record(&counts, "POST /jobs"));
}Check a block
hash.crc32c computes CRC-32C, the Castagnoli checksum. Use it to detect a corrupted copy of a block. It is not a signature, because anyone can compute one.
Castagnoli's polynomial is not the IEEE one behind std.hash.Crc32. For "123456789" this module returns 0xE306_9283 and std.hash.Crc32 returns 0xCBF4_3926. The hardware implements Castagnoli: SSE4.2's crc32 and ARMv8's crc32c fold eight bytes per instruction. iSCSI, ext4, btrfs, and the LevelDB family store this checksum, so a format that interoperates with one of them stores this value.
hash(bytes) returns the digest of one buffer. append(digest, bytes) continues a digest over another buffer, and 0 starts the chain. A chain of append calls equals one hash over the concatenation, so a writer that checksums chunk by chunk stores one u32 between calls. Do not seed std.hash.crc.@"CRC-32/ISCSI" with that stored value: its crc field is the digest in the SSE4.2 kernel and the raw state in the generic one. A value that one kernel continues, the other does not.
The kernel comes from the build target. x86-64 with SSE4.2 and aarch64 with the ARMv8 CRC extension run the instruction. Every other target gets slice-by-16 tables. There is no run-time dispatch, so name the CPU with -Dcpu=....
const std = @import("std");
const hash = @import("stdx").hash;
const crc32c = hash.crc32c;
// A writer that checksums chunk by chunk stores one u32 between calls, and
// the chain equals one pass over the whole message.
test "a stored digest continues the next chunk" {
const header = "frame:0001";
const body = "the payload that follows the header";
const stored = crc32c.hash(header);
try std.testing.expectEqual(crc32c.hash(header ++ body), crc32c.append(stored, body));
}
// A hole in the middle is ordinary bytes. The chain does not restart.
test "a zero word does not reset the chain" {
const head = "header";
const tail = "payload";
const hole: [8]u8 = @splat(0);
const after_head = crc32c.hash(head);
const after_hole = crc32c.append(after_head, &hole);
try std.testing.expectEqual(
crc32c.hash(head ++ hole ++ tail),
crc32c.append(after_hole, tail),
);
}
test "the reference check value" {
try std.testing.expectEqual(@as(u32, 0xE306_9283), crc32c.hash("123456789"));
}Pool fixed-size records
heap has two pools for records that come in known sizes.
SlabAllocator(.{ .size_classes = ... }) has the allocator shape. alloc takes the gpa and a size, rounds the size up to the first class that fits, and returns a pointer. free takes the same size back. A size above every class is a normal allocation from the same gpa, and free returns it the same way. deinit takes the gpa, and in Debug and ReleaseSafe it asserts that every allocation was freed first. queryCapacity reports the pooled capacity.
alloc panics when the gpa cannot serve it. It has no error return, so a caller that must handle allocation failure uses SizeClassPool or a plain allocator.
SizeClassPool(&.{ 16, 64, 256 }) carves its classes, free lists, and metadata from one caller-owned backing. create returns a byte slice of the requested length, and a request above the largest class returns error.OutOfMemory. destroy takes the slice back unchanged.
const std = @import("std");
const SlabAllocator = @import("stdx").heap.SlabAllocator;
// Records are 96 bytes. The 128-byte class holds them with 32 to spare,
// and preheat maps the first 16 slots at init. Anything above the largest
// class falls back to the gpa passed to `alloc`.
const Slab = SlabAllocator(.{ .size_classes = &.{
.{ .size = 128, .preheat = 16 },
.{ .size = 1024 },
} });
test "a record comes from its size class" {
var slab: Slab = try .init(std.testing.allocator);
defer slab.deinit(std.testing.allocator);
const record = slab.alloc(std.testing.allocator, 96);
@memset(record[0..96], 0);
slab.free(std.testing.allocator, record, 96);
// The type retains no gpa, so the same one goes to every call.
try std.testing.expect(slab.queryCapacity(std.testing.allocator) >= 128 * 16);
}Allocate in bulk
heap.Bump(.{ ... }) returns an arena type for a job's values. The chunk sizes are part of the type, so an instance carries only its allocator and its chunk list. create and alloc take memory from a chunk, free does nothing, and deinit returns every chunk. Pointers stay valid as the arena grows, and the child allocator is called only when a chunk is needed.
Use it instead of std.heap.ArenaAllocator when one thread owns the arena and the job allocates in a loop. std's arena is thread-safe, so every allocation takes an atomic operation on the chunk cursor. Bump has no atomics, and it must not be shared between threads.
reset(.retain_capacity) empties every chunk and keeps the memory for the next job. reset(.free_all) returns the chunks to the child allocator. A request above max_chunk gets a chunk of its own size.
The arena's State type is the chunk list without the allocator, so it holds two pointers. Store it in a struct that gets copied, promote it where the allocations happen, and copy the state back before the promoted value goes out of scope. This is the std.heap.ArenaAllocator.State pattern.
const std = @import("std");
const heap = @import("stdx").heap;
// The chunk sizes are part of the type. An instance carries only the
// allocator and the chunk list.
const Arena = heap.Bump(.{
.first_chunk = 4096,
.max_chunk = 64 * 1024,
});
// One arena per job. The values are immutable and die together.
fn evaluate(allocator: std.mem.Allocator) !u64 {
var total: u64 = 0;
for (0..100) |index| {
const value = try allocator.create(u64);
value.* = index;
total += value.*;
}
return total;
}
test "an arena per job" {
var bump: Arena = .init(std.testing.allocator);
defer bump.deinit();
try std.testing.expectEqual(@as(u64, 4950), try evaluate(bump.allocator()));
}
test "a reset refills the chunks" {
var bump: Arena = .init(std.testing.allocator);
defer bump.deinit();
const first = try bump.allocator().create(u64);
bump.reset(.retain_capacity);
const again = try bump.allocator().create(u64);
try std.testing.expectEqual(first, again);
}
// A struct that is copied by value stores the state, not the arena, and
// promotes it where the allocations happen.
const Table = struct {
arena: Arena.State = .empty,
fn build(self: *Table, gpa: std.mem.Allocator, count: usize) ![]const *const u64 {
var arena = self.arena.promote(gpa);
defer self.arena = arena.state;
const values = try arena.allocator().alloc(*const u64, count);
for (values, 0..) |*slot, index| {
const value = try arena.allocator().create(u64);
value.* = index;
slot.* = value;
}
return values;
}
fn deinit(self: *Table, gpa: std.mem.Allocator) void {
var arena = self.arena.promote(gpa);
arena.deinit();
self.* = undefined;
}
};
test "a stored state" {
var table: Table = .{};
defer table.deinit(std.testing.allocator);
const values = try table.build(std.testing.allocator, 8);
try std.testing.expectEqual(@as(u64, 7), values[7].*);
}Pool entries with intrusive links
slot.Pool(Entry, "prev", "next") holds a fixed set of entries that come and go, with O(1) acquire and release. The two link fields live inside the entry, named at comptime, so a walk of the live entries reads only the entries it visits, not every slot in the table.
Two constructors share one implementation. Pool(Entry, "prev", "next") takes a slice at init, so its capacity is known at runtime: an allocated connection table, for example. Array(Entry, "prev", "next", n) owns an [n]Entry and is the form to put in a struct that is copied or returned, because a Pool holds a slice into storage it does not own.
The link fields carry the handle type. u32 is the usual choice, and a narrow type such as std.math.IntFittingRange packs a small table.
acquire returns a handle and links the entry at the back of the list, or returns error.NoSpaceLeft when every entry is live. acquireFront links it at the front instead, which is what a recency-ordered cache wants. release takes the handle back. The handle is the entry's index, so a caller recovers the index by keeping the handle and never by pointer arithmetic. get returns the entry, and isLive answers whether a handle is live. moveToFront reorders a live entry, and popFront and popBack remove an end; lru is built on the first two.
iterator walks the live entries in acquisition order. next advances before the body runs, so the body may release the entry it was handed. Releasing any other entry during the walk is not supported.
The pool writes only the two link fields. An acquired entry still holds what the previous occupant left, so initialize every field you read. A handle released twice trips an assert in a safe build.
const std = @import("std");
const slot = @import("stdx").slot;
// The links live in the entry, at comptime-known field names. The pool owns
// these two fields; every other field is yours. Their type is the handle type,
// and a narrow type such as u16 packs a small table.
const Stream = struct {
prev: u32,
next: u32,
id: u32,
open: bool,
};
const Pool = slot.Pool(Stream, "prev", "next");
test "acquire, release, and walk in acquisition order" {
// Capacity is the slice length, so a local array is a fixed-size pool.
var entries: [4]Stream = undefined;
var pool: Pool = .init(&entries);
var handles: [3]u32 = undefined;
for (&handles, 0..) |*handle, index| {
handle.* = try pool.acquire();
pool.get(handle.*).id = @intCast(index);
pool.get(handle.*).open = true;
}
// Release the middle stream. The walk keeps acquisition order.
pool.release(handles[1]);
try std.testing.expect(!pool.isLive(handles[1]));
var seen: [2]u32 = undefined;
var count: usize = 0;
var it = pool.iterator();
while (it.next()) |item| : (count += 1) seen[count] = item.entry.id;
try std.testing.expectEqualSlices(u32, &.{ 0, 2 }, seen[0..count]);
}
test "a full pool reports it" {
var entries: [1]Stream = undefined;
var pool: Pool = .init(&entries);
const handle = try pool.acquire();
try std.testing.expectError(error.NoSpaceLeft, pool.acquire());
// The handle is the entry's index, so a caller never needs pointer
// arithmetic to recover it.
try std.testing.expectEqual(@as(u32, 0), handle);
pool.release(handle);
try std.testing.expectEqual(handle, try pool.acquire());
}
test "release the entry a walk is visiting" {
var entries: [3]Stream = undefined;
var pool: Pool = .init(&entries);
for (0..3) |_| _ = try pool.acquire();
// The iterator moves to the next entry before the body runs, so releasing
// the entry it handed over is safe.
var it = pool.iterator();
while (it.next()) |item| {
pool.release(item.handle);
}
try std.testing.expectEqual(@as(usize, 0), pool.count());
}
// The owning form keeps the array inside the pool, so the whole value can be
// copied or returned, and the capacity is part of the type.
const Cache = slot.Array(Stream, "prev", "next", 16);
test "an owning pool" {
var cache: Cache = .empty;
const handle = try cache.acquire();
cache.get(handle).id = 7;
// The front of the list is the entry most recently moved there.
cache.moveToFront(handle);
try std.testing.expectEqual(@as(u32, 7), cache.popFront().?.id);
try std.testing.expectEqual(@as(usize, 0), cache.count());
}
test "runtime capacity from an allocated slice" {
const entries = try std.testing.allocator.alloc(Stream, 128);
defer std.testing.allocator.free(entries);
var pool: Pool = .init(entries);
try std.testing.expectEqual(@as(usize, 128), pool.capacity());
const handle = try pool.acquire();
pool.get(handle).id = 7;
try std.testing.expectEqual(@as(u32, 7), pool.get(handle).id);
}Fixed-size byte values
mem.Array(N) wraps [N]u8, with the length in the type. init takes the bytes, zero is an initialized all-zero value, and secureZero clears the bytes in a way that the optimizer cannot remove. Use it for keys and other secrets.
The module also adds vectorized scans. findScalarLast walks backwards and findAny walks forwards; both match the std function of the same name and return the same index. lastIndexOfNonZero has no std equivalent.
const std = @import("std");
const memx = @import("stdx").mem;
// The length lives in the type, so a key cannot be copied with the wrong
// width. `secureZero` clears the bytes in a way the optimizer keeps.
const Key = memx.Array(32);
test "a byte value zeroes on request" {
var key: Key = .init(@splat(0xab));
key.secureZero();
const zero: [32]u8 = @splat(0);
try std.testing.expectEqualSlices(u8, &zero, &key.data);
}
test "the backwards scans return the last match" {
const bytes = [_]u8{ 0x01, 0x02, 0x00, 0x00 };
try std.testing.expectEqual(@as(?usize, 1), memx.lastIndexOfNonZero(&bytes));
const values = [_]u16{ 7, 9, 7, 3 };
try std.testing.expectEqual(@as(?usize, 2), memx.findScalarLast(u16, &values, 7));
try std.testing.expectEqual(@as(?usize, 3), memx.findAny(u16, &values, &.{ 3, 5 }));
}Random bytes
random.fill writes secure random bytes with no Io value and no error. Each thread owns a ChaCha generator, seeded on its first call from the platform's secure source: getrandom on Linux, arc4random_buf on macOS. Later calls take no syscall and no lock. A failed seed panics, because no fallback keeps the guarantee.
The module compiles on Linux and macOS only.
const std = @import("std");
const random = @import("stdx").random;
// No `Io` value, no error union: the generator never fails after it seeds.
fn newSessionToken() [16]u8 {
var token: [16]u8 = undefined;
random.fill(&token);
return token;
}
test "two tokens differ" {
const first = newSessionToken();
const second = newSessionToken();
try std.testing.expect(!std.mem.eql(u8, &first, &second));
}
test "the fill takes any byte slice" {
var nonce: [12]u8 = undefined;
random.fill(&nonce);
random.fill(&.{});
// A zero-length fill is a no-op, not an error.
try std.testing.expect(nonce.len == 12);
}Write to stdio
stdio.err and stdio.out are ready on import. There is no init and no allocator. print formats like Io.Writer.print and appends no newline. No method returns an error: the first failed write latches, and later writes on that stream drop.
Output is buffered, so call stdio.flush() before exit. A panic never reaches the buffer, so panic reporting stays with std.debug.print. The streams ride std.Options.debug_io, which supports one thread only.
const std = @import("std");
const stdio = @import("stdx").stdio;
// `stdio.err` and `stdio.out` are ready on import, so most code never
// builds a `Stream`. This one writes to a pipe and leaves the process's
// own stdio alone, which is also how to test code that formats output.
test "a stream buffers until flush" {
const fds = try std.Io.Threaded.pipe2(.{ .NONBLOCK = true });
defer std.Io.Threaded.closeFd(fds[0]);
defer std.Io.Threaded.closeFd(fds[1]);
var stream: stdio.Stream = undefined;
stream = .{
.buffer = undefined,
.file_writer = .initStreaming(
.{ .handle = fds[1], .flags = .{ .nonblocking = false } },
std.testing.io,
&stream.buffer,
),
};
// No method returns an error, and nothing lands until flush.
stream.print("{s}: {d}\n", .{ "cache miss", 42 });
stream.flush();
var buf: [64]u8 = undefined;
const n = try std.posix.read(fds[0], &buf);
try std.testing.expectEqualStrings("cache miss: 42\n", buf[0..n]);
}API reference only
Two modules in the table have no example here. posix is described under Work with a raw socket fd. pages is API reference only: it releases whole kernel pages with MADV_DONTNEED, and it depends on the Linux zero-fill guarantee for the next touch. That guarantee has no Darwin equivalent, so the module is Linux only by design.