stdx API reference Changelog View on GitHub

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

pub fn decode(comptime N: comptime_int, src: *const SymbolCount(N)) error{InvalidSymbol}![N]u8

src

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.

pub fn encode(comptime N: comptime_int, bytes: *const [N]u8) SymbolCount(N)

src

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.

pub const standard = Codec(standard_alphabet, '=')

src

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.

pub const url_safe = Codec(url_safe_alphabet, '=')

src

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.

pub const Error = …

src
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.

pub fn encode(dest: []u8, source: []const u8) []const u8

src

Encode source into dest and return the characters written. dest.len must be at least encodedLen(source.len).

pub fn decode(dest: []u8, source: []const u8) Error![]u8

src

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

pub inline fn clear(self: *Self) void

src

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.

pub inline fn isSet(self: *const Self, index: usize) bool

src

pub inline fn set(self: *Self, index: usize) void

src

pub fn unset(self: *Self, index: usize) void

src

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.

pub const bits: u64 = math.ceilPowerOfTwoAssert(u64, @max(optimal_bits, 2))

src

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.

pub const Index = math.IntFittingRange(0, bits)

src

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.

pub const empty: Self = .{ .bit_set = .empty, .added = 0 }

src

A filter with no keys added.

Functions

pub fn count(self: *const Self) u64

src

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.

pub fn add(self: *Self, key: T) void

src

Add key: set its hash_functions probe bits. Adding is infallible — the capacity is fixed and the bits are shared.

pub fn contains(self: *const Self, key: T) bool

src

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.

pub fn clear(self: *Self) void

src

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.

pub const bits: u64 = math.ceilPowerOfTwoAssert(u64, @max(optimal_bits, 2))

src

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.

pub const Index = math.IntFittingRange(0, bits)

src

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.

pub const empty: Self = .{ .bit_set = .empty, .added = 0 }

src

A filter with no keys added.

Functions

pub fn count(self: *const Self) u64

src

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.

pub fn add(self: *Self, key: T) void

src

Add key: set its hash_functions probe bits. Adding is infallible — the capacity is fixed and the bits are shared.

pub fn contains(self: *const Self, key: T) bool

src

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.

pub fn clear(self: *Self) void

src

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.

pub const bits: u64 = math.ceilPowerOfTwoAssert(u64, @max(optimal_bits, 2))

src

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.

pub const Index = math.IntFittingRange(0, bits)

src

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.

pub const empty: Self = .{ .bit_set = .empty, .added = 0 }

src

A filter with no keys added.

Functions

pub fn count(self: *const Self) u64

src

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.

pub fn add(self: *Self, key: T) void

src

Add key: set its hash_functions probe bits. Adding is infallible — the capacity is fixed and the bits are shared.

pub fn contains(self: *const Self, key: T) bool

src

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.

pub fn clear(self: *Self) void

src

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

pub const Index = std.math.IntFittingRange(0, buffer_capacity)

src

Smallest integer type that can hold 0..capacity.

pub const capacity: Index = @intCast(buffer_capacity)

src

Maximum number of entries the map can hold.

pub const empty: Self = …

src
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.

pub const init: Self = …

src
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.

pub fn count(self: *const Self) Index

src

Number of entries currently stored.

pub fn keys(self: *Self) []K

src

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.

pub fn values(self: *Self) []V

src

The values in insertion order. The slice is invalidated by the next insertion or removal.

pub fn get(self: *const Self, key: K) ?V

src

Value stored for key, or null.

pub fn getPtr(self: *Self, key: K) ?*V

src

Pointer to the value stored for key, or null. The pointer is invalidated by the next insertion or removal.

pub fn contains(self: *const Self, key: K) bool

src

Whether key is stored in the map.

pub fn put(self: *Self, key: K, value: V) error{NoSpaceLeft}!void

src

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.

pub fn getOrPut(self: *Self, key: K) error{NoSpaceLeft}!GetOrPutResult

src

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.

pub fn clear(self: *Self) void

src

Remove all entries, keeping the storage. The map is immediately reusable.

pub fn iterator(self: *Self) Iterator

src

An iterator over the entries in insertion order. Modifying the map invalidates it.

Types

struct Entry

src

Pointers to a key and value stored in the map.

Fields

key_ptr: *K
value_ptr: *V

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

key_ptr: *K
value_ptr: *V
index: Index

struct Iterator

src

Fields

map: *Self
index: Index

Functions

pub fn next(it: *Iterator) ?Entry

src

The next entry in insertion order, or null.

pub fn reset(it: *Iterator) void

src

Reset the iterator to the first entry.

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

pub const Index = std.math.IntFittingRange(0, buffer_capacity)

src

Smallest integer type that can hold 0..capacity.

pub const capacity: Index = @intCast(buffer_capacity)

src

Maximum number of entries the map can hold.

pub const empty: Self = …

src
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.

pub const init: Self = …

src
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.

pub fn count(self: *const Self) Index

src

Number of entries currently stored.

pub fn keys(self: *Self) []K

src

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.

pub fn values(self: *Self) []V

src

The values in insertion order. The slice is invalidated by the next insertion or removal.

pub fn get(self: *const Self, key: K) ?V

src

Value stored for key, or null.

pub fn getPtr(self: *Self, key: K) ?*V

src

Pointer to the value stored for key, or null. The pointer is invalidated by the next insertion or removal.

pub fn contains(self: *const Self, key: K) bool

src

Whether key is stored in the map.

pub fn put(self: *Self, key: K, value: V) error{NoSpaceLeft}!void

src

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.

pub fn getOrPut(self: *Self, key: K) error{NoSpaceLeft}!GetOrPutResult

src

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.

pub fn clear(self: *Self) void

src

Remove all entries, keeping the storage. The map is immediately reusable.

pub fn iterator(self: *Self) Iterator

src

An iterator over the entries in insertion order. Modifying the map invalidates it.

Types

struct Entry

src

Pointers to a key and value stored in the map.

Fields

key_ptr: *K
value_ptr: *V

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

key_ptr: *K
value_ptr: *V
index: Index

struct Iterator

src

Fields

map: *Self
index: Index

Functions

pub fn next(it: *Iterator) ?Entry

src

The next entry in insertion order, or null.

pub fn reset(it: *Iterator) void

src

Reset the iterator to the first entry.

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

pub const Index = std.math.IntFittingRange(0, buffer_capacity)

src

Smallest integer type that can hold 0..capacity.

pub const capacity: Index = @intCast(buffer_capacity)

src

Maximum number of entries the map can hold.

pub const empty: Self = …

src
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.

pub const init: Self = …

src
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.

pub fn count(self: *const Self) Index

src

Number of entries currently stored.

pub fn keys(self: *Self) []K

src

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.

pub fn values(self: *Self) []V

src

The values in insertion order. The slice is invalidated by the next insertion or removal.

pub fn get(self: *const Self, key: K) ?V

src

Value stored for key, or null.

pub fn getPtr(self: *Self, key: K) ?*V

src

Pointer to the value stored for key, or null. The pointer is invalidated by the next insertion or removal.

pub fn contains(self: *const Self, key: K) bool

src

Whether key is stored in the map.

pub fn put(self: *Self, key: K, value: V) error{NoSpaceLeft}!void

src

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.

pub fn getOrPut(self: *Self, key: K) error{NoSpaceLeft}!GetOrPutResult

src

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.

pub fn clear(self: *Self) void

src

Remove all entries, keeping the storage. The map is immediately reusable.

pub fn iterator(self: *Self) Iterator

src

An iterator over the entries in insertion order. Modifying the map invalidates it.

Types

struct Entry

src

Pointers to a key and value stored in the map.

Fields

key_ptr: *K
value_ptr: *V

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

key_ptr: *K
value_ptr: *V
index: Index

struct Iterator

src

Fields

map: *Self
index: Index

Functions

pub fn next(it: *Iterator) ?Entry

src

The next entry in insertion order, or null.

pub fn reset(it: *Iterator) void

src

Reset the iterator to the first entry.

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

pub fn init(allocator: Allocator, limit: usize) BoundedWriter

src

pub fn deinit(self: *BoundedWriter) void

src

pub fn written(self: *BoundedWriter) []const u8

src

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.

  1. 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.max sets it per map.
  2. 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 u8 keys 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.
  3. 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

struct Config

src
pub const Config = map.Config

Compile-time knobs for a map's nodes.

Fields

max: u16 = 31

Maximum keys per node, odd and at least 3. A split leaves (max - 1) / 2 keys on each side with the middle one promoted.

width: ?u16 = null

Bytes of each window kept in the node: 2, 4, or 8. Null takes the context's inline_width, which is the width its measurements chose.

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 bytes offset..offset + 8 of an encoding of key that sorts as the key sorts, big-endian and zero-padded past its end. The contract: if a's encoding sorts before b's, then a < b. Equal encodings decide nothing; the map compares the real keys. A context without inlineKey gets 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.

shared_prefix: u16

Length of the prefix every key in the map shares, kept in step with the extremes.

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

pub const empty: Self = …

src
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.

pub const init: Self = …

src
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.

pub fn count(self: *const Self) usize

src

Number of entries in the map.

pub fn isEmpty(self: *const Self) bool

src

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.

pub fn get(self: *const Self, key: K) ?V

src

Value stored for key, or null.

pub fn getPtr(self: *const Self, key: K) ?*V

src

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.

