API reference
Extensions to the Zig 0.17 standard library: fixed-capacity containers, strict parsers, IPv4 types, and the primitives std lacks.
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.
The guide at https://baskingspot.dev/stdx/ says which module to use for a task, with examples. These pages are the reference for each symbol.
module
base32
src
Crockford base32 codec for fixed-shape machine tokens.
more
std has base64 but no base32. The shape here is the fixed one: a
token on the wire is exactly 8 * N / 5 Crockford symbols carrying
N bytes (N a multiple of 5), so the token round-trips to a
fixed-size binary key — smaller records, fixed-size equality instead
of a string compare, and the decode itself is the validation:
anything that fails to decode is garbage, no separate check.
Machine-generated and strictly lowercase on the wire: encode emits
the lowercase Crockford alphabet (32 symbols, excluding i, l,
o, u — unambiguous when read aloud), and decode rejects
everything outside it — uppercase letters and the excluded letters
all fail. No case folding, no O/I/L aliases: an alias table
would make two spellings one token, which is exactly what a
stable-token scheme must not do.
Allocation-free, fixed-shape, MSB-first packing, no padding path at all — the bit counts close by construction.
Functions
Decode exactly 8 * N / 5 lowercase Crockford-base32 symbols into
N bytes, MSB-first. Case-sensitive: errors on any symbol outside
the lowercase alphabet — uppercase and the excluded letters
i/l/o/u all fail. No padding: the bit counts close by
construction.
Encode N bytes into 8 * N / 5 lowercase Crockford-base32
symbols, MSB-first. The exact inverse of decode.
Types
type fn
SymbolCount
src
pub fn SymbolCount(comptime N: comptime_int) type
Symbols that encode N bytes: 8 * N / 5, an integer because
N is a multiple of 5.
module
base64
src
Base64 (RFC 4648) that moves whole vectors per instruction.
more
std has a base64 codec, and it is scalar: it reads 16 bytes into a
u128, shifts the 6-bit fields out one at a time, and indexes the
alphabet for each character. That is roughly four instructions per
byte of output. The alphabet translation is a 64-entry lookup, which
a SIMD table permute does for 16 bytes at once; on aarch64 the
3-in/4-out byte interleave that base64 needs is an addressing mode,
not arithmetic.
The codec is the alphabet plus the pad character, nothing else. It is
a comptime parameter, so every lookup table a kernel indexes is a
const array in the binary and every if (pad_char) is resolved
before code generation. Encode writes characters and returns the slice
it wrote. Decode writes bytes, returns the slice it wrote, and is the
validation: padding and the unused trailing bits of a partial group
are both checked, so anything that decodes is canonical base64.
The kernel is chosen from the target CPU at compile time, not at run
time: aarch64 gets NEON, x86-64 gets AVX2 or AVX-512 VBMI when the target
has them, and anything else gets std's codec. There is no CPUID probe and
no indirect call, so a build for the x86-64 baseline has no acceleration
and a build for x86_64_v3 has it compiled in.
An x86-64 Debug build takes Zig's self-hosted backend by default, which
cannot assemble a vector register operand, so those builds get std's
codec too. Set use_llvm = true on the build step to keep the kernels
in a Debug build.
Streaming, whitespace tolerance, and the IgnoreDecoder shape are not
here. A caller that has to skip newlines has a format problem, not a
codec problem.
Constants
pub const standard_alphabet = …
src
value
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".*The alphabet of RFC 4648 section 4.
pub const url_safe_alphabet = …
src
value
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".*The alphabet of RFC 4648 section 5.
Standard base64, padded: RFC 4648 section 4.
pub const standard_no_pad = Codec(standard_alphabet, null)
src
Standard base64, unpadded: RFC 4648 section 3.2.
URL-safe base64, padded: RFC 4648 section 5.
pub const url_safe_no_pad = Codec(url_safe_alphabet, null)
src
URL-safe base64, unpadded: RFC 4648 section 5 with section 3.2's
trailing-byte rule.
value
error{
/// A byte in the input is not in the alphabet. A pad character where
/// it does not belong is reported as this error or as `InvalidPadding`
/// depending on which path found it; both mean the input is rejected.
InvalidCharacter,
/// The input length, the pad characters, or the unused trailing bits
/// of a partial group are not valid for this codec.
InvalidPadding,
/// `dest` is too small for the decoded output.
NoSpaceLeft,
}Types
type fn
Codec
src
pub fn Codec(comptime alphabet: [64]u8, comptime pad_char: ?u8) type
A base64 codec: 64 distinct alphabet characters and an optional pad
character. standard and the three other constants are the codecs RFC
4648 defines; a caller with its own alphabet calls this directly.
Functions
pub fn encodedLen(source_len: usize) usize
src
The byte count encode produces for source_len input bytes.
pub fn decodedUpperBound(source_len: usize) usize
src
The largest byte count decode can produce for source_len
input bytes. Padding makes the exact count smaller: use this to
size a buffer in one pass, or decodedLen to size it exactly.
pub fn decodedLen(source: []const u8) Error!usize
src
The exact byte count decode produces for source, or the
error decode returns for the length alone.
Encode source into dest and return the characters written.
dest.len must be at least encodedLen(source.len).
Decode source into dest and return the bytes written.
dest.len must be at least decodedLen(source).
The input must be canonical: padding in place, and the unused bits of a partial trailing group zero.
module
bit_set
src
Fixed-capacity bitsets. Scratch is the reusable form: its backing words
stay dirty between uses, and a data word is read only after set claims
it. A reset costs the words a request touched, not the whole capacity.
Types
type fn
Scratch
src
pub fn Scratch(comptime capacity: usize) type
A fixed-capacity set of indices over dirty words.
more
Initialize in place: var set: Scratch(1 << 14) = undefined; set.clear();.
There is no by-value constructor. Returning or copying the set copies the
data words, and this type exists to avoid that cost; clear writes only
the initialized-word map.
The data words are undefined on first use and stale after a reset, until
set claims their word. The initialized-word map marks the words that
set has zeroed for this generation. isSet and unset never read a
data word unless the map marks it, so unclaimed bytes are never observed.
Fields
bits: Bits
initialized: Initialized
Functions
Start a generation: forget every word and claim none. The data
words stay as they are. This is also the initializer for a value
declared undefined.
Clear index. A word that was never touched reads as unset, so
this is a no-op there.
module
bloom
src
Fixed-capacity Bloom filters: contains never misses an added key, and
it reports an absent key as present at a bounded rate. The storage is a
std.bit_set.Static embedded in the value, so a filter is a flat value
with no allocator, no initialization failure, and no failure mode on
add.
more
Sizing is comptime metaprogramming. Bloom computes the optimal bit
count for the request, rounds it up to a power of two so probe
positions mask instead of reduce, derives the probe count, and
recomputes the false-positive rate that the rounded filter delivers.
The recomputed value is actual_rate: the request is a target,
actual_rate is the truth.
One 64-bit hash per key drives every probe (Kirsch-Mitzenmacher): the low half picks the first bit and a forced-odd stride from the high half walks the rest, so a power-of-two table cannot collapse onto a subset of its bits.
Types
type fn
Auto
src
pub fn Auto(
comptime T: type,
comptime item_count: comptime_int,
comptime target_rate: comptime_float,
) type
A Bloom that hashes keys with std.hash_map.AutoContext, like std's
AutoHashMap: one context, no type-dependent routing. Slices — including
[]const u8 — are rejected by std.hash.autoHash; string keys use
String.
Fields
bit_set: std.bit_set.Static(bits)
Membership bits, indexed by the masked probe positions.
added: u64
Number of add calls since the last init or clear.
Constants
pub const expected_items: u64 = item_count
src
Number of distinct keys the filter is sized for: the
actual_rate contract holds at this count.
pub const requested_rate: f64 = target_rate
src
The requested false-positive rate, echoed for reference. It is
a target, not a bound; actual_rate is the delivered rate.
Bits of storage: the smallest power of two at or above
optimal_bits, floored at 2. Power-of-two sizing turns the
probe modulo into a mask.
pub const hash_functions: u64 = @max(1, optimal_hash_functions)
src
Probes per key, floored at 1 so every key sets at least one bit.
A probe position or the number of probes: both bounded by
comptime-known sizes, so the narrowest fitting integer is the
storage. The repo's buffer.Array convention.
pub const actual_rate: f64 = …
src
value
blk: {
const base: f64 = 1 - @exp(
-@as(comptime_float, hash_functions) * item_count / @as(comptime_float, bits),
);
var rate: f64 = 1;
var probe: Probe = 0;
while (probe < hash_functions) : (probe += 1) rate *= base;
break :blk rate;
}False-positive rate at expected_items distinct keys,
recomputed from bits and hash_functions after the
power-of-two rounding: (1 - e^(-k n / m))^k. This is the
delivered rate; the request is only a target.
A filter with no keys added.
Functions
Number of add calls since the last init or clear. A
repeated add counts again, and adds past expected_items keep
counting: this is a call counter, not the number of distinct
keys, and not the population count of the bits.
Add key: set its hash_functions probe bits. Adding is
infallible — the capacity is fixed and the bits are shared.
Whether key was added. No false negatives: a key passed to
add always tests true. A true result for an absent key is the
documented false positive.
Remove every key and reset count to zero.
type fn
String
src
pub fn String(
comptime item_count: comptime_int,
comptime target_rate: comptime_float,
) type
A Bloom for string keys, like std's StringHashMap: the one context
that hashes []const u8 by content. Key memory is managed by the caller.
Fields
bit_set: std.bit_set.Static(bits)
Membership bits, indexed by the masked probe positions.
added: u64
Number of add calls since the last init or clear.
Constants
pub const expected_items: u64 = item_count
src
Number of distinct keys the filter is sized for: the
actual_rate contract holds at this count.
pub const requested_rate: f64 = target_rate
src
The requested false-positive rate, echoed for reference. It is
a target, not a bound; actual_rate is the delivered rate.
Bits of storage: the smallest power of two at or above
optimal_bits, floored at 2. Power-of-two sizing turns the
probe modulo into a mask.
pub const hash_functions: u64 = @max(1, optimal_hash_functions)
src
Probes per key, floored at 1 so every key sets at least one bit.
A probe position or the number of probes: both bounded by
comptime-known sizes, so the narrowest fitting integer is the
storage. The repo's buffer.Array convention.
pub const actual_rate: f64 = …
src
value
blk: {
const base: f64 = 1 - @exp(
-@as(comptime_float, hash_functions) * item_count / @as(comptime_float, bits),
);
var rate: f64 = 1;
var probe: Probe = 0;
while (probe < hash_functions) : (probe += 1) rate *= base;
break :blk rate;
}False-positive rate at expected_items distinct keys,
recomputed from bits and hash_functions after the
power-of-two rounding: (1 - e^(-k n / m))^k. This is the
delivered rate; the request is only a target.
A filter with no keys added.
Functions
Number of add calls since the last init or clear. A
repeated add counts again, and adds past expected_items keep
counting: this is a call counter, not the number of distinct
keys, and not the population count of the bits.
Add key: set its hash_functions probe bits. Adding is
infallible — the capacity is fixed and the bits are shared.
Whether key was added. No false negatives: a key passed to
add always tests true. A true result for an absent key is the
documented false positive.
Remove every key and reset count to zero.
type fn
Custom
src
pub fn Custom(
comptime T: type,
comptime Context: type,
comptime item_count: comptime_int,
comptime target_rate: comptime_float,
) type
A Bloom filter over T that is sized for item_count distinct keys at
the requested false-positive rate target_rate.
more
Sizing: bits is the smallest power of two at or above the optimal bit
count for the request, hash_functions is the optimal probe count for
the unrounded count, and actual_rate is the false-positive rate the
filter delivers at expected_items distinct keys. The request is a
target: rounding bits up can beat it, and a tiny request can miss it.
Contract: contains never returns false for a key passed to add. An
absent key tests true at actual_rate while the filter holds
expected_items distinct keys. The rate degrades as distinct keys are
added. At 2 * expected_items, each probe bit is set with probability
1 - a^2 instead of 1 - a (a = exp(-hash_functions * expected_items / bits)), so the rate grows by about (1 + a)^hash_functions — near
17x for the 100-item filter in the tests. The design point is not a
bound.
Auto hashes with std.hash_map.AutoContext, String with
std.hash_map.StringContext — the std AutoHashMap/StringHashMap split,
because std.hash.autoHash rejects slices: string keys are a separate
entry point, not silent routing.
The parameters are named item_count and target_rate rather than
expected_items and requested_rate because a container declaration
cannot shadow a parameter of the enclosing function; the requested
values are exposed as those constants instead.
Fields
bit_set: std.bit_set.Static(bits)
Membership bits, indexed by the masked probe positions.
added: u64
Number of add calls since the last init or clear.
Constants
pub const expected_items: u64 = item_count
src
Number of distinct keys the filter is sized for: the
actual_rate contract holds at this count.
pub const requested_rate: f64 = target_rate
src
The requested false-positive rate, echoed for reference. It is
a target, not a bound; actual_rate is the delivered rate.
Bits of storage: the smallest power of two at or above
optimal_bits, floored at 2. Power-of-two sizing turns the
probe modulo into a mask.
pub const hash_functions: u64 = @max(1, optimal_hash_functions)
src
Probes per key, floored at 1 so every key sets at least one bit.
A probe position or the number of probes: both bounded by
comptime-known sizes, so the narrowest fitting integer is the
storage. The repo's buffer.Array convention.
pub const actual_rate: f64 = …
src
value
blk: {
const base: f64 = 1 - @exp(
-@as(comptime_float, hash_functions) * item_count / @as(comptime_float, bits),
);
var rate: f64 = 1;
var probe: Probe = 0;
while (probe < hash_functions) : (probe += 1) rate *= base;
break :blk rate;
}False-positive rate at expected_items distinct keys,
recomputed from bits and hash_functions after the
power-of-two rounding: (1 - e^(-k n / m))^k. This is the
delivered rate; the request is only a target.
A filter with no keys added.
Functions
Number of add calls since the last init or clear. A
repeated add counts again, and adds past expected_items keep
counting: this is a call counter, not the number of distinct
keys, and not the population count of the bits.
Add key: set its hash_functions probe bits. Adding is
infallible — the capacity is fixed and the bits are shared.
Whether key was added. No false negatives: a key passed to
add always tests true. A true result for an absent key is the
documented false positive.
Remove every key and reset count to zero.
module
bounded_array_hash_map
src
Fixed-capacity insertion-ordered hash map: std.AutoArrayHashMapUnmanaged's
data structure with its capacity fixed at comptime and its storage embedded
in the value, so no allocator is involved and insertion fails only with
error.NoSpaceLeft.
more
Index-header sizing, probing and deletion are ported from Zig 0.16.0
std.array_hash_map (MIT, Zig contributors; see LICENSE-ZIG). Entries keep
insertion order: overwriting a key leaves its position alone, orderedRemove
compacts the entry arrays, and swapRemove moves the last entry into the
removed entry's position.
Types
type fn
Auto
src
pub fn Auto(
comptime K: type,
comptime V: type,
buffer_capacity: comptime_int,
) type
A Bounded that hashes keys with std.hash_map.AutoContext, like std's
AutoHashMap: one context, no type-dependent routing. Slices — including
[]const u8 — are rejected by std.hash.autoHash; string keys use
String.
Fields
key_buffer: [capacity]K
Keys in insertion order; only key_buffer[0..len] is populated.
value_buffer: [capacity]V
Values matching key_buffer, in insertion order.
hash_buffer: [capacity]u32
Hash of key_buffer[i], so equality checks run only on hash
matches (std's store_hash = true layout).
index_buffer: [index_len]IndexSlot
The open-addressed index over the entry arrays.
len: Index
Number of populated entries.
context: Context
Constants
Smallest integer type that can hold 0..capacity.
Maximum number of entries the map can hold.
value
.{
.key_buffer = undefined,
.value_buffer = undefined,
.hash_buffer = undefined,
.index_buffer = @splat(IndexSlot.empty),
.len = 0,
.context = undefined,
}A map containing no entries. The context is undefined, as in
std.PriorityQueue.empty; use initContext to set it.
value
.{
.key_buffer = undefined,
.value_buffer = undefined,
.hash_buffer = undefined,
.index_buffer = @splat(IndexSlot.empty),
.len = 0,
.context = .{},
}Initialize and return a map with a default-initialized context.
Convenience for stateless contexts such as
std.hash_map.AutoContext and std.array_hash_map.StringContext;
contexts that carry state must use initContext.
Functions
pub fn initContext(context: Context) Self
src
Initialize and return a map with context.
Number of entries currently stored.
The keys in insertion order. Writing through this slice is allowed only if it does not change key hashes or equality; the slice is invalidated by the next insertion or removal.
The values in insertion order. The slice is invalidated by the next insertion or removal.
Value stored for key, or null.
Pointer to the value stored for key, or null. The pointer is
invalidated by the next insertion or removal.
Whether key is stored in the map.
Insert or overwrite key. An overwrite replaces the value in place
and does not change insertion order. Returns error.NoSpaceLeft
when the map is full and key is new.
pub fn putAssumeCapacity(self: *Self, key: K, value: V) void
src
Insert or overwrite key, asserting the map has room for a new
key. An overwrite at capacity takes the checked put.
Find or insert key. On a full map an existing key is still found;
a new key returns error.NoSpaceLeft. A new entry's value is
undefined until the caller initializes value_ptr.
pub fn getOrPutAssumeCapacity(self: *Self, key: K) GetOrPutResult
src
Find or insert key, asserting the map is not full.
pub fn orderedRemove(self: *Self, key: K) bool
src
Remove key, shifting the entries after it forward so the
insertion order of the remaining entries is preserved. Returns
false when key is absent.
pub fn swapRemove(self: *Self, key: K) bool
src
Remove key by moving the last entry into its position. O(1), but
the order of the remaining entries changes: the last entry takes
the removed entry's position. Returns false when key is absent.
Remove all entries, keeping the storage. The map is immediately reusable.
An iterator over the entries in insertion order. Modifying the map invalidates it.
Types
struct
GetOrPutResult
src
Result of getOrPut. When found_existing is false the key has
been written into the map and the value is undefined until the
caller initializes value_ptr.
Fields
type fn
String
src
pub fn String(
comptime V: type,
buffer_capacity: comptime_int,
) type
A Bounded for string keys, like std's StringHashMap: the one context
that hashes []const u8 by content. Key memory is managed by the caller.
Fields
key_buffer: [capacity]K
Keys in insertion order; only key_buffer[0..len] is populated.
value_buffer: [capacity]V
Values matching key_buffer, in insertion order.
hash_buffer: [capacity]u32
Hash of key_buffer[i], so equality checks run only on hash
matches (std's store_hash = true layout).
index_buffer: [index_len]IndexSlot
The open-addressed index over the entry arrays.
len: Index
Number of populated entries.
context: Context
Constants
Smallest integer type that can hold 0..capacity.
Maximum number of entries the map can hold.
value
.{
.key_buffer = undefined,
.value_buffer = undefined,
.hash_buffer = undefined,
.index_buffer = @splat(IndexSlot.empty),
.len = 0,
.context = undefined,
}A map containing no entries. The context is undefined, as in
std.PriorityQueue.empty; use initContext to set it.
value
.{
.key_buffer = undefined,
.value_buffer = undefined,
.hash_buffer = undefined,
.index_buffer = @splat(IndexSlot.empty),
.len = 0,
.context = .{},
}Initialize and return a map with a default-initialized context.
Convenience for stateless contexts such as
std.hash_map.AutoContext and std.array_hash_map.StringContext;
contexts that carry state must use initContext.
Functions
pub fn initContext(context: Context) Self
src
Initialize and return a map with context.
Number of entries currently stored.
The keys in insertion order. Writing through this slice is allowed only if it does not change key hashes or equality; the slice is invalidated by the next insertion or removal.
The values in insertion order. The slice is invalidated by the next insertion or removal.
Value stored for key, or null.
Pointer to the value stored for key, or null. The pointer is
invalidated by the next insertion or removal.
Whether key is stored in the map.
Insert or overwrite key. An overwrite replaces the value in place
and does not change insertion order. Returns error.NoSpaceLeft
when the map is full and key is new.
pub fn putAssumeCapacity(self: *Self, key: K, value: V) void
src
Insert or overwrite key, asserting the map has room for a new
key. An overwrite at capacity takes the checked put.
Find or insert key. On a full map an existing key is still found;
a new key returns error.NoSpaceLeft. A new entry's value is
undefined until the caller initializes value_ptr.
pub fn getOrPutAssumeCapacity(self: *Self, key: K) GetOrPutResult
src
Find or insert key, asserting the map is not full.
pub fn orderedRemove(self: *Self, key: K) bool
src
Remove key, shifting the entries after it forward so the
insertion order of the remaining entries is preserved. Returns
false when key is absent.
pub fn swapRemove(self: *Self, key: K) bool
src
Remove key by moving the last entry into its position. O(1), but
the order of the remaining entries changes: the last entry takes
the removed entry's position. Returns false when key is absent.
Remove all entries, keeping the storage. The map is immediately reusable.
An iterator over the entries in insertion order. Modifying the map invalidates it.
Types
struct
GetOrPutResult
src
Result of getOrPut. When found_existing is false the key has
been written into the map and the value is undefined until the
caller initializes value_ptr.
Fields
type fn
Custom
src
pub fn Custom(
comptime K: type,
comptime V: type,
comptime Context: type,
buffer_capacity: comptime_int,
) type
A hash map that stores up to buffer_capacity key-value pairs in arrays
embedded in the value, indexed by std.array_hash_map's open-addressed
header. Entries are kept in insertion order.
more
Context may follow either std convention: std.array_hash_map's
hash(self, K) u32 / eql(self, K, K, usize) bool, or std.hash_map's
hash(self, K) u64 / eql(self, K, K) bool. Hashes are narrowed to u32
internally, and each entry's hash is stored.
The parameter is named buffer_capacity rather than capacity because Zig
rejects a container declaration that shadows an enclosing function
parameter; the bound is exposed as the capacity constant instead.
Fields
key_buffer: [capacity]K
Keys in insertion order; only key_buffer[0..len] is populated.
value_buffer: [capacity]V
Values matching key_buffer, in insertion order.
hash_buffer: [capacity]u32
Hash of key_buffer[i], so equality checks run only on hash
matches (std's store_hash = true layout).
index_buffer: [index_len]IndexSlot
The open-addressed index over the entry arrays.
len: Index
Number of populated entries.
context: Context
Constants
Smallest integer type that can hold 0..capacity.
Maximum number of entries the map can hold.
value
.{
.key_buffer = undefined,
.value_buffer = undefined,
.hash_buffer = undefined,
.index_buffer = @splat(IndexSlot.empty),
.len = 0,
.context = undefined,
}A map containing no entries. The context is undefined, as in
std.PriorityQueue.empty; use initContext to set it.
value
.{
.key_buffer = undefined,
.value_buffer = undefined,
.hash_buffer = undefined,
.index_buffer = @splat(IndexSlot.empty),
.len = 0,
.context = .{},
}Initialize and return a map with a default-initialized context.
Convenience for stateless contexts such as
std.hash_map.AutoContext and std.array_hash_map.StringContext;
contexts that carry state must use initContext.
Functions
pub fn initContext(context: Context) Self
src
Initialize and return a map with context.
Number of entries currently stored.
The keys in insertion order. Writing through this slice is allowed only if it does not change key hashes or equality; the slice is invalidated by the next insertion or removal.
The values in insertion order. The slice is invalidated by the next insertion or removal.
Value stored for key, or null.
Pointer to the value stored for key, or null. The pointer is
invalidated by the next insertion or removal.
Whether key is stored in the map.
Insert or overwrite key. An overwrite replaces the value in place
and does not change insertion order. Returns error.NoSpaceLeft
when the map is full and key is new.
pub fn putAssumeCapacity(self: *Self, key: K, value: V) void
src
Insert or overwrite key, asserting the map has room for a new
key. An overwrite at capacity takes the checked put.
Find or insert key. On a full map an existing key is still found;
a new key returns error.NoSpaceLeft. A new entry's value is
undefined until the caller initializes value_ptr.
pub fn getOrPutAssumeCapacity(self: *Self, key: K) GetOrPutResult
src
Find or insert key, asserting the map is not full.
pub fn orderedRemove(self: *Self, key: K) bool
src
Remove key, shifting the entries after it forward so the
insertion order of the remaining entries is preserved. Returns
false when key is absent.
pub fn swapRemove(self: *Self, key: K) bool
src
Remove key by moving the last entry into its position. O(1), but
the order of the remaining entries changes: the last entry takes
the removed entry's position. Returns false when key is absent.
Remove all entries, keeping the storage. The map is immediately reusable.
An iterator over the entries in insertion order. Modifying the map invalidates it.
Types
struct
GetOrPutResult
src
Result of getOrPut. When found_existing is false the key has
been written into the map and the value is undefined until the
caller initializes value_ptr.
Fields
module
BoundedWriter
src
A bounded Io.Writer backed by a dynamically-allocated buffer with a hard
byte ceiling. When a drain or rebase would push the buffered content
past limit, the writer returns error.WriteFailed instead of growing.
more
This is the bounded counterpart to std.Io.Writer.Allocating: same
accumulating-writer semantics (flush is a no-op, all buffered content is
retained), but the buffer never exceeds limit bytes. Useful for
serializing unbounded input into a fixed-size output — e.g. building a JSON
response from a large result set without risking OOM.
Functions
module
btree
src
Ordered map: a B+tree whose nodes are sized for one cache-miss budget, with inline keys and per-node prefix stripping so a lookup reads a few cache lines instead of one per key compared.
more
std has no ordered map with owned nodes: std.Treap takes a node per
element from the caller, and the hash maps do not order. This module is the
sorted-iteration and range container the standard library lacks.
The design is Xiangpeng Hao's, from "bbtree: fastest ordered map" (https://bbtree.xiangpeng.systems/post/) and the Rust implementation at https://github.com/XiangpengHao/bbtree. This module is a Zig implementation of those ideas, not a port of that code.
Three costs rank the work, as his cost model does: chained cache misses, instructions, and cache coherence traffic. Inline keys and prefix keys trace further back, to Graefe and Larson (ICDE 2001) and Bayer and Unterauer (TODS 1977); the outer-fence rule for the spines is his.
- Node size. A node holds 31 keys, so a search is a linear scan over
a few cache lines, never a pointer chase per key.
Config.maxsets it per map. - Inline keys. Each key's first bytes, as one big-endian word, sit in
a dense array in front of the keys. A search compares those words with
one vector compare and a popcount, and reads a real key only when two
words tie. For
[]const u8keys this keeps the comparison off the heap. An internal node holds only windows and child pointers: the separator to a child's left is that child's own smallest key, so no node carries one key copy per slot. The count that turns a compare into a position keeps one counter per lane and adds them up once, because a single wide vector makes the compiler shuffle each compare back down to a scalar. - Prefix keys. Every key in a node shares the bytes its two fences (the nearest separators around it) share. The node stores that shared length and keeps windows at that offset, so long common prefixes cost nothing. The map's own smallest and largest keys fence the borders, so the shared prefix applies to the whole tree, not only the middle of it where separators exist on both sides.
A wrong inlineKey implementation gives wrong answers, never undefined
behavior: the map never indexes with a window without bounding it by the
node length.
Threading
The map is not thread safe. Use it from one thread at a time. Two concurrent readers are not supported either, because the pointer guard is a plain counter in Debug and ReleaseSafe, and an insertion or removal moves or frees nodes.
Upstream also ships a concurrent map. It puts a version lock on every node, reads inner nodes optimistically, and keeps freed nodes on a free list instead of returning them to the allocator. None of that is here. Adding it is a separate design, not a flag on this one.
Keys are values: the map copies a key into the separators that route to
it, and never frees a key. []const u8 keys are slices the caller owns
and must keep alive while the map holds them.
The map grows, and it owns the entries, so a pointer it hands out does not
survive every call. getPtr, getOrPut, and an iterator address a leaf;
an insertion or removal in that leaf shifts entries, and a split or merge
frees the node. lockPointers makes that a bug report instead of a silent
one, in Debug and ReleaseSafe:
map.lockPointers();
defer map.unlockPointers();
const score = map.getPtr(key) orelse return;
const other = map.getPtr(other_key) orelse return;
// Any insertion or removal here asserts instead of invalidating.Functions
pub fn compareBytes(a: []const u8, b: []const u8) Order
src
Lexicographic order over u8 slices, eight bytes at a time, with the
final short tail zero-padded and the length as the tie-break.
Types
type fn
Custom
src
pub const Custom = map.Custom
A map ordered by Context.compare, with inline keys when Context
declares inlineKey.
more
Context declares:
pub fn compare(self: Context, a: K, b: K) std.math.Order— required.pub fn inlineKey(self: Context, key: K, offset: usize) u64— optional. Returns bytesoffset..offset + 8of an encoding ofkeythat sorts as the key sorts, big-endian and zero-padded past its end. The contract: ifa's encoding sorts beforeb's, thena < b. Equal encodings decide nothing; the map compares the real keys. A context withoutinlineKeygets the plain B+tree: same shape, same correctness, full-key binary search.
Fields
used: usize
Number of entries in the map.
root: ?Node
Root node, or null when the map is empty.
pointer_stability: stability.SafetyLock
Debug and ReleaseSafe only: while a borrow is outstanding, every call that can move or free an entry asserts instead.
lowest: ?K
Smallest key in the map, the outer fence of the left spine.
highest: ?K
Largest key in the map, the outer fence of the right spine.
context: Context
The ordering and inline-key hooks.
Constants
value
.{
.used = 0,
.root = null,
.pointer_stability = .init,
.shared_prefix = 0,
.lowest = null,
.highest = null,
.context = undefined,
}A map with no entries. The context is undefined, as in
std.PriorityQueue.empty; use initContext whenever the
comparator reads it.
value
.{
.used = 0,
.root = null,
.pointer_stability = .init,
.shared_prefix = 0,
.lowest = null,
.highest = null,
.context = .{},
}A map with no entries and a default-initialized context, for
stateless contexts such as Auto's and String's. Use
initContext when the comparator reads the context.
Functions
pub fn initContext(context: Context) Self
src
A map with no entries and the given context.
Number of entries in the map.
Whether the map has no entries.
pub fn lockPointers(self: *Self) void
src
Forbid entry invalidation until unlockPointers. While locked,
any call that can move or free a stored entry (every insertion,
removal, and clearAndFree) fails an assertion in Debug and
ReleaseSafe, and does nothing in ReleaseFast.
more
Bracket the lifetime of pointers from getPtr and getOrPut,
and of an iterator over node memory, with this call. The counter
is not atomic, so this guard assumes one thread at a time like
everything else here.
It may be called several times, so independent borrowers can hold
the map at once; unlockPointers restores the previous state when
called as many times. This is the rule std.ArrayList states for
its own lockPointers.
pub fn unlockPointers(self: *Self) void
src
Undo one call to lockPointers.
Value stored for key, or null.
Pointer to the value stored for key, or null. Any insertion,
removal, or clearAndFree invalidates it; lockPointers turns
that into an assertion in Debug and ReleaseSafe instead.
Pointer to the value stored for key; when absent, inserts key
with an undefined value and reports found_existing = false. The
caller must initialize value_ptr in that case.
Insert key with value, replacing any existing value.
Insert key with value, returning the value replaced.
Remove key, returning whether it was present.
pub fn fetchRemove(self: *Self, gpa: Allocator, key: K) ?V
src
Remove key, returning the value it held.
pub fn clearAndFree(self: *Self, gpa: Allocator) void
src
Remove every entry and free every node.
Iterate entries in ascending key order.
pub fn iteratorFrom(self: *const Self, key: K, inclusive: bool) Iterator
src
Iterate entries from key upward. inclusive keeps an entry whose
key equals key; otherwise iteration starts after it. A key that
is not in the map starts at the next larger key. The iterator is
empty when key is greater than the map's largest stored key.
The smallest entry, or null.
The largest entry, or null.
Types
struct
Entry
src
Pointers to a stored key and value. An entry lives in a leaf, so
another leaf's churn does not move it, but any insertion or removal
in its own leaf does, and a split or a merge can free the leaf
outright. lockPointers turns those calls into an assertion while
the pointers are in use.
Fields
struct
GetOrPutResult
src
Result of getOrPut. When found_existing is false the key has
been written and the value is undefined until the caller sets it.
Fields
type fn
Auto
src
pub const Auto = map.Auto
An ordered map for integer keys.
Fields
used: usize
Number of entries in the map.
root: ?Node
Root node, or null when the map is empty.
pointer_stability: stability.SafetyLock
Debug and ReleaseSafe only: while a borrow is outstanding, every call that can move or free an entry asserts instead.
lowest: ?K
Smallest key in the map, the outer fence of the left spine.
highest: ?K
Largest key in the map, the outer fence of the right spine.
context: Context
The ordering and inline-key hooks.
Constants
value
.{
.used = 0,
.root = null,
.pointer_stability = .init,
.shared_prefix = 0,
.lowest = null,
.highest = null,
.context = undefined,
}A map with no entries. The context is undefined, as in
std.PriorityQueue.empty; use initContext whenever the
comparator reads it.
value
.{
.used = 0,
.root = null,
.pointer_stability = .init,
.shared_prefix = 0,
.lowest = null,
.highest = null,
.context = .{},
}A map with no entries and a default-initialized context, for
stateless contexts such as Auto's and String's. Use
initContext when the comparator reads the context.
Functions
pub fn initContext(context: Context) Self
src
A map with no entries and the given context.
Number of entries in the map.
Whether the map has no entries.
pub fn lockPointers(self: *Self) void
src
Forbid entry invalidation until unlockPointers. While locked,
any call that can move or free a stored entry (every insertion,
removal, and clearAndFree) fails an assertion in Debug and
ReleaseSafe, and does nothing in ReleaseFast.
more
Bracket the lifetime of pointers from getPtr and getOrPut,
and of an iterator over node memory, with this call. The counter
is not atomic, so this guard assumes one thread at a time like
everything else here.
It may be called several times, so independent borrowers can hold
the map at once; unlockPointers restores the previous state when
called as many times. This is the rule std.ArrayList states for
its own lockPointers.
pub fn unlockPointers(self: *Self) void
src
Undo one call to lockPointers.
Value stored for key, or null.
Pointer to the value stored for key, or null. Any insertion,
removal, or clearAndFree invalidates it; lockPointers turns
that into an assertion in Debug and ReleaseSafe instead.
Pointer to the value stored for key; when absent, inserts key
with an undefined value and reports found_existing = false. The
caller must initialize value_ptr in that case.
Insert key with value, replacing any existing value.
Insert key with value, returning the value replaced.
Remove key, returning whether it was present.
pub fn fetchRemove(self: *Self, gpa: Allocator, key: K) ?V
src
Remove key, returning the value it held.
pub fn clearAndFree(self: *Self, gpa: Allocator) void
src
Remove every entry and free every node.
Iterate entries in ascending key order.
pub fn iteratorFrom(self: *const Self, key: K, inclusive: bool) Iterator
src
Iterate entries from key upward. inclusive keeps an entry whose
key equals key; otherwise iteration starts after it. A key that
is not in the map starts at the next larger key. The iterator is
empty when key is greater than the map's largest stored key.
The smallest entry, or null.
The largest entry, or null.
Types
struct
Entry
src
Pointers to a stored key and value. An entry lives in a leaf, so
another leaf's churn does not move it, but any insertion or removal
in its own leaf does, and a split or a merge can free the leaf
outright. lockPointers turns those calls into an assertion while
the pointers are in use.
Fields
struct
GetOrPutResult
src
Result of getOrPut. When found_existing is false the key has
been written and the value is undefined until the caller sets it.
Fields
type fn
String
src
pub const String = map.String
An ordered map for []const u8 keys. Key memory is managed by the
caller, and must stay alive while the map holds it.
Fields
used: usize
Number of entries in the map.
root: ?Node
Root node, or null when the map is empty.
pointer_stability: stability.SafetyLock
Debug and ReleaseSafe only: while a borrow is outstanding, every call that can move or free an entry asserts instead.
lowest: ?K
Smallest key in the map, the outer fence of the left spine.
highest: ?K
Largest key in the map, the outer fence of the right spine.
context: Context
The ordering and inline-key hooks.
Constants
value
.{
.used = 0,
.root = null,
.pointer_stability = .init,
.shared_prefix = 0,
.lowest = null,
.highest = null,
.context = undefined,
}A map with no entries. The context is undefined, as in
std.PriorityQueue.empty; use initContext whenever the
comparator reads it.
value
.{
.used = 0,
.root = null,
.pointer_stability = .init,
.shared_prefix = 0,
.lowest = null,
.highest = null,
.context = .{},
}A map with no entries and a default-initialized context, for
stateless contexts such as Auto's and String's. Use
initContext when the comparator reads the context.
Functions
pub fn initContext(context: Context) Self
src
A map with no entries and the given context.
Number of entries in the map.
Whether the map has no entries.
pub fn lockPointers(self: *Self) void
src
Forbid entry invalidation until unlockPointers. While locked,
any call that can move or free a stored entry (every insertion,
removal, and clearAndFree) fails an assertion in Debug and
ReleaseSafe, and does nothing in ReleaseFast.
more
Bracket the lifetime of pointers from getPtr and getOrPut,
and of an iterator over node memory, with this call. The counter
is not atomic, so this guard assumes one thread at a time like
everything else here.
It may be called several times, so independent borrowers can hold
the map at once; unlockPointers restores the previous state when
called as many times. This is the rule std.ArrayList states for
its own lockPointers.
pub fn unlockPointers(self: *Self) void
src
Undo one call to lockPointers.
Value stored for key, or null.
Pointer to the value stored for key, or null. Any insertion,
removal, or clearAndFree invalidates it; lockPointers turns
that into an assertion in Debug and ReleaseSafe instead.
Pointer to the value stored for key; when absent, inserts key
with an undefined value and reports found_existing = false. The
caller must initialize value_ptr in that case.
Insert key with value, replacing any existing value.
Insert key with value, returning the value replaced.
Remove key, returning whether it was present.
pub fn fetchRemove(self: *Self, gpa: Allocator, key: K) ?V
src
Remove key, returning the value it held.
pub fn clearAndFree(self: *Self, gpa: Allocator) void
src
Remove every entry and free every node.
Iterate entries in ascending key order.
pub fn iteratorFrom(self: *const Self, key: K, inclusive: bool) Iterator
src
Iterate entries from key upward. inclusive keeps an entry whose
key equals key; otherwise iteration starts after it. A key that
is not in the map starts at the next larger key. The iterator is
empty when key is greater than the map's largest stored key.
The smallest entry, or null.
The largest entry, or null.
Types
struct
Entry
src
Pointers to a stored key and value. An entry lives in a leaf, so
another leaf's churn does not move it, but any insertion or removal
in its own leaf does, and a split or a merge can free the leaf
outright. lockPointers turns those calls into an assertion while
the pointers are in use.
Fields
struct
GetOrPutResult
src
Result of getOrPut. When found_existing is false the key has
been written and the value is undefined until the caller sets it.
Fields
type fn
AutoContext
src
pub const AutoContext = map.AutoContext
A Context for integer keys: numeric order, plus inline keys made of the
key's own big-endian bytes. Only integer types pass the compile-time
check: a float has no total order (NaN), and nothing else has a
big-endian encoding to compare.
Auto uses it. Reach for it directly to build a Custom map over a key
type that wraps an integer, and delegate compare, inlineKey, and
inline_width to it.
Constants
pub const inline_width: u16 = 2
src
Two bytes: with eight-byte keys, the first two already separate neighbours, and sixteen lanes then share one cache line with the node header.
Functions
pub fn encodedLen(_: Self, _: K) usize
src
The length of the key's encoding.
struct
BytesContext
src
pub const BytesContext = map.BytesContext
A Context for []const u8 keys: byte order, plus inline keys made of the
key's bytes. The one context that orders slices.
String uses it. Reach for it directly to build a Custom map over a key
that carries more than its bytes, and delegate compare, inlineKey,
compareFrom, and inline_width to it.
Constants
pub const inline_width: u16 = 4
src
Four bytes: byte strings share long prefixes and then differ late, so a two-byte window ties far more often than it saves in cache lines.
Functions
Compare eight bytes at a time as big-endian words instead of calling
memcmp: keys are short, and the call is not inlined.
pub fn compareFrom(_: BytesContext, a: []const u8, b: []const u8, offset: usize) Order
src
Compare past the bytes a window already showed equal. The empty
suffixes of two keys that both end before offset do not decide;
the map falls back to compare, which does.
pub fn encodedLen(_: BytesContext, key: []const u8) usize
src
The length of the key's encoding.
module
buffer
src
Fixed-capacity buffers over caller-owned or embedded storage.
Array(T, capacity) embeds its storage and Slice(T) borrows the
caller's; both append and share one API — the append/assume-capacity
pairs, remainingCapacity, clear. Queue(T) is the two-cursor form
over borrowed storage: elements enter at the tail, leave from the front,
and rebase compacts.
Types
type fn
Array
src
pub fn Array(comptime T: type, comptime buffer_capacity: comptime_int) type
Fixed-capacity buffer backed by an array.
Useful for building messages or accumulating bytes without heap allocation.
Fields
Constants
Functions
pub fn constSlice(self: *const Self) []align(align_bytes) const T
src
pub fn unusedCapacitySlice(self: *Self) []align(align_bytes) T
src
pub fn remainingCapacity(self: *const Self) Index
src
pub fn appendAssumeCapacity(self: *Self, item: T) void
src
pub fn appendSlice(self: *Self, items: []const T) error{NoSpaceLeft}!void
src
pub fn appendSliceAssumeCapacity(self: *Self, items: []const T) void
src
Return the element at index i of the slice.
Set the value of the element at index i of the slice.
The last item, removed; null when empty. Matches std.ArrayList.pop.
Set the length, e.g. after writing into the raw buffer or
unusedCapacitySlice() out of band.
more
Takes usize so callers never narrow before the check: the
Index parameter let resize(@intCast(n)) trap only where
@intCast traps — and in ReleaseFast not even there — and
it caught only values above Index's max, not above
capacity. The panic is the contract: it traps in every
mode. Use resizeUnchecked when the caller has proved the
bound.
pub fn resizeUnchecked(self: *Self, new_len: usize) void
src
resize without the panic check. Asserts
new_len <= capacity, so an overstep is undefined behavior in
ReleaseFast.
pub fn secureZero(self: *Self) void
src
Zero the full storage and reset.
pub fn secureClear(self: *Self) void
src
Zero the used span and reset. A full wipe for buffers whose
writes all land below len (append, set) and whose every reset
goes through here: nothing past len was written since the last
secureClear, so the used span is everything this buffer holds.
type fn
ArrayAligned
src
pub fn ArrayAligned(
comptime T: type,
comptime alignment: Alignment,
comptime buffer_capacity: comptime_int,
) type
A fixed-capacity Array with a caller-chosen alignment: over-
aligned SIMD storage, 128-bit types, anything .of(T) cannot
express from outside the module.
Fields
Constants
Functions
pub fn constSlice(self: *const Self) []align(align_bytes) const T
src
pub fn unusedCapacitySlice(self: *Self) []align(align_bytes) T
src
pub fn remainingCapacity(self: *const Self) Index
src
pub fn appendAssumeCapacity(self: *Self, item: T) void
src
pub fn appendSlice(self: *Self, items: []const T) error{NoSpaceLeft}!void
src
pub fn appendSliceAssumeCapacity(self: *Self, items: []const T) void
src
Return the element at index i of the slice.
Set the value of the element at index i of the slice.
The last item, removed; null when empty. Matches std.ArrayList.pop.
Set the length, e.g. after writing into the raw buffer or
unusedCapacitySlice() out of band.
more
Takes usize so callers never narrow before the check: the
Index parameter let resize(@intCast(n)) trap only where
@intCast traps — and in ReleaseFast not even there — and
it caught only values above Index's max, not above
capacity. The panic is the contract: it traps in every
mode. Use resizeUnchecked when the caller has proved the
bound.
pub fn resizeUnchecked(self: *Self, new_len: usize) void
src
resize without the panic check. Asserts
new_len <= capacity, so an overstep is undefined behavior in
ReleaseFast.
pub fn secureZero(self: *Self) void
src
Zero the full storage and reset.
pub fn secureClear(self: *Self) void
src
Zero the used span and reset. A full wipe for buffers whose
writes all land below len (append, set) and whose every reset
goes through here: nothing past len was written since the last
secureClear, so the used span is everything this buffer holds.
type fn
Slice
src
pub fn Slice(comptime T: type) type
A bounded append-only view over storage the caller owns.
Fields
Constants
Functions
pub fn constSlice(self: *const Self) []const T
src
pub fn unusedCapacitySlice(self: *Self) []T
src
pub fn remainingCapacity(self: *const Self) usize
src
pub fn appendAssumeCapacity(self: *Self, item: T) void
src
pub fn appendSlice(self: *Self, items: []const T) error{NoSpaceLeft}!void
src
pub fn appendSliceAssumeCapacity(self: *Self, items: []const T) void
src
pub fn retainFrom(self: *Self, items: []const T) error{NoSpaceLeft}!void
src
pub fn retainFromAssumeCapacity(self: *Self, items: []const T) void
src
retainFrom without the error return. Asserts
items.len <= capacity.
Set the length, e.g. after writing into the raw buffer out
of band. The panic is the contract: it traps in every mode.
See Array's resize. Use resizeUnchecked when the caller
has proved the bound.
pub fn resizeUnchecked(self: *Self, new_len: usize) void
src
resize without the panic check. Asserts
new_len <= capacity, so an overstep is undefined behavior in
ReleaseFast.
type fn
Queue
src
pub fn Queue(comptime T: type) type
A first-in first-out queue over caller-owned storage.
more
Elements enter at the tail and leave from the front. unusedCapacitySlice
is the free tail: write into it, then pass the count to advance.
buffered is the unconsumed front: read it, then pass the count to
toss. rebase moves the unconsumed elements to the front and is the
only method that moves them.
The names follow std.Io.Reader (buffered, bufferedLen, toss,
peek, take, rebase) and std.Io.Writer (unusedCapacitySlice,
unusedCapacityLen, advance). A queue has no source to refill from, so
peek and take panic on a short buffer instead of returning an error,
and rebase takes no capacity hint: the whole backing is the target.
Every bounds-checked cursor operation has an Unchecked form. It asserts
the same bound instead of panicking, so the check remains in Debug and
ReleaseSafe and compiles out in ReleaseFast, where an overstep is
undefined behavior.
Fields
buffer: []T
The full storage. seek <= end <= buffer.len at all times.
seek: usize
The first unconsumed element.
end: usize
One past the last written element.
Constants
Functions
Use buffer as the whole capacity. The queue starts empty.
True when nothing is buffered. Same as bufferedLen() == 0.
The unconsumed elements, contiguous. Invalidated by rebase.
pub fn constBuffered(self: *const Self) []const T
src
The const form of buffered.
pub fn bufferedLen(self: *const Self) usize
src
pub fn unusedCapacitySlice(self: *Self) []T
src
The free tail. Write into this slice, then call advance.
pub fn unusedCapacityLen(self: *const Self) usize
src
Commit n elements written into unusedCapacitySlice.
Panics when n exceeds the free tail. The check panics in every
build mode: a cursor past the storage is a slice panic later, or
an out-of-bounds write in ReleaseFast. Use advanceUnchecked
when the caller has already proved the bound.
pub fn advanceUnchecked(self: *Self, n: usize) void
src
advance without the panic check. Asserts
n <= unusedCapacityLen().
Drop n elements from the front.
Panics when n exceeds bufferedLen. Use tossUnchecked when
the caller has already proved the bound.
pub fn tossUnchecked(self: *Self, n: usize) void
src
toss without the panic check. Asserts n <= bufferedLen().
pub fn tossBuffered(self: *Self) void
src
Drop every unconsumed element. The tail stays where it is; call
rebase to make the whole backing writable again.
The next n unconsumed elements, without dropping them.
Panics when fewer than n are buffered. Check bufferedLen first
when the length comes from the input. Use peekUnchecked when the
caller has already proved the bound.
pub fn peekUnchecked(self: *Self, n: usize) []T
src
peek without the panic check. Asserts n <= bufferedLen().
The next n unconsumed elements, and drop them.
Panics when fewer than n are buffered. The returned slice is
invalidated by the next rebase. Use takeUnchecked when the
caller has already proved the bound.
pub fn takeUnchecked(self: *Self, n: usize) []T
src
take without the panic check. Asserts n <= bufferedLen().
Move the unconsumed elements to the front of the backing.
more
Invalidates every slice returned by buffered, constBuffered,
peek, and take; the move is a @memmove, so those slices can
overlap the destination. The whole backing is the target, so this
needs no capacity argument. A no-op when seek is already zero.
Reset both cursors. The backing bytes stay.
pub fn backingSlice(self: *Self) []T
src
The full backing, cursors ignored. Use it to hand raw storage to a subsystem that keeps its own offsets.
pub fn constBackingSlice(self: *const Self) []const T
src
The const form of backingSlice.
pub fn secureZero(self: *Self) void
src
Zero the whole backing and reset both cursors.
The whole backing, not the buffered span: consumed elements remain
before seek, and rebase leaves a stale copy of the unconsumed
elements in the range it moved from. Use this before releasing
storage that held secrets.
module
count_min
src
Fixed-capacity Count-Min Sketch (Cormode & Muthukrishnan, 2005):
approximate frequency counting in a flat [depth][width]Counter grid with
no allocator, no initialization failure, and saturating arithmetic so
counters never wrap around.
more
estimate never undercounts a key whose true frequency fits in Counter:
with probability at least 1 - delta, the estimate exceeds the true count
by at most epsilon * total_count. Both standard updates (add) and
conservative updates (addConservative, Estan & Varghese 2002) are
supported; conservative updates raise only the minimum counter(s) for a
key, which sharply reduces overestimation on skewed streams while keeping
the upper-bound invariant intact across non-negative merges. halve shifts
every counter right by one bit for sliding-window decay and TinyLFU cache
admission.
Sketch is the hash-level primitive driven directly by uniform 64-bit
hashes. Custom, Auto, and String layer key hashing on top using the
std.hash_map split and delegate every operation to Sketch.
Types
struct
Config
src
Comptime sizing and counter configuration for a Count-Min Sketch.
Fields
Counter: type = u32
Unsigned integer type stored in each cell (up to 64 bits).
depth: u32 = 4
Number of independent hash rows (>= 1).
width: u32 = 1024
Number of counters per row; must be a power of two (>= 1).
Functions
Derive depth and power-of-two width from the textbook error bounds
(epsilon, delta). Rounding width up to a power of two improves the
delivered Sketch.epsilon relative to the requested bound.
type fn
Auto
src
pub fn Auto(comptime T: type, comptime config: Config) type
A Count-Min Sketch that hashes keys with std.hash_map.AutoContext.
Slices — including []const u8 — are rejected by std.hash.autoHash;
string keys use String.
Fields
sketch: Raw
Underlying hash-level sketch.
Constants
Unsigned integer type stored in each cell.
Number of hash rows.
Number of counters per row (power of two).
Delivered additive error factor e / width.
Delivered failure probability bound exp(-depth).
An empty sketch with every counter at zero.
Functions
Add amount to key across all depth rows (saturating).
pub fn addConservative(self: *Self, key: T, amount: Counter) void
src
Conservatively add amount to key: raise each row's counter only
up to estimate(key) +| amount, reducing overestimation on skewed
streams.
Estimate the frequency of key. Never undercounts unless a counter
saturated or halve decayed past counts.
Total added weight since initialization or clear (saturating).
Add other's counters into self cell-by-cell (saturating).
Right-shift every counter and the total count by one bit for exponential aging / TinyLFU decay.
Reset every counter and the total count to zero.
type fn
String
src
pub fn String(comptime config: Config) type
A Count-Min Sketch for string keys ([]const u8), using
std.hash_map.StringContext. Key memory is managed by the caller.
Fields
sketch: Raw
Underlying hash-level sketch.
Constants
Unsigned integer type stored in each cell.
Number of hash rows.
Number of counters per row (power of two).
Delivered additive error factor e / width.
Delivered failure probability bound exp(-depth).
An empty sketch with every counter at zero.
Functions
Add amount to key across all depth rows (saturating).
pub fn addConservative(self: *Self, key: T, amount: Counter) void
src
Conservatively add amount to key: raise each row's counter only
up to estimate(key) +| amount, reducing overestimation on skewed
streams.
Estimate the frequency of key. Never undercounts unless a counter
saturated or halve decayed past counts.
Total added weight since initialization or clear (saturating).
Add other's counters into self cell-by-cell (saturating).
Right-shift every counter and the total count by one bit for exponential aging / TinyLFU decay.
Reset every counter and the total count to zero.
type fn
Custom
src
pub fn Custom(comptime T: type, comptime Context: type, comptime config: Config) type
A Count-Min Sketch over keys of type T, hashing through Context
(which must provide hash(Context, T) u64) and delegating all counter
operations to Sketch(config).
Fields
sketch: Raw
Underlying hash-level sketch.
Constants
Unsigned integer type stored in each cell.
Number of hash rows.
Number of counters per row (power of two).
Delivered additive error factor e / width.
Delivered failure probability bound exp(-depth).
An empty sketch with every counter at zero.
Functions
Add amount to key across all depth rows (saturating).
pub fn addConservative(self: *Self, key: T, amount: Counter) void
src
Conservatively add amount to key: raise each row's counter only
up to estimate(key) +| amount, reducing overestimation on skewed
streams.
Estimate the frequency of key. Never undercounts unless a counter
saturated or halve decayed past counts.
Total added weight since initialization or clear (saturating).
Add other's counters into self cell-by-cell (saturating).
Right-shift every counter and the total count by one bit for exponential aging / TinyLFU decay.
Reset every counter and the total count to zero.
type fn
Sketch
src
pub fn Sketch(comptime config: Config) type
The hash-level Count-Min Sketch primitive: a flat [depth][width]Counter
matrix driven directly by uniform 64-bit hashes.
Row column indices are sliced from disjoint log2(width)-bit fields of the
64-bit hash so rows remain independent even at small widths; if
depth * log2(width) > 64, a SplitMix64 refill supplies fresh bits.
Fields
Constants
Unsigned integer type stored in each cell.
Number of hash rows.
Number of counters per row (power of two).
Delivered additive error factor e / width.
Delivered failure probability bound exp(-depth).
value
.{
.rows = @splat(@splat(0)),
.total = 0,
}An empty sketch with every counter at zero.
Functions
Add amount to the counters selected by hash (saturating).
pub fn addHashConservative(self: *Self, hash: u64, amount: Counter) void
src
Conservatively add amount to the counters selected by hash:
raise each counter only to min_counter +| amount.
pub fn estimateHash(self: *const Self, hash: u64) Counter
src
Estimate the frequency associated with hash as the minimum across
all depth rows.
Total added weight since initialization or clear (saturating).
Fold other into self by saturating elementwise addition.
Halve every counter and the total count (integer shift right by 1).
Reset every counter and the total count to zero.
module
cuckoo
src
Fixed-capacity Cuckoo filters (Fan, Andersen, Kaminsky, and Mitzenmacher, CoNEXT 2014): approximate set membership with deletion, stored in a flat table of 4-slot fingerprint buckets with no allocator and SIMD-accelerated bucket probes.
more
Each key hashes to a nonzero fingerprint and two candidate buckets i1 and
i2 = i1 ^ delta(fp). Because XOR is its own inverse, a fingerprint can be
relocated between its two buckets without storing the original key, and
remove deletes a key's fingerprint from either bucket. When both buckets
are full, add performs up to max_kicks random relocations; if the table
is too full to settle, add rolls back every relocation so the filter is
unchanged and returns error.FilterFull.
Contract: contains never returns false for a key that was added and not
removed. remove is only valid for keys currently present in the filter:
removing an absent key can delete a colliding key's fingerprint and cause a
false negative. Duplicate adds store duplicate fingerprints (up to 8 copies
across the two buckets).
Filter is the hash-level primitive driven directly by uniform 64-bit
hashes. Custom, Auto, and String layer key hashing on top using the
std.hash_map split and delegate every bucket operation to Filter.
Constants
value
error{
/// Relocation exhausted `max_kicks` without finding an empty slot. The
/// filter state is rolled back unchanged.
FilterFull,
}Errors returned when inserting into a Cuckoo filter.
Types
struct
Config
src
Comptime sizing and fingerprint configuration for a Cuckoo filter.
Fields
buckets: u32 = 256
Number of 4-slot buckets; must be a power of two (>= 1).
Fingerprint: type = u16
Byte-aligned unsigned fingerprint type: u8 (~3.1% max FPR), u16
(~0.012% max FPR), or u32 (~1.9e-9 max FPR).
max_kicks: u32 = 500
Maximum fingerprint relocations attempted before rolling back and
returning error.FilterFull.
Functions
pub fn fromCapacity(
comptime capacity: comptime_int,
comptime target_rate: comptime_float,
) Config
src
Derive a configuration sized to hold at least capacity items (at a
<= 90% design load factor) with a full-load false-positive rate at or
below target_rate.
type fn
Auto
src
pub fn Auto(comptime T: type, comptime config: Config) type
A Cuckoo filter that hashes keys with std.hash_map.AutoContext.
Slices — including []const u8 — are rejected by std.hash.autoHash;
string keys use String.
Fields
filter: Raw
Underlying hash-level filter.
Constants
pub const Fingerprint = Raw.Fingerprint
src
Fingerprint integer type stored in each slot.
pub const bucket_count: u32 = Raw.bucket_count
src
Number of 4-slot buckets (power of two).
pub const slot_count: u64 = Raw.slot_count
src
Total fingerprint slots (4 * bucket_count).
Maximum relocation steps before add rolls back and returns error.FilterFull.
pub const max_false_positive_rate: f64 = Raw.max_false_positive_rate
src
Worst-case false-positive rate at full load (8 / (2^bits - 1)).
An empty filter with no stored fingerprints.
Functions
Add key to the filter. Returns error.FilterFull without
modifying the filter if relocation cannot find a free slot.
Whether key may be in the filter. Never returns false for a key
that was added and not removed.
Remove one copy of key's fingerprint. Returns true if a matching
fingerprint was removed, false otherwise. Only call for keys that
were previously added; removing an absent key can evict a colliding
key's fingerprint.
Number of fingerprints currently stored in the filter.
pub fn loadFactor(self: *const Self) f64
src
Fraction of slots currently occupied (count() / slot_count).
Remove every fingerprint and reset count to zero.
type fn
String
src
pub fn String(comptime config: Config) type
A Cuckoo filter for string keys ([]const u8), using
std.hash_map.StringContext. Key memory is managed by the caller.
Fields
filter: Raw
Underlying hash-level filter.
Constants
pub const Fingerprint = Raw.Fingerprint
src
Fingerprint integer type stored in each slot.
pub const bucket_count: u32 = Raw.bucket_count
src
Number of 4-slot buckets (power of two).
pub const slot_count: u64 = Raw.slot_count
src
Total fingerprint slots (4 * bucket_count).
Maximum relocation steps before add rolls back and returns error.FilterFull.
pub const max_false_positive_rate: f64 = Raw.max_false_positive_rate
src
Worst-case false-positive rate at full load (8 / (2^bits - 1)).
An empty filter with no stored fingerprints.
Functions
Add key to the filter. Returns error.FilterFull without
modifying the filter if relocation cannot find a free slot.
Whether key may be in the filter. Never returns false for a key
that was added and not removed.
Remove one copy of key's fingerprint. Returns true if a matching
fingerprint was removed, false otherwise. Only call for keys that
were previously added; removing an absent key can evict a colliding
key's fingerprint.
Number of fingerprints currently stored in the filter.
pub fn loadFactor(self: *const Self) f64
src
Fraction of slots currently occupied (count() / slot_count).
Remove every fingerprint and reset count to zero.
type fn
Custom
src
pub fn Custom(comptime T: type, comptime Context: type, comptime config: Config) type
A Cuckoo filter over keys of type T, hashing through Context (which must
provide hash(Context, T) u64) and delegating all bucket operations to
Filter(config).
Fields
filter: Raw
Underlying hash-level filter.
Constants
pub const Fingerprint = Raw.Fingerprint
src
Fingerprint integer type stored in each slot.
pub const bucket_count: u32 = Raw.bucket_count
src
Number of 4-slot buckets (power of two).
pub const slot_count: u64 = Raw.slot_count
src
Total fingerprint slots (4 * bucket_count).
Maximum relocation steps before add rolls back and returns error.FilterFull.
pub const max_false_positive_rate: f64 = Raw.max_false_positive_rate
src
Worst-case false-positive rate at full load (8 / (2^bits - 1)).
An empty filter with no stored fingerprints.
Functions
Add key to the filter. Returns error.FilterFull without
modifying the filter if relocation cannot find a free slot.
Whether key may be in the filter. Never returns false for a key
that was added and not removed.
Remove one copy of key's fingerprint. Returns true if a matching
fingerprint was removed, false otherwise. Only call for keys that
were previously added; removing an absent key can evict a colliding
key's fingerprint.
Number of fingerprints currently stored in the filter.
pub fn loadFactor(self: *const Self) f64
src
Fraction of slots currently occupied (count() / slot_count).
Remove every fingerprint and reset count to zero.
type fn
Filter
src
pub fn Filter(comptime config: Config) type
The hash-level Cuckoo filter primitive: a flat array of 4-slot fingerprint buckets driven directly by uniform 64-bit hashes.
Fields
Constants
pub const Fingerprint = config.Fingerprint
src
Fingerprint integer type stored in each slot (0 marks an empty slot).
pub const bucket_count: u32 = config.buckets
src
Number of 4-slot buckets (power of two).
pub const slot_count: u64 = @as(u64, bucket_count) * 4
src
Total fingerprint slots (4 * bucket_count).
Maximum relocation steps before addHash rolls back and returns error.FilterFull.
pub const max_false_positive_rate: f64 =
8.0 / @as(f64, @floatFromInt(math.maxInt(Fingerprint)))
src
Worst-case false-positive rate at full load (8 / (2^bits - 1)).
value
.{
.buckets = @splat(@splat(0)),
.len = 0,
.rng_state = initial_seed,
}An empty filter with no stored fingerprints.
Functions
Insert a uniform 64-bit hash into the filter. Returns
error.FilterFull without modifying the filter if relocation
exhausts max_kicks.
pub fn containsHash(self: *const Self, hash: u64) bool
src
Whether hash may be in the filter.
pub fn removeHash(self: *Self, hash: u64) bool
src
Remove one copy of hash's fingerprint. Returns true if removed.
Number of fingerprints currently stored in the filter.
pub fn loadFactor(self: *const Self) f64
src
Fraction of slots currently occupied (count() / slot_count).
Remove every fingerprint and reset count to zero.
module
dotenv
src
.env file parsing: KEY=VALUE lines, quotes, and comments.
more
std has no parser for this format, and every project that reads one writes its own trimming, comment, and quoting rules. A loader that quietly disagrees with the file it was given resolves an empty value or a stale key, and the mistake shows up as a wrong port, not as an error. This parser implements one grammar and names the line that does not fit:
- One assignment per line. A line ends at
\nor at the end of the source, and a\rimmediately before either belongs to the terminator, so a CRLF file parses like an LF file. The source may start with a UTF-8 BOM. - Leading spaces and tabs are skipped. A line whose first other byte is
#is a comment. A line of nothing but spaces and tabs is blank. exportfollowed by a space or a tab before the key is ignored. The key matches[A-Za-z_][A-Za-z0-9_]*; anything else iserror.InvalidKey. A line with no=iserror.MissingEquals.- Spaces and tabs around
=, and after an unquoted value, are trimmed. - An unquoted value runs to the end of the line. A
#preceded by a space or a tab begins a comment; any other#is part of the value, soPASSWORD=#secretkeeps its#. - A single-quoted value is literal up to the next
'. No escape is interpreted. - A double-quoted value accepts
\n,\r,\t,\\,\", and\$. Any other escape iserror.InvalidEscape. Both quoted forms may span lines, and inside them every byte is taken as written, CRLF included. - A quoted value may be followed by spaces, a tab, and a comment on the
same line. Anything else is
error.TrailingCharacters.
Duplicate keys are kept in order, and Doc.get returns the last one;
nothing here decides which assignment the caller believes. Nothing expands
a variable either: expansion needs an environment, which belongs to the
caller, not to the file. $VAR stays four bytes.
The parse allocates nothing. A key or a value is a slice of the caller's
source, or of a caller-owned scratch buffer when a double-quoted escape
needs decoding. The entry list is a caller-owned array. A file larger than
either reports error.EntriesFull or error.ScratchFull rather than
growing.
Constants
value
error{
/// A line is neither blank, a comment, nor an assignment.
MissingEquals,
/// The key is empty or holds a byte outside `[A-Za-z_][A-Za-z0-9_]*`.
InvalidKey,
/// A backslash in a double-quoted value is followed by a byte outside
/// `n`, `r`, `t`, `\`, `"`, and `$`.
InvalidEscape,
/// A quoted value reaches the end of the source with no closing quote.
UnterminatedQuote,
/// A quoted value is followed by a byte other than a blank, a comment, or
/// the line terminator.
TrailingCharacters,
/// The caller's entry array is full.
EntriesFull,
/// The caller's scratch buffer is full.
ScratchFull,
}Why a parse stopped.
Functions
pub fn parse(
source: []const u8,
entries: []Entry,
scratch: []u8,
options: ParseOptions,
) Error!Doc
src
Parse source into entries, with the decoded bytes of double-quoted
escapes going into scratch.
more
scratch holds one byte per decoded escape and is empty for a source with
no escaped value. A source of n bytes never needs more than n bytes of
scratch: a decoded value is never longer than the text it came from, and
the values it holds are disjoint. The contract matches sort.radix, whose
scratch is also the caller's.
Nothing is allocated and nothing is copied except an escaped value. Keys,
unquoted values, and quoted values without escapes point into source;
an escaped value points into scratch. The returned Doc is a window
into entries. All three outlive the Doc, and none of them may move
while it is in use.
A capacity that is too small is an error, not a panic:
error.EntriesFull when the file holds more assignments than entries,
and error.ScratchFull when the escapes decode to more bytes than
scratch holds. A caller that does not know the count allocates
entries from an arena and retries on error.EntriesFull.
A failure returns one of Error. Set options.diagnostics to a
Diagnostics value to receive the position of the byte that stopped the
parse. Nothing is copied: the parser writes into that value directly, and
it stays untouched when the parse succeeds.
The bytes of 1-based line, without the line terminator and without the
BOM that line 1 may start with. The result is empty when line is past
the last line. Use it to show the diagnostics for a failed parse beside
the text that caused them.
Types
struct
Diagnostics
src
Where a parse stopped, and why. parse fills every field before it
returns the error, and writes nothing at all when the parse succeeds.
Fields
offset: usize
Byte offset into the original source. For EntriesFull this is the
start of the entry that did not fit; for ScratchFull it is the
escape whose decoded byte did not fit.
line: u32
The 1-based line of offset, counted on the original bytes.
column: u32
The 1-based column of offset, counted in bytes from the last newline
before it. On the first line a UTF-8 BOM counts like any other byte,
the way std.json.Diagnostics.getColumn counts it.
problem: Error
The failure.
Functions
The problem in a few words, for a log line.
struct
ParseOptions
src
Options for parse.
Fields
diagnostics: ?*Diagnostics = null
Filled on a failed parse. Untouched when the parse succeeds.
struct
Doc
src
A parsed source: every entry in file order, duplicates included.
Fields
entries: []const Entry
The entries in file order. A repeated key appears once per assignment.
Functions
The value of the last entry for key, or null. The scan runs
backwards, so the last assignment to a key wins. This is linear in the
entry count, which for a configuration file is tens of entries.
module
enums
src
Enum utilities beyond std.enums: turn a comptime list of byte
strings into an enum whose tags are the strings, and look up the tag
with the string length checked first.
more
Open generates a non-exhaustive enum. The miss is an unnamed value, so
else is the miss arm and no tag name is reserved:
const Modes = enums.Open(.{ "transaction", "session", "statement" });
switch (Modes.match(value)) {
.transaction => startTransaction(),
.session => startSession(),
.statement => runStatement(),
else => return error.InvalidMode,
}
Closed takes the name of a fallback tag and generates an exhaustive
enum. The compiler then checks that every tag has an arm:
const Modes = enums.Closed(.{ "transaction", "session", "statement" }, "other");
switch (Modes.match(value)) {
.transaction => startTransaction(),
.session => startSession(),
.statement => runStatement(),
.other => return error.InvalidMode,
}
The lookup compares bytes exactly, not text. A tag is any non-empty
byte string without a null byte, so "content-type" is the tag
.@"content-type". For keys that cannot be tag names, use
static_map.String or std.StaticStringMap.
stringToEnum is std.meta.stringToEnum for an existing enum, with
fixed-length loads.
Functions
pub fn stringToEnum(comptime E: type, value: []const u8) ?E
src
The enum value for value, or null. The contract of
std.meta.stringToEnum, with fixed-length loads.
Types
type fn
Open
src
pub fn Open(comptime names: anytype) type
A non-exhaustive enum generated from names, plus the lookup.
names is a tuple of byte strings. Each becomes a tag with the same
name. match returns the tag, or miss when the value is not one of
them.
Constants
value
blk: {
const IntTag = math.IntFittingRange(0, names.len);
var name_array: [names.len][]const u8 = undefined;
var value_array: [names.len]IntTag = undefined;
for (names, 0..) |name, i| {
name_array[i] = name;
value_array[i] = @intCast(i);
}
const final_names = name_array;
const final_values = value_array;
break :blk @Enum(IntTag, .nonexhaustive, &final_names, &final_values);
}The generated enum: one tag per name, plus the unnamed miss value.
The value match returns for bytes that are not a name.
value
keys: {
var arr: [names.len][]const u8 = undefined;
for (names, 0..) |name, i| arr[i] = name;
const final = arr;
break :keys &final;
}The names, in the order of the literal.
The number of names.
Functions
The tag for value, or miss.
Whether value is one of the names.
type fn
Closed
src
pub fn Closed(comptime names: anytype, comptime fallback: []const u8) type
An exhaustive enum generated from names, plus fallback as the tag for
a value that matches no name.
The switch over match must name every tag, fallback included.
Constants
value
blk: {
const total = names.len + 1;
const IntTag = math.IntFittingRange(0, total - 1);
var name_array: [total][]const u8 = undefined;
var value_array: [total]IntTag = undefined;
for (names, 0..) |name, i| {
name_array[i] = name;
value_array[i] = @intCast(i);
}
name_array[names.len] = fallback;
value_array[names.len] = @intCast(names.len);
const final_names = name_array;
const final_values = value_array;
break :blk @Enum(IntTag, .exhaustive, &final_names, &final_values);
}The generated enum: one tag per name, plus fallback.
The tag match returns for bytes that are not a name.
value
keys: {
var arr: [names.len][]const u8 = undefined;
for (names, 0..) |name, i| arr[i] = name;
const final = arr;
break :keys &final;
}The names, in the order of the literal, without the fallback.
The number of names, without the fallback.
Functions
The tag for value, or miss.
Whether value is one of the names.
module
fmt
src
Format extensions to std.fmt.
Strict decode and parse helpers where std.fmt is liberal: one integer
grammar, Go's boolean spellings, no bases, no underscores. Bad comptime
literals are compile errors, not runtime ones.
Functions
atoiWith with default options: overflow returns error.Overflow, and
leading zeros are allowed.
pub inline fn atoiUnchecked(comptime T: type, buf: []const u8) Error(.unchecked)!T
src
atoiWith with .{ .overflow = .unchecked }: the caller guarantees the
value fits T. The accumulation loop is identical to atoi — with SWAR
there is nothing left to skip in the loop; only the final validation and
cast differ. Cannot return error.Overflow; error.InvalidCharacter
still applies.
pub fn atoiWith(
comptime T: type,
buf: []const u8,
comptime options: Options,
) Error(options.overflow)!T
src
Parse buf as a base-10 integer of type T with explicit options.
more
Every byte of buf must belong to the number ("1234x" is an error, not
1234). A signed T accepts an optional leading + or - and parses
-0 as 0, unless Options rejects either form; an unsigned T accepts
digits only, like std.fmt.parseUnsigned. atoi never skips whitespace.
With .{ .overflow = .unchecked } the caller asserts the value fits T;
see Overflow.unchecked for the exact contract.
Comptime adds no checking of its own. With .checked the digit-count
validation runs as usual; with .unchecked it does not, and only Zig's
own comptime rules reject a value — @intCast for narrow types, the
arithmetic for wider ones. A u64 or i64 magnitude that wraps and lands
in range is returned, at comptime exactly as at runtime.
pub inline fn comptimeHex(comptime encoded: []const u8) [encoded.len / 2]u8
src
Decode the comptime hex literal encoded. The output length is half the
literal's length; a bad literal is a compile error.
Parse a boolean with the spellings of Go's strconv.ParseBool: 1, t,
T, TRUE, true, True, and the same set for false. Returns null for
anything else.
module
hash
src
Hash extensions to std.hash.
more
RapidHash is a port of rapidhash V3: a 64-bit non-cryptographic hash
that takes an explicit seed, like std.hash.Wyhash.hash. Its output
reproduces upstream's reference values on every host. Upstream and
license are in THIRD_PARTY.md.
crc32c is CRC-32C (Castagnoli), where the digest itself is the state:
hash for one buffer, and append(digest, more) to continue from a
stored one. The polynomial is not std.hash.Crc32's IEEE one, and
std.hash.crc.@"CRC-32/ISCSI"'s crc field is a digest only on some
targets. The kernels are SSE4.2 on x86-64, ARMv8's crc32c on aarch64,
and slice-by-16 tables elsewhere.
Types
module
RapidHash
src
Rapidhash V3: a fast 64-bit non-cryptographic hash, and the explicit-seed
drop-in for std.hash.Wyhash.hash. Every read is unaligned
little-endian, so the output is independent of the host and reproduces
upstream's values.
more
Three variants differ in how much memory-level parallelism the bulk loop
exposes: hash runs seven lanes over 112-byte blocks, hashMicro five
over 80, hashNano three over 48. A narrower variant returns exactly
what hash returns while the input fits its block size — up to 80 bytes
for micro, 48 for nano — so a caller trades bulk throughput for code size
without changing short-key hashes.
The seed is explicit, like std.hash.Wyhash.hash. Upstream's no-seed
entry points use seed 0; pass 0 for that behavior. No seeded-by-default
convenience is provided.
Functions
Hash input with seed: the 7-lane general variant, a drop-in for
std.hash.Wyhash.hash with the same explicit-seed signature.
Hash input with seed using the 5-lane variant. Returns exactly what
hash returns for inputs up to 80 bytes; beyond that the bulk loop
starts and the value diverges from hash.
Hash input with seed using the 3-lane variant. Returns exactly what
hash returns for inputs up to 48 bytes; beyond that the bulk loop
starts and the value diverges from hash.
Types
struct
StringContext
src
The string-keyed context, std.hash_map.StringContext's shape: one
rapidhash call per key, hashing the bytes of the string. Key memory is
managed by the caller.
Functions
type fn
AutoContext
src
pub fn AutoContext(comptime T: type) type
The auto-keyed context, std.hash_map.AutoContext's shape. The key
is walked by std.hash.autoHash, which normalizes as it goes — bool as
0/1, enums as tags, signed as unsigned, narrow ints trimmed, structs
field-by-field so padding never enters the stream — and every chunk
seed-chains through rapidhash. Unique-representation keys walk to a
single chunk, so they are exactly one one-shot call; everything else
pays one call per chunk. Slices are rejected, exactly as std's
AutoContext rejects them: hash string contents with StringContext.
Functions
module
crc32c
src
CRC-32C, the Castagnoli checksum: hash for one buffer, and append to
continue a digest that is already stored.
more
Castagnoli's polynomial is not IEEE 802.3's, the one std.hash.Crc32
computes. The reflected forms are 0x82F63B78 against 0xEDB88320, and the
check value of "123456789" separates them: 0xE306_9283 here,
0xCBF4_3926 there. Castagnoli is the one the hardware implements, since
SSE4.2's crc32 and ARMv8's crc32c are one instruction per eight bytes,
so the formats that checksum in bulk store it: iSCSI (RFC 3720), ext4,
btrfs, and the LevelDB family.
append takes a finalized digest and returns one. A stored checksum seeds
the next fragment, and a chain of append calls equals one hash over the
concatenation. 0 starts a chain, and append(digest, "") is digest, so
a writer that appends empty fragments stays correct. No type holds state:
the digest is the whole of it, which is what a persisted field stores.
std.hash.crc.@"CRC-32/ISCSI" is the same checksum with the opposite
convention. Its crc field holds the finalized digest in the SSE4.2
kernel and the raw running state in the generic one, so a stored value
means different things on different targets: a digest that continues a
chain through one kernel does not through the other. Nothing but a digest
crosses this module's API, so append(hash(a), b) is hash(a ++ b)
everywhere.
The kernel comes from the target CPU at compile time: SSE4.2 on x86-64,
the ARMv8 CRC instructions on aarch64, slice-by-16 tables elsewhere. Both
instruction kernels run three independent chains, one per cycle of the
instruction's latency, and combine them with a table operator. There is no
run-time dispatch: a baseline build gets the table kernel, and
-Dcpu=... decides.
Functions
The CRC-32C digest of bytes.
The CRC-32C digest of bytes, continued from the digest previous.
previous is 0 for the first fragment of a message. append(digest, "") returns digest unchanged, so an empty fragment costs nothing and
changes nothing.
module
heap
src
Heap extensions to std.heap.
Allocator shapes std lacks: fixed-capacity pooling without a retained allocator, and a single-threaded bump arena.
Types
type fn
Bump
src
pub const Bump = @import("heap/bump.zig").Bump
Returns a bump arena type. The chunk sizes are part of the type, so an instance carries no configuration and the growth policy is constant.
Fields
child_allocator: Allocator
state: State
Functions
Creates an empty arena. No memory is allocated until the first request.
The Allocator face. A request above max_chunk is served by a
dedicated chunk, so allocation fails only when the child allocator
fails. The returned value points at self: do not move the arena
while a derived allocator is in use.
Releases every chunk. The arena must not be used afterwards;
reset is the way to empty an arena that stays alive.
Empties the arena. retain_capacity is the cheap reset for a loop
that parses or evaluates one job per round; free_all hands the
memory back and is what deinit does.
Types
struct
State
src
The chunk list without the allocator. The configuration is part of
the type, so a state is two pointers. Promote it to allocate, and
copy bump.state back afterward.
Fields
chunks: ?*Chunk
The head of the chunk list, in allocation order.
current: ?*Chunk
The chunk the next allocation tries first.
Constants
Functions
Wraps a stored state in a usable arena. The chunks themselves are shared; the head and the cursor are copied, so write the result back before the promoted value goes out of scope:
more
var arena = self.arena.promote(gpa);
defer self.arena = arena.state;
enum
ResetMode
src
The two ways to empty the arena. retain_capacity keeps every
chunk and refills them in order; free_all returns them to the
child allocator.
Fields
free_all free_all
retain_capacity retain_capacity
type fn
SizeClassPool
src
pub const SizeClassPool = @import("heap/size_class_pool.zig").SizeClassPool
A pool of byte blocks over caller-owned storage.
more
The classes are a strictly increasing list of positive sizes. A request
uses the first class large enough, so create(17) takes the 64-byte class
in &.{ 16, 64 }. live_bytes counts the requested lengths;
live_class_bytes counts the class sizes, which is what the backing
actually holds.
Fields
backing: []u8
fixed: heap.FixedBufferAllocator
pools: Pools
live_bytes: usize
Requested bytes currently live.
live_class_bytes: usize
Class bytes currently assigned to live blocks.
Constants
The class sizes, as usize, for a caller that sizes a backing.
Functions
Use backing as the whole storage. Every class and its metadata
comes from it; nothing else is allocated.
Assert that every block was destroyed, then reset the pool. The backing stays with the caller and can be reused.
The check is a std.debug.assert: it runs in Debug and ReleaseSafe
and compiles out in ReleaseFast.
Create a block of size bytes from the first class that fits.
Returns error.OutOfMemory when the class pool has no room or the
size is above the largest class. A failed create changes neither
counter. size must be nonzero.
Return a block from create to its class pool.
Pass the slice from create unchanged: its length selects the
class. The block's memory stays with the pool for reuse by that
class.
type fn
SlabAllocator
src
pub const SlabAllocator = slab_allocator.SlabAllocator
Generates a slab allocator for the configured size classes.
queryCapacity reports pooled arena capacity and excludes fallback allocations.
Fields
pools: Pools
live_counts: LiveCounts
Constants
Functions
Allocates a nonzero number of bytes or panics on allocator exhaustion.
Frees the original pointer using the same nonzero size passed to alloc.
pub fn queryCapacity(self: *const Self, gpa: Allocator) usize
src
module
intern
src
One copy of each distinct string, one u32 id per string.
more
A compiler, an evaluator, or a config loader reads the same handful of names thousands of times: field names, environment keys, option names. Interning copies each name once and turns every later comparison into an integer compare.
Bytes live in chunks. A name is copied into the tail of the current chunk,
and a name that does not fit gets a new chunk, so an intern allocates only
when a chunk fills instead of once per name. One table holds a slice per id
for an O(1) get; the map the pool is built on holds the same slices as
keys, hashed with std.hash_map.StringContext.
The pool is unmanaged: the allocator is a parameter of intern and
deinit. An instance is a plain value with no hidden child pointer, so a
static or comptime instance costs only its fields.
There is no deletion and no thread safety. An id stays valid until
deinit.
Constants
What intern can fail with: allocation, and nothing else.
Types
struct
Pool
src
A string pool with stable ids.
Ids are dense: the first intern is 0 and each new string takes the next integer. Interning bytes that are already present returns the id of the stored copy, so two callers that intern equal bytes get the same id.
Fields
chunks: std.ArrayList(Chunk)
Every chunk, in allocation order.
current: ?usize
Index of the chunk that takes the next copy, or null before the first intern.
names: std.ArrayList([]const u8)
The stored bytes, indexed by id.
ids: swiss.String(u32)
The stored bytes to id. The keys are the slices in names.
Constants
pub const chunk_size: usize = 4096
src
Payload bytes in one chunk. A longer name gets a chunk of its own.
value
.{
.chunks = .empty,
.current = null,
.names = .empty,
.ids = .init,
}A pool holding nothing.
Functions
The id of bytes, copying the bytes into the pool on the first call.
Returns the existing id when the bytes are already present. The copy is
written before either table is published, so error.OutOfMemory leaves
the pool consistent; it may hold unused chunk space.
The bytes for id. Asserts id is one this pool handed out.
The id of bytes without inserting it.
The number of distinct strings interned.
Release every chunk and both tables. The pool is undefined afterward.
module
jsonc
src
JSON with comments, for configuration files.
more
JSONC is RFC 8259 JSON plus // and /* */ comments and a trailing comma
before } or ]. This module does not parse JSON. It copies the source,
blanks every comment byte and trailing comma to a space, and hands the copy
to std.json, so std owns every JSON rule and every JSON error.
The copy has the same length as the source and every byte keeps its offset.
A std.json.Diagnostics read from the copy reports the line and column of
the same byte in the caller's input.
A UTF-8 BOM at offset 0 is blanked. That is the one leniency beyond
comments and trailing commas. JSON5 needs a real parser and stays out:
single quotes, unquoted keys, hex numbers, NaN, Infinity, and a leading
or trailing decimal point.
Constants
value
error{
/// A `/*` with no closing `*/`. `scrubWithDiagnostics` and
/// `scrubInPlaceWithDiagnostics` report the position in `Diagnostics`.
UnterminatedBlockComment,
}Failures of the scrubber itself. Every JSON failure comes from std.json
after the scrub, not from here.
pub const ParseError = Error || json.ParseError(json.Scanner)
src
The errors of parseFromSlice: a scrub failure, or any error that
std.json reports for the copy.
Functions
pub fn scrub(
allocator: Allocator,
source: []const u8,
options: Options,
) (Error || Allocator.Error)!Scrubbed
src
Copy source into a new buffer and blank its comments and trailing commas
to spaces. The copy has the same length as source, and a UTF-8 BOM at
offset 0 is blanked too.
For the position of an error.UnterminatedBlockComment, use
scrubWithDiagnostics.
pub fn scrubWithDiagnostics(
allocator: Allocator,
source: []const u8,
options: Options,
diagnostics: *Diagnostics,
) (Error || Allocator.Error)!Scrubbed
src
scrub, with the position of a failure written to diagnostics.
pub fn scrubInPlace(buffer: []u8, options: Options) Error!void
src
Blank the comments, the trailing commas, and a UTF-8 BOM at offset 0 in
buffer without allocating.
The buffer is the caller's source and is modified in place. On
error.UnterminatedBlockComment, bytes before the opening /* may already
be blanked.
pub fn scrubInPlaceWithDiagnostics(
buffer: []u8,
options: Options,
diagnostics: *Diagnostics,
) Error!void
src
scrubInPlace, with the position of a failure written to diagnostics.
pub fn parseFromSlice(
comptime T: type,
allocator: Allocator,
source: []const u8,
options: Options,
parse_options: json.ParseOptions,
) ParseError!Parsed(T)
src
Parse source as JSONC into T. std.json does the parse.
The returned value owns the scrubbed copy, so a string in value stays
valid until deinit. parse_options passes to std.json unchanged.
Types
struct
Diagnostics
src
The position of a scrub failure, in the caller's source.
Fields
offset: usize
Byte offset of the opening /*.
line: usize
1-based line at offset.
column: usize
1-based column at offset.
Constants
The state before any scrub runs: offset 0, line 1, column 1.
struct
Options
src
What the scrub accepts beyond JSON.
Fields
comments: bool = true
Accept // and /* */ comments. When false, a comment byte reaches
std.json unchanged and fails there.
trailing_commas: bool = true
Accept a comma that follows a value and precedes } or ]. When
false, the comma reaches std.json unchanged and fails there.
type fn
Parsed
src
pub fn Parsed(comptime T: type) type
The result of parseFromSlice. It owns the parsed allocations and the
scrubbed copy, and a string in value can point into either.
Fields
value: T
The parsed value.
parsed: json.Parsed(T)
The std.json result, which owns the parsed allocations.
scrubbed: Scrubbed
The copy that value may point into.
Functions
Free the parsed allocations and the copy.
module
lru
src
A fixed-capacity least-recently-used cache.
more
String(V, capacity) and Auto(K, V, capacity) store up to capacity
entries with no allocator. get moves a hit to the front; put evicts the
least-recently-used entry when a new key arrives at capacity.
The index is a bounded_array_hash_map from key to node handle. The nodes
live in one slot.Array, whose intrusive doubly linked list orders them from
most to least recently used; the links are slot.Handles, not pointers.
get only relinks, so a hit is constant time and no entry data moves.
A value pointer from get or peek keeps its address for the cache's
lifetime. Once its entry is removed, a later put can reuse the node, so
the old pointer then refers to the new value.
Eviction is the caller's job to clean up. put returns the displaced
entry, either the old value for an existing key or the entry evicted for a
new one. popLru and popMru return a whole entry. There is no eviction
callback: a callback could reenter the cache while it is mid-update.
Types
type fn
Custom
src
pub fn Custom(
comptime K: type,
comptime V: type,
comptime Context: type,
buffer_capacity: comptime_int,
) type
A bounded LRU with Custom's hash context.
Fields
Constants
A cache with no entries and a default-initialized context, for
stateless contexts such as Auto's and String's. Use
initContext when the context carries state.
Functions
pub fn initContext(context: Context) Self
src
A cache with no entries and the given context.
Number of cached entries.
Whether key is cached. Does not change recency.
The value for key, moved to the most-recently-used position.
The value for key, without changing recency.
Insert or update key. An update moves the entry to the front and
returns the old value in replaced. A new key at capacity evicts
the tail and returns it in evicted.
Remove key and return its value.
Remove and return the least-recently-used entry.
Remove and return the most-recently-used entry.
Drop every entry, keeping the storage. The values are not returned;
drain with the iterator first when V owns resources.
An iterator from most to least recently used. Modify the cache
during iteration only through the returned value pointers: get,
put, remove, and clear invalidate the iterator.
Types
type fn
Auto
src
pub fn Auto(comptime K: type, comptime V: type, buffer_capacity: comptime_int) type
Fields
Constants
A cache with no entries and a default-initialized context, for
stateless contexts such as Auto's and String's. Use
initContext when the context carries state.
Functions
pub fn initContext(context: Context) Self
src
A cache with no entries and the given context.
Number of cached entries.
Whether key is cached. Does not change recency.
The value for key, moved to the most-recently-used position.
The value for key, without changing recency.
Insert or update key. An update moves the entry to the front and
returns the old value in replaced. A new key at capacity evicts
the tail and returns it in evicted.
Remove key and return its value.
Remove and return the least-recently-used entry.
Remove and return the most-recently-used entry.
Drop every entry, keeping the storage. The values are not returned;
drain with the iterator first when V owns resources.
An iterator from most to least recently used. Modify the cache
during iteration only through the returned value pointers: get,
put, remove, and clear invalidate the iterator.
Types
type fn
String
src
pub fn String(comptime V: type, buffer_capacity: comptime_int) type
Fields
Constants
A cache with no entries and a default-initialized context, for
stateless contexts such as Auto's and String's. Use
initContext when the context carries state.
Functions
pub fn initContext(context: Context) Self
src
A cache with no entries and the given context.
Number of cached entries.
Whether key is cached. Does not change recency.
The value for key, moved to the most-recently-used position.
The value for key, without changing recency.
Insert or update key. An update moves the entry to the front and
returns the old value in replaced. A new key at capacity evicts
the tail and returns it in evicted.
Remove key and return its value.
Remove and return the least-recently-used entry.
Remove and return the most-recently-used entry.
Drop every entry, keeping the storage. The values are not returned;
drain with the iterator first when V owns resources.
An iterator from most to least recently used. Modify the cache
during iteration only through the returned value pointers: get,
put, remove, and clear invalidate the iterator.
Types
module
mem
src
Memory extensions to std.mem.
Fixed-size byte values and memory scans that std leaves to hand-rolled code.
Functions
pub fn lastIndexOfNonZero(buf: []const u8) ?usize
src
Return the index of the last non-zero byte in buf, or null if all zeros.
more
Fast path: if the last byte is non-zero, returns immediately.
SIMD path: processes chunk_len bytes at a time backwards, where
chunk_len is target-optimal (suggestVectorLength).
Scalar path: handles the remaining prefix shorter than chunk_len.
buf must be non-empty — caller is responsible for ensuring this.
pub fn findScalarLast(comptime T: type, slice: []const T, value: T) ?usize
src
Return the index of the last element of slice equal to value, or null
if no element matches.
more
Semantics match mem.findScalarLast, which is a scalar backwards loop;
this function exists to add the SIMD path.
Fast path: if the last element matches, returns immediately.
SIMD path: compares chunk_len elements at a time backwards, where
chunk_len is target-optimal (suggestVectorLength).
Scalar path: the remaining prefix shorter than chunk_len, and element
types without vector support, delegate to mem.findScalarLast.
Return the index of the first element of slice equal to any element of
values, or null if none match.
more
Semantics match mem.findAny, which delegates to findAnyPos, a
nested scalar loop that is O(slice.len * values.len); this function exists
to add the SIMD path.
SIMD path: compares chunk_len elements at a time forwards against every
value, ORs the match masks, and returns the first set lane, where
chunk_len is target-optimal (suggestVectorLength).
Scalar path: the remaining suffix shorter than chunk_len, and element
types without vector support, delegate to mem.findAny.
Types
type fn
Array
src
pub fn Array(comptime len: comptime_int) type
A fixed-size byte array wrapper with explicit initialization and zeroing.
Fields
data: Data
Constants
Functions
pub inline fn secureZero(self: *Self) void
src
module
multi_array
src
The struct-of-arrays pair: Array (fixed length) and Buffer (fixed
capacity, runtime len) — the std convention of short flavor names inside
a package that names the concept, like std.array_hash_map.Auto.
more
std.MultiArrayList(T) splits a struct (or tagged union) into one array
per field, but backs them with a heap allocation sized at runtime and a
runtime byte-offset map. These siblings embed the field arrays instead:
Array(T, length) is the comptime-length counterpart of mem.Array
(exactly length elements, no len field), and Buffer(T, capacity) is
the buffer.Array counterpart (fixed capacity, runtime len, list API,
no allocator). The field arrays are generated as one .auto layout
struct at comptime, so the compiler handles alignment and padding — std's
runtime offset sorting disappears entirely.
Types
type fn
Array
src
pub fn Array(comptime T: type, comptime length: comptime_int) type
A struct-of-arrays container of exactly length elements of T, stored
inline — the fixed-size sibling of std.MultiArrayList and the
comptime-length sibling of mem.Array.
more
Each field of T lives in its own [length]FieldType array, so a
computation touching only some fields walks contiguous memory, and T's
padding never repeats per element. There is no runtime len:
items(.x) returns *[length]F, which coerces to slices and casts to
vector types (@Vector(length, F)).
T may be a struct or a tagged union; unions are stored as tags and
data arrays like std.MultiArrayList.
Fields
storage: Storage(T, length)
Constants
The number of elements; also the length of every field array.
Functions
pub fn constItems(
self: *const Self,
comptime field: Field,
) *const [length]FieldType(field)
src
The [length]F array for field over a const reference.
The [length]F array for field.
Gather the element at index back into a T.
Scatter elem into the per-field arrays at index.
Scatter value into every element.
Exchange the elements at a and b.
Build from an array of structs (AoS to SoA).
Gather every element into an array of structs (SoA to AoS).
Stable sort of all len elements. Preserves the relative order of
equal elements; sortUnstable is a faster alternative when that
does not matter.
ctx has the following method:
fn lessThan(ctx: @TypeOf(ctx), a_index: usize, b_index: usize) bool
pub fn sortUnstable(self: *Self, ctx: anytype) void
src
Unstable sort of all len elements. The relative order of equal
elements may change.
ctx has the following method:
fn lessThan(ctx: @TypeOf(ctx), a_index: usize, b_index: usize) bool
type fn
Buffer
src
pub fn Buffer(comptime T: type, comptime buffer_capacity: comptime_int) type
A fixed-capacity struct-of-arrays list — the buffer.Array sibling of
std.MultiArrayList. Storage is embedded ([capacity]FieldType per
field), len is runtime, and there is no allocator: appending to a full
list returns error.NoSpaceLeft.
T may be a struct or a tagged union; unions are stored as tags and
data arrays like std.MultiArrayList.
Fields
Constants
Functions
pub fn constItems(self: *const Self, comptime field: Field) []const FieldType(field)
src
The []F slice of populated values for field over a const
reference.
The []F slice of populated values for field.
Gather the element at index back into a T.
Scatter elem into the per-field arrays at index.
pub fn remainingCapacity(self: *const Self) Index
src
Extend the list by 1 element. Returns error.NoSpaceLeft if the
list is full.
pub fn appendAssumeCapacity(self: *Self, elem: T) void
src
Extend the list by 1 element. Asserts that capacity is sufficient to hold an additional item.
pub fn appendSlice(self: *Self, values: []const T) error{NoSpaceLeft}!void
src
Extend the list by values.len elements. Returns
error.NoSpaceLeft if they do not all fit.
pub fn appendSliceAssumeCapacity(self: *Self, values: []const T) void
src
appendSlice without the error return. Asserts the capacity for
every value.
Extend the list by 1 element, returning the index of the
uninitialized slot. Returns error.NoSpaceLeft if the list is full.
pub fn addOneAssumeCapacity(self: *Self) usize
src
Extend the list by 1 element, returning the index of the uninitialized slot. Asserts that capacity is sufficient to hold an additional item.
Remove and return the last element, or return null if the list
is empty.
Insert elem at index, shifting all elements from index up by
one. Returns error.NoSpaceLeft if the list is full.
pub fn insertAssumeCapacity(self: *Self, index: usize, elem: T) void
src
Insert elem at index, shifting all elements from index up by
one. Asserts that capacity is sufficient and index <= len.
pub fn swapRemove(self: *Self, index: usize) void
src
Remove the element at index by swapping the last element into its
place. Fast, but does not retain list ordering.
pub fn orderedRemove(self: *Self, index: usize) void
src
Remove the element at index, shifting the elements above it down
to preserve order.
Adjust the list's length to new_len. Index cannot express a
value above capacity, so no bounds check is needed. Does not
initialize added slots, if any.
Stable sort of the populated elements. Preserves the relative
order of equal elements; sortUnstable is a faster alternative
when that does not matter.
ctx has the following method:
fn lessThan(ctx: @TypeOf(ctx), a_index: usize, b_index: usize) bool
pub fn sortUnstable(self: *Self, ctx: anytype) void
src
Unstable sort of the populated elements. The relative order of
equal elements may change.
ctx has the following method:
fn lessThan(ctx: @TypeOf(ctx), a_index: usize, b_index: usize) bool
module
net
src
Networking extensions to std.Io.net.
IPv4 addressing: a portless address and CIDR prefixes, plus the 6-byte
Ip4Endpoint (octets + port) for raw-fd callers and per-connection
records, following
net.Ip4Address and Go's net/netip. fd-level socket helpers live in
posix.
Constants
pub const Ip4Address = net.Ip4Address
src
pub const Ip6Address = net.Ip6Address
src
Types
struct
Ip4
src
Fields
bytes: [4]u8
Constants
pub const unspecified: Ip4 = .{ .bytes = @splat(0) }
src
pub const ParseError = Ip4Address.ParseError
src
Functions
Parse dotted-quad notation, with Ip4Address.parse semantics:
hostnames and IPv6 are parse errors, and non-canonical quads (leading
zeros) are too.
Canonical input takes the fast path in net/ip4.zig; everything it
rejects is malformed or non-canonical and goes to diagnose, which
names the error.
pub fn parseComptime(comptime s: []const u8) Ip4
src
Parses at compile time, reporting the offending string and error on
failure. For literal-driven comptime tables, where parse +
catch unreachable only says "reached unreachable code".
Converts from an IPv4-mapped IPv6 address, or returns null.
Given an Ip4Address, converts it to an Ip4 stripping the port.
Given an IpAddress, converts it to an Ip4 directly, or from an
IPv4-mapped IPv6 address, or returns null.
pub fn isUnspecified(self: Ip4) bool
src
pub fn isLoopback(self: Ip4) bool
src
127.0.0.0/8.
RFC 1918: 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16.
pub fn isMulticast(self: Ip4) bool
src
224.0.0.0/4.
pub fn isLinkLocalUnicast(self: Ip4) bool
src
169.254.0.0/16.
pub fn isLinkLocalMulticast(self: Ip4) bool
src
224.0.0.0/24, RFC 4291 §2.7.1: the link-local multicast block. All such addresses are also isMulticast.
pub fn isBroadcast(self: Ip4) bool
src
pub fn isGlobalUnicast(self: Ip4) bool
src
Matches Go netip: private and link-local addresses still count as global unicast — they are routable, just not on the public internet.
Dotted-quad numeric order: lexicographic octet order, endian-free.
Follows the std convention of returning math.Order.
The next address in numeric order, or null past 255.255.255.255.
The previous address in numeric order, or null before 0.0.0.0.
The prefix of bits bits with this address as its network address,
masked to canonical form, like Go's Addr.Prefix.
Returns null unless slice is exactly 4 bytes, like Go's
AddrFromSlice.
struct
Prefix4
src
IPv4 CIDR prefix: an Ip4 network address plus a prefix length in bits.
IPv6 prefixes are parse errors: a caller that needs dual-stack matching
composes two prefixes itself.
Fields
Constants
pub const ParseError = …
src
value
Ip4.ParseError || error{
/// No '/' in the input.
NoSlash,
/// The bits field was empty, non-canonical, or not a plain integer.
InvalidBits,
/// The prefix length exceeds 32.
BitsOutOfRange,
}Functions
pub fn parseComptime(comptime s: []const u8) Prefix4
src
Parses at compile time, reporting the offending string and error on
failure, like Ip4.parseComptime.
Containment by octet-prefix compare: whole octets match exactly, then the leading bits of the next octet are masked. No endian conversion.
The canonical form with host bits zeroed, like Go's Prefix.Masked.
Whether the two prefixes cover at least one common address: one contains the other's network address.
pub fn isSingleIp(self: Prefix4) bool
src
Whether the prefix contains exactly one address: 32 bits.
struct
Ip4Endpoint
src
IPv4 address as octets + port — 6 bytes, the same layout as
std.Io.net.Ip4Address, and small enough for a per-connection record.
The type exists because std's cannot be extended, and toSockaddrIn
needs a receiver: the kernel struct that bind(2) and connect(2)
take, port in network order. The rest is the conversions and port
helpers around it.
Fields
Functions
Parse the address part from dotted-quad notation; the port rides
along, not from the string. HostPort.parse splits config text that
carries both.
pub fn toSockaddrIn(self: Ip4Endpoint) posix.sockaddr.in
src
The kernel struct, port in network order: what bind(2) and
connect(2) take.
struct
HostPort
src
A host and port split from config text.
The bracket and colon rules follow Go's net.SplitHostPort. The config
policy is added here: a default port, a numeric u16, and no empty host,
empty port, or port 0. The host is not validated as a name or an address;
that stays the caller's policy.
Fields
Constants
value
error{
/// The text before the port is empty.
EmptyHost,
/// A colon is present and the port text is empty.
EmptyPort,
/// The port is not a decimal value in 1..65535.
InvalidPort,
/// An unbracketed host contains more than one colon.
UnbracketedIpv6,
/// A bracketed host has no closing `]`, or text after `]` that is not
/// a colon.
InvalidBrackets,
}Functions
Split text into a host and a port. The text may be host,
host:port, [host], or [host]:port. A missing port takes
default_port.
Brackets are removed from the returned host.
module
once
src
Set-once values and lazy initialization.
more
Cell(T) holds one value that is set at most once. get returns null
until the value exists. getOrInit initializes it on the first call and
returns a pointer, so later calls pay one branch.
Lazy(T, init) is a cell whose initializer is fixed at compile time.
Cell and Lazy are single-threaded. SyncCell and SyncLazy add an
atomic fast path and an Io.Mutex on the first initialization, so one
thread initializes while the others wait. The fast path takes no lock.
set returns error.AlreadySet when a value exists. take moves the
value out of an unsync cell. Do not copy a cell after use.
Types
type fn
Cell
src
pub fn Cell(comptime T: type) type
A single-threaded set-once value.
Fields
value: T
initialized: bool
Constants
Functions
The value, or null.
pub fn isInitialized(self: *Self) bool
src
Whether a value has been set.
Set the value. Returns error.AlreadySet when one exists.
The value, initialized by f on the first call.
pub fn getOrTryInit(self: *Self, ctx: anytype, comptime f: anytype) InitError(f)!*T
src
Like getOrInit, for an initializer that can fail. A failed call
leaves the cell empty, so a later call can try again.
Move the value out and empty the cell.
type fn
SyncCell
src
pub fn SyncCell(comptime T: type) type
A set-once value shared by threads.
Fields
Constants
value
.{
.mutex = .init,
.state = .init(.uninit),
.value = undefined,
}Functions
The value, or null. The fast path is one acquire load.
pub fn isInitialized(self: *Self) bool
src
Whether a value has been set.
Set the value. Returns error.AlreadySet when one exists.
pub fn getOrInit(
self: *Self,
io: Io,
ctx: anytype,
comptime f: fn (@TypeOf(ctx)) T,
) Io.Cancelable!*T
src
The value, initialized by f on the first call. Threads that
arrive during the first call wait on the mutex.
pub fn getOrTryInit(
self: *Self,
io: Io,
ctx: anytype,
comptime f: anytype,
) (InitError(f) || Io.Cancelable)!*T
src
Like getOrInit, for an initializer that can fail. A failed call
leaves the cell empty, so a later call can try again.
type fn
Lazy
src
pub fn Lazy(comptime T: type, comptime init: fn () T) type
A single-threaded lazy value. init runs on the first get.
Fields
cell: Cell(T)
Constants
Functions
The value, initialized on the first call.
pub fn isInitialized(self: *Self) bool
src
Whether the value has been initialized.
Move the value out and empty the cell.
type fn
SyncLazy
src
pub fn SyncLazy(comptime T: type, comptime init: fn () T) type
A thread-safe lazy value. init runs on the first get.
Fields
cell: SyncCell(T)
Constants
Functions
The value, initialized on the first call.
pub fn isInitialized(self: *Self) bool
src
Whether the value has been initialized.
module
posix
src
POSIX extensions to std.posix.
more
Socket address queries by fd, returning a typed net.Ip4Address. std's
posix.getpeername fills a caller-supplied sockaddr, and std has no
posix.getsockname. For callers that own raw socket handles (io_uring
data paths); code holding an Io.net.Socket should prefer the typed APIs
instead.
OptionalFd packs an absent descriptor into -1, avoiding the tag and
padding of Zig's optional descriptor. It carries no ownership or close policy.
setsockopt/getsockopt decode errno over the raw calls, mapping EINVAL
to error.InvalidOptionValue — std's own wrappers map it to unreachable,
which no caller setting options from configuration can survive.
Constants
pub const GetSockNameError =
posix.GetSockNameError ||
posix.UnexpectedError ||
error{AddressFamilyNotSupported}
src
pub const SetSockOptError =
posix.UnexpectedError ||
error{
/// The level/name/value combination is not one the kernel
/// accepts: a real runtime condition for config-derived option
/// values. std's own `posix.setsockopt` maps EINVAL to
/// `unreachable`, which is why callers that set options from
/// configuration hand-decode errno over the raw call instead.
InvalidOptionValue,
/// `SO_RCVTIMEO`/`SO_SNDTIMEO` with a timeout the kernel rejects.
TimeoutTooBig,
SystemResources,
PermissionDenied,
OperationNotSupported,
}
src
Functions
pub fn getpeername(fd: posix.socket_t) GetSockNameError!net.Ip4Address
src
Peer address of a connected socket, by fd. error.SocketUnconnected
covers ENOTCONN — std's posix.getpeername does the conversion, so
this wrapper does not decode errno by hand.
pub fn getsockname(fd: posix.socket_t) GetSockNameError!net.Ip4Address
src
Local address of a socket, by fd. The port is the bound (possibly ephemeral) port, which is how a caller recovers the real port after binding to port 0.
std wraps getpeername but not getsockname, so this decodes errno over
the raw call.
pub fn setsockopt(
fd: posix.socket_t,
level: i32,
optname: u32,
opt: c_int,
) SetSockOptError!void
src
Set a one-c_int socket option, decoding errno over the raw call.
pub fn getsockopt(fd: posix.socket_t, level: i32, optname: u32) SetSockOptError!c_int
src
Read a one-c_int socket option, e.g. SO.ERROR probes.
Types
struct
OptionalFd
src
An optional POSIX descriptor in one four-byte word. -1 is .none.
Descriptor zero is a valid descriptor.
Fields
fd: posix.fd_t
Constants
Functions
Encode a descriptor, or .none from null. This does not duplicate the
descriptor. The supplied descriptor must be nonnegative.
Return the descriptor, or null for .none.
module
prefix_map
src
Prefix maps: a compressed radix tree of byte-string keys, built from a literal at compile time or at runtime.
more
The map answers two questions. get is an exact lookup. getLongestPrefix
returns the value of the longest stored key that is a prefix of the input,
which is the shape a route table or a layered config lookup needs.
The tree stores one node per branching point or key end. A node carries the bytes shared by every key under it, so a long common prefix costs one node and one compare. Its children are a sorted range in a flat array. The nodes, child edges, prefix bytes, and values are contiguous slices, so a comptime-built map is a constant with no runtime initialization, and a runtime-built map is four allocations.
The keys are copied into the tree. The input slices do not need to outlive
init, and values are copied into the value array.
Types
type fn
Map
src
pub fn Map(comptime V: type) type
Fields
Functions
The number of keys in the map.
The value for key, or null.
pub fn getLongestPrefix(self: Self, key: []const u8) ?V
src
The value of the longest stored key that is a prefix of key, or
null when no stored key is a prefix.
Whether key is one of the stored keys.
pub inline fn initComptime(comptime kvs: anytype) Self
src
Build a map from a literal during compilation. The result is a constant: all of its storage is in the binary, and it has no runtime initialization.
A duplicate key is a compile error.
Build a map from kvs with allocator. The keys and values are
copied. Release the map with deinit.
A duplicate key returns error.DuplicateKey.
Free a map built with init. Do not call this for a map built with
initComptime: that storage is a constant.
module
priority_queue
src
Fixed-capacity priority queue: the binary heap of std.PriorityQueue with
its capacity fixed at comptime and its storage embedded in the value. No
allocator is involved, so insertion fails only with error.NoSpaceLeft.
more
The heap logic and public surface mirror std's: compareFn returns
Order.lt when its second argument should be popped before its third,
iterator walks storage order without consuming the queue, and
initContext carries the comparator's context. Like std's empty, the
empty value leaves the context undefined; use initContext whenever the
comparator dereferences it.
Types
type fn
Custom
src
pub fn Custom(
comptime T: type,
comptime Context: type,
buffer_capacity: comptime_int,
comptime compareFn: fn (context: Context, a: T, b: T) Order,
) type
A priority queue that stores up to buffer_capacity elements in a
[buffer_capacity]T array embedded in the value.
The parameter is named buffer_capacity rather than capacity because
Zig rejects a container declaration that shadows an enclosing function
parameter; the bound is exposed as the capacity constant instead.
Fields
Constants
Smallest integer type that can hold 0..capacity.
Maximum number of elements the queue can hold.
value
.{
.buffer = undefined,
.len = 0,
.context = undefined,
}A priority queue containing no elements. The context is undefined,
as in std.PriorityQueue.empty; use initContext to set it.
Functions
pub fn initContext(context: Context) Self
src
Initialize and return a priority queue with context.
Insert elem, maintaining priority. Returns error.NoSpaceLeft
when the queue is already at capacity.
pub fn pushAssumeCapacity(self: *Self, elem: T) void
src
Insert elem, maintaining priority. Asserts that the queue is not
at capacity.
Add each element in items, maintaining priority. All or nothing:
the capacity check precedes every insertion, so on
error.NoSpaceLeft the queue is untouched. This mirrors std's
pushSlice, which reserves capacity up front.
pub fn pushSliceAssumeCapacity(self: *Self, items: []const T) void
src
pushSlice without the error return. Asserts the queue has room
for every element.
Look at the highest priority element. Returns null if empty;
does not modify the queue.
Remove and return the highest priority element. Returns null if
empty.
Remove and return the element at index. Indices follow iterator
order, which is not necessarily priority order. Asserts that
index < count().
Number of elements currently in the queue.
Remove all elements. The capacity is unchanged, so the queue can be refilled immediately.
Replace the first element that compares equal to elem with
new_elem, maintaining priority. Returns error.ElementNotFound
if no stored element compares equal to elem.
Return an iterator over the stored elements. Like std's, it walks storage order (not priority order) without consuming the queue; any modification invalidates it.
Types
module
random
src
Io-less secure randomness: a per-thread CSPRNG, lazily seeded once
from the platform's secure source — the behavior of Io.random
without the Io. A failed seed is fatal: there is no fallback that
preserves the guarantee.
more
Thread-safety comes from isolation, std's own mechanism: every
thread owns its generator, seeded on its first fill, so there are
no locks and no atomics anywhere. The first fill on a thread pays
one syscall for the seed; every later fill is ChaCha out of
thread-local state, and no RNG state is shared to steal.
Functions
Fill buffer with cryptographically secure random bytes from the
thread's lazily seeded CSPRNG. Never fails; thread-safe by
isolation.
module
set
src
A bounded set: bounded_array_hash_map with V = void plus the set
algebra Map(K, void) doesn't carry. The map underneath gives
Custom/Auto/String construction and insertion-ordered iteration;
this module adds the in-place algebra — intersect, unite,
subtract — and the membership predicates — subsetOf, disjointWith.
All algebra is in-place and allocation-free. intersect, subsetOf, and
disjointWith iterate self; unite and subtract iterate other. No
operation picks the smaller side. Pass the smaller set as other to
unite and subtract, and call the other three on the smaller set.
Types
type fn
Custom
src
pub fn Custom(comptime K: type, comptime Context: type, buffer_capacity: comptime_int) type
The underlying bounded map's constructors, Custom/Auto/String
wrapped in set vocabulary: add/remove/contains over a
V = void map, plus the algebra.
Fields
map: Map
Constants
Maximum number of keys the set can hold.
Functions
pub fn initContext(context: Context) Self
src
Add key. Returns true if key was newly added, false if
already present. A new key that does not fit the fixed capacity
returns error.NoSpaceLeft and is not added.
pub fn addAssumeCapacity(self: *Self, key: K) bool
src
add without the error return. Asserts the set has room for a
new key.
Remove key. Returns false when absent.
The keys in insertion order. Invalidated by the next add or remove.
Remove every key this set does not share with other.
In-place: iterates self, probes other. Neither set changes
in other.
Add every key of other. Returns error.NoSpaceLeft when self
reached capacity — the adds that fit are kept.
pub fn uniteAssumeCapacity(self: *Self, other: *Self) void
src
unite without the error return. Asserts room for every new key.
Remove every key of other. Returns nothing: absent keys are
not an error.
Every key of self is in other.
pub fn supersetOf(self: *Self, other: *Self) bool
src
Every key of other is in self.
pub fn disjointWith(self: *Self, other: *Self) bool
src
No key appears in both.
type fn
Auto
src
pub fn Auto(comptime K: type, buffer_capacity: comptime_int) type
Fields
map: Map
Constants
Maximum number of keys the set can hold.
Functions
pub fn initContext(context: Context) Self
src
Add key. Returns true if key was newly added, false if
already present. A new key that does not fit the fixed capacity
returns error.NoSpaceLeft and is not added.
pub fn addAssumeCapacity(self: *Self, key: K) bool
src
add without the error return. Asserts the set has room for a
new key.
Remove key. Returns false when absent.
The keys in insertion order. Invalidated by the next add or remove.
Remove every key this set does not share with other.
In-place: iterates self, probes other. Neither set changes
in other.
Add every key of other. Returns error.NoSpaceLeft when self
reached capacity — the adds that fit are kept.
pub fn uniteAssumeCapacity(self: *Self, other: *Self) void
src
unite without the error return. Asserts room for every new key.
Remove every key of other. Returns nothing: absent keys are
not an error.
Every key of self is in other.
pub fn supersetOf(self: *Self, other: *Self) bool
src
Every key of other is in self.
pub fn disjointWith(self: *Self, other: *Self) bool
src
No key appears in both.
type fn
String
src
pub fn String(comptime buffer_capacity: comptime_int) type
Fields
map: Map
Constants
Maximum number of keys the set can hold.
Functions
pub fn initContext(context: Context) Self
src
Add key. Returns true if key was newly added, false if
already present. A new key that does not fit the fixed capacity
returns error.NoSpaceLeft and is not added.
pub fn addAssumeCapacity(self: *Self, key: K) bool
src
add without the error return. Asserts the set has room for a
new key.
Remove key. Returns false when absent.
The keys in insertion order. Invalidated by the next add or remove.
Remove every key this set does not share with other.
In-place: iterates self, probes other. Neither set changes
in other.
Add every key of other. Returns error.NoSpaceLeft when self
reached capacity — the adds that fit are kept.
pub fn uniteAssumeCapacity(self: *Self, other: *Self) void
src
unite without the error return. Asserts room for every new key.
Remove every key of other. Returns nothing: absent keys are
not an error.
Every key of self is in other.
pub fn supersetOf(self: *Self, other: *Self) bool
src
Every key of other is in self.
pub fn disjointWith(self: *Self, other: *Self) bool
src
No key appears in both.
module
slot
src
A fixed-capacity pool of caller-owned entries: O(1) acquire and release, an intrusive doubly linked list over the live entries, and a free list that costs no memory.
more
The links live inside the entry, in two fields the caller names at comptime, so walking the live set reads only the entries it visits. That is the point of the shape: a table of a thousand entries with a handful live costs one cache line per live entry to walk, not one per stored entry.
The link fields carry the handle type. Any unsigned integer works, and the
type decides how many entries fit: u32 holds four billion, and a narrow
type such as std.math.IntFittingRange packs a small table. Both fields
must have the same type. The type's maximum value is the "no neighbor"
sentinel, so the capacity is at most that value.
Two constructors, one implementation:
Pool(Entry, "prev", "next")holds a[]Entrygiven atinit, for a capacity known at runtime, such as a connection table sized from config.Array(Entry, "prev", "next", n)owns an[n]Entry, for a capacity known at comptime. APoolvalue holds a slice, so it must not be copied; the owning form is what a self-contained value uses.
acquire returns a handle and links the entry at the back of the list.
release takes the handle back. The handle is the entry's index, so a
caller recovers the index by keeping the handle, never by pointer arithmetic
on a *Entry. get returns the entry for a handle.
The list order is the caller's. A pool that never reorders iterates in
acquisition order, and moveToFront reorders, which is how a
recency-ordered cache is built on top (lru is).
The free list is lazy: the first acquisitions come from the entries in index
order, and released handles go on a stack in front of them. Nothing walks
the storage at init, so empty is a plain value. A free entry points
prev at its own handle, so releasing the same handle twice trips an assert
in a safe build instead of handing the slot to two callers.
The pool owns the link fields and the caller owns everything else. An acquired entry is not cleared, and the pool never writes a field other than the two links.
Not thread-safe.
Types
type fn
Pool
src
pub fn Pool(
comptime Entry: type,
comptime prev_field: []const u8,
comptime next_field: []const u8,
) type
A pool over a []Entry given at init, for a capacity known at runtime.
prev_field and next_field name the two link fields the pool owns. They
must exist, be distinct, and share one unsigned integer type.
Fields
entries: []Entry
The whole storage, in handle order.
state: State
The list and free-list bookkeeping.
Constants
The type of both link fields, read from the entry.
No neighbor.
The list and free-list bookkeeping.
One live entry and the handle that names it.
A walk over the live entries, front to back.
A pool over no storage. Only init replaces the slice.
Functions
Use entries as the whole storage. Every entry starts free.
Contents other than the link fields are left as they are.
Number of live entries.
The whole capacity.
Take a free entry and return its handle. Returns
error.NoSpaceLeft when every entry is live.
pub fn acquireAssumeCapacity(self: *Self) Handle
src
acquire without the error return. Asserts an entry is free.
pub fn acquireFront(self: *Self) error{NoSpaceLeft}!Handle
src
Take a free entry and link it at the front of the list. Returns
error.NoSpaceLeft when every entry is live.
pub fn acquireFrontAssumeCapacity(self: *Self) Handle
src
acquireFront without the error return. Asserts an entry is free.
The entry for handle. Asserts only that the handle is in range;
whether it is live is the caller's business, and isLive answers
it.
Whether handle is live. An out-of-range or never-acquired handle
is not.
Return handle to the free list. Asserts handle is live.
The entry's other fields keep their values until the slot is acquired again.
pub fn moveToFront(self: *Self, handle: Handle) void
src
Move a live entry to the front of the list.
Remove the front entry and release its handle. The entry comes back by value, with its link fields stale.
Remove the back entry and release its handle. The entry comes back by value, with its link fields stale.
Walk the live entries from front to back.
type fn
Array
src
pub fn Array(
comptime Entry: type,
comptime prev_field: []const u8,
comptime next_field: []const u8,
comptime max_entries: comptime_int,
) type
A pool that owns an [max_entries]Entry, for a capacity known at comptime.
prev_field and next_field name the two link fields the pool owns, as in
Pool. Use this form inside a struct that is copied or returned: a Pool
holds a slice, and a slice into the same struct would not survive the copy.
Fields
entries: [max_entries]Entry
The storage, inside the value.
state: State
The list and free-list bookkeeping.
Constants
The type of both link fields, read from the entry.
No neighbor.
The list and free-list bookkeeping.
One live entry and the handle that names it.
A walk over the live entries, front to back.
A pool with an untouched array. Every entry is free.
Functions
Number of live entries.
The whole capacity.
Take a free entry and return its handle. Returns
error.NoSpaceLeft when every entry is live.
pub fn acquireAssumeCapacity(self: *Self) Handle
src
acquire without the error return. Asserts an entry is free.
pub fn acquireFront(self: *Self) error{NoSpaceLeft}!Handle
src
Take a free entry and link it at the front of the list. Returns
error.NoSpaceLeft when every entry is live.
pub fn acquireFrontAssumeCapacity(self: *Self) Handle
src
acquireFront without the error return. Asserts an entry is free.
The entry for handle. Asserts only that the handle is in range.
Whether handle is live. An out-of-range or never-acquired handle
is not.
Return handle to the free list. Asserts handle is live.
pub fn moveToFront(self: *Self, handle: Handle) void
src
Move a live entry to the front of the list.
Remove the front entry and release its handle. The entry comes back by value, with its link fields stale.
Remove the back entry and release its handle. The entry comes back by value, with its link fields stale.
Walk the live entries from front to back.
module
sort
src
Sorting that std.mem.sort does not have: a stable radix sort for
integers, and selection of the k-th element.
more
radix sorts signed and unsigned integers with one pass per digit. It is
stable and needs a caller-owned scratch slice. nth partitions a slice so
the value at n is the n-th smallest, in expected O(n); select returns
that value.
Use radix for large, unordered integer arrays. std.mem.sortUnstable
(pdqsort) wins on sorted or nearly sorted input; at small sizes the fixed
passes do not pay off.
Constants
pub const RadixError = error{NoSpaceLeft}
src
Functions
Stable LSD radix sort for integers.
scratch must have at least items.len elements and must not overlap
items. Returns error.NoSpaceLeft when it is shorter.
pub fn radixAssumeCapacity(comptime T: type, items: []T, scratch: []T) void
src
Stable LSD radix sort for integers. Asserts that scratch is large enough
and does not overlap items.
pub fn nth(
comptime T: type,
items: []T,
n: usize,
context: anytype,
comptime lessThan: fn (@TypeOf(context), T, T) bool,
) void
src
Partition items so that items[n] is the n-th smallest element. Every
element before it is less than or equal to it under lessThan; every
element after it is greater than or equal to it. The order inside each
side is unspecified.
Expected O(n). A run of bad pivots falls back to an unstable sort of the
active range, so the worst case is O(n log n). Panics when n is not a
valid index.
pub fn select(
comptime T: type,
items: []T,
n: usize,
context: anytype,
comptime lessThan: fn (@TypeOf(context), T, T) bool,
) T
src
The n-th smallest element, by the same rules as nth.
module
static_map
src
Comptime-generated static maps: the bounded map's Robin Hood probe logic built at compile time from a literal, immutable, zero runtime initialization.
more
std covers string keys (std.StaticStringMap(V) with initComptime) and
dense enums (std.EnumMap); sparse non-string keys — opcode tables,
protocol constants — have nothing. This module fills that gap by building
a bounded_array_hash_map.Custom at comptime and exposing it as a
constant: the whole table lives in .rodata, lookups are a probe walk
with no allocation and no lazy init.
The literal is a tuple of .{key, value} tuples, std's
StaticStringMap.initComptime shape. A duplicate key is a compile error,
not a silent overwrite.
Types
type fn
Custom
src
pub fn Custom(
comptime K: type,
comptime V: type,
comptime Context: type,
comptime kvs: anytype,
) type
A static map with an explicit context, comptime-built from kvs.
Constants
value
blk: {
const Map = map_mod.Custom(K, V, Context, kvs.len);
var m: Map = .init;
for (kvs) |kv| {
const result = m.getOrPut(kv[0]) catch unreachable;
if (result.found_existing) {
@compileError("static map: duplicate key " ++ debugKey(kv[0]));
}
result.value_ptr.* = kv[1];
}
break :blk m;
}The comptime-filled table. All state is a compile-time constant.
The number of entries: always kvs.len — duplicates are
compile errors, so nothing is dropped.
The keys in insertion order: a comptime-known slice.
The values in insertion order: a comptime-known slice.
Functions
The value for key, or null.
pub fn getAssertPresent(key: K) V
src
The value for key. Asserts presence — the table is a literal,
so an absent key is a programming error, not a runtime case.
type fn
Auto
src
pub fn Auto(comptime K: type, comptime V: type, comptime kvs: anytype) type
A static map with std's auto context. Slices — including []const u8 —
are rejected by std.hash.autoHash; string keys use String.
more
A key whose hash reads padding bits is a compile error: an integer, bool,
or enum tag narrower than a byte, or any type that contains one.
autoHash hashes those bits differently at comptime than at runtime, so
every lookup of a comptime-built table would miss. Use Custom with your
own context for such keys.
Constants
value
blk: {
const Map = map_mod.Custom(K, V, Context, kvs.len);
var m: Map = .init;
for (kvs) |kv| {
const result = m.getOrPut(kv[0]) catch unreachable;
if (result.found_existing) {
@compileError("static map: duplicate key " ++ debugKey(kv[0]));
}
result.value_ptr.* = kv[1];
}
break :blk m;
}The comptime-filled table. All state is a compile-time constant.
The number of entries: always kvs.len — duplicates are
compile errors, so nothing is dropped.
The keys in insertion order: a comptime-known slice.
The values in insertion order: a comptime-known slice.
Functions
The value for key, or null.
pub fn getAssertPresent(key: K) V
src
The value for key. Asserts presence — the table is a literal,
so an absent key is a programming error, not a runtime case.
type fn
String
src
pub fn String(comptime V: type, comptime kvs: anytype) type
A static string-keyed map, like std.StaticStringMap — string keys are
a separate entry point because std.hash.autoHash rejects slices.
Constants
value
blk: {
const Map = map_mod.Custom(K, V, Context, kvs.len);
var m: Map = .init;
for (kvs) |kv| {
const result = m.getOrPut(kv[0]) catch unreachable;
if (result.found_existing) {
@compileError("static map: duplicate key " ++ debugKey(kv[0]));
}
result.value_ptr.* = kv[1];
}
break :blk m;
}The comptime-filled table. All state is a compile-time constant.
The number of entries: always kvs.len — duplicates are
compile errors, so nothing is dropped.
The keys in insertion order: a comptime-known slice.
The values in insertion order: a comptime-known slice.
Functions
The value for key, or null.
pub fn getAssertPresent(key: K) V
src
The value for key. Asserts presence — the table is a literal,
so an absent key is a programming error, not a runtime case.
module
stdio
src
Buffered, error-free stdio: statically initialized singleton streams for stderr and stdout. No init function, no allocator — import and speak.
more
The writers ride std.Options.debug_io, the statically initialized
single-threaded Io that std.debug.print uses. That Io supports
neither concurrency nor cancellation, so these streams belong to one
thread.
No method returns an error. The first failed write latches the file
writer's failure mode, and every later write on that stream drops.
Output is buffered — nothing lands until flush, so a program must
flush before it exits, and an abort never reaches a flush: panic
reporting stays with std.debug.print. print is Io.Writer.print
without the error return; the caller ends the line, nothing appends a
newline.
Constants
The process's stderr.
The process's stdout.
Functions
Flush both streams. Buffered output does not land without this, so call it before exit. A failed flush is dropped; one dead stream does not stop the other from flushing.
Types
struct
Stream
src
One buffered stream over a std file, with the buffer and the file writer embedded, so an instance owns its whole state.
more
The method set is libc's FILE* write surface: print is fprintf,
write/writeAll are fwrite, writeByte is fputc, flush is
fflush. print formats exactly as Io.Writer.print does; nothing
appends a newline. The first failed write latches the writer's
failure mode, and later writes drop.
Fields
buffer: [4096]u8
file_writer: Io.File.Writer
Functions
The *Io.Writer behind the stream, for the interfaces that take one.
module
swiss
src
Swiss-table hash maps: the hashbrown / Abseil / Go 1.24 lineage.
The resizable map built on these primitives is swiss/map.zig.
more
The control-byte encoding is Abseil's, for its stated reasons: empty
is 0x80 so an empty match is a sign-style test; deleted is 0xFE
so empty and deleted are distinguishable and both sort below
sentinel; a full byte carries the H2 fingerprint in its low 7 bits
with the top bit clear, so full-vs-special is one bit. H2 is the
hash's top 7 bits and H1 its low bits (the hashbrown/Abseil
direction — Go's reversal exists for its extendible-hashing
directory, which this design does not have).
Probes read a group of control bytes at once and match with the
repo's SIMD idiom: compare against a broadcast, bitcast the bool
vector to an integer mask, iterate the set bits with @ctz.
The table mirrors its first group_width - 1 control bytes at the
end, so a probe whose group spans the array end reads the wrapped
bytes and the mask's lane index can be taken modulo the bucket
count — the hashbrown/Abseil trick (their kWidth - 1 cloned
bytes). sentinel is reserved by the encoding but never appears
in a table's control bytes.
Constants
Top bit set, all others clear: an empty slot. Enables a sign-style empty match on a group of bytes.
Top bit set, bit 0 clear: a tombstone. Distinguishable from empty
by one bit; both sort below sentinel.
0xFF. Reserved by the Abseil/Go encoding for whole-array bulk
operations; a table never stores it — its mirrored tail
replicates real bytes instead.
pub const group_width = …
src
value
if (std.simd.suggestVectorLength(u8)) |width|
@min(width, 16)
else
8Group width: 16 where the target has 128-bit vectors, 8 scalar.
more
The cap is design, not hardware: the group width is welded to the
table's arithmetic — the 7/8 load factor, the empties-per-group math,
the bucket_mask < 8 small-table branches (which exist because a
16-wide group is wider than the smallest tables), the probe stride,
the mirror size. This port is hashbrown's 16-group design, validated
at 16 and 8 only; a wider group is a different table whose arithmetic
needs re-deriving, not a wider load. (Contrast mem's scan functions,
where the vector width is a pure perf knob and rides suggestVectorLength
uncapped.) Zig's native vector-to-mask idiom is why 16 works on
aarch64, where hashbrown's hand-written NEON chose 8.
The group mask type: one bit per lane, @bitCast of the compare's
bool vector — the repo's shipped idiom.
Functions
A full control byte: the top 7 bits of the hash in the low 7 bits, top bit clear.
The lanes holding a full byte (any H2).
pub fn matchEmpty(bytes: *const [group_width]u8) Mask
src
The lanes holding empty.
pub fn matchDeleted(bytes: *const [group_width]u8) Mask
src
The lanes holding deleted.
pub fn matchEmptyOrDeleted(bytes: *const [group_width]u8) Mask
src
The lanes holding an empty or deleted byte — the probe's stop condition. Equivalent to "top bit set", since every special byte in a table (or its mirror) has it and no full byte does.
The lanes holding a full byte whose H2 equals tag — a candidate
slot for a key with that fingerprint.
The group's first set lane in mask, or null.
Types
type fn
Custom
src
pub const Custom = map.Custom
A resizable Swiss-table hash map that grows on the heap through the allocator passed to each operation.
more
Context follows the std.hash_map convention: hash(self, K) u64 and
eql(self, K, K) bool. The hash's low bits pick the starting bucket and
its top 7 bits form the H2 tag; a context that hashes to a narrower
integer should spread it across the u64 itself, because a hash whose top
7 bits are constant makes the tag match every full lane in a group.
Fields
ctrl: []u8
Control byte per bucket, plus a mirrored tail: `ctrl[bucket_count
- j]
duplicatesctrl[j % bucket_count]`, so a group read that runs past the last bucket reads the wrapped bytes. Zero-length in the empty map.
keys: []K
Key of the entry in each bucket; a bucket holds an entry only while its control byte is full.
values: []V
Value of the entry in each bucket.
bucket_count: usize
Number of buckets, a power of two; 0 in the empty map.
used: usize
Number of live entries.
context: Context
Constants
value
.{
.ctrl = &.{},
.keys = &.{},
.values = &.{},
.bucket_count = 0,
.used = 0,
.context = undefined,
}A map containing no entries. The context is undefined, as in
std.PriorityQueue.empty; use initContext to set it. Reads and
count work without allocating; the first insertion allocates
the initial table.
value
.{
.ctrl = &.{},
.keys = &.{},
.values = &.{},
.bucket_count = 0,
.used = 0,
.context = .{},
}Initialize and return a map with a default-initialized context.
Convenience for stateless contexts such as
std.hash_map.AutoContext and std.hash_map.StringContext;
contexts that carry state must use initContext.
Functions
pub fn initContext(context: Context) Self
src
Initialize and return a map with context.
Number of entries currently stored.
Number of entries the table can hold before the next insertion grows it: 7/8 of the bucket count, with at least one bucket left empty. The empty map has capacity 0.
Rebuild the table at its current bucket count, clearing every tombstone.
more
Churn — removals with no growth — leaves tombstones behind, and each one lengthens the probe path of a key that crosses it. Call this when a long-lived map holds few live entries after many removals. Capacity and bucket count do not change, so a map at its load limit cannot grow here.
Pointers into the table — from getPtr, getOrPut, or an iterator
— are invalidated, and bucket order changes. An empty map is
untouched.
Value stored for key, or null. Reads never allocate.
Pointer to the value stored for key, or null. The pointer is
invalidated by the next insertion or growth.
Whether key is stored in the map.
Insert or overwrite key.
Find or insert key. A new entry's value is undefined until the
caller initializes value_ptr. The table grows when live entries
fill the capacity, so the only failure is the allocator failing.
Remove key. Returns false when key is absent. The bucket
becomes a tombstone.
pub fn clearRetainingCapacity(self: *Self) void
src
Remove all entries, keeping the storage. Every control byte,
mirrored tail included, becomes empty.
pub fn clearAndFree(self: *Self, gpa: Allocator) void
src
Remove all entries and release the storage, returning to the empty state; the next insertion allocates again.
pub fn ensureTotalCapacity(
self: *Self,
gpa: Allocator,
expected: usize,
) Allocator.Error!void
src
Grow so that expected entries fit without another allocation;
no-op when the current capacity already covers expected.
Release the storage and invalidate the map.
An iterator over the entries in bucket order. The entry pointers alias the map's storage; the iterator is invalidated by the next insertion, removal or growth.
pub fn keyIterator(self: *Self) KeyIterator
src
An iterator over the keys in bucket order, matching iterator()
step for step. The pointers alias the map's storage; the iterator
is invalidated by the next insertion, removal or growth.
pub fn valueIterator(self: *Self) ValueIterator
src
An iterator over the values in bucket order, matching
keyIterator() step for step. The pointers alias the map's
storage; the iterator is invalidated by the next insertion,
removal or growth.
Types
struct
GetOrPutResult
src
Result of getOrPut. When found_existing is false the key has
been written into the map and the value is undefined until the
caller initializes value_ptr.
Fields
type fn
Auto
src
pub const Auto = map.Auto
A Custom that hashes keys with std.hash_map.AutoContext, like std's
AutoHashMap: one context, no type-dependent routing. Slices — including
[]const u8 — are rejected by std.hash.autoHash; string keys use
String.
Fields
ctrl: []u8
Control byte per bucket, plus a mirrored tail: `ctrl[bucket_count
- j]
duplicatesctrl[j % bucket_count]`, so a group read that runs past the last bucket reads the wrapped bytes. Zero-length in the empty map.
keys: []K
Key of the entry in each bucket; a bucket holds an entry only while its control byte is full.
values: []V
Value of the entry in each bucket.
bucket_count: usize
Number of buckets, a power of two; 0 in the empty map.
used: usize
Number of live entries.
context: Context
Constants
value
.{
.ctrl = &.{},
.keys = &.{},
.values = &.{},
.bucket_count = 0,
.used = 0,
.context = undefined,
}A map containing no entries. The context is undefined, as in
std.PriorityQueue.empty; use initContext to set it. Reads and
count work without allocating; the first insertion allocates
the initial table.
value
.{
.ctrl = &.{},
.keys = &.{},
.values = &.{},
.bucket_count = 0,
.used = 0,
.context = .{},
}Initialize and return a map with a default-initialized context.
Convenience for stateless contexts such as
std.hash_map.AutoContext and std.hash_map.StringContext;
contexts that carry state must use initContext.
Functions
pub fn initContext(context: Context) Self
src
Initialize and return a map with context.
Number of entries currently stored.
Number of entries the table can hold before the next insertion grows it: 7/8 of the bucket count, with at least one bucket left empty. The empty map has capacity 0.
Rebuild the table at its current bucket count, clearing every tombstone.
more
Churn — removals with no growth — leaves tombstones behind, and each one lengthens the probe path of a key that crosses it. Call this when a long-lived map holds few live entries after many removals. Capacity and bucket count do not change, so a map at its load limit cannot grow here.
Pointers into the table — from getPtr, getOrPut, or an iterator
— are invalidated, and bucket order changes. An empty map is
untouched.
Value stored for key, or null. Reads never allocate.
Pointer to the value stored for key, or null. The pointer is
invalidated by the next insertion or growth.
Whether key is stored in the map.
Insert or overwrite key.
Find or insert key. A new entry's value is undefined until the
caller initializes value_ptr. The table grows when live entries
fill the capacity, so the only failure is the allocator failing.
Remove key. Returns false when key is absent. The bucket
becomes a tombstone.
pub fn clearRetainingCapacity(self: *Self) void
src
Remove all entries, keeping the storage. Every control byte,
mirrored tail included, becomes empty.
pub fn clearAndFree(self: *Self, gpa: Allocator) void
src
Remove all entries and release the storage, returning to the empty state; the next insertion allocates again.
pub fn ensureTotalCapacity(
self: *Self,
gpa: Allocator,
expected: usize,
) Allocator.Error!void
src
Grow so that expected entries fit without another allocation;
no-op when the current capacity already covers expected.
Release the storage and invalidate the map.
An iterator over the entries in bucket order. The entry pointers alias the map's storage; the iterator is invalidated by the next insertion, removal or growth.
pub fn keyIterator(self: *Self) KeyIterator
src
An iterator over the keys in bucket order, matching iterator()
step for step. The pointers alias the map's storage; the iterator
is invalidated by the next insertion, removal or growth.
pub fn valueIterator(self: *Self) ValueIterator
src
An iterator over the values in bucket order, matching
keyIterator() step for step. The pointers alias the map's
storage; the iterator is invalidated by the next insertion,
removal or growth.
Types
struct
GetOrPutResult
src
Result of getOrPut. When found_existing is false the key has
been written into the map and the value is undefined until the
caller initializes value_ptr.
Fields
type fn
String
src
pub const String = map.String
A Custom for string keys, like std's StringHashMap: the one context
that hashes []const u8 by content. Key memory is managed by the caller.
Fields
ctrl: []u8
Control byte per bucket, plus a mirrored tail: `ctrl[bucket_count
- j]
duplicatesctrl[j % bucket_count]`, so a group read that runs past the last bucket reads the wrapped bytes. Zero-length in the empty map.
keys: []K
Key of the entry in each bucket; a bucket holds an entry only while its control byte is full.
values: []V
Value of the entry in each bucket.
bucket_count: usize
Number of buckets, a power of two; 0 in the empty map.
used: usize
Number of live entries.
context: Context
Constants
value
.{
.ctrl = &.{},
.keys = &.{},
.values = &.{},
.bucket_count = 0,
.used = 0,
.context = undefined,
}A map containing no entries. The context is undefined, as in
std.PriorityQueue.empty; use initContext to set it. Reads and
count work without allocating; the first insertion allocates
the initial table.
value
.{
.ctrl = &.{},
.keys = &.{},
.values = &.{},
.bucket_count = 0,
.used = 0,
.context = .{},
}Initialize and return a map with a default-initialized context.
Convenience for stateless contexts such as
std.hash_map.AutoContext and std.hash_map.StringContext;
contexts that carry state must use initContext.
Functions
pub fn initContext(context: Context) Self
src
Initialize and return a map with context.
Number of entries currently stored.
Number of entries the table can hold before the next insertion grows it: 7/8 of the bucket count, with at least one bucket left empty. The empty map has capacity 0.
Rebuild the table at its current bucket count, clearing every tombstone.
more
Churn — removals with no growth — leaves tombstones behind, and each one lengthens the probe path of a key that crosses it. Call this when a long-lived map holds few live entries after many removals. Capacity and bucket count do not change, so a map at its load limit cannot grow here.
Pointers into the table — from getPtr, getOrPut, or an iterator
— are invalidated, and bucket order changes. An empty map is
untouched.
Value stored for key, or null. Reads never allocate.
Pointer to the value stored for key, or null. The pointer is
invalidated by the next insertion or growth.
Whether key is stored in the map.
Insert or overwrite key.
Find or insert key. A new entry's value is undefined until the
caller initializes value_ptr. The table grows when live entries
fill the capacity, so the only failure is the allocator failing.
Remove key. Returns false when key is absent. The bucket
becomes a tombstone.
pub fn clearRetainingCapacity(self: *Self) void
src
Remove all entries, keeping the storage. Every control byte,
mirrored tail included, becomes empty.
pub fn clearAndFree(self: *Self, gpa: Allocator) void
src
Remove all entries and release the storage, returning to the empty state; the next insertion allocates again.
pub fn ensureTotalCapacity(
self: *Self,
gpa: Allocator,
expected: usize,
) Allocator.Error!void
src
Grow so that expected entries fit without another allocation;
no-op when the current capacity already covers expected.
Release the storage and invalidate the map.
An iterator over the entries in bucket order. The entry pointers alias the map's storage; the iterator is invalidated by the next insertion, removal or growth.
pub fn keyIterator(self: *Self) KeyIterator
src
An iterator over the keys in bucket order, matching iterator()
step for step. The pointers alias the map's storage; the iterator
is invalidated by the next insertion, removal or growth.
pub fn valueIterator(self: *Self) ValueIterator
src
An iterator over the values in bucket order, matching
keyIterator() step for step. The pointers alias the map's
storage; the iterator is invalidated by the next insertion,
removal or growth.
Types
struct
GetOrPutResult
src
Result of getOrPut. When found_existing is false the key has
been written into the map and the value is undefined until the
caller initializes value_ptr.
Fields
module
time
src
Io-less clock reads in std.Io.Timestamp values, for Linux and
macOS.
more
std.Io.Timestamp.now wants an Io that code without an event loop
does not carry, and each read is one clock_gettime anyway — vDSO on
Linux, one libc call on macOS — so now goes to the raw layer
directly, in std's own types: Clock in, Timestamp out, and the
whole Duration conversion ladder (toMicroseconds,
toMilliseconds, toSeconds) comes with the type.
CachedClock is the first-class cache: the caller owns the instance
and the refresh cadence — an event loop stores one and ticks it once
per iteration, making every timestamp during the tick one atomic
load instead of a clock call.
Duration, Timestamp, and their optional forms pack timeouts into one
64-bit word while distinguishing elapsed time from a clock reading.
writeRfc3339 turns an Io.Timestamp into UTC RFC 3339 text with a
comptime fractional width, for log lines and protocol headers.
Constants
pub const OptionalDuration = Optional(Duration)
src
pub const OptionalTimestamp = Optional(Timestamp)
src
pub const Rfc3339Error = @import("time/rfc3339.zig").Error
src
Functions
writeRfc3339 pub fn write(
writer: *Io.Writer,
timestamp: Io.Timestamp,
comptime precision: Precision,
) Error!void
src
Write timestamp as UTC RFC 3339: YYYY-MM-DDTHH:MM:SS[.fff]Z.
The precision sets the number of fractional digits. The value is
truncated to that width, not rounded. A year outside 0000-9999 returns
error.TimestampOutOfRange.
Read clock directly. One clock call, no Io.
more
The switch is exhaustive over Io.Clock on purpose: if std grows
a clock, this becomes a compile error rather than a silent wrong
mapping. The .awake and .boot arms carry the per-OS mapping
std's Io.Clock docs spell out; dead platform arms are pruned, and
the other three clocks share members on both.
Types
type fn
CachedClock
src
pub const CachedClock = @import("time/cached_clock.zig").CachedClock
Fields
cached: i64
Constants
Functions
Read the clock and store it. Returns the full-precision sample — the cache keeps one word.
The cached time — stale-never-ahead, or a direct read from a cold clock.
Drop the cache so the next read goes direct. A test that
pins time with refresh restores the clock with this.
module
Duration
src
A nonnegative elapsed time in one 64-bit word.
Conversions from std.Io.Duration reject negative or unrepresentable values.
Unit constructors reject multiplication overflow. A u64 nanosecond value
covers almost 585 years; an event loop never needs std's wider range here.
Constants
value
error{
/// A std value is negative or does not fit in a `u64`, or arithmetic exceeds
/// the duration's range.
OutOfRange,
}Functions
pub fn fromNanoseconds(value: u64) Duration
src
pub fn fromMicroseconds(value: u64) Error!Duration
src
pub fn fromMilliseconds(value: u64) Error!Duration
src
pub fn fromSeconds(value: u64) Error!Duration
src
pub fn fromNanosecondsComptime(comptime value: u64) Duration
src
Construct known nanoseconds without a failing unit conversion.
pub fn fromMicrosecondsComptime(comptime value: u64) Duration
src
Convert known microseconds. Overflow is a compile error.
pub fn fromMillisecondsComptime(comptime value: u64) Duration
src
Convert known milliseconds. Overflow is a compile error.
pub fn fromSecondsComptime(comptime value: u64) Duration
src
Convert known seconds. Overflow is a compile error.
Convert a std duration without accepting a negative elapsed time.
Widen the duration for a std wait. Every value fits std's i96.
pub fn toMicroseconds(self: Duration) u64
src
pub fn toMilliseconds(self: Duration) u64
src
type fn
Optional
src
pub const Optional = @import("time/Optional.zig").Optional
T is one of the time values with a u64 nanoseconds field.
Fields
nanoseconds: u64
Constants
value
error{
/// The supplied value equals the word reserved for `none`.
OutOfRange,
}Functions
Store an optional value. null returns none.
pub fn fromNanosecondsComptime(comptime value: u64) Self
src
Construct known nanoseconds. The reserved sentinel is a compile error.
pub fn fromMicrosecondsComptime(comptime value: u64) Self
src
Convert known microseconds. Overflow and the sentinel are compile errors.
pub fn fromMillisecondsComptime(comptime value: u64) Self
src
Convert known milliseconds. Overflow and the sentinel are compile errors.
pub fn fromSecondsComptime(comptime value: u64) Self
src
Convert known seconds. Overflow and the sentinel are compile errors.
Return the stored value, or null for none.
module
RateLimit
src
One log line per interval, with a count of the lines it held back.
A condition that repeats per connection or per accept (a full fd table)
would otherwise write one line per event. The caller logs only when
admit returns a count, and puts that count in the entry.
Constants
A one-second interval, with no line sent and nothing held back yet.
Functions
Null: hold this line back. Otherwise log it, with the returned count of
the lines held back since the previous one. now is a monotonic
sample.
module
Timestamp
src
A nonnegative clock reading in one 64-bit word.
more
Nanoseconds since the clock's epoch cover almost 585 years. The caller picks
one clock, such as .awake for deadlines, and does not mix it with another.
This type identifies a point on a clock; it does not support a negative
elapsed time. Use durationTo for a later reading and compare for either
ordering. Wall-clock formatting retains Io.Timestamp in RFC 3339 helpers.
now reads a clock straight into this type, for a caller that wants the
compact value and not the wide one.
Constants
Functions
pub fn fromNanoseconds(value: u64) Timestamp
src
pub fn fromMicroseconds(value: u64) Error!Timestamp
src
pub fn fromMilliseconds(value: u64) Error!Timestamp
src
pub fn fromSeconds(value: u64) Error!Timestamp
src
pub fn fromNanosecondsComptime(comptime value: u64) Timestamp
src
Construct known nanoseconds without a failing unit conversion.
pub fn fromMicrosecondsComptime(comptime value: u64) Timestamp
src
Convert known microseconds. Overflow is a compile error.
pub fn fromMillisecondsComptime(comptime value: u64) Timestamp
src
Convert known milliseconds. Overflow is a compile error.
pub fn fromSecondsComptime(comptime value: u64) Timestamp
src
Convert known seconds. Overflow is a compile error.
Convert a std timestamp. Values before the clock's epoch or beyond the
u64 nanosecond range return error.OutOfRange.
Widen the reading for std. Every value fits std's i96.
Read clock directly into a compact timestamp.
more
One clock read and no error union, so a struct field takes a decl literal:
started: Timestamp = .now(.awake). Every Io.Clock counts up from an epoch
that puts the reading inside u64 nanoseconds: .awake and .boot from
boot, .real from 1970, and the CPU clocks from zero. A safe build asserts
that range instead of hiding a catch unreachable at every call site.
The time from this timestamp to a fresh reading of clock.
more
The clock is a comptime parameter. Only the monotonic clocks can answer
without an error return: .awake, .boot, .cpu_process, and
.cpu_thread never step backwards, so the duration is never negative.
.real can step back, so elapsed(.real) is a compile error; take two wall
samples and use durationTo, which reports the step as error.OutOfRange.
The clock must be the one this timestamp came from. A Timestamp from
another clock can compare later than the reading and trips the assert in a
safe build.
pub fn toMicroseconds(self: Timestamp) u64
src
pub fn toMilliseconds(self: Timestamp) u64
src
Return the timestamp after duration, without restarting its budget.
pub fn durationTo(self: Timestamp, later: Timestamp) Error!Duration
src
Return later - self. A later reading before this timestamp cannot become
a nonnegative duration and returns error.OutOfRange.
enum
Rfc3339Precision
src
pub const Rfc3339Precision = @import("time/rfc3339.zig").Precision
The fractional-second width.
Fields
seconds seconds
No fractional part.
milliseconds milliseconds
Three digits: milliseconds.
microseconds microseconds
Six digits: microseconds.
nanoseconds nanoseconds
Nine digits: nanoseconds.
struct
WallFromAwake
src
Wall time derived from an .awake sample, through the offset between
the two clocks computed once at process startup. Both clocks are
process-wide, so the offset is identical on every thread: compute it
once, before threads spawn, and share the value.
more
The pattern this serves: a loop ticks one CachedClock(.awake) per
iteration and serves both deadline math and log timestamps from that
single sample — deadline math reads mono.now(), log timestamps read
toWall(mono.now()) — so a log line's timestamp is the same sample the
loop acted on. One clock read per tick, not two.
Derived wall never moves backwards within the process: the offset is
fixed and .awake never steps back, so timestamps keep monotonic
ordering — an NTP step cannot reorder log lines. The trade: derived
wall is not true wall; it drifts if the wall clock is stepped after
startup, bounded by the startup offset plus drift. For log timestamps
that is the right trade. True wall is what CachedClock(.real) and
now(.real) are for.
offset_ns is i64 nanoseconds: real-minus-awake ≈ real since the
epoch, so it carries the same year-2262 ceiling the CachedClock doc
flags for .real.
Fields
offset_ns: i64
Constants
pub const uninitialized: WallFromAwake = .{ .offset_ns = 0 }
src
Functions
The startup offset: read both clocks once and store the value wherever the process keeps startup state.
The wall time of an .awake sample.
module
timers
src
A set of timers over Io.Timestamp, backed by std.Treap.
more
An experiment: Go's time package mirrored onto Zig without
goroutines. The collection owns no clock and no wake machinery —
the caller drives every tick: a loop sleeps until next() and
calls expire(now) when it wakes, which fires everything due.
The entries are intrusive and caller-owned, std.Treap's own
shape: nothing is allocated, nothing is created by the
collection. The caller constructs a Timer — standalone, in an
array, or embedded in a connection record — and arms it into a
Timers. arm links it, stop unlinks it, and the node pointer
is the handle: removal is by node, never by key search.
Callbacks follow libxev's shape: the callback receives the
collection and the Timer back, and @fieldParentPtr recovers
the caller's enclosing record — no separate context pointer.
Callbacks run inside expire, after the tree surgery on their
own entry is complete, so a callback may arm, reset, or stop any
timer, including its own.
Constants
The erased callback shape expire invokes: the collection and the
entry back. Typed callbacks are stored through an inlining wrapper
built by arm — libxev's trick — so a fire costs one call through
this pointer with the typed body inlined into the wrapper, the
same indirection libxev carries.
Functions
A disarm-only callback for timers whose fire is observed by
armed and next() rather than a callback: a free function, the
void-record shape of arm's typed callbacks.
Types
struct
Timer
src
One timer, caller-owned. Construct it anywhere; arm links it
into a Timers and the node is the handle.
Fields
node: Treap(Key, keyOrder).Node
period: ?Io.Duration
A period re-arms the timer each time it fires: Go's Ticker.
The next deadline is the fired deadline plus the period, not
the caller's now, so drift never accumulates.
callback: ?Callback
Invoked by expire after the entry's tree surgery is
complete. A null callback fires silently — armed is the
observable state.
armed: bool
True between arm and fire-or-stop. stop and reset
report it: false means the timer already fired or was stopped.
Constants
value
.{
.node = undefined,
.period = null,
.callback = null,
.armed = false,
}The one-shot timer: no period, no callback — arm it, it fires
once. The fields carry no defaults, so a bare .{} does not
construct. Embed .one_shot as a record field default for the
common embedded shape.
Functions
The repeating timer: it fires, and .rearm from its callback
re-arms it at the fired deadline plus this period. The Go
split — NewTimer vs NewTicker — without a second type.
The armed deadline, or the last one a fired or stopped timer had. The timer must have been armed at least once: the node key of a never-armed timer is undefined.
struct
Timers
src
A set of timers over Io.Timestamp. No clock, no wake, no
allocation: the caller drives ticks and owns every entry. One
loop owns the set: no method is thread-safe, and no atomics are
involved.
Fields
treap: Treap(Key, keyOrder)
seq: u64
The tie-breaking sequence: equal deadlines fire in arm order. Wraps at 2^64 arms — ~585,000 years at a million arms a second, where wrapped ties would sort before live ones. Unreachable in practice; a process that lives that long can re-create its timers.
Constants
Functions
Arm a timer to fire at at. The timer must not be armed.
Arming an already-armed timer is a caller bug the assert
makes loud; reset is the re-arm path.
more
cb is the typed callback, inlined through the stored erased
pointer (libxev's trick): its first parameter is the enclosing
record's pointer type, and the wrapper recovers the record by
@fieldParentPtr("timer", ...) — so the record's Timer field
must be named timer. A void first parameter arms a timer
that is not embedded anywhere.
Stop an armed timer. Returns true if it was armed and is now
stopped; false if it had already fired or been stopped —
Go's Timer.Stop semantics, without the channel to drain.
Re-arm a timer to fire at at, armed or fired. Returns true
if it was still armed (reset before firing); false if it had
fired or been stopped — Go 1.23 Reset semantics. There is
no stale-delivery race to reason about: nothing is delivered
except inside expire, and false only means it fired.
The earliest armed deadline, what a loop sleeps toward:
Io.Timeout sleeps until this minus now. Null when nothing
is armed — a loop with a null next sleeps on its other
events.
Fire everything due at now, earliest first, ties in arm
order. A period timer re-arms at its deadline plus its period
when its callback returns .rearm, so the callback runs with
the entry disarmed and decides the next fire. Callbacks run
with the caller's tree consistent: a callback may arm, reset,
or stop any timer, including its own.
module
ultraloglog
src
Approximate distinct counting with UltraLogLog (Otmar Ertl, PVLDB 2024):
a flat [1 << precision]u8 register array with no allocator, no
initialization failure, and lossless merging across sketches of the same
precision (or downsizing to a lower precision).
more
Each byte stores the maximum run length seen in its substream in the high six bits plus two history bits indicating whether the two immediately preceding run lengths also occurred. Compared to HyperLogLog at the same accuracy, UltraLogLog uses about 28% less memory while keeping byte-aligned random access. Cardinality estimation uses the paper's Optimal FGRA estimator, including its small-range and large-range corrections, so one formula covers counts from zero up to 2^64.
Sketch is the hash-level primitive: it takes pre-hashed 64-bit values
directly. Custom, Auto, and String layer key hashing on top using the
std.hash_map split, delegating every register operation to Sketch.
Register encoding (the +4p - 8 byte shift so saturation always lands at
255) and the Optimal FGRA estimator follow Dynatrace's hash4j reference
implementation (Apache-2.0; see THIRD_PARTY.md).
Constants
pub const min_precision: u5 = 3
src
Minimum supported precision (2^3 = 8 registers).
pub const max_precision: u5 = 26
src
Maximum supported precision (2^26 = 67,108,864 registers).
value
error{
/// A register byte falls outside the states reachable at this precision.
InvalidRegister,
}Errors returned when validating a serialized register array.
Types
type fn
Auto
src
pub fn Auto(comptime T: type, comptime p: comptime_int) type
An UltraLogLog sketch that hashes keys with std.hash_map.AutoContext.
Slices — including []const u8 — are rejected by std.hash.autoHash;
string keys use String.
Fields
sketch: Raw
Underlying hash-level sketch.
Constants
Precision parameter p; the sketch holds 2^p byte registers.
pub const register_count: usize = Raw.register_count
src
Number of byte registers (1 << precision).
pub const relative_standard_error: f64 = Raw.relative_standard_error
src
Asymptotic relative standard error (sqrt(v / 2^p), about 0.782 / sqrt(2^p)).
An empty sketch with all registers zeroed.
Functions
Hash key with Context and insert it into the sketch.
Insert a pre-hashed uniform 64-bit value directly.
Estimate the number of distinct keys added to this sketch.
Fold other into self. The result matches inserting the union of
both streams into one sketch.
pub fn downsize(
self: *const Self,
comptime target_precision: comptime_int,
) Custom(T, Context, target_precision)
src
Return an equivalent sketch at target_precision <= precision.
Whether no keys have been added since initialization or clear.
Reset all registers to zero.
Borrow the raw byte registers for serialization.
Reconstruct a sketch from serialized register bytes, validating
that every byte is reachable at precision.
type fn
String
src
pub fn String(comptime p: comptime_int) type
An UltraLogLog sketch for string keys ([]const u8), using
std.hash_map.StringContext. Key memory is managed by the caller.
Fields
sketch: Raw
Underlying hash-level sketch.
Constants
Precision parameter p; the sketch holds 2^p byte registers.
pub const register_count: usize = Raw.register_count
src
Number of byte registers (1 << precision).
pub const relative_standard_error: f64 = Raw.relative_standard_error
src
Asymptotic relative standard error (sqrt(v / 2^p), about 0.782 / sqrt(2^p)).
An empty sketch with all registers zeroed.
Functions
Hash key with Context and insert it into the sketch.
Insert a pre-hashed uniform 64-bit value directly.
Estimate the number of distinct keys added to this sketch.
Fold other into self. The result matches inserting the union of
both streams into one sketch.
pub fn downsize(
self: *const Self,
comptime target_precision: comptime_int,
) Custom(T, Context, target_precision)
src
Return an equivalent sketch at target_precision <= precision.
Whether no keys have been added since initialization or clear.
Reset all registers to zero.
Borrow the raw byte registers for serialization.
Reconstruct a sketch from serialized register bytes, validating
that every byte is reachable at precision.
type fn
Custom
src
pub fn Custom(comptime T: type, comptime Context: type, comptime p: comptime_int) type
An UltraLogLog sketch over keys of type T, hashing through Context
(which must provide hash(Context, T) u64) and delegating all register
work to Sketch(p).
Fields
sketch: Raw
Underlying hash-level sketch.
Constants
Precision parameter p; the sketch holds 2^p byte registers.
pub const register_count: usize = Raw.register_count
src
Number of byte registers (1 << precision).
pub const relative_standard_error: f64 = Raw.relative_standard_error
src
Asymptotic relative standard error (sqrt(v / 2^p), about 0.782 / sqrt(2^p)).
An empty sketch with all registers zeroed.
Functions
Hash key with Context and insert it into the sketch.
Insert a pre-hashed uniform 64-bit value directly.
Estimate the number of distinct keys added to this sketch.
Fold other into self. The result matches inserting the union of
both streams into one sketch.
pub fn downsize(
self: *const Self,
comptime target_precision: comptime_int,
) Custom(T, Context, target_precision)
src
Return an equivalent sketch at target_precision <= precision.
Whether no keys have been added since initialization or clear.
Reset all registers to zero.
Borrow the raw byte registers for serialization.
Reconstruct a sketch from serialized register bytes, validating
that every byte is reachable at precision.
type fn
Sketch
src
pub fn Sketch(comptime p: comptime_int) type
The hash-level UltraLogLog primitive: a flat [1 << p]u8 array driven
directly by uniform 64-bit hashes.
Typical precisions: p = 10 (1 KiB, ~2.4% RSE), p = 12 (4 KiB, ~1.2%
RSE), p = 14 (16 KiB, ~0.61% RSE), p = 16 (64 KiB, ~0.31% RSE).
Fields
registers: [register_count]u8
Constants
Precision parameter p; the sketch holds 2^p byte registers.
pub const register_count: usize = @as(usize, 1) << p
src
Number of byte registers (1 << precision).
pub const relative_standard_error: f64 = …
src
value
@sqrt(
fgra.variance_factor / @as(comptime_float, register_count),
)Asymptotic relative standard error (sqrt(v / 2^p), about 0.782 / sqrt(2^p)).
An empty sketch with all registers zeroed.
Functions
Insert a uniform 64-bit hash into the sketch. Requires a
high-quality hash (such as std.hash.Wyhash or stdx.hash.RapidHash)
whose bits are uniformly distributed.
Estimate the number of distinct hashes added using the Optimal FGRA
estimator (Ertl 2024 Algorithm 6). Returns 0.0 for an empty sketch
and +inf if every register is saturated at 255.
Fold other into self. Idempotent, commutative, and associative.
pub fn downsize(
self: *const Self,
comptime target_precision: comptime_int,
) Sketch(target_precision)
src
Produce an equivalent sketch at a smaller (or equal) precision
target_precision. The result is bit-for-bit identical to inserting
the original hashes directly at target_precision.
Whether all registers are zero.
Reset all registers to zero.
Borrow the raw register bytes for serialization.
Reconstruct a sketch from serialized register bytes. Returns
error.InvalidRegister if any byte is not a reachable state at
precision.
module
Uuid
src
RFC 9562 UUIDs: generate (v4, v7), parse, format.
more
Generation is Io-less: v4 draws all 128 bits from random.fill, v7
takes its timestamp from time.now(.real) and the rest from
random.fill. v7 is ordered across milliseconds but not within one —
the monotonic counter of RFC 9562 §5.2 needs mutable state, which a
bare constructor refuses to smuggle, so callers that need same-ms
ordering serialize at their end.
parse accepts the canonical 36-byte form, either case, and does not
reject unknown versions or variants: an unparseable future UUID is
still a UUID.
Constants
pub const ParseError = …
src
value
error{
/// Not exactly 36 bytes.
InvalidLength,
/// A hyphen is missing or misplaced.
InvalidHyphen,
/// A non-hex digit where one belongs.
InvalidCharacter,
}Functions
Generate a v4 (random) UUID. Six bits are fixed: version 4, variant 10.
The bits come from random.fill: a per-thread CSPRNG seeded from the
platform's secure source, the Io.random semantics — satisfying RFC
9562 §6.2. Every thread's RNG state is its own, never shared.
Generate a v7 UUID: the leading 48 bits are the Unix timestamp in milliseconds, big-endian; the rest is random. Ordered across milliseconds, unordered within one — see the module doc.
Parse the canonical 36-byte form, either case.
Types
module
wire
src
Forward-only encoding and decoding of caller-owned bytes, with the byte order fixed at comptime.
more
Writer(.big) and Writer(.little) write fixed-width integers, enums, and
packed structs in the chosen order, byte slices, reserved slots, and LEB128
varints. A reserved slot is the reason this exists as a type: a length
prefix, checksum, or tag is often known only after the body, and reserve
hands back the bytes to fill later.
Reader(.big) and Reader(.little) are the inverse. They read the same
widths and hand back zero-copy slices of the bytes they were given: a run of
n bytes, or the bytes before a delimiter. The peek forms return the same
values and leave the cursor alone.
A varint carries its own length, so it has no width parameter and no slot.
appendLeb128 and readLeb128 take the sign from the type: an unsigned
width writes ULEB128 and a signed one writes SLEB128.
A packed struct has a defined bit layout and no padding, so it writes as its
backing integer in one store, and a run of values wider than a byte takes
appendSliceEndian and readSliceEndian, which order each element instead
of copying bytes.
Every fallible method has an unchecked form. The checked form returns an error; the unchecked form asserts the same bound, so it panics in Debug and ReleaseSafe and compiles out in ReleaseFast, where an overstep writes or reads out of bounds. A parser that has checked the total length once uses the unchecked forms so it does not branch on every field.
Why not std.Io.Reader and std.Io.Writer
Those are stream interfaces: a vtable, a buffer the reader refills from a
source, and one error.WriteFailed for every sink failure. This is the
layer underneath them. read is std.mem.readInt plus one compare, and
std.Io.Reader.takeInt inlines to the same instructions on a fixed buffer,
so taking it on would add a vtable and a coarser error set and buy nothing.
std.Io.Reader has no unchecked forms at all, which is the other half of
the point. On the write side append is also cheaper than writeInt,
because writeInt routes through writeAll, which does not inline: five
integers cost five calls there and none here.
Constants
pub const Leb128Error = …
src
value
error{
/// The bytes ended before the terminator byte.
UnexpectedEof,
/// A byte past the width of the type does not extend the value.
Overflow,
}The error set of Reader.readLeb128.
Types
type fn
Writer
src
pub fn Writer(comptime endian: std.builtin.Endian) type
A forward-only writer of big- or little-endian values into caller-owned bytes.
The byte order is a comptime parameter, so Writer(.big) and
Writer(.little) are different types and each fixed-width store compiles
to its own code. The byte slices and reserved slots are order-agnostic.
Fields
Constants
pub const byte_order = endian
src
The byte order this writer uses.
A writer over no storage. Only zero-length writes fit.
Functions
Use buffer as the whole capacity. The writer starts empty.
The whole storage length.
The bytes written so far, mutable for in-place work such as encryption.
pub fn constBuffered(self: *const Self) []const u8
src
The const form of buffered.
pub fn unusedCapacitySlice(self: *Self) []u8
src
The free tail. Write into this slice, then call advance. The slice
is only valid until the next append or advance.
pub fn unusedCapacityLen(self: *const Self) usize
src
The number of free bytes.
Reset the write cursor. The written bytes stay in the backing.
Commit n bytes written into unusedCapacitySlice. Returns
error.NoSpaceLeft when n exceeds the free tail.
pub fn advanceAssumeCapacity(self: *Self, n: usize) void
src
advance without the error return. Asserts
n <= unusedCapacityLen().
Append an integer, enum, or packed struct in the writer's byte order.
more
Integers of any byte width work, including u24, u48, u128,
and the signed types. An enum is written as its backing integer, and
a packed struct too, since it has no padding: its fields fill that
integer from its low bit. Returns error.NoSpaceLeft when the value
does not fit.
pub fn appendAssumeCapacity(self: *Self, comptime T: type, value: T) void
src
append without the error return. Asserts the value fits.
pub fn appendSlice(self: *Self, bytes: []const u8) error{NoSpaceLeft}!void
src
Append a byte slice. Returns error.NoSpaceLeft when it does not
fit.
pub fn appendSliceAssumeCapacity(self: *Self, bytes: []const u8) void
src
appendSlice without the error return. Asserts the slice fits.
pub fn appendSliceEndian(
self: *Self,
comptime Elem: type,
values: []const Elem,
) error{NoSpaceLeft}!void
src
Append a slice of integers or packed structs in the writer's byte
order, one element at a time. Returns error.NoSpaceLeft when the
run does not fit.
appendSlice copies bytes verbatim, which is wrong for an array of
multi-byte values on a host whose order differs. This one writes
through append, so the caller gets the same bytes as a loop.
pub fn appendSliceEndianAssumeCapacity(
self: *Self,
comptime Elem: type,
values: []const Elem,
) void
src
appendSliceEndian without the error return. Asserts the run fits.
Reserve n bytes and return them. The caller fills the slot later,
for a length prefix, checksum, or tag that is not known until the
body is written. Returns error.NoSpaceLeft when the slot does not
fit.
pub fn reserveAssumeCapacity(self: *Self, comptime n: usize) *[n]u8
src
reserve without the error return. Asserts the slot fits.
pub fn appendLeb128(self: *Self, comptime T: type, value: T) error{NoSpaceLeft}!void
src
Append a LEB128-encoded integer.
An unsigned value writes unsigned LEB128 and a signed value
writes signed LEB128. The length follows from the value, so the
write is never padded and never needs a slot. Returns
error.NoSpaceLeft when the encoding does not fit.
pub fn appendLeb128AssumeCapacity(self: *Self, comptime T: type, value: T) void
src
appendLeb128 without the error return. Asserts the encoding fits.
Drop the last n bytes from the output. Asserts n fits the bytes
written.
A speculatively written field that the caller decides against comes
back off the output this way. The bytes stay in the backing, so a
later append overwrites them, and a slot below the new cursor is no
longer part of buffered.
type fn
Reader
src
pub fn Reader(comptime endian: std.builtin.Endian) type
A forward-only reader of big- or little-endian values from caller-owned bytes.
more
The byte order is a comptime parameter, so Reader(.big) and
Reader(.little) are different types and each fixed-width load compiles to
its own code. The byte slices and skips are order-agnostic.
The read, readSlice, readUntil, and skip forms return
error.UnexpectedEof when the request exceeds the unread bytes. The
peek forms return the same values and leave the cursor alone. The
assume forms assert the same bound instead. Bounds are checked as
n > remaining().len, never end + n, which would wrap in ReleaseFast.
A failed read never moves the cursor, so a framer can restore its start and retry once more bytes arrive.
Fields
buffer: []const u8
The full storage.
end: usize
One past the last read byte. A caller that tracks offsets may read
the field, and a caller that backtracks may assign it, such as a
framer that restores the start of a partial message. Prefer
consumed and remaining for the slices.
Constants
pub const byte_order = endian
src
The byte order this reader uses.
A reader over no storage. Only zero-length reads fit.
Functions
Use buffer as the whole storage. The reader starts empty.
The whole storage length.
The bytes read so far.
The unread bytes.
Read an integer, enum, or packed struct in the reader's byte order.
Returns error.UnexpectedEof when the value does not fit.
more
Integers of any byte width work, including u24, u48, u128,
and the signed types. An enum is read as its backing integer, and a
packed struct too. Only non-exhaustive enums are allowed: an unknown
tag is representable, so validation stays with the caller instead of
a panic here.
pub fn assumeRead(self: *Self, comptime T: type) T
src
read without the error return. Asserts the value fits.
Read the next value without moving the cursor. Returns
error.UnexpectedEof when the value does not fit.
This is how a decoder looks at a tag or a length before it commits to reading it, or decides which decoder to route a field to.
pub fn assumePeek(self: *Self, comptime T: type) T
src
peek without the error return. Asserts the value fits.
pub fn readSliceEndian(
self: *Self,
comptime Elem: type,
dest: []Elem,
) error{UnexpectedEof}!void
src
Read dest.len integers or packed structs in the reader's byte
order into dest. Returns error.UnexpectedEof when the run does
not fit.
This is the one read that cannot hand back a slice: the values are
only Elem once the byte order is applied, so the bytes have to
land somewhere first. On a host whose order already matches, a
readSlice and a cast do the same job.
pub fn assumeReadSliceEndian(self: *Self, comptime Elem: type, dest: []Elem) void
src
readSliceEndian without the error return. Asserts the run fits.
Read n bytes as a zero-copy slice. Returns
error.UnexpectedEof when the slice does not fit.
pub fn assumeReadSlice(self: *Self, n: usize) []const u8
src
readSlice without the error return. Asserts the slice fits.
Read the next n bytes without moving the cursor. Returns
error.UnexpectedEof when the slice does not fit.
pub fn assumePeekSlice(self: *Self, n: usize) []const u8
src
peekSlice without the error return. Asserts the slice fits.
Read the bytes before delimiter, then consume the delimiter. The
returned slice is a zero-copy view and excludes the delimiter.
more
This is the lengthless field: a C string ends at a NUL, a line at a
newline. The delimiter is a parameter, not a fixed 0, so the rule
"a field with no terminator is error.UnexpectedEof" lives in one
place rather than in every protocol decoder.
Returns error.UnexpectedEof when delimiter is not in the unread
bytes. The cursor does not move in that case, and the delimiter is
consumed only on success.
pub fn assumeReadUntil(self: *Self, delimiter: u8) []const u8
src
readUntil without the error return. Asserts delimiter is in the
unread bytes.
Peek the bytes before delimiter without moving the cursor. The
delimiter is not consumed and is not part of the slice.
Returns error.UnexpectedEof when delimiter is not in the unread
bytes.
pub fn assumePeekUntil(self: *Self, delimiter: u8) []const u8
src
peekUntil without the error return. Asserts delimiter is in the
unread bytes.
Skip n bytes. Returns error.UnexpectedEof when the skip does not
fit.
pub fn assumeSkip(self: *Self, n: usize) void
src
skip without the error return. Asserts the skip fits.
pub fn readLeb128(self: *Self, comptime T: type) Leb128Error!T
src
Read a LEB128-encoded integer.
more
An unsigned T reads unsigned LEB128 and a signed T reads signed
LEB128. The encoding carries its own length, so no width is read
here and none is written by appendLeb128.
Returns error.UnexpectedEof when the bytes end before the
terminator. Returns error.Overflow when a byte past the width of
T is not a valid extension of the value, so a redundant tail is
rejected without stranding the cursor: the whole encoding is
consumed first. A failed read leaves the cursor where it was.
pub fn assumeReadLeb128(self: *Self, comptime T: type) T
src
readLeb128 without the error return. Asserts the bytes are there
and the encoding fits.
module
pages
src
Linux-only by design; the comptime branch prunes the import on other platforms so the package builds on darwin.
Constants
The intentional std.heap.page_allocator. See the module doc for the
contracts that make an allocation through this alias deliberate.
Functions
Reserve n items of T as one private anonymous mapping, untouched:
the kernel supplies zero pages at first touch. Nothing here rides
Allocator.alloc — its undefined-fill touches every byte of the
allocation at once, which is exactly the resident memory a lazy
reservation exists to avoid. The reservation is whole kernel pages
alone: release drops it exactly.
Unreserve a reserve mapping: rawFree, never the freeing interface —
its undefined-fill would touch the whole reservation again on the way
out. An empty reservation unreserves nothing.
pub fn allocForTest(gpa: Allocator, n: usize) ![]u8
src
A block of n pages aligned to pageSize(), for tests. Free it with
freeForTest.
pub fn freeForTest(gpa: Allocator, block: []u8) void
src
The whole kernel pages inside bytes: empty when bytes spans none.
Drop the whole pages inside bytes. Best effort: on failure the pages
stay resident and keep their bytes, which the caller already wiped.
module
slot_ring
src
Linux-only by design; the comptime branch prunes the import on other platforms so the package builds on darwin.
Types
enum
Wake
src
The wake mechanism. Decided by the consumer's shape, so it is compile-time.
Fields
none none
No wake state at all: the caller drives every drain. Nothing is spent on the producer path and no field exists for waking.
eventfd eventfd
A best-effort eventfd poke, gated on an armed consumer: no
syscall while no consumer is armed, and a poke per commit while
one is. The fd is exposed for a poll loop; armDoorbell and
disarmDoorbell bracket the wait. A lost poke only delays the
drain until the next event — the ring is the source of truth,
the fd is only a doorbell.
futex futex
The armed-waiter-bit futex protocol for a dedicated blocking consumer thread: a generation counter in the low bits, the waiter flag in bit 31, both RMWs on the same word so the notify gate and the waiter's arm cannot miss each other. Includes the shutdown handshake.
enum
OnFull
src
What a producer does when the claimed slot is still owned: the consumer has not released it, or a producer is stalled mid-write.
Fields
drop_new drop_new
Drop the new message: acquire returns null. The logging
default — never block, never corrupt, and the loss is one
message, visible to the caller. Bounded loss: under a stall,
the newest messages are the ones refused.
drop_oldest drop_oldest
Displace the oldest committed message and claim its slot, so
the newest message lands and the loss moves to the oldest.
crossbeam's force_push on this stamp substrate: the
ring owns the consumer cursor (readHead), the consumer's
claiming read(buf) wins that cursor with a CAS before it
copies, and a displacing producer wins the same CAS to drop the
oldest — one cursor CAS arbitrates, so a slot's bytes are never
copied and displaced at once. A displacement that cannot win
the cursor in bounded steps — a reader mid-copy, or a displacer
that won and has not freed its slot — refuses the claim: the
new message drops, as under drop_new. The consumer reads
through read(buf), which copies into the caller's buffer
inside its window; no borrowed slice is returned.
struct
Options
src
The options of Mpsc. Comptime throughout: each configuration
compiles to its own code, per the fmt.AtoiOptions convention.
Fields
slot_size: comptime_int = 1024
Total slot size in bytes, stamp word included. Must be a
multiple of the cache line: adjacent slots must not share one,
or producers on neighboring slots dirty each other's stamps.
The payload capacity is slot_size - 8.
wake: Wake = .none
The wake mechanism. See Wake.
on_full: OnFull = .drop_new
What a producer does when the claimed slot is still owned. See
OnFull.
type fn
Mpsc
src
pub fn Mpsc(comptime options: Options) type
An MPSC slot ring. Build with Mpsc(options); the instance is
initialized with init.
Fields
slots: []align(atomic.cache_line) Slot
mask: u64
lap_shift: u6
The shift from a claim position to its lap: positions are per-slot counts, laps are per-revolution counts.
hot: Hot align(atomic.cache_line)
Producer-touched state, on its own line.
read_head: if (options.on_full == .drop_oldest)
atomic.Value(u64)
else
void align(cursor_align)
.drop_oldest: the ring-owned consumer cursor. The
consumer's claiming read(buf) advances it with an
acquire/release CAS; a producer reads it and advances it
only to displace the oldest message under the full
condition. .drop_new has no such word — the caller owns
the cursor.
displaced: if (options.on_full == .drop_oldest)
atomic.Value(u64)
else
void align(cursor_align)
.drop_oldest: successful displacements, one per dropped
oldest message. Loss accounting, read like head(). Its
own cache line: the fetchAdd must not dirty read_head's
line, which the consumer's claiming CAS touches every
message.
shutdown: if (options.wake == .futex) atomic.Value(bool) else void
Futex flavor: set once, read only by the waiter's loop — cold on the producer path.
io: if (options.wake == .futex) Io else void
Futex flavor: the Io whose futex wait/wake backs the protocol. Captured at init so arm, wait, and wake all dispatch through one backend.
notify_fd: if (options.wake == .eventfd) linux.fd_t else void
Eventfd flavor: the doorbell fd, created at init before any allocation, so a failed creation leaks nothing and propagates.
Constants
pub const payload_size: usize = options.slot_size - @sizeOf(u64)
src
Payload bytes per slot: the stamp word is part of the slot.
value
if (options.on_full == .drop_oldest) void else struct {
payload: []const u8,
slot: *Slot,
lap: u32,
/// Release the slot back to producers: write the stamp of
/// the next lap, the free word the wrapping producer is
/// waiting to see. The release store orders the consumer's
/// last read of the payload before the next producer's write.
///
/// The stamp still names this read's lap: the single
/// consumer owns it until this store, so any other value is
/// a mis-sequenced release (out of order, or a second
/// release of an already-released slot) — loud in Debug.
pub fn release(self: Read) void {
assert(@as(u32, @truncate(self.slot.stamp.load(.monotonic) >> 32)) == self.lap);
self.slot.stamp.store(@as(u64, self.lap +% 1) << 32, .release);
}
}.drop_new's borrowed read lease on one slot: the committed
payload, plus the slot and its lap, so release writes the
next-lap stamp without recomputing the slot address. Under
.drop_oldest the type is void: a borrowed slice cannot be
made safe against displacement, so the claiming read(buf)
copies inside its won window instead.
Functions
Initialize the ring. num_slots rounds up to a power of
two. The io parameter is the futex backend, ignored by the
other flavors.
Tear the ring down. Requires no active producers, consumer, or leases — the caller quiesces first.
Claim a slot for writing. Returns null when the slot the
head points at is still owned — the consumer has not
released it, or the producer that claimed it is stalled
mid-write (the on_full policy); a refused claim burns no
position, so the consumer never sees a hole.
more
The claim is a CAS on the head, Vyukov's shape: positions are claimed strictly in order, so only one producer can hold a lap of a slot, and a failed claim leaves the head where it was. Under contention a producer retries at the new head — one hint between attempts — rather than ever blocking.
.drop_oldest: an owned slot with a committed message is
not refused. The producer displaces the oldest message —
CAS-advances the ring-owned consumer cursor past it and
frees its slot — then retries the claim, so the newest
message lands and the oldest is dropped. An owned slot
whose stamp names no committed message is a producer stalled
mid-write; there is nothing to displace, and freeing that
slot would let the late commit rewind the stamp, so the
claim is refused. A displacement that cannot win the cursor
in bounded steps — the consumer is inside its claimed
window, or another displacer won and has not freed the slot
— also refuses: the claim returns null and the new message
drops, so a paused consumer or displacer stalls no producer.
pub fn read(
self: if (options.on_full == .drop_oldest) *Self else *const Self,
arg: if (options.on_full == .drop_oldest) []u8 else u64,
) if (options.on_full == .drop_oldest) ?[]u8 else ?Read
src
.drop_new: the committed payload at read_pos, or null
when it is not committed yet — a producer claimed but has
not finished writing. The single consumer owns read_pos
and advances past a slot only by releasing the read lease;
the returned Read borrows the slot.
more
.drop_oldest: the claiming consume. Loads the ring-owned
cursor, checks the slot at it is committed — a stamp naming
the cursor's lap with a nonzero length — and CAS-advances
the cursor past it, acquire/release, before it touches
payload bytes. A lost CAS returns null and reads no payload:
a displacer took the cursor, and the message is its loss. A
won CAS owns the window — a displacer's expected cursor
value is now stale, so it cannot free this slot — so the
payload is copied into buf and the slot is freed with the
next-lap stamp, a release store. Returns buf[0..len].
The ordering, and why no other fence is needed: the committed stamp's acquire-load observes the producer's publication, so the payload reads happen after it; the cursor CAS excludes displacement for the won window; and the final release store orders the copied reads before the next producer's write.
A buf smaller than the committed length is a caller bug:
the Debug assert and the ReleaseSafe slice check are loud,
and ReleaseFast is undefined. Size the buffer to
payload_size.
Number of claims handed out, committed or not.
.drop_oldest: the ring-owned consumer cursor, the next
position the consumer may read. A displacing producer can
advance it at any time, and the claiming read(buf) loads
it itself; this is for accounting and for callers that need
the cursor without consuming.
pub fn displacedCount(self: *const Self) u64
src
.drop_oldest: messages displaced by producers, one per
oldest message dropped to make room for a newer one. Loss
accounting, read like head().
Number of slots in the ring.
Eventfd flavor: the fd to poll. Created at init — a caller
that prefers a caller-driven ring without an fd uses the
.none flavor.
pub fn armDoorbell(self: *Self) void
src
Eventfd flavor: arm the doorbell for the wait about to happen. The consumer brackets its wait with the arm and the disarm:
more
// {
// ring.armDoorbell();
// defer ring.disarmDoorbell();
// // Re-check the ring; wait only if it is still empty.
// }
// Then acknowledge the doorbell if it rang, and drain.
Disarm on EVERY wake — doorbell, socket, timer, anything.
The arm is the producers' gate: a commit observes the armed
bit and pokes, and with no arm there is no poke, so the
re-check after the arm is what finds commits that landed
unannounced. Do not call ackDoorbell between the final
empty check and the wait: the counter is the pending
notification, and the ack erases it. A caller that never
arms gets no pokes between generation carries: each commit
bumps the generation, and the 31-bit carry into the waiter
bit arms a phantom waiter until an arm/disarm cycle clears
it.
pub fn disarmDoorbell(self: *Self) void
src
Eventfd flavor: disarm the doorbell on every wake, whatever woke the consumer. The armed bit gates the producers' pokes, so a consumer that stays armed pays a write syscall per commit; the disarm is the release RMW that clears it.
pub fn ackDoorbell(self: *Self) void
src
Eventfd flavor: drain the doorbell counter. The consumer
calls this when the fd reads ready, before draining the
ring — the ring is the source of truth, the counter only
arms the poll again. Benign on an unwoken fd (the read
returns EAGAIN), so a spurious ack cannot wedge the doorbell.
Never call it between the final empty check and the wait:
the counter is the pending notification, and the ack erases
it (see armDoorbell).
pub fn waitForData(self: *Self, read_pos: u64) bool
src
Futex flavor: wait until the slot at the consumer's position
is committed, or shutdown is requested and everything
committed before it is drained. Returns true when there is
data to read, false when the consumer should exit.
.drop_oldest ignores read_pos: the ring owns the cursor.
pub fn requestShutdown(self: *Self) void
src
Futex flavor: request shutdown and wake the consumer.
waitForData returns false once everything committed
before this is drained. Requires producers to have stopped
claiming first.
pub fn isShutdown(self: *const Self) bool
src
Futex flavor: has shutdown been requested?
Types
struct
Lease
src
The producer's lease on one slot.
Fields
slot: *Slot
pos: u64
The claim position, for logging and truncation markers.
lap: u32
The lap of the claim, carried so commit builds the
stamp word without reloading the shift and recomputing
it — one load and one shift off every commit.
spent: bool
Set by commit: a second commit can rewind the stamp
after the consumer released the slot, wedging the ring
permanently — the assert makes the misuse loud in Debug.
Functions
A writer over the slot payload. end is the length to
commit.
Commit the message: publish the payload under the lease's lap, then wake the consumer per the flavor. The wake is folded in so a commit cannot forget it.
The ring position of this lease, for logging and truncation markers.