pub fn getOrPut(self: *Self, gpa: Allocator, key: K) !GetOrPutResult

src

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.

pub fn put(self: *Self, gpa: Allocator, key: K, value: V) !void

src

Insert key with value, replacing any existing value.

pub fn fetchPut(self: *Self, gpa: Allocator, key: K, value: V) !?V

src

Insert key with value, returning the value replaced.

pub fn remove(self: *Self, gpa: Allocator, key: K) bool

src

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.

pub fn iterator(self: *const Self) Iterator

src

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.

pub fn first(self: *const Self) ?Entry

src

The smallest entry, or null.

pub fn last(self: *const Self) ?Entry

src

The largest entry, or null.

Types

struct Element

src

One stored entry.

Fields

key: K
value: V

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

key_ptr: *K
value_ptr: *V

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

struct Iterator

src

Ascending iterator over a map. The frames address nodes, so a mutation while the iterator is live is a use-after-free; bracket the walk with lockPointers to make that assert.

Fields

frames: [max_depth]IterFrame
depth: usize

Functions

pub fn next(self: *Iterator) ?Entry

src

Next entry in ascending key order.

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.

shared_prefix: u16

Length of the prefix every key in the map shares, kept in step with the extremes.

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

pub const empty: Self = …

src
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.

pub const init: Self = …

src
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.

pub fn count(self: *const Self) usize

src

Number of entries in the map.

pub fn isEmpty(self: *const Self) bool

src

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.

pub fn get(self: *const Self, key: K) ?V

src

Value stored for key, or null.

pub fn getPtr(self: *const Self, key: K) ?*V

src

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.

pub fn getOrPut(self: *Self, gpa: Allocator, key: K) !GetOrPutResult

src

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.

pub fn put(self: *Self, gpa: Allocator, key: K, value: V) !void

src

Insert key with value, replacing any existing value.

pub fn fetchPut(self: *Self, gpa: Allocator, key: K, value: V) !?V

src

Insert key with value, returning the value replaced.

pub fn remove(self: *Self, gpa: Allocator, key: K) bool

src

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.

pub fn iterator(self: *const Self) Iterator

src

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.

pub fn first(self: *const Self) ?Entry

src

The smallest entry, or null.

pub fn last(self: *const Self) ?Entry

src

The largest entry, or null.

Types

struct Element

src

One stored entry.

Fields

key: K
value: V

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

key_ptr: *K
value_ptr: *V

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

struct Iterator

src

Ascending iterator over a map. The frames address nodes, so a mutation while the iterator is live is a use-after-free; bracket the walk with lockPointers to make that assert.

Fields

frames: [max_depth]IterFrame
depth: usize

Functions

pub fn next(self: *Iterator) ?Entry

src

Next entry in ascending key order.

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.

shared_prefix: u16

Length of the prefix every key in the map shares, kept in step with the extremes.

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

pub const empty: Self = …

src
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.

pub const init: Self = …

src
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.

pub fn count(self: *const Self) usize

src

Number of entries in the map.

pub fn isEmpty(self: *const Self) bool

src

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.

pub fn get(self: *const Self, key: K) ?V

src

Value stored for key, or null.

pub fn getPtr(self: *const Self, key: K) ?*V

src

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.

pub fn getOrPut(self: *Self, gpa: Allocator, key: K) !GetOrPutResult

src

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.

pub fn put(self: *Self, gpa: Allocator, key: K, value: V) !void

src

Insert key with value, replacing any existing value.

pub fn fetchPut(self: *Self, gpa: Allocator, key: K, value: V) !?V

src

Insert key with value, returning the value replaced.

pub fn remove(self: *Self, gpa: Allocator, key: K) bool

src

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.

pub fn iterator(self: *const Self) Iterator

src

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.

pub fn first(self: *const Self) ?Entry

src

The smallest entry, or null.

pub fn last(self: *const Self) ?Entry

src

The largest entry, or null.

Types

struct Element

src

One stored entry.

Fields

key: K
value: V

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

key_ptr: *K
value_ptr: *V

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

struct Iterator

src

Ascending iterator over a map. The frames address nodes, so a mutation while the iterator is live is a use-after-free; bracket the walk with lockPointers to make that assert.

Fields

frames: [max_depth]IterFrame
depth: usize

Functions

pub fn next(self: *Iterator) ?Entry

src

Next entry in ascending key order.

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 compare(_: Self, a: K, b: K) Order

src

pub fn encodedLen(_: Self, _: K) usize

src

The length of the key's encoding.

pub fn inlineKey(_: Self, key: K, offset: usize) u64

src

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

pub fn compare(_: BytesContext, a: []const u8, b: []const u8) Order

src

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 inlineKey(_: BytesContext, key: []const u8, offset: usize) u64

src

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

buffer: [capacity]T align(align_bytes)
len: Index

Constants

pub const Index = std.math.IntFittingRange(0, buffer_capacity)

src

pub const capacity: Index = @intCast(buffer_capacity)

src

pub const empty: Self = .{ .buffer = undefined, .len = 0 }

src

Functions

pub fn constSlice(self: *const Self) []align(align_bytes) const T

src

pub fn slice(self: *Self) switch (@TypeOf(&self.buffer)) { *align(align_bytes) [capacity]T => []align(align_bytes) T, *align(align_bytes) const [capacity]T => []align(align_bytes) const T, else => unreachable, }

src

pub fn unusedCapacitySlice(self: *Self) []align(align_bytes) T

src

pub fn remainingCapacity(self: *const Self) Index

src

pub fn append(self: *Self, item: T) error{NoSpaceLeft}!void

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 get(self: *const Self, i: usize) T

src

Return the element at index i of the slice.

pub fn set(self: *Self, i: usize, item: T) void

src

Set the value of the element at index i of the slice.

pub fn pop(self: *Self) ?T

src

The last item, removed; null when empty. Matches std.ArrayList.pop.

pub fn resize(self: *Self, new_len: usize) void

src

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 clear(self: *Self) void

src

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

buffer: [capacity]T align(align_bytes)
len: Index

Constants

pub const Index = std.math.IntFittingRange(0, buffer_capacity)

src

pub const capacity: Index = @intCast(buffer_capacity)

src

pub const empty: Self = .{ .buffer = undefined, .len = 0 }

src

Functions

pub fn constSlice(self: *const Self) []align(align_bytes) const T

src

pub fn slice(self: *Self) switch (@TypeOf(&self.buffer)) { *align(align_bytes) [capacity]T => []align(align_bytes) T, *align(align_bytes) const [capacity]T => []align(align_bytes) const T, else => unreachable, }

src

pub fn unusedCapacitySlice(self: *Self) []align(align_bytes) T

src

pub fn remainingCapacity(self: *const Self) Index

src

pub fn append(self: *Self, item: T) error{NoSpaceLeft}!void

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 get(self: *const Self, i: usize) T

src

Return the element at index i of the slice.

pub fn set(self: *Self, i: usize, item: T) void

src

Set the value of the element at index i of the slice.

pub fn pop(self: *Self) ?T

src

The last item, removed; null when empty. Matches std.ArrayList.pop.

pub fn resize(self: *Self, new_len: usize) void

src

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 clear(self: *Self) void

src

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

buffer: []T
len: usize

Constants

pub const empty: Self = .{ .buffer = &.{}, .len = 0 }

src

Functions

pub fn init(buffer: []T) Self

src

pub fn constSlice(self: *const Self) []const T

src

pub fn slice(self: *Self) []T

src

pub fn unusedCapacitySlice(self: *Self) []T

src

pub fn remainingCapacity(self: *const Self) usize

src

pub fn append(self: *Self, item: T) error{NoSpaceLeft}!void

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.

pub fn pop(self: *Self) ?T

src

pub fn resize(self: *Self, new_len: usize) void

src

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.

pub fn clear(self: *Self) void

src

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

pub const empty: Self = .{ .buffer = &.{}, .seek = 0, .end = 0 }

src

Functions

pub fn init(buffer: []T) Self

src

Use buffer as the whole capacity. The queue starts empty.

pub fn capacity(self: *const Self) usize

src

pub fn isEmpty(self: *const Self) bool

src

True when nothing is buffered. Same as bufferedLen() == 0.

pub fn buffered(self: *Self) []T

src

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

pub fn advance(self: *Self, n: usize) void

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().

pub fn toss(self: *Self, n: usize) void

src

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.

pub fn peek(self: *Self, n: usize) []T

src

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().

pub fn take(self: *Self, n: usize) []T

src

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().

pub fn rebase(self: *Self) void

src

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.

pub fn clear(self: *Self) void

src

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 ErrorBounds

src

Error-bound sizing parameters for Config.fromError.

Fields

epsilon: f64

Additive error bound as a fraction of total added weight: 0 < epsilon < 1. Sets width = ceilPowerOfTwo(ceil(e / epsilon)).

delta: f64

Failure probability bound: 0 < delta < 1. Sets depth = ceil(ln(1 / delta)).

Counter: type = u32

Unsigned integer counter type (u8, u16, u32, u64, etc.).

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

pub fn fromError(comptime bounds: ErrorBounds) Config

src

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

pub const Counter = Raw.Counter

src

Unsigned integer type stored in each cell.

pub const depth: u32 = Raw.depth

src

Number of hash rows.

pub const width: u32 = Raw.width

src

Number of counters per row (power of two).

pub const epsilon: f64 = Raw.epsilon

src

Delivered additive error factor e / width.

pub const delta: f64 = Raw.delta

src

Delivered failure probability bound exp(-depth).

pub const empty: Self = .{ .sketch = .empty }

src

An empty sketch with every counter at zero.

Functions

pub fn add(self: *Self, key: T, amount: Counter) void

src

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.

pub fn estimate(self: *const Self, key: T) Counter

src

Estimate the frequency of key. Never undercounts unless a counter saturated or halve decayed past counts.

pub fn count(self: *const Self) u64

src

Total added weight since initialization or clear (saturating).

pub fn merge(self: *Self, other: *const Self) void

src

Add other's counters into self cell-by-cell (saturating).

pub fn halve(self: *Self) void

src

Right-shift every counter and the total count by one bit for exponential aging / TinyLFU decay.

pub fn clear(self: *Self) void

src

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

pub const Counter = Raw.Counter

src

Unsigned integer type stored in each cell.

pub const depth: u32 = Raw.depth

src

Number of hash rows.

pub const width: u32 = Raw.width

src

Number of counters per row (power of two).

pub const epsilon: f64 = Raw.epsilon

src

Delivered additive error factor e / width.

pub const delta: f64 = Raw.delta

src

Delivered failure probability bound exp(-depth).

pub const empty: Self = .{ .sketch = .empty }

src

An empty sketch with every counter at zero.

Functions

pub fn add(self: *Self, key: T, amount: Counter) void

src

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.

pub fn estimate(self: *const Self, key: T) Counter

src

Estimate the frequency of key. Never undercounts unless a counter saturated or halve decayed past counts.

pub fn count(self: *const Self) u64

src

Total added weight since initialization or clear (saturating).

pub fn merge(self: *Self, other: *const Self) void

src

Add other's counters into self cell-by-cell (saturating).

pub fn halve(self: *Self) void

src

Right-shift every counter and the total count by one bit for exponential aging / TinyLFU decay.

pub fn clear(self: *Self) void

src

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

pub const Counter = Raw.Counter

src

Unsigned integer type stored in each cell.

pub const depth: u32 = Raw.depth

src

Number of hash rows.

pub const width: u32 = Raw.width

src

Number of counters per row (power of two).

pub const epsilon: f64 = Raw.epsilon

src

Delivered additive error factor e / width.

pub const delta: f64 = Raw.delta

src

Delivered failure probability bound exp(-depth).

pub const empty: Self = .{ .sketch = .empty }

src

An empty sketch with every counter at zero.

Functions

pub fn add(self: *Self, key: T, amount: Counter) void

src

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.

pub fn estimate(self: *const Self, key: T) Counter

src

Estimate the frequency of key. Never undercounts unless a counter saturated or halve decayed past counts.

pub fn count(self: *const Self) u64

src

Total added weight since initialization or clear (saturating).

pub fn merge(self: *Self, other: *const Self) void

src

Add other's counters into self cell-by-cell (saturating).

pub fn halve(self: *Self) void

src

Right-shift every counter and the total count by one bit for exponential aging / TinyLFU decay.

pub fn clear(self: *Self) void

src

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

rows: [depth][width]Counter
total: u64

Constants

pub const Counter = config.Counter

src

Unsigned integer type stored in each cell.

pub const depth: u32 = config.depth

src

Number of hash rows.

pub const width: u32 = config.width

src

Number of counters per row (power of two).

pub const epsilon: f64 = math.e / @as(f64, @floatFromInt(width))

src

Delivered additive error factor e / width.

pub const delta: f64 = @exp(-@as(f64, @floatFromInt(depth)))

src

Delivered failure probability bound exp(-depth).

pub const empty: Self = …

src
value
.{
            .rows = @splat(@splat(0)),
            .total = 0,
        }

An empty sketch with every counter at zero.

Functions

pub fn addHash(self: *Self, hash: u64, amount: Counter) void

src

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.

pub fn count(self: *const Self) u64

src

Total added weight since initialization or clear (saturating).

pub fn merge(self: *Self, other: *const Self) void

src

Fold other into self by saturating elementwise addition.

pub fn halve(self: *Self) void

src

Halve every counter and the total count (integer shift right by 1).

pub fn clear(self: *Self) void

src

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

pub const Error = …

src
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).

pub const max_kicks: u32 = Raw.max_kicks

src

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)).

pub const empty: Self = .{ .filter = .empty }

src

An empty filter with no stored fingerprints.

Functions

pub fn add(self: *Self, key: T) Error!void

src

Add key to the filter. Returns error.FilterFull without modifying the filter if relocation cannot find a free slot.

pub fn contains(self: *const Self, key: T) bool

src

Whether key may be in the filter. Never returns false for a key that was added and not removed.

pub fn remove(self: *Self, key: T) bool

src

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.

pub fn count(self: *const Self) u64

src

Number of fingerprints currently stored in the filter.

pub fn loadFactor(self: *const Self) f64

src

Fraction of slots currently occupied (count() / slot_count).

pub fn clear(self: *Self) void

src

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).

pub const max_kicks: u32 = Raw.max_kicks

src

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)).

pub const empty: Self = .{ .filter = .empty }

src

An empty filter with no stored fingerprints.

Functions

pub fn add(self: *Self, key: T) Error!void

src

Add key to the filter. Returns error.FilterFull without modifying the filter if relocation cannot find a free slot.

pub fn contains(self: *const Self, key: T) bool

src

Whether key may be in the filter. Never returns false for a key that was added and not removed.

pub fn remove(self: *Self, key: T) bool

src

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.

pub fn count(self: *const Self) u64

src

Number of fingerprints currently stored in the filter.

pub fn loadFactor(self: *const Self) f64

src

Fraction of slots currently occupied (count() / slot_count).

pub fn clear(self: *Self) void

src

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).

pub const max_kicks: u32 = Raw.max_kicks

src

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)).

pub const empty: Self = .{ .filter = .empty }

src

An empty filter with no stored fingerprints.

Functions

pub fn add(self: *Self, key: T) Error!void

src

Add key to the filter. Returns error.FilterFull without modifying the filter if relocation cannot find a free slot.

pub fn contains(self: *const Self, key: T) bool

src

Whether key may be in the filter. Never returns false for a key that was added and not removed.

pub fn remove(self: *Self, key: T) bool

src

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.

pub fn count(self: *const Self) u64

src

Number of fingerprints currently stored in the filter.

pub fn loadFactor(self: *const Self) f64

src

Fraction of slots currently occupied (count() / slot_count).

pub fn clear(self: *Self) void

src

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

buckets: [bucket_count]Bucket
len: u64
rng_state: u64

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).

pub const max_kicks: u32 = config.max_kicks

src

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)).

pub const empty: Self = …

src
value
.{
            .buckets = @splat(@splat(0)),
            .len = 0,
            .rng_state = initial_seed,
        }

An empty filter with no stored fingerprints.

Functions

pub fn addHash(self: *Self, hash: u64) Error!void

src

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.

pub fn count(self: *const Self) u64

src

Number of fingerprints currently stored in the filter.

pub fn loadFactor(self: *const Self) f64

src

Fraction of slots currently occupied (count() / slot_count).

pub fn clear(self: *Self) void

src

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 \n or at the end of the source, and a \r immediately 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.
  • export followed by a space or a tab before the key is ignored. The key matches [A-Za-z_][A-Za-z0-9_]*; anything else is error.InvalidKey. A line with no = is error.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, so PASSWORD=#secret keeps 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 is error.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

pub const Error = …

src
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.

pub fn lineText(source: []const u8, line: u32) []const u8

src

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 Entry

src

One KEY=VALUE assignment. key and value point into the caller's source or scratch, and stay valid while both live. line is the 1-based line where the key starts.

Fields

key: []const u8
value: []const u8
line: u32

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

pub fn message(self: Diagnostics) []const u8

src

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

pub fn get(self: Doc, key: []const u8) ?[]const u8

src

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

pub const Tag = …

src
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.

pub const miss: Tag = @fromBackingInt(@intCast(names.len))

src

The value match returns for bytes that are not a name.

pub const keys: []const []const u8 = …

src
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.

pub const count: usize = names.len

src

The number of names.

Functions

pub fn match(value: []const u8) Tag

src

The tag for value, or miss.

pub fn has(value: []const u8) bool

src

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

pub const Tag = …

src
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.

pub const miss: Tag = @field(Tag, fallback)

src

The tag match returns for bytes that are not a name.

pub const keys: []const []const u8 = …

src
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.

pub const count: usize = names.len

src

The number of names, without the fallback.

Functions

pub fn match(value: []const u8) Tag

src

The tag for value, or miss.

pub fn has(value: []const u8) bool

src

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

pub inline fn atoi(comptime T: type, buf: []const u8) Error(.checked)!T

src

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.

pub fn parseBool(raw: []const u8) ?bool

src

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

pub fn hash(seed: u64, input: []const u8) u64

src

Hash input with seed: the 7-lane general variant, a drop-in for std.hash.Wyhash.hash with the same explicit-seed signature.

pub fn hashMicro(seed: u64, input: []const u8) u64

src

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.

pub fn hashNano(seed: u64, input: []const u8) u64

src

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

pub fn hash(_: StringContext, s: []const u8) u64

src

pub fn eql(_: StringContext, a: []const u8, b: []const u8) bool

src

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

pub fn hash(_: Self, key: T) u64

src

pub fn eql(_: Self, a: T, b: T) bool

src

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

pub fn hash(bytes: []const u8) u32

src

The CRC-32C digest of bytes.

pub fn append(previous: u32, bytes: []const u8) u32

src

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

pub fn init(child_allocator: Allocator) Self

src

Creates an empty arena. No memory is allocated until the first request.

pub fn allocator(self: *Self) Allocator

src

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.

pub fn deinit(self: *Self) void

src

Releases every chunk. The arena must not be used afterwards; reset is the way to empty an arena that stays alive.

pub fn reset(self: *Self, mode: ResetMode) void

src

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

pub const empty: State = .{ .chunks = null, .current = null }

src

Functions

pub fn promote(state: State, child_allocator: Allocator) Self

src

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

pub const sizes = class_sizes

src

The class sizes, as usize, for a caller that sizes a backing.

Functions

pub fn init(backing: []u8) Self

src

Use backing as the whole storage. Every class and its metadata comes from it; nothing else is allocated.

pub fn deinit(self: *Self) void

src

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.

pub fn create(self: *Self, size: usize) error{OutOfMemory}![]u8

src

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.

pub fn destroy(self: *Self, block: []u8) void

src

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

pub const Ptr = [*]align(config.alignment.toByteUnits()) u8

src

Functions

pub fn init(gpa: Allocator) Allocator.Error!Self

src

pub fn deinit(self: *Self, gpa: Allocator) void

src

pub fn alloc(self: *Self, gpa: Allocator, size: usize) Ptr

src

Allocates a nonzero number of bytes or panics on allocator exhaustion.

pub fn free(self: *Self, gpa: Allocator, ptr: Ptr, size: usize) void

src

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

pub const Error = Allocator.Error

src

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.

pub const init: Pool = …

src
value
.{
        .chunks = .empty,
        .current = null,
        .names = .empty,
        .ids = .init,
    }

A pool holding nothing.

Functions

pub fn intern(self: *Pool, gpa: Allocator, bytes: []const u8) Error!u32

src

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.

pub fn get(self: *const Pool, id: u32) []const u8

src

The bytes for id. Asserts id is one this pool handed out.

pub fn lookup(self: *const Pool, bytes: []const u8) ?u32

src

The id of bytes without inserting it.

pub fn count(self: *const Pool) usize

src

The number of distinct strings interned.

pub fn deinit(self: *Pool, gpa: Allocator) void

src

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

pub const Error = …

src
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

pub const init: Diagnostics = .{ .offset = 0, .line = 1, .column = 1 }

src

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.

struct Scrubbed

src

An owned scrubbed copy of a source. Byte i of bytes is byte i of the source, either unchanged or replaced by a space.

Fields

bytes: []u8

The copy. Its length equals the source length.

allocator: Allocator

The allocator that owns bytes.

Functions

pub fn deinit(self: *Scrubbed) void

src

Free the copy.

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

pub fn deinit(self: *Self) void

src

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

map: Map
nodes: Nodes

Constants

pub const Map = bounded_array_hash_map.Custom(K, NodeIndex, Context, buffer_capacity)

src

pub const Index = Map.Index

src

pub const capacity = Map.capacity

src

pub const init: Self = .{ .map = .init, .nodes = .empty }

src

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.

pub const empty: Self = .{ .map = .empty, .nodes = .empty }

src

Functions

pub fn initContext(context: Context) Self

src

A cache with no entries and the given context.

pub fn count(self: *const Self) Index

src

Number of cached entries.

pub fn contains(self: *const Self, key: K) bool

src

Whether key is cached. Does not change recency.

pub fn get(self: *Self, key: K) ?*V

src

The value for key, moved to the most-recently-used position.

pub fn peek(self: *Self, key: K) ?*V

src

The value for key, without changing recency.

pub fn put(self: *Self, key: K, value: V) PutResult

src

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.

pub fn remove(self: *Self, key: K) ?V

src

Remove key and return its value.

pub fn popLru(self: *Self) ?Entry

src

Remove and return the least-recently-used entry.

pub fn popMru(self: *Self) ?Entry

src

Remove and return the most-recently-used entry.

pub fn clear(self: *Self) void

src

Drop every entry, keeping the storage. The values are not returned; drain with the iterator first when V owns resources.

pub fn iterator(self: *Self) Iterator

src

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

struct Entry

src

Fields

key: K
value: V

struct Item

src

Fields

key: K
value: *V

struct PutResult

src

What one put displaced. replaced is the old value for the same key; evicted is the entry the capacity bound pushed out.

Fields

replaced: ?V
evicted: ?Entry

Constants

pub const empty: PutResult = .{ .replaced = null, .evicted = null }

src

A put that replaced and evicted nothing.

struct Iterator

src

Fields

inner: NodePool.Iterator

Functions

pub fn next(self: *Iterator) ?Item

src

The next entry from most to least recently used, or null.

pub fn reset(self: *Iterator) void

src

Restart at the most-recently-used entry.

type fn Auto

src
pub fn Auto(comptime K: type, comptime V: type, buffer_capacity: comptime_int) type

Fields

map: Map
nodes: Nodes

Constants

pub const Map = bounded_array_hash_map.Custom(K, NodeIndex, Context, buffer_capacity)

src

pub const Index = Map.Index

src

pub const capacity = Map.capacity

src

pub const init: Self = .{ .map = .init, .nodes = .empty }

src

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.

pub const empty: Self = .{ .map = .empty, .nodes = .empty }

src

Functions

pub fn initContext(context: Context) Self

src

A cache with no entries and the given context.

pub fn count(self: *const Self) Index

src

Number of cached entries.

pub fn contains(self: *const Self, key: K) bool

src

Whether key is cached. Does not change recency.

pub fn get(self: *Self, key: K) ?*V

src

The value for key, moved to the most-recently-used position.

pub fn peek(self: *Self, key: K) ?*V

src

The value for key, without changing recency.

pub fn put(self: *Self, key: K, value: V) PutResult

src

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.

pub fn remove(self: *Self, key: K) ?V

src

Remove key and return its value.

pub fn popLru(self: *Self) ?Entry

src

Remove and return the least-recently-used entry.

pub fn popMru(self: *Self) ?Entry

src

Remove and return the most-recently-used entry.

pub fn clear(self: *Self) void

src

Drop every entry, keeping the storage. The values are not returned; drain with the iterator first when V owns resources.

pub fn iterator(self: *Self) Iterator

src

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

struct Entry

src

Fields

key: K
value: V

struct Item

src

Fields

key: K
value: *V

struct PutResult

src

What one put displaced. replaced is the old value for the same key; evicted is the entry the capacity bound pushed out.

Fields

replaced: ?V
evicted: ?Entry

Constants

pub const empty: PutResult = .{ .replaced = null, .evicted = null }

src

A put that replaced and evicted nothing.

struct Iterator

src

Fields

inner: NodePool.Iterator

Functions

pub fn next(self: *Iterator) ?Item

src

The next entry from most to least recently used, or null.

pub fn reset(self: *Iterator) void

src

Restart at the most-recently-used entry.

type fn String

src
pub fn String(comptime V: type, buffer_capacity: comptime_int) type

Fields

map: Map
nodes: Nodes

Constants

pub const Map = bounded_array_hash_map.Custom(K, NodeIndex, Context, buffer_capacity)

src

pub const Index = Map.Index

src

pub const capacity = Map.capacity

src

pub const init: Self = .{ .map = .init, .nodes = .empty }

src

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.

pub const empty: Self = .{ .map = .empty, .nodes = .empty }

src

Functions

pub fn initContext(context: Context) Self

src

A cache with no entries and the given context.

pub fn count(self: *const Self) Index

src

Number of cached entries.

pub fn contains(self: *const Self, key: K) bool

src

Whether key is cached. Does not change recency.

pub fn get(self: *Self, key: K) ?*V

src

The value for key, moved to the most-recently-used position.

pub fn peek(self: *Self, key: K) ?*V

src

The value for key, without changing recency.

pub fn put(self: *Self, key: K, value: V) PutResult

src

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.

pub fn remove(self: *Self, key: K) ?V

src

Remove key and return its value.

pub fn popLru(self: *Self) ?Entry

src

Remove and return the least-recently-used entry.

pub fn popMru(self: *Self) ?Entry

src

Remove and return the most-recently-used entry.

pub fn clear(self: *Self) void

src

Drop every entry, keeping the storage. The values are not returned; drain with the iterator first when V owns resources.

pub fn iterator(self: *Self) Iterator

src

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

struct Entry

src

Fields

key: K
value: V

struct Item

src

Fields

key: K
value: *V

struct PutResult

src

What one put displaced. replaced is the old value for the same key; evicted is the entry the capacity bound pushed out.

Fields

replaced: ?V
evicted: ?Entry

Constants

pub const empty: PutResult = .{ .replaced = null, .evicted = null }

src

A put that replaced and evicted nothing.

struct Iterator

src

Fields

inner: NodePool.Iterator

Functions

pub fn next(self: *Iterator) ?Item

src

The next entry from most to least recently used, or null.

pub fn reset(self: *Iterator) void

src

Restart at the most-recently-used entry.

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.

pub fn findAny(comptime T: type, slice: []const T, values: []const T) ?usize

src

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

pub const Data = [len]u8

src

pub const empty: Self = .{ .data = undefined }

src

pub const zero: Self = .{ .data = @splat(0) }

src

Functions

pub inline fn init(data: Data) Self

src

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

pub const len: usize = @intCast(length)

src

The number of elements; also the length of every field array.

pub const Field = meta.FieldEnum(Elem)

src

pub const empty: Self = .{ .storage = undefined }

src

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.

pub fn items(self: *Self, comptime field: Field) *[length]FieldType(field)

src

The [length]F array for field.

pub fn get(self: *const Self, index: usize) T

src

Gather the element at index back into a T.

pub fn set(self: *Self, index: usize, elem: T) void

src

Scatter elem into the per-field arrays at index.

pub fn fill(self: *Self, value: T) void

src

Scatter value into every element.

pub fn swap(self: *Self, a: usize, b: usize) void

src

Exchange the elements at a and b.

pub fn fromArray(values: [length]T) Self

src

Build from an array of structs (AoS to SoA).

pub fn toArray(self: *const Self) [length]T

src

Gather every element into an array of structs (SoA to AoS).

pub fn sort(self: *Self, ctx: anytype) void

src

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

storage: Storage(T, capacity)
len: Index

Constants

pub const Index = std.math.IntFittingRange(0, buffer_capacity)

src

pub const capacity: Index = @intCast(buffer_capacity)

src

pub const Field = meta.FieldEnum(Elem)

src

pub const empty: Self = .{ .storage = undefined, .len = 0 }

src

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.

pub fn items(self: *Self, comptime field: Field) []FieldType(field)

src

The []F slice of populated values for field.

pub fn get(self: *const Self, index: usize) T

src

Gather the element at index back into a T.

pub fn set(self: *Self, index: usize, elem: T) void

src

Scatter elem into the per-field arrays at index.

pub fn remainingCapacity(self: *const Self) Index

src

pub fn append(self: *Self, elem: T) error{NoSpaceLeft}!void

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.

pub fn addOne(self: *Self) error{NoSpaceLeft}!usize

src

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.

pub fn pop(self: *Self) ?T

src

Remove and return the last element, or return null if the list is empty.

pub fn insert(self: *Self, index: usize, elem: T) error{NoSpaceLeft}!void

src

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.

pub fn resize(self: *Self, new_len: Index) void

src

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.

pub fn clear(self: *Self) void

src

pub fn sort(self: *Self, ctx: anytype) void

src

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

pub const IpAddress = net.IpAddress

src

Types

struct Ip4

src

Fields

bytes: [4]u8

Constants

pub const unspecified: Ip4 = .{ .bytes = @splat(0) }

src

pub const loopback: Ip4 = .{ .bytes = .{ 127, 0, 0, 1 } }

src

pub const broadcast: Ip4 = .{ .bytes = .{ 255, 255, 255, 255 } }

src

pub const ParseError = Ip4Address.ParseError

src

Functions

pub fn init(bytes: [4]u8) Ip4

src

pub fn parse(buf: []const u8) ParseError!Ip4

src

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".

pub fn fromIp6(ip6: Ip6Address) ?Ip4

src

Converts from an IPv4-mapped IPv6 address, or returns null.

pub fn fromIp4(ip4: Ip4Address) Ip4

src

Given an Ip4Address, converts it to an Ip4 stripping the port.

pub fn fromAny(addr: IpAddress) ?Ip4

src

Given an IpAddress, converts it to an Ip4 directly, or from an IPv4-mapped IPv6 address, or returns null.

pub fn eql(a: Ip4, b: Ip4) bool

src

pub fn isUnspecified(self: Ip4) bool

src

pub fn isLoopback(self: Ip4) bool

src

127.0.0.0/8.

pub fn isPrivate(self: Ip4) bool

src

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.

pub fn order(self: Ip4, other: Ip4) math.Order

src

Dotted-quad numeric order: lexicographic octet order, endian-free. Follows the std convention of returning math.Order.

pub fn next(self: Ip4) ?Ip4

src

The next address in numeric order, or null past 255.255.255.255.

pub fn prev(self: Ip4) ?Ip4

src

The previous address in numeric order, or null before 0.0.0.0.

pub fn prefix(self: Ip4, bits: u8) error{BitsOutOfRange}!Prefix4

src

The prefix of bits bits with this address as its network address, masked to canonical form, like Go's Addr.Prefix.

pub fn fromSlice(slice: []const u8) ?Ip4

src

Returns null unless slice is exactly 4 bytes, like Go's AddrFromSlice.

pub fn withPort(self: Ip4, port: u16) Ip4Address

src

pub fn format(self: Ip4, w: *Io.Writer) Io.Writer.Error!void

src

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

addr: Ip4
bits: u8

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 init(addr: Ip4, bits: u8) Prefix4

src

pub fn parse(s: []const u8) ParseError!Prefix4

src

pub fn parseComptime(comptime s: []const u8) Prefix4

src

Parses at compile time, reporting the offending string and error on failure, like Ip4.parseComptime.

pub fn contains(self: Prefix4, ip: Ip4) bool

src

Containment by octet-prefix compare: whole octets match exactly, then the leading bits of the next octet are masked. No endian conversion.

pub fn masked(self: Prefix4) Prefix4

src

The canonical form with host bits zeroed, like Go's Prefix.Masked.

pub fn overlaps(self: Prefix4, other: Prefix4) bool

src

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.

pub fn format(self: Prefix4, w: *Io.Writer) Io.Writer.Error!void

src

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

bytes: [4]u8
port: u16

Functions

pub fn init(bytes: [4]u8, port: u16) Ip4Endpoint

src

pub fn parse(buf: []const u8, port: u16) Ip4.ParseError!Ip4Endpoint

src

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 withPort(self: Ip4Endpoint, port: u16) Ip4Endpoint

src

pub fn toIp4(self: Ip4Endpoint) Ip4

src

pub fn toStd(self: Ip4Endpoint) Ip4Address

src

pub fn fromStd(addr: Ip4Address) Ip4Endpoint

src

pub fn toSockaddrIn(self: Ip4Endpoint) posix.sockaddr.in

src

The kernel struct, port in network order: what bind(2) and connect(2) take.

pub fn format(self: Ip4Endpoint, w: *Io.Writer) Io.Writer.Error!void

src

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

host: []const u8
port: u16

Constants

pub const Error = …

src
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

pub fn parse(text: []const u8, default_port: u16) Error!HostPort

src

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

pub const empty: Self = .{ .value = undefined, .initialized = false }

src

Functions

pub fn get(self: *Self) ?*T

src

The value, or null.

pub fn isInitialized(self: *Self) bool

src

Whether a value has been set.

pub fn set(self: *Self, value: T) error{AlreadySet}!void

src

Set the value. Returns error.AlreadySet when one exists.

pub fn getOrInit(self: *Self, ctx: anytype, comptime f: fn (@TypeOf(ctx)) T) *T

src

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.

pub fn take(self: *Self) ?T

src

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

mutex: Io.Mutex
state: atomic.Value(State)
value: T

Constants

pub const empty: Self = …

src
value
.{
            .mutex = .init,
            .state = .init(.uninit),
            .value = undefined,
        }

pub const SetError = error{AlreadySet} || Io.Cancelable

src

Functions

pub fn get(self: *Self) ?*T

src

The value, or null. The fast path is one acquire load.

pub fn isInitialized(self: *Self) bool

src

Whether a value has been set.

pub fn set(self: *Self, io: Io, value: T) SetError!void

src

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

pub const empty: Self = .{ .cell = .empty }

src

Functions

pub fn get(self: *Self) *T

src

The value, initialized on the first call.

pub fn isInitialized(self: *Self) bool

src

Whether the value has been initialized.

pub fn take(self: *Self) ?T

src

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

pub const empty: Self = .{ .cell = .empty }

src

Functions

pub fn get(self: *Self, io: Io) Io.Cancelable!*T

src

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

pub const none: OptionalFd = .{ .fd = -1 }

src

Functions

pub fn init(fd: ?posix.fd_t) OptionalFd

src

Encode a descriptor, or .none from null. This does not duplicate the descriptor. The supplied descriptor must be nonnegative.

pub inline fn get(self: OptionalFd) ?posix.fd_t

src

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

nodes: []const Node
children: []const Child
prefix_bytes: []const u8
values: []const V

Functions

pub fn count(self: Self) usize

src

The number of keys in the map.

pub fn get(self: Self, key: []const u8) ?V

src

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.

pub fn has(self: Self, key: []const u8) bool

src

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.

pub fn init(kvs: anytype, allocator: Allocator) !Self

src

Build a map from kvs with allocator. The keys and values are copied. Release the map with deinit.

A duplicate key returns error.DuplicateKey.

pub fn deinit(self: Self, allocator: Allocator) void

src

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

buffer: [capacity]T
len: Index
context: Context

Constants

pub const Index = math.IntFittingRange(0, buffer_capacity)

src

Smallest integer type that can hold 0..capacity.

pub const capacity: Index = @intCast(buffer_capacity)

src

Maximum number of elements the queue can hold.

pub const empty: Self = …

src
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.

pub fn push(self: *Self, elem: T) error{NoSpaceLeft}!void

src

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.

pub fn pushSlice(self: *Self, items: []const T) error{NoSpaceLeft}!void

src

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.

pub fn peek(self: *const Self) ?T

src

Look at the highest priority element. Returns null if empty; does not modify the queue.

pub fn pop(self: *Self) ?T

src

Remove and return the highest priority element. Returns null if empty.

pub fn popIndex(self: *Self, index: usize) T

src

Remove and return the element at index. Indices follow iterator order, which is not necessarily priority order. Asserts that index < count().

pub fn count(self: *const Self) Index

src

Number of elements currently in the queue.

pub fn clear(self: *Self) void

src

Remove all elements. The capacity is unchanged, so the queue can be refilled immediately.

pub fn update(self: *Self, elem: T, new_elem: T) error{ElementNotFound}!void

src

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.

pub fn iterator(self: *Self) Iterator

src

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

struct Iterator

src

Fields

queue: *Custom(T, Context, buffer_capacity, compareFn)
index: Index

Functions

pub fn next(it: *Iterator) ?T

src

pub fn reset(it: *Iterator) void

src

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

pub fn fill(buffer: []u8) void

src

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

pub const Map = map_mod.Custom(K, void, Context, buffer_capacity)

src

pub const Index = Map.Index

src

pub const capacity: Index = Map.capacity

src

Maximum number of keys the set can hold.

pub const empty: Self = .{ .map = .empty }

src

pub const init: Self = .{ .map = .init }

src

Functions

pub fn initContext(context: Context) Self

src

pub fn count(self: *const Self) Index

src

pub fn contains(self: *const Self, key: K) bool

src

pub fn add(self: *Self, key: K) error{NoSpaceLeft}!bool

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.

pub fn remove(self: *Self, key: K) bool

src

Remove key. Returns false when absent.

pub fn clear(self: *Self) void

src

pub fn keys(self: *Self) []K

src

The keys in insertion order. Invalidated by the next add or remove.

pub fn intersect(self: *Self, other: *Self) void

src

Remove every key this set does not share with other. In-place: iterates self, probes other. Neither set changes in other.

pub fn unite(self: *Self, other: *Self) error{NoSpaceLeft}!void

src

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.

pub fn subtract(self: *Self, other: *Self) void

src

Remove every key of other. Returns nothing: absent keys are not an error.

pub fn subsetOf(self: *Self, other: *Self) bool

src

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

pub const Map = map_mod.Custom(K, void, Context, buffer_capacity)

src

pub const Index = Map.Index

src

pub const capacity: Index = Map.capacity

src

Maximum number of keys the set can hold.

pub const empty: Self = .{ .map = .empty }

src

pub const init: Self = .{ .map = .init }

src

Functions

pub fn initContext(context: Context) Self

src

pub fn count(self: *const Self) Index

src

pub fn contains(self: *const Self, key: K) bool

src

pub fn add(self: *Self, key: K) error{NoSpaceLeft}!bool

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.

pub fn remove(self: *Self, key: K) bool

src

Remove key. Returns false when absent.

pub fn clear(self: *Self) void

src

pub fn keys(self: *Self) []K

src

The keys in insertion order. Invalidated by the next add or remove.

pub fn intersect(self: *Self, other: *Self) void

src

Remove every key this set does not share with other. In-place: iterates self, probes other. Neither set changes in other.

pub fn unite(self: *Self, other: *Self) error{NoSpaceLeft}!void

src

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.

pub fn subtract(self: *Self, other: *Self) void

src

Remove every key of other. Returns nothing: absent keys are not an error.

pub fn subsetOf(self: *Self, other: *Self) bool

src

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

pub const Map = map_mod.Custom(K, void, Context, buffer_capacity)

src

pub const Index = Map.Index

src

pub const capacity: Index = Map.capacity

src

Maximum number of keys the set can hold.

pub const empty: Self = .{ .map = .empty }

src

pub const init: Self = .{ .map = .init }

src

Functions

pub fn initContext(context: Context) Self

src

pub fn count(self: *const Self) Index

src

pub fn contains(self: *const Self, key: K) bool

src

pub fn add(self: *Self, key: K) error{NoSpaceLeft}!bool

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.

pub fn remove(self: *Self, key: K) bool

src

Remove key. Returns false when absent.

pub fn clear(self: *Self) void

src

pub fn keys(self: *Self) []K

src

The keys in insertion order. Invalidated by the next add or remove.

pub fn intersect(self: *Self, other: *Self) void

src

Remove every key this set does not share with other. In-place: iterates self, probes other. Neither set changes in other.

pub fn unite(self: *Self, other: *Self) error{NoSpaceLeft}!void

src

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.

pub fn subtract(self: *Self, other: *Self) void

src

Remove every key of other. Returns nothing: absent keys are not an error.

pub fn subsetOf(self: *Self, other: *Self) bool

src

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 []Entry given at init, 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. A Pool value 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

pub const Handle = core.Handle

src

The type of both link fields, read from the entry.

pub const none = core.none

src

No neighbor.

pub const State = core.State

src

The list and free-list bookkeeping.

pub const Item = core.Item

src

One live entry and the handle that names it.

pub const Iterator = core.Iterator

src

A walk over the live entries, front to back.

pub const empty: Self = .{ .entries = &.{}, .state = .empty }

src

A pool over no storage. Only init replaces the slice.

Functions

pub fn init(entries: []Entry) Self

src

Use entries as the whole storage. Every entry starts free.

Contents other than the link fields are left as they are.

pub fn count(self: *const Self) usize

src

Number of live entries.

pub fn capacity(self: *const Self) usize

src

The whole capacity.

pub fn acquire(self: *Self) error{NoSpaceLeft}!Handle

src

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.

pub fn get(self: *Self, handle: Handle) *Entry

src

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.

pub fn isLive(self: *const Self, handle: Handle) bool

src

Whether handle is live. An out-of-range or never-acquired handle is not.

pub fn release(self: *Self, handle: Handle) void

src

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.

pub fn popFront(self: *Self) ?Entry

src

Remove the front entry and release its handle. The entry comes back by value, with its link fields stale.

pub fn popBack(self: *Self) ?Entry

src

Remove the back entry and release its handle. The entry comes back by value, with its link fields stale.

pub fn iterator(self: *Self) Iterator

src

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

pub const Handle = core.Handle

src

The type of both link fields, read from the entry.

pub const none = core.none

src

No neighbor.

pub const State = core.State

src

The list and free-list bookkeeping.

pub const Item = core.Item

src

One live entry and the handle that names it.

pub const Iterator = core.Iterator

src

A walk over the live entries, front to back.

pub const empty: Self = .{ .entries = undefined, .state = .empty }

src

A pool with an untouched array. Every entry is free.

Functions

pub fn count(self: *const Self) usize

src

Number of live entries.

pub fn capacity(self: *const Self) usize

src

The whole capacity.

pub fn acquire(self: *Self) error{NoSpaceLeft}!Handle

src

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.

pub fn get(self: *Self, handle: Handle) *Entry

src

The entry for handle. Asserts only that the handle is in range.

pub fn isLive(self: *const Self, handle: Handle) bool

src

Whether handle is live. An out-of-range or never-acquired handle is not.

pub fn release(self: *Self, handle: Handle) void

src

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.

pub fn popFront(self: *Self) ?Entry

src

Remove the front entry and release its handle. The entry comes back by value, with its link fields stale.

pub fn popBack(self: *Self) ?Entry

src

Remove the back entry and release its handle. The entry comes back by value, with its link fields stale.

pub fn iterator(self: *Self) Iterator

src

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

pub fn radix(comptime T: type, items: []T, scratch: []T) RadixError!void

src

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

pub const map = …

src
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.

pub const count: usize = kvs.len

src

The number of entries: always kvs.len — duplicates are compile errors, so nothing is dropped.

pub const keys = map.key_buffer[0..kvs.len]

src

The keys in insertion order: a comptime-known slice.

pub const values = map.value_buffer[0..kvs.len]

src

The values in insertion order: a comptime-known slice.

Functions

pub fn get(key: K) ?V

src

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.

pub fn has(key: K) bool

src

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

pub const map = …

src
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.

pub const count: usize = kvs.len

src

The number of entries: always kvs.len — duplicates are compile errors, so nothing is dropped.

pub const keys = map.key_buffer[0..kvs.len]

src

The keys in insertion order: a comptime-known slice.

pub const values = map.value_buffer[0..kvs.len]

src

The values in insertion order: a comptime-known slice.

Functions

pub fn get(key: K) ?V

src

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.

pub fn has(key: K) bool

src

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

pub const map = …

src
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.

pub const count: usize = kvs.len

src

The number of entries: always kvs.len — duplicates are compile errors, so nothing is dropped.

pub const keys = map.key_buffer[0..kvs.len]

src

The keys in insertion order: a comptime-known slice.

pub const values = map.value_buffer[0..kvs.len]

src

The values in insertion order: a comptime-known slice.

Functions

pub fn get(key: K) ?V

src

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.

pub fn has(key: K) bool

src

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

pub const err: *Stream = &err_instance

src

The process's stderr.

pub const out: *Stream = &out_instance

src

The process's stdout.

Functions

pub fn flush() void

src

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

pub fn writer(self: *Stream) *Io.Writer

src

The *Io.Writer behind the stream, for the interfaces that take one.

pub fn print(self: *Stream, comptime fmt: []const u8, args: anytype) void

src

pub fn write(self: *Stream, bytes: []const u8) usize

src

pub fn writeAll(self: *Stream, bytes: []const u8) void

src

pub fn writeByte(self: *Stream, byte: u8) void

src

pub fn flush(self: *Stream) void

src

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

pub const empty = 0x80

src

Top bit set, all others clear: an empty slot. Enables a sign-style empty match on a group of bytes.

pub const deleted = 0xFE

src

Top bit set, bit 0 clear: a tombstone. Distinguishable from empty by one bit; both sort below sentinel.

pub const sentinel = 0xFF

src

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
    8

Group 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.

pub const Mask = @Int(.unsigned, group_width)

src

The group mask type: one bit per lane, @bitCast of the compare's bool vector — the repo's shipped idiom.

Functions

pub fn full(h2: u64) u8

src

A full control byte: the top 7 bits of the hash in the low 7 bits, top bit clear.

pub fn matchFull(bytes: *const [group_width]u8) Mask

src

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.

pub fn matchH2(bytes: *const [group_width]u8, tag: u8) Mask

src

The lanes holding a full byte whose H2 equals tag — a candidate slot for a key with that fingerprint.

pub fn firstSet(mask: Mask) ?u6

src

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

pub const empty: Self = …

src
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.

pub const init: Self = …

src
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.

pub fn count(self: *const Self) usize

src

Number of entries currently stored.

pub fn capacity(self: *const Self) usize

src

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.

pub fn rehash(self: *Self, gpa: Allocator) Allocator.Error!void

src

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.

pub fn get(self: *const Self, key: K) ?V

src

Value stored for key, or null. Reads never allocate.

pub fn getPtr(self: *Self, key: K) ?*V

src

Pointer to the value stored for key, or null. The pointer is invalidated by the next insertion or growth.

pub fn contains(self: *const Self, key: K) bool

src

Whether key is stored in the map.

pub fn put(self: *Self, gpa: Allocator, key: K, value: V) Allocator.Error!void

src

Insert or overwrite key.

pub fn getOrPut(self: *Self, gpa: Allocator, key: K) Allocator.Error!GetOrPutResult

src

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.

pub fn remove(self: *Self, key: K) bool

src

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.

pub fn deinit(self: *Self, gpa: Allocator) void

src

Release the storage and invalidate the map.

pub fn iterator(self: *Self) Iterator

src

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 Entry

src

Pointers to a key and value stored in the map.

Fields

key_ptr: *K
value_ptr: *V

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

struct Iterator

src

Fields

map: *Self
slot: usize

Functions

pub fn next(it: *Iterator) ?Entry

src

The next entry in bucket order, or null.

pub fn reset(it: *Iterator) void

src

Reset the iterator to the first bucket.

struct KeyIterator

src

Fields

map: *Self
slot: usize

Functions

pub fn next(it: *KeyIterator) ?*K

src

The next key in bucket order, or null.

pub fn reset(it: *KeyIterator) void

src

Reset the iterator to the first bucket.

struct ValueIterator

src

Fields

map: *Self
slot: usize

Functions

pub fn next(it: *ValueIterator) ?*V

src

The next value in bucket order, or null.

pub fn reset(it: *ValueIterator) void

src

Reset the iterator to the first bucket.

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

pub const empty: Self = …

src
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.

pub const init: Self = …

src
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.

pub fn count(self: *const Self) usize

src

Number of entries currently stored.

pub fn capacity(self: *const Self) usize

src

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.

pub fn rehash(self: *Self, gpa: Allocator) Allocator.Error!void

src

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.

pub fn get(self: *const Self, key: K) ?V

src

Value stored for key, or null. Reads never allocate.

pub fn getPtr(self: *Self, key: K) ?*V

src

Pointer to the value stored for key, or null. The pointer is invalidated by the next insertion or growth.

pub fn contains(self: *const Self, key: K) bool

src

Whether key is stored in the map.

pub fn put(self: *Self, gpa: Allocator, key: K, value: V) Allocator.Error!void

src

Insert or overwrite key.

pub fn getOrPut(self: *Self, gpa: Allocator, key: K) Allocator.Error!GetOrPutResult

src

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.

pub fn remove(self: *Self, key: K) bool

src

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.

pub fn deinit(self: *Self, gpa: Allocator) void

src

Release the storage and invalidate the map.

pub fn iterator(self: *Self) Iterator

src

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 Entry

src

Pointers to a key and value stored in the map.

Fields

key_ptr: *K
value_ptr: *V

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

struct Iterator

src

Fields

map: *Self
slot: usize

Functions

pub fn next(it: *Iterator) ?Entry

src

The next entry in bucket order, or null.

pub fn reset(it: *Iterator) void

src

Reset the iterator to the first bucket.

struct KeyIterator

src

Fields

map: *Self
slot: usize

Functions

pub fn next(it: *KeyIterator) ?*K

src

The next key in bucket order, or null.

pub fn reset(it: *KeyIterator) void

src

Reset the iterator to the first bucket.

struct ValueIterator

src

Fields

map: *Self
slot: usize

Functions

pub fn next(it: *ValueIterator) ?*V

src

The next value in bucket order, or null.

pub fn reset(it: *ValueIterator) void

src

Reset the iterator to the first bucket.

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

pub const empty: Self = …

src
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.

pub const init: Self = …

src
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.

pub fn count(self: *const Self) usize

src

Number of entries currently stored.

pub fn capacity(self: *const Self) usize

src

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.

pub fn rehash(self: *Self, gpa: Allocator) Allocator.Error!void

src

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.

pub fn get(self: *const Self, key: K) ?V

src

Value stored for key, or null. Reads never allocate.

pub fn getPtr(self: *Self, key: K) ?*V

src

Pointer to the value stored for key, or null. The pointer is invalidated by the next insertion or growth.

pub fn contains(self: *const Self, key: K) bool

src

Whether key is stored in the map.

pub fn put(self: *Self, gpa: Allocator, key: K, value: V) Allocator.Error!void

src

Insert or overwrite key.

pub fn getOrPut(self: *Self, gpa: Allocator, key: K) Allocator.Error!GetOrPutResult

src

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.

pub fn remove(self: *Self, key: K) bool

src

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.

pub fn deinit(self: *Self, gpa: Allocator) void

src

Release the storage and invalidate the map.

pub fn iterator(self: *Self) Iterator

src

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 Entry

src

Pointers to a key and value stored in the map.

Fields

key_ptr: *K
value_ptr: *V

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

struct Iterator

src

Fields

map: *Self
slot: usize

Functions

pub fn next(it: *Iterator) ?Entry

src

The next entry in bucket order, or null.

pub fn reset(it: *Iterator) void

src

Reset the iterator to the first bucket.

struct KeyIterator

src

Fields

map: *Self
slot: usize

Functions

pub fn next(it: *KeyIterator) ?*K

src

The next key in bucket order, or null.

pub fn reset(it: *KeyIterator) void

src

Reset the iterator to the first bucket.

struct ValueIterator

src

Fields

map: *Self
slot: usize

Functions

pub fn next(it: *ValueIterator) ?*V

src

The next value in bucket order, or null.

pub fn reset(it: *ValueIterator) void

src

Reset the iterator to the first bucket.

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.

pub fn now(clock: Io.Clock) Io.Timestamp

src

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

pub const init: Self = .{ .cached = 0 }

src

Functions

pub fn refresh(self: *Self) Io.Timestamp

src

Read the clock and store it. Returns the full-precision sample — the cache keeps one word.

pub fn now(self: *Self) Io.Timestamp

src

The cached time — stale-never-ahead, or a direct read from a cold clock.

pub fn clear(self: *Self) void

src

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

pub const zero: Duration = .{ .nanoseconds = 0 }

src

pub const Error = …

src
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.

pub fn fromStd(duration: Io.Duration) Error!Duration

src

Convert a std duration without accepting a negative elapsed time.

pub fn toStd(self: Duration) Io.Duration

src

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

pub fn toSeconds(self: Duration) u64

src

pub fn add(self: Duration, other: Duration) Error!Duration

src

pub fn format(self: Duration, writer: *Io.Writer) Io.Writer.Error!void

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

Constants

pub const none: Self = .{ .nanoseconds = math.maxInt(u64) }

src

pub const Error = …

src
value
error{
            /// The supplied value equals the word reserved for `none`.
            OutOfRange,
        }

Functions

pub fn init(value: ?T) Error!Self

src

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.

pub fn get(self: Self) ?T

src

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

pub const default: RateLimit = .{ .next_ms = 0, .suppressed = 0, .interval_ms = 1_000 }

src

A one-second interval, with no line sent and nothing held back yet.

Functions

pub fn init(interval: Io.Duration) RateLimit

src

pub fn admit(self: *RateLimit, now: Io.Timestamp) ?u32

src

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

pub const zero: Timestamp = .{ .nanoseconds = 0 }

src

pub const Error = Duration.Error

src

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.

pub fn fromStd(timestamp: Io.Timestamp) Error!Timestamp

src

Convert a std timestamp. Values before the clock's epoch or beyond the u64 nanosecond range return error.OutOfRange.

pub fn toStd(self: Timestamp) Io.Timestamp

src

Widen the reading for std. Every value fits std's i96.

pub fn now(clock: Io.Clock) Timestamp

src

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.

pub fn elapsed(self: Timestamp, comptime clock: Io.Clock) Duration

src

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

pub fn toSeconds(self: Timestamp) u64

src

pub fn add(self: Timestamp, duration: Duration) Error!Timestamp

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.

pub fn compare(self: Timestamp, other: Timestamp) math.Order

src

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

pub fn compute() WallFromAwake

src

The startup offset: read both clocks once and store the value wherever the process keeps startup state.

pub fn toWall(self: WallFromAwake, awake: Io.Timestamp) Io.Timestamp

src

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

pub const Callback = *const fn (timers: *Timers, timer: *Timer) Action

src

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

pub fn disarm(_: void, _: *Timers, _: *Timer) Action

src

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

enum Action

src

What expire does with a timer after its callback returns: re-arm a period timer for its next fire, or let it stay fired.

Fields

disarm disarm
rearm rearm

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

pub const one_shot: Timer = …

src
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

pub fn repeat(period: Io.Duration) Timer

src

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.

pub fn deadline(self: *const Timer) Io.Timestamp

src

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

pub const empty: Timers = .{ .treap = .{}, .seq = 0 }

src

Functions

pub fn arm( self: *Timers, timer: *Timer, at: Io.Timestamp, comptime cb: anytype, ) void

src

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.

pub fn stop(self: *Timers, timer: *Timer) bool

src

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.

pub fn reset(self: *Timers, timer: *Timer, at: Io.Timestamp) bool

src

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.

pub fn next(self: *const Timers) ?Io.Timestamp

src

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.

pub fn expire(self: *Timers, now: Io.Timestamp) void

src

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).

pub const Error = …

src
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

pub const precision: u5 = Raw.precision

src

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)).

pub const empty: Self = .{ .sketch = .empty }

src

An empty sketch with all registers zeroed.

Functions

pub fn add(self: *Self, key: T) void

src

Hash key with Context and insert it into the sketch.

pub fn addHash(self: *Self, hash: u64) void

src

Insert a pre-hashed uniform 64-bit value directly.

pub fn estimate(self: *const Self) f64

src

Estimate the number of distinct keys added to this sketch.

pub fn merge(self: *Self, other: *const Self) void

src

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.

pub fn isEmpty(self: *const Self) bool

src

Whether no keys have been added since initialization or clear.

pub fn clear(self: *Self) void

src

Reset all registers to zero.

pub fn asBytes(self: *const Self) *const [register_count]u8

src

Borrow the raw byte registers for serialization.

pub fn fromBytes(bytes: [register_count]u8) Error!Self

src

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

pub const precision: u5 = Raw.precision

src

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)).

pub const empty: Self = .{ .sketch = .empty }

src

An empty sketch with all registers zeroed.

Functions

pub fn add(self: *Self, key: T) void

src

Hash key with Context and insert it into the sketch.

pub fn addHash(self: *Self, hash: u64) void

src

Insert a pre-hashed uniform 64-bit value directly.

pub fn estimate(self: *const Self) f64

src

Estimate the number of distinct keys added to this sketch.

pub fn merge(self: *Self, other: *const Self) void

src

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.

pub fn isEmpty(self: *const Self) bool

src

Whether no keys have been added since initialization or clear.

pub fn clear(self: *Self) void

src

Reset all registers to zero.

pub fn asBytes(self: *const Self) *const [register_count]u8

src

Borrow the raw byte registers for serialization.

pub fn fromBytes(bytes: [register_count]u8) Error!Self

src

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

pub const precision: u5 = Raw.precision

src

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)).

pub const empty: Self = .{ .sketch = .empty }

src

An empty sketch with all registers zeroed.

Functions

pub fn add(self: *Self, key: T) void

src

Hash key with Context and insert it into the sketch.

pub fn addHash(self: *Self, hash: u64) void

src

Insert a pre-hashed uniform 64-bit value directly.

pub fn estimate(self: *const Self) f64

src

Estimate the number of distinct keys added to this sketch.

pub fn merge(self: *Self, other: *const Self) void

src

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.

pub fn isEmpty(self: *const Self) bool

src

Whether no keys have been added since initialization or clear.

pub fn clear(self: *Self) void

src

Reset all registers to zero.

pub fn asBytes(self: *const Self) *const [register_count]u8

src

Borrow the raw byte registers for serialization.

pub fn fromBytes(bytes: [register_count]u8) Error!Self

src

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

pub const precision: u5 = p

src

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)).

pub const empty: Self = .{ .registers = @splat(0) }

src

An empty sketch with all registers zeroed.

Functions

pub fn addHash(self: *Self, hash: u64) void

src

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.

pub fn estimate(self: *const Self) f64

src

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.

pub fn merge(self: *Self, other: *const Self) void

src

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.

pub fn isEmpty(self: *const Self) bool

src

Whether all registers are zero.

pub fn clear(self: *Self) void

src

Reset all registers to zero.

pub fn asBytes(self: *const Self) *const [register_count]u8

src

Borrow the raw register bytes for serialization.

pub fn fromBytes(bytes: [register_count]u8) Error!Self

src

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 nil: Uuid = .{ .bytes = @splat(0) }

src

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

pub fn version(self: Uuid) Version

src

pub fn v4() Uuid

src

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.

pub fn v7() Uuid

src

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.

pub fn parse(s: []const u8) ParseError!Uuid

src

Parse the canonical 36-byte form, either case.

pub fn format(self: Uuid, w: *Io.Writer) Io.Writer.Error!void

src

pub fn eql(a: Uuid, b: Uuid) bool

src

Types

enum Version

src
pub const Version = enum(u4)

The version nibble.

Fields

v1 v1 = 1
v2 v2 = 2
v3 v3 = 3
v4 v4 = 4
v5 v5 = 5
v6 v6 = 6
v7 v7 = 7
v8 v8 = 8
_ _

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

buffer: []u8

The full storage.

end: usize

One past the last written byte.

Constants

pub const byte_order = endian

src

The byte order this writer uses.

pub const empty: Self = .{ .buffer = &.{}, .end = 0 }

src

A writer over no storage. Only zero-length writes fit.

Functions

pub fn init(buffer: []u8) Self

src

Use buffer as the whole capacity. The writer starts empty.

pub fn capacity(self: *const Self) usize

src

The whole storage length.

pub fn buffered(self: *Self) []u8

src

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.

pub fn clear(self: *Self) void

src

Reset the write cursor. The written bytes stay in the backing.

pub fn advance(self: *Self, n: usize) error{NoSpaceLeft}!void

src

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().

pub fn append(self: *Self, comptime T: type, value: T) error{NoSpaceLeft}!void

src

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.

pub fn reserve(self: *Self, comptime n: usize) error{NoSpaceLeft}!*[n]u8

src

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.

pub fn undo(self: *Self, n: usize) void

src

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.

pub const empty: Self = .{ .buffer = &.{}, .end = 0 }

src

A reader over no storage. Only zero-length reads fit.

Functions

pub fn init(buffer: []const u8) Self

src

Use buffer as the whole storage. The reader starts empty.

pub fn capacity(self: *const Self) usize

src

The whole storage length.

pub fn consumed(self: *const Self) []const u8

src

The bytes read so far.

pub fn remaining(self: *const Self) []const u8

src

The unread bytes.

pub fn read(self: *Self, comptime T: type) error{UnexpectedEof}!T

src

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.

pub fn peek(self: *Self, comptime T: type) error{UnexpectedEof}!T

src

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.

pub fn readSlice(self: *Self, n: usize) error{UnexpectedEof}![]const u8

src

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.

pub fn peekSlice(self: *Self, n: usize) error{UnexpectedEof}![]const u8

src

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.

pub fn readUntil(self: *Self, delimiter: u8) error{UnexpectedEof}![]const u8

src

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.

pub fn peekUntil(self: *Self, delimiter: u8) error{UnexpectedEof}![]const u8

src

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.

pub fn skip(self: *Self, n: usize) error{UnexpectedEof}!void

src

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

pub const allocator: Allocator = std.heap.page_allocator

src

The intentional std.heap.page_allocator. See the module doc for the contracts that make an allocation through this alias deliberate.

Functions

pub fn reserve(comptime T: type, n: usize) []T

src

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.

pub fn unreserve(memory: anytype) void

src

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

pub fn whole(bytes: []u8) []u8

src

The whole kernel pages inside bytes: empty when bytes spans none.

pub fn release(bytes: []u8) void

src

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.

pub const Read = …

src
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

pub fn init(self: *Self, gpa: Allocator, io: Io, num_slots: usize) !void

src

Initialize the ring. num_slots rounds up to a power of two. The io parameter is the futex backend, ignored by the other flavors.

pub fn deinit(self: *Self, gpa: Allocator) void

src

Tear the ring down. Requires no active producers, consumer, or leases — the caller quiesces first.

pub fn acquire(self: *Self) ?Lease

src

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.

pub fn head(self: *const Self) u64

src

Number of claims handed out, committed or not.

pub fn readHead(self: *const Self) u64

src

.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().

pub fn numSlots(self: *const Self) usize

src

Number of slots in the ring.

pub fn pollFd(self: *const Self) linux.fd_t

src

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 Slot

src
pub const Slot = extern struct

One slot: the stamp word first, so the consumer's acquire load of it prefetches the payload start on the same line.

Fields

stamp: atomic.Value(u64) align(8)

High half: the lap this slot's current claim belongs to. Low half: committed payload length, 0 = not committed. The full lease protocol in one word.

payload: [payload_size]u8

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

pub fn writer(self: Lease) Io.Writer

src

A writer over the slot payload. end is the length to commit.

pub fn commit(self: *Lease, self_ring: *Self, len: u32) void

src

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.

pub fn index(self: Lease) u64

src

The ring position of this lease, for logging and truncation markers.