Languages and runtimesDive 05 of 06

Zig comptime: the compiler runs your code

Build a tiny binary protocol with types as values, a derived packet codec and a CRC table. Follow ordinary Zig code through compile-time evaluation into the bytes and instructions that survive.

Levels
8
Reading
40 min
Depth
Idea to Machine
Published
You write one languageconst crc_table = makeTable();const Wire = Packet(Header);const bytes = Wire.encode(message);
Evaluated by the compiler

Learn the shape. Do the setup.

Read the two field types. Build 256 CRC entries. Generate a codec for this packet.

id: u16kind: u83 wire bytes
The program never repeats this work.
Emitted into the binary

Keep the results. Run on messages.

.rodata · CRC table · first 4 of 256 words
0000000077073096ee0e612c990951ba
.text · specialized encoder

Write id low byte, id high byte, then kind.

341207message: id = 0x1234, kind = 7

Compile time turns a description into a tool. Runtime uses that tool on data that arrives later.

Level 01/08Idea

One source, two times to run

A sensor sends a three-byte message: a two-byte identifier followed by a one-byte kind. Your receiver must agree with the sender about field order, byte order and length. Tomorrow a second message adds a timestamp. You could write another encoder, another decoder and another collection of tests. Or you could describe the fields once and let a tool produce the repetitive parts.

Now add a CRC to detect accidental corruption. A byte-at-a-time CRC implementation usually needs a lookup table. You can paste a thousand bytes of constants into the source, generate a file before compiling, initialize a table at startup, or ask the compiler to run the table-building function. Finally, your diagnostic line wants an integer where the format says {d}. That disagreement should be caught before the sensor is deployed.

These look like three different features: generics, code generation and static checking. Zig connects them through one capability. The compiler can evaluate ordinary Zig code, including loops and local mutation, when the inputs are available during compilation. A function can accept a type, inspect it and return another type. A function can build an array. A function can reject a string. The useful distinction is when the work runs.

Evaluation during compilation, before the target program executes. Zig can require an expression to be evaluated at this time, and some values, including types, can only exist at this time. is short for compile time. It does not mean “run the completed application early.” The compiler analyzes source and evaluates the portions that require known values. Other portions become instructions for the target machine. A compile-time table builder can produce data that runtime code reads, just as a handwritten constant array can.

The small program we will build · protocol.zig, Zig 0.17.1
const Header = struct { id: u16, kind: u8 };
const Wire = Packet(Header);

pub fn main() !void {
    const message: Header = .{ .id = 0x1234, .kind = 7 };
    const bytes = Wire.encode(message);
    const received = try Wire.decode(&bytes);
    const format = "id={d} kind={x}\n";
    checkFormat(format, &.{ u16, u8 });
    std.debug.print(format, .{ received.id, received.kind });
    std.debug.print("crc={x}\n", .{crc32(&bytes)});
}

The program calls a generic Packet(Header) constructor, encodes a value, decodes the resulting bytes and prints a checked diagnostic. It computes a CRC over the three payload bytes. Our tiny codec accepts ordinary structs whose runtime fields are u8, u16 or u32; it rejects other field types. That boundary makes the wire format explicit. An industrial protocol would also need framing, schema evolution and an agreed location and byte order for the CRC.

Keep two test cases in mind throughout. A valid message has bytes 34 12 07 and must decode to identifier 4660 and kind 7. A truncated message has only 34 12 and must fail before the decoder reads the kind. Compile-time machinery earns its place only if both cases remain easy to explain. Generating fast code for a valid message while obscuring how invalid input is handled would make this library worse.

What are the alternatives?

Every tool below can remove repetition. The differences lie in the material you manipulate and the rules that constrain the generated program. A textual macro sees tokens; a type-aware function sees values and types. Those are different powers. Zig deliberately does not offer arbitrary syntax-tree rewriting through comptime. You build values, select declarations and construct types within the language’s normal grammar.

MechanismHow our protocol might be builtBoundary to learn
C preprocessorExpand an X-macro field list into declarations and operations.Token substitution before type checking; no normal typed execution.
C++ templates + constexprInstantiate codec templates; compute constants with constexpr or consteval functions.Templates, constant evaluation and constraints interact through several language mechanisms.
Rust generics + proc macrosUse traits for a codec contract and a derive macro to generate implementations.Generic type checking and a separate token-based procedural macro API.
Go genericsShare constrained algorithms; use explicit codecs, reflection or source generation for fields.Type parameters do not expose arbitrary struct fields for compile-time iteration.
Zig comptimeCall Packet(T), inspect T and build the CRC table with ordinary Zig functions.Values used to choose types and field names must be known during analysis.

Putting computation in the compiler trades deployment work for build work. It can eliminate startup initialization, validate assumptions early and specialize a hot path. It can also lengthen builds and multiply machine code when many distinct arguments create many specializations. “Compile-time” describes where you pay, not a promise that the work is free.

There is a particularly useful division in a protocol library. Field types, widths and names are fixed by the protocol schema. Field values arrive from sensors, files or sockets. Move the first group into compilation and keep the second group at runtime. Then a packet encoder can be entirely specific about what to write while still accepting a new identifier on every call.

Comptime makes the compiler a place where your library code can run. Its outputs can be constants, types and a specialized runtime program.

Level 02/08Interface

What can the compiler know?

Before deriving anything, decide what the compiler can know. The identifier u16 names a type. The literal 16 is a known number. An ordinary function parameter n: u32 has a known type but an unknown value while the function is analyzed as runtime code. That separation between knowing a value and knowing its type explains much of Zig’s generic programming.

A comptime parameter requires its caller to supply a compile-time value. The caller can supply u16, a fixed length, a boolean policy or a string. The compiler can then use that argument in places where a runtime value would be impossible, such as an array length or a return type. A sensor reading cannot choose the static element type of an array halfway through a running function.

A comptime expression requires evaluation now. A comptime block applies that requirement to a block of work. A comptime var is mutable compiler-side state whose updates must happen during compilation. None of these constructs asks the optimizer to try its best. If an evaluated path needs an unavailable runtime value, compilation fails.

Ordinary const has a narrower meaning: you cannot reassign the binding. A local const next = n + 1 still depends on n. Conversely, a container-level initializer is evaluated at compile time, so our file-level const crc_table = makeTable() needs no extra comptime keyword. Context, rather than the spelling of the arithmetic, supplies the timing requirement.

Known value, runtime value, or compile error?

Each row is independent, inside fn inspect(n: u32). square(x: u32) returns x * x. Select a row and make a prediction.

Classify the selected expression.

The value of the initializer is what matters, not just the const keyword.

Eight fixed language-reference cases; this widget classifies these snippets, rather than parsing arbitrary Zig.

Classify eight independent expressions. Knowing n’s type is enough for @TypeOf(n), but forcing n’s value into comptime produces an error.

Numbers that have not picked a storage format

An integer literal starts as comptime_int. It can represent an arbitrary-precision integer during compilation; it is not an invisible runtime bignum allocation. A floating-point literal starts as comptime_float. These literal types let surrounding context choose an appropriate concrete type. Assigning 16 to a u8 is fine; assigning 300 to a u8 cannot be represented and fails.

When a value needs runtime storage, give it a runtime-representable type. A runtime mutable counter needs something such as usize, not an unconstrained comptime_int. The compiler also checks operations that it actually evaluates. Known unsigned overflow with ordinary + is an error. If wrapping is the intended arithmetic, Zig spells that intention with operators such as +%. CRC uses XOR and shifts, so its recurrence needs no overflowing addition.

Inline means something specific

inline for expands a loop during analysis. Its element captures and index are known for each iteration, which lets the loop body choose a different field type at each expansion. The body can still contain runtime work. Our future encoder reads runtime packet values inside such a loop; only the description of which field to read is known ahead of time.

inline while similarly requires compile-time control over iteration. It is useful when the next iteration depends on compiler-side state. It is not the same request as “please make this machine-code loop fast.” Ordinary loops are already evaluated when their enclosing context requires comptime. Adding inline to every loop is unnecessary and can increase generated code for work better left as a runtime loop.

From basics.zig · compile-time mutation and literal coercion
test "comptime basics" {
    const scale = comptime square(4);
    comptime var count: usize = 0;
    inline while (count < 3) : (count += 1) {
        try std.testing.expect(count < 3);
    }
    const half = 0.5;
    const typed: f32 = half;
    try std.testing.expectEqual(@as(u32, 16), scale);
    try std.testing.expectEqual(@as(f32, 0.5), typed);
}

The three expanded iterations above each check a known count. square is an ordinary function returning x * x; the explicit comptime call evaluates it with four. The same definition can accept a runtime u32 elsewhere. There is no separate constexpr version to maintain. The important restriction is whether every operation on the evaluated path supports this execution context.

One last distinction prevents confusion when inspecting assembly. An optimizer may fold a runtime-eligible expression into a constant. That does not retroactively make the expression legal as a type or array length. Language-level compile-time knowledge determines whether the source is valid; backend constant propagation determines how valid runtime code is implemented.

Check yourselfInside fn read(n: u32), which binding is necessarily a compile-time value?

Const controls reassignment. Comptime controls when a value must be available. Those are independent properties.

Level 03/08Interface

A function that returns a type

A Zig type can be a function argument or result. The type of that value is spelled type. Because types have no ordinary runtime representation, a function returning a type is evaluated during compilation. This is enough machinery to express a generic container: accept an element type, return a struct that uses it.

The small List below is a borrowed view, not an owning dynamic array. Its items slice refers to storage owned elsewhere. Instantiating List(u16) constructs a struct type with a []u16 field and a method returning ?u16. Instantiating List(u8) constructs a different type. Neither call allocates a list or fills its elements.

A type constructor and a duck-typed reader · basics.zig
fn List(comptime T: type) type {
    return struct {
        items: []T,

        pub fn first(self: @This()) ?T {
            return if (self.items.len == 0) null else self.items[0];
        }
    };
}

fn firstItem(list: anytype) @TypeOf(list.items[0]) {
    return list.items[0];
}

The anonymous struct captures the known type parameter T. @This() names the struct currently being defined. Its first method takes a runtime value of that struct. This makes the timing boundary visible: the method’s signature depends on compilation; its length check and element load can happen on each runtime call.

Zig preserves the identity of these generated types for repeated calls with the same arguments to the same type-returning function. This matters when two parts of a program name List(u16): they agree on one type, rather than producing incompatible anonymous structs on every mention. Distinct named struct declarations remain distinct types, even if they have identical fields.

Packet(Header)call site A
Packet(Header)call site B
One generated typeencode(Header) [3]u8decode([]const u8) !Header
Packet(Reading)different argument
A different generated typeencode(Reading) [7]u8decode([]const u8) !Reading
Repeated Packet(Header) calls agree on a generated type. Packet(Reading) has a different input type and produces a different codec interface.

This behavior is often described as memoization of generic instantiations. It is useful to reason in terms of identity and reuse, but do not turn it into a build-time benchmark prediction. A compiler still needs to discover declarations, analyze dependencies and generate any runtime functions that are referenced. Sharing a type does not promise zero cost for every use in a large project.

Anytype carries a type, not a hidden object box

The second function accepts anytype. The compiler infers a concrete parameter type at each call. Accessing list.items then checks whether that type has the required field. The compiler uses @TypeOf(list.items[0]) to determine the return type. It need not read the first element during compilation; it only needs to know what type such an access produces.

That is a form of An interface checked from the operations a concrete type supports, such as having an items field, rather than from an explicit implements declaration.. There is no virtual method lookup or dynamic type tag implied by anytype. A call with a type lacking items fails when that specialization is analyzed. A call with an empty slice is a separate runtime bounds problem: type compatibility does not establish that an element exists.

Use an explicit comptime T: type when the caller needs to choose a type directly, especially if no runtime argument provides it. Use anytype when the argument’s concrete type supplies the information. In either case, unnecessary generic parameters multiply the combinations the compiler must consider. A fixed []const u8 parameter is often easier to understand when a function only needs bytes.

Instantiate the protocol

Our packet type follows the same pattern, but it exposes operations rather than storing a payload. Packet(Header) returns a namespace-like struct containing wire_size, encode and decode. The encoder accepts a Header; the decoder returns a Header. No packet object needs to carry field names at runtime.

Change the schema below and inspect the generated plan. Then edit a value: the schema stays fixed while the payload bytes change. Finally, remove the last byte and ask the decoder to read it. That failure belongs at runtime because message length is a property of incoming data, not a fact the library can generally know while it is compiled.

Generated encode plan · little-endian

id: u16 → offsets 0–1
kind: u8 → offset 2
Total: 3 bytes

Wire bytes · one cell = one byte

341207

Payload CRC-32: 0x3ab3712e.

Header instantiated. Edit a value or decode the bytes.

No decode result yet.
Instantiate three concrete packet schemas, encode real little-endian bytes and decode editable input. Every wire-byte cell represents exactly one byte.

A generic library can be a function from known values to a type. Instances of that type still hold and process ordinary runtime data.

Level 04/08Interface

Turn fields into a wire protocol

The packet constructor needs three pieces of information: field names, field types and their declaration order. @typeInfo(T) returns a tagged description of a type. Switch on that description to reject non-struct inputs. The struct case, spelled .@"struct" because struct is a keyword, exposes the field information.

In Zig 0.17 the names, types and field attributes are parallel arrays. Iterating them together binds a known field name, field type and attributes on each pass. The constructor rejects a comptime field with a diagnostic such as “Packet field kind: comptime fields are not supported.” It accepts only the unsigned integer widths that the protocol defines. A field of type f32, a pointer or a nested object also receives a compile error naming the field. Supporting another category should mean defining its wire representation, not blindly copying its storage bytes.

Source field order becomes explicit wire order

id: u16bits 0–7bits 8–15
kind: u8bits 0–7
offset 034id low
offset 112id high
offset 207kind

Wire size: 2 + 1 = 3 bytes. The Zig struct’s storage size and field offsets are separate.

Header’s declared fields become a three-byte little-endian wire format. This mapping does not depend on the compiler’s storage layout for the ordinary struct.

The supported-field rule is also a versioning rule for the protocol. Adding a field changes the wire size and can make an old receiver reject a new message. Comptime will regenerate both sides when you rebuild them together, but it cannot update a device already deployed in the field. Give a real protocol a version or message-kind discriminator, decide how unknown variants are handled, and test compatibility across separately built programs.

Serialization is a contract, not a memory dump

An ordinary Zig struct is free to have a storage layout different from declaration order. Alignment and padding also make @sizeOf(T) a poor definition of a portable wire format. Our wire size is the sum of the explicitly supported field widths. Header has two bytes of identifier plus one byte of kind, so it always writes three bytes.

Each integer is written least significant byte first. With id = 0x1234, byte zero is 0x34 and byte one is 0x12. The decoder performs the inverse shifts and ORs. It first checks for an exact length, so no indexing can happen on a shorter input and trailing bytes cannot be silently ignored. Real framing might choose to decode a prefix and return the consumed length; this protocol deliberately requires one complete payload.

Packet(T) · unsigned runtime fields u8/u16/u32 · Zig 0.17.1
pub fn Packet(comptime T: type) type {
    const info = switch (@typeInfo(T)) {
        .@"struct" => |s| s,
        else => @compileError("Packet expects a struct"),
    };
    const size = blk: {
        var n: usize = 0;
        for (info.field_names, info.field_types, info.field_attrs) |name, F, attrs| {
            if (attrs.@"comptime")
                @compileError("Packet field " ++ name ++ ": comptime fields are not supported");
            switch (@typeInfo(F)) {
                .int => |int| {
                    if (int.signedness != .unsigned or
                        (int.bits != 8 and int.bits != 16 and int.bits != 32))
                        @compileError("Packet field " ++ name ++ ": use u8, u16 or u32");
                },
                else => @compileError("Packet field " ++ name ++ ": use u8, u16 or u32"),
            }
            n += @sizeOf(F);
        }
        break :blk n;
    };
    return struct {
        pub const wire_size = size;

        pub fn encode(value: T) [size]u8 {
            var out: [size]u8 = undefined;
            var offset: usize = 0;
            inline for (info.field_names, info.field_types) |name, F| {
                inline for (0..@sizeOf(F)) |j| {
                    out[offset + j] = @truncate(@field(value, name) >> @intCast(8 * j));
                }
                offset += @sizeOf(F);
            }
            return out;
        }

        pub fn decode(bytes: []const u8) error{BadLength}!T {
            if (bytes.len != size) return error.BadLength;
            var value: T = undefined;
            var offset: usize = 0;
            inline for (info.field_names, info.field_types) |name, F| {
                var field: F = 0;
                inline for (0..@sizeOf(F)) |j| {
                    field |= @as(F, bytes[offset + j]) << @intCast(8 * j);
                }
                @field(value, name) = field;
                offset += @sizeOf(F);
            }
            return value;
        }
    };
}

The constructor’s first loop validates the schema and computes the array size. The returned encoder then uses inline for so that each field access has a known name and type. @field(value, name) is equivalent to a normal named access once the name is resolved. It does not search for a string in the running program.

The nested loop expands each byte position of a supported integer. The shift amount is known and valid for that field width. @truncate intentionally keeps the lowest eight bits after shifting. In the decoder, coercing a byte to the destination field type before shifting ensures the high bits fit in the integer being assembled. Each field starts at zero and is assigned before the completed value is returned.

The error union error{BadLength}!T distinguishes an incoming-data failure from a schema error. A bad schema prevents compilation through @compileError. Bad bytes return a runtime error that the caller can handle with try, catch or an error switch. Moving schema work earlier does not remove the need to validate untrusted messages later.

Reflection can build as well as inspect

Older Zig explanations use @Type to turn a type description back into a type. The 0.17 interface instead has dedicated constructors, including @Int, @Struct, @Enum and @Tuple. For example, @Int(.unsigned, 24) produces u24. These constructors still require known inputs. A runtime byte cannot choose the number of bits in a local variable’s static type.

For this codec, returning a struct literal is simpler than constructing a reflected struct description. You would reach for a constructor when field names or field types themselves are computed. In both cases, you must define an interface that callers can use. A thousand dynamically assembled fields may be legal and still be harder to maintain than a small explicit schema.

@hasDecl asks about a public declaration in a namespace; @hasField asks about a field. A library can use those checks to discover an optional custom encoder, but it must then validate the encoder’s signature. Convenience helpers in std.meta can save repetitive reflection code. We use the builtins here so that the flow from type information to byte operations remains visible.

Check yourselfWhy does this encoder sum field widths instead of copying @sizeOf(Header) bytes?

Compile-time reflection can remove runtime field discovery. It cannot invent the protocol’s meaning; you still choose widths, ordering and validation.

Level 05/08Runtime

Spend compilation on a table

We have generated the codec’s structure. Now generate data. CRC-32 processes a stream of bits with a polynomial recurrence. A byte-at-a-time implementation precomputes what eight recurrence steps do to each possible low byte. There are 28 = 256 possibilities, and each result fits in a 32-bit word. The table occupies 256 × 4 = 1024 bytes.

Our variant is CRC-32/ISO-HDLC, commonly called IEEE CRC-32. It starts the running register at 0xffffffff, processes reflected input and XORs the final register with 0xffffffff. The reflected polynomial is 0xedb88320, corresponding to the conventional polynomial representation 0x04c11db7. These choices are part of the algorithm. Using the same polynomial with different initialization or reflection conventions can produce a different CRC.

One table entry · start with index 1

00000000000000000000000000000001

Low bit is 1: shift right, then XOR the reflected polynomial.

cnext = (c ≫ 1) ⊕ 0xedb88320
Start
0x00000001
After one bit
0xedb88320
After eight bits
0x77073096
The low bit chooses whether to XOR the reflected polynomial after a right shift. Eight such steps turn table index 1 into 0x77073096.

For a table entry, start with its index as the register. Repeat eight times: shift right one bit, XORing the polynomial when the old low bit was one. This yields the contribution of that byte. The runtime update combines the incoming byte with the old register’s low byte, uses that as a table index, and XORs the table word with the register shifted right by eight.

The standard check input 123456789, interpreted as nine ASCII bytes, produces 0xcbf43926. That check value, and the algorithm’s other parameters, appear in the CRC catalogue. An empty payload produces zero with these initialization and finalization choices. The live calculator below uses UTF-8, so non-ASCII characters can occupy more than one input byte.

The same ordinary functions build constants and process runtime bytes
pub fn makeTable() [256]u32 {
    @setEvalBranchQuota(4096);
    var table: [256]u32 = undefined;
    var i: usize = 0;
    while (i < table.len) : (i += 1) {
        var c: u32 = @intCast(i);
        var bit: usize = 0;
        while (bit < 8) : (bit += 1) {
            c = (c >> 1) ^ (if (c & 1 != 0) @as(u32, 0xedb88320) else 0);
        }
        table[i] = c;
    }
    return table;
}

const crc_table = makeTable();

pub fn crc32(bytes: []const u8) u32 {
    var c: u32 = 0xffffffff;
    for (bytes) |byte| {
        const index: u8 = @truncate(c ^ byte);
        c = (c >> 8) ^ crc_table[index];
    }
    return c ^ 0xffffffff;
}

You can validate the table independently of the table-driven update. For each byte, apply the bitwise recurrence eight times and compare it with the corresponding table word. Then compare a complete payload against a trusted implementation or published check value. A round-trip encoder test alone would not catch two matching mistakes; both encoder and decoder could agree on the wrong byte order. The same principle applies to the CRC: an independent expected value checks the external contract.

Why the table builder asks for a budget

A compiler that executes user code needs a way to stop runaway evaluation. Zig’s default evaluation branch quota is 1000 backwards branches. Loops and recursive evaluation can consume this budget. @setEvalBranchQuota raises it for the relevant evaluation; requesting a smaller limit does not lower an already larger quota.

Our table builder runs eight inner loop iterations and one outer continuation for each entry. Counting those loop back edges gives 9 × 256 = 2304. Calling the builder costs one more branch, so this initializer needs 2305 in total: Zig 0.17.1 fails at quota 2304 and passes at 2305. At the default quota, 111 entries pass and 112 fail. The shown function requests 4096. The experiment counts the two loops’ edges; its default-budget pass/fail boundary agrees with the compiler.

0 / 4096 backwards branches · fixed scale
020484096
table[1] = not built
Little-endian bytes: not built

Ready. Building all 256 entries requires 2304 loop back edges.

CRC-32 = 0xcbf43926

Loop-edge model of the shown two while loops: 8 inner + 1 outer per entry. Calling this builder also costs one branch: the shown initializer needs 2305 in total. Runtime CRC uses the full table independently of the quota experiment.

Build the CRC table under a branch budget, inspect a word and its bytes, then compute a payload CRC. The bar uses one fixed linear scale from zero to 4096 branches.

Increase the quota only after understanding the work. A missing loop update, explosive recursion or repeated table construction might be the actual problem. A branch count is a guardrail, not a clock: a single iteration can manipulate a large value, and compiler allocation and dependency work also take time. Measure build time and memory when compile-time computation becomes a significant part of your application.

Returning the array by value is important. The builder owns a local array while it runs, assigns every element and returns the completed value. The file-level constant receives that value. It does not contain a pointer into a temporary compiler frame, and the executable does not need a startup function that fills the array before the first message arrives.

Only use a lookup table when the tradeoff suits the target. A tiny microcontroller might prefer a bitwise CRC to save a kilobyte of read-only data. A throughput-oriented implementation might use several tables or dedicated hardware with the correct polynomial. The x86 crc32 instruction computes CRC-32C, whose polynomial differs from IEEE CRC-32; the instruction’s name alone does not make it a replacement for this function.

A CRC detects many accidental errors but provides no authentication. Anyone able to alter a message can compute the CRC of the altered payload. If the protocol needs to establish who sent a reading, add a suitable authentication design rather than assigning a security property to this table.

A compile-time calculation can leave behind only its result. The build pays to construct the table; runtime pays for the lookup algorithm and the data it reads.

Level 06/08Runtime

Reject a bad format before running

The packet’s diagnostic line has two kinds of input. Its format string is fixed in the source, while its identifier and kind may come from a decoded message. A formatter can inspect the first input and the types of the others before any concrete message exists. This is the same division we used for the codec: known structure chooses runtime operations.

Zig’s formatting APIs take a compile-time format string. A call such as std.debug.print("id={d}", .{received.id}) exposes both the string and the tuple’s field types to analysis. The parser can reject a malformed placeholder, a missing argument or a specifier incompatible with an argument type. Formatting the actual integer and writing its digits still happen when the call runs.

The little checker below isolates that idea. It accepts sequential {d}, {x} and {s}, plus doubled braces for literal brace characters. Its numeric types are u8 and u16; its text type is []const u8. It intentionally leaves widths, positional arguments and user-defined formatters to the standard library.

2 arguments checked. Format accepted.

Argument 1: u16 accepts {d}.
Argument 2: u8 accepts {x}.

Runtime output after the type check

id=4660 kind=7

Sequential {d}, {x}, {s}, {{ and }} only; no widths, positional arguments or custom formatters. The browser checks this declared subset, not the complete std.fmt grammar.

Edit a real format string and change the argument types. An accepted format produces a preview; a rejected one identifies the incompatible argument or malformed brace.

The parser walks left to right. An opening brace begins a placeholder unless the next character is another opening brace. A placeholder must have exactly one supported specifier followed by a closing brace. The checker consumes one argument type for each placeholder and verifies that none remain unused. It never needs the integer’s actual value.

Notice how an escaped sequence behaves. In {{id={d}}}, the first pair produces a literal opening brace, the middle placeholder consumes one integer, and the last pair produces a literal closing brace. Escape handling must come before placeholder recognition. Treating every brace as an argument delimiter would reject a valid literal or count the wrong number of arguments.

A small comptime format checker · full std.fmt supports more syntax
pub fn checkFormat(comptime format: []const u8, comptime Types: []const type) void {
    comptime {
        var i: usize = 0;
        var arg: usize = 0;
        while (i < format.len) : (i += 1) {
            const c = format[i];
            if ((c == '{' or c == '}') and i + 1 < format.len and format[i + 1] == c) {
                i += 1;
            } else if (c == '{') {
                if (i + 2 >= format.len or format[i + 2] != '}')
                    @compileError("expected {d}, {x} or {s}");
                const spec = format[i + 1];
                if (spec != 'd' and spec != 'x' and spec != 's')
                    @compileError("unsupported format specifier");
                if (arg >= Types.len) @compileError("missing argument");
                const T = Types[arg];
                if (spec == 's') {
                    if (T != []const u8) @compileError("{s} expects []const u8");
                } else {
                    if (T != u8 and T != u16) @compileError("{d}/{x} expects u8 or u16");
                }
                arg += 1;
                i += 2;
            } else if (c == '}') {
                @compileError("unmatched closing brace");
            }
        }
        if (arg != Types.len) @compileError("unused argument");
    }
}

This checker returns void. Its useful product is a proof that the call obeys a contract, or a compile error if it does not. The small program calls it with explicit argument types, then uses the standard formatter, which performs its own checking. A production wrapper would derive types from its argument tuple so there is no second list to keep synchronized.

A diagnostic should explain the caller’s mistake at the level of the API. “Unsupported field temperature: expected an unsigned integer” is more useful than an internal union-access error. @compileError lets a generic library move that message toward the boundary where the contract is violated. It also participates in normal analysis: an error in a specialization that is never needed may never be reached.

Compile-time format checking does not make all logging work disappear. An unknown integer still needs conversion to decimal or hexadecimal, and a runtime output destination can fail or block. The known format removes repeated parsing and moves type disagreement to compilation. It says nothing by itself about the cost or scheduling behavior of the writer.

That separation is especially useful after Zig’s I/O API changes. This example uses std.debug.print for a small diagnostic rather than relying on old std.io.getStdOut().writer() examples. A real application should pick an appropriate current Reader/Writer and I/O interface for its target. The comptime format contract is a layer above the decision about where bytes are ultimately written.

Check yourselfThe format is known, but the u16 identifier arrives over a socket. What can be checked before the identifier arrives?

Compile-time code can produce a checked plan rather than a visible value. A format string is a small program whose structure is known before its data.

Level 07/08System

Inside semantic analysis

There is no separate general-purpose Zig interpreter launched beside the compiler for our library. Compile-time evaluation belongs to semantic analysis. The compiler’s internal representations let it follow known control flow, model values and memory, and turn the remaining operations into a typed runtime program.

First the tokenizer recognizes tokens and the parser produces an abstract syntax tree. AstGen lowers that tree into Zig Intermediate Representation: a compact, largely untyped representation produced from the syntax tree before semantic analysis resolves concrete types and values.. Sema then resolves names and types, analyzes needed functions and evaluates operations that must produce known values. Its runtime output is Analyzed Intermediate Representation: typed instructions describing the runtime computation that remains after semantic analysis.. Code generation lowers that computation through a selected backend, and the linker combines the resulting objects and data.

Source textTokenizer + parserASTAstGenZIR · untyped instructions
Sema · semantic analysis

Resolve types and names. Evaluate comptime paths. Analyze each needed specialization.

Packet(Header)makeTable()
AIR · typed runtime instructionsCode generationLLVM or native backendObject files + linkerExecutable: .text + data

Compile-time values feed analysis and constants. Runtime instructions continue into AIR and code generation.

Semantic analysis is the junction between compiler-side execution and typed runtime instructions. Both backend paths consume the results of the same language analysis.

Trace one value through the compiler

Take the square function from our introductory example and use its result as a runtime scale factor. The source has two multiplications. One takes the known argument four; the other takes the unknown argument n. The comptime block requires the first to finish during analysis. Only the second multiplication needs target instructions.

Source · trace.zig
fn square(x: u32) u32 {
    return x * x;
}

export fn scale(n: u32) u32 {
    const factor = comptime square(4);
    return n * factor;
}
Real ZIR indices and tags · selected instructions
%3: param
%5: mul
%13: param
%15: block_comptime
%16: decl_val
%18: call
%19: int 4
%25: mul
%28: ret_node
Sema · follow the known call

Bind square’s x to the known u32 value 4. Evaluate instruction %5: 4 × 4 = 16. The comptime block returns that value as factor.

Add @compileLog(factor) after its declaration to ask Sema what it knows. The diagnostic probe prints:

Real compile-log output · probe intentionally exits with an error
@as(u32, 16)
AIR meaning · schematic typed computation, not a dump
argument n: u32
constant factor: u32 = 16
product: u32 = multiply(n, 16)
return product
Real unoptimized LLVM IR · lowered after Sema and AIR
define internal i32 @trace.scale(i32 %0) unnamed_addr #0 !dbg !1 {
Entry:
  call void @llvm.dbg.value(metadata i32 %0, metadata !3, metadata !DIExpression()), !dbg !2
  call void @llvm.dbg.value(metadata i32 16, metadata !5, metadata !DIExpression()), !dbg !4
  %1 = mul nuw i32 %0, 16, !dbg !6
  ret i32 %1, !dbg !7
}
A real ZIR tag capture and Sema diagnostic follow square(4) to 16. The AIR panel shows the typed computation schematically; the captured LLVM IR confirms that only n × 16 remains at runtime.

The ZIR numbers are storage indices, not an execution timeline. Instruction %3 represents square’s parameter, %5 its multiplication, and %15 the forced comptime block in scale. That block contains the declaration reference, call and argument literal. Sema follows this structured information, binds x to four and computes sixteen. Instruction %25 describes the multiplication that uses runtime parameter %13.

The capture tool zir-tags.zig parses trace.zig with the shipped std.zig.Ast, calls std.zig.AstGen.generate, then prints instruction indices and tags. The figure selects the relevant instructions. The official compiler binary rejects zig ast-check -t trace.zig with “-t option only available in builds of zig with debug extensions.” It accepts --verbose-air but emits no AIR text here, so the AIR panel labels its typed computation as schematic. The LLVM panel is actual compiler output, including its debug-metadata references.

To probe Sema, insert @compileLog(factor) immediately after the declaration. Compilation intentionally stops with a compile-log diagnostic reporting the known u32 value sixteen. Remove the probe to build the runtime function. Its ordinary multiplication still obeys Zig’s overflow rules: Debug builds check it, while the captured ReleaseFast lowering assumes unsigned overflow does not occur. Inputs through 268435455 keep this example’s product within u32.

Commands used for the ZIR inventory and LLVM capture · Zig 0.17.1, native x86-64 Linux
zig run zir-tags.zig
zig build-obj trace.zig -O ReleaseFast -fllvm --verbose-air \
  --verbose-llvm-ir=trace.ll -femit-bin=trace.o

When Sema analyzes Packet(Header), the argument is a known type. The field metadata is therefore known, the validation loop can execute, and the return value is a new struct type. When it later analyzes Wire.encode, each expanded field access has a specific integer type. The packet value itself can remain unknown, so its loads and byte writes become runtime instructions.

When it analyzes crc_table, the initializer must produce a constant. The local variables and loops in makeTable are evaluated within compiler memory. When it analyzes a runtime call to crc32, the input bytes remain unknown. The loop over incoming data becomes runtime control flow while references to the completed table become references to constant data.

The distinction is sometimes called partial evaluation: execute a program with the inputs you already have and leave a residual program for the inputs you do not. Here the known input is a schema and the residual program is an encoder. Zig integrates that split with type checking, so evaluation can also determine the residual program’s types. This is why a type-valued parameter needs stronger guarantees than a number the backend might later discover is constant.

Lazy analysis changes where errors appear

Zig does not eagerly type-check every function body in every imported file. Declarations and generic specializations are analyzed as they are needed. A function that is never referenced can contain a semantic error that the current build does not report. A referenced generic function can be valid for one argument type and invalid for another. The file still has to parse; lazy semantic analysis is not permission to include broken syntax.

This is useful for platform-specific branches and broad generic libraries, but it changes testing strategy. Merely importing a module does not establish that every advertised operation works. Instantiate the types you support and call their methods in tests. For this library, test each supported integer width, length failures and distinct schemas, rather than relying only on successful construction of Packet(Header).

Comptime memory is still memory with rules

The evaluator needs to represent arrays, structs, slices and pointers, not just arithmetic constants. A compile-time pointer denotes storage the compiler can reason about, including an offset and relevant type information. It is not an arbitrary usable address in the target process. Host and target may even have different pointer widths and byte orders.

Local mutation is allowed when the target of that mutation belongs to the compile-time evaluation. A runtime-dependent branch cannot decide how to update compiler-side state: compilation would then depend on an input that does not exist yet. Likewise, returning a pointer to expired temporary storage is a lifetime problem, even when no target instructions have run. Known execution exposes invalid operations as compilation errors.

Compiler-owned storagemakeTable’s local array[256]u32

Mutable while evaluation runs. Every element is assigned before the value is returned.

Returned valuecrc_table256 × 4 = 1024 bytes

The array value becomes a constant. No pointer to a temporary compiler stack frame escapes.

Runtime addressRead-only table datacrc_table[index]

A target address is assigned when data is emitted and linked. Compiler memory addresses are never copied into the executable.

The table crosses the boundary as a completed array value. The compiler’s temporary storage and the executable’s linked read-only address belong to different execution environments.

A normal general-purpose allocator depends on runtime facilities and cannot simply allocate target heap memory while the compiler evaluates a constant. Fixed arrays and comptime-friendly data structures are the natural tools for bounded calculations. The compiler itself allocates memory to represent those values; “no runtime allocation” does not imply “no compiler memory cost.”

Ordinary filesystem and network operations also do not become available just because a function is marked comptime. @embedFile is an explicit compiler facility for bringing a build input into a constant. It is a different mechanism from opening an arbitrary file through runtime I/O. Put broader generation work in build steps with explicit inputs and outputs.

Cross-compilation makes the separation particularly concrete. If a host computer builds firmware for another architecture, compile-time arithmetic describes the target program’s values and type properties. @sizeOf(usize) follows the target’s pointer-sized integer, not the host process that happens to run the compiler. The evaluator must preserve target semantics rather than treating every value as a native host integer. Our explicit u16/u8 wire contract avoids a dependency on either machine’s pointer size.

Backends and rebuilds

The native x86 backend became the default for supported x86-64 Debug builds in the 0.15 line; the 0.16 notes describe faster compilation with weaker optimized code quality than LLVM. LLVM remains an important path for optimized builds and other targets. Backend defaults depend on target and build mode, so record both when comparing output.

For the 0.17 line, incremental compilation is available to most x86_64-linux projects through zig build -fincremental --watch. A changed schema can invalidate its generated codec; a changed table algorithm can invalidate its constant. Incremental compilation reuses unaffected work rather than making dependencies disappear.

Sema knows which facts are available now. It evaluates the known part and describes the unknown part as runtime instructions.

Level 08/08Machine

What reaches the binary

At the machine boundary, the question is simple: what must the target still do? The receiver can get an identifier it has never seen, so it needs instructions that encode and decode new values. It does not need to discover that the identifier has type u16. It needs the CRC lookup words if it processes unknown payloads with the table algorithm. It does not need to reconstruct those words at startup.

For our three-byte packet on little-endian x86-64, the core encoder can be a two-byte store followed by a one-byte store. The decoder can use a zero-extending two-byte load and a one-byte load after the length check. These instructions naturally implement the selected wire order on this target. A big-endian target must produce the same wire bytes through a different instruction sequence.

Exported capture wrappers · assembly.zig, definitions from protocol.zig
const protocol = @import("protocol.zig");
const Header = struct { id: u16, kind: u8 };
const Wire = protocol.Packet(Header);

export fn encode_header(out: *[3]u8, id: u16, kind: u8) void {
    out.* = Wire.encode(.{ .id = id, .kind = kind });
}

export fn decode_header(bytes: [*]const u8, len: usize, out_id: *u16, out_kind: *u8) bool {
    const h = Wire.decode(bytes[0..len]) catch return false;
    out_id.* = h.id;
    out_kind.* = h.kind;
    return true;
}

export fn crc_payload(bytes: [*]const u8, len: usize) u32 {
    return protocol.crc32(bytes[0..len]);
}
Real Zig 0.17.1 output · x86_64-linux-gnu, ReleaseFast, LLVM · encode and decode excerpts
	.p2align	4
	.type	.Lassembly.encode_header,@function
.Lassembly.encode_header:
	.cfi_startproc
	mov	word ptr [rdi], si
	mov	byte ptr [rdi + 2], dl
	ret
.Lfunc_end2:
	.size	.Lassembly.encode_header, .Lfunc_end2-.Lassembly.encode_header
	.cfi_endproc

	.p2align	4
	.type	.Lassembly.decode_header,@function
.Lassembly.decode_header:
	.cfi_startproc
	cmp	rsi, 3
	jne	.LBB1_1
	movzx	eax, word ptr [rdi]
	movzx	esi, byte ptr [rdi + 2]
	mov	word ptr [rdx], ax
	mov	byte ptr [rcx], sil
	mov	al, 1
	ret
.LBB1_1:
	xor	eax, eax
	ret
.Lfunc_end1:
	.size	.Lassembly.decode_header, .Lfunc_end1-.Lassembly.decode_header
	.cfi_endproc
Real CRC loop excerpt · one byte update from the unrolled loop
.LBB0_6:
	movzx	r9d, byte ptr [rdi + rax]
	xor	r9b, cl
	shr	ecx, 8
	movzx	r9d, r9b
	xor	ecx, dword ptr [4*r9 + .L__anon_2762]

These are captured instructions from Zig 0.17.1 with -target x86_64-linux-gnu -O ReleaseFast -fllvm -fomit-frame-pointer -fstrip. Exported wrappers keep their inputs unknown. The encoder receives its destination in rdi, identifier in si and kind in dl. The decoder receives bytes in rdi, length in rsi, and output pointers in rdx and rcx; al returns success. Its length check and failure branch are visible alongside the two field loads.

The listings preserve the capture’s local labels and CFI directives. The CRC excerpt shows one update from a loop unrolled across several input bytes; its final XOR loads a word from the table symbol .L__anon_2762. The exact output depends on optimization, inlining, register allocation and backend choice. Debug mode can retain extra checks and local bookkeeping. The language promises the behavior, not a fixed number of instructions.

Those distinctions matter when checking a claim about “zero overhead.” The codec has no runtime field enumeration, dynamic dispatch or string lookup. It still has input-dependent data movement, length validation on decode and whatever calling-convention costs remain after optimization. Safety checks and useful error handling are part of the chosen operation, not evidence that generic code failed to specialize.

Retained when referenced at runtime.text

encode / decode / CRC instructions

.rodata · table prefix on little-endian x86-64
00 00 00 0096 30 07 772c 61 0e eeba 51 09 9919 c4 6d 078f f4 6a 7035 a5 63 e9a3 95 64 9e
8 words shown · 32 of 1024 bytes
No runtime execution needed

Field enumeration

Type validation

The table-building loops

The format parser’s type checks

Debug information can still carry names and types.
Runtime references can retain specialized instructions and the CRC table. The shown .rodata prefix contains real table bytes; section names and placement depend on the object format and linker.

The captured ELF object’s .rodata section has size 0x400: exactly 1024 bytes. Its flags include allocation but not writing. Here is the entire emitted table, with byte offsets at left and four four-byte groups per row. The prefix 00000000 96300777 2c610eee ba510999 is the first four table words in little-endian memory order.

Captured .rodata · 1024 bytes · offsets and raw byte groups
0000  00000000 96300777 2c610eee ba510999
0010  19c46d07 8ff46a70 35a563e9 a395649e
0020  3288db0e a4b8dc79 1ee9d5e0 88d9d297
0030  2b4cb609 bd7cb17e 072db8e7 911dbf90
0040  6410b71d f220b06a 4871b9f3 de41be84
0050  7dd4da1a ebe4dd6d 51b5d4f4 c785d383
0060  56986c13 c0a86b64 7af962fd ecc9658a
0070  4f5c0114 d96c0663 633d0ffa f50d088d
0080  c8206e3b 5e10694c e44160d5 727167a2
0090  d1e4033c 47d4044b fd850dd2 6bb50aa5
00a0  faa8b535 6c98b242 d6c9bbdb 40f9bcac
00b0  e36cd832 755cdf45 cf0dd6dc 593dd1ab
00c0  ac30d926 3a00de51 8051d7c8 1661d0bf
00d0  b5f4b421 23c4b356 9995bacf 0fa5bdb8
00e0  9eb80228 0888055f b2d90cc6 24e90bb1
00f0  877c6f2f 114c6858 ab1d61c1 3d2d66b6
0100  9041dc76 0671db01 bc20d298 2a10d5ef
0110  8985b171 1fb5b606 a5e4bf9f 33d4b8e8
0120  a2c90778 34f9000f 8ea80996 18980ee1
0130  bb0d6a7f 2d3d6d08 976c6491 015c63e6
0140  f4516b6b 62616c1c d8306585 4e0062f2
0150  ed95066c 7ba5011b c1f40882 57c40ff5
0160  c6d9b065 50e9b712 eab8be8b 7c88b9fc
0170  df1ddd62 492dda15 f37cd38c 654cd4fb
0180  5861b24d ce51b53a 7400bca3 e230bbd4
0190  41a5df4a d795d83d 6dc4d1a4 fbf4d6d3
01a0  6ae96943 fcd96e34 468867ad d0b860da
01b0  732d0444 e51d0333 5f4c0aaa c97c0ddd
01c0  3c710550 aa410227 10100bbe 86200cc9
01d0  25b56857 b3856f20 09d466b9 9fe461ce
01e0  0ef9de5e 98c9d929 2298d0b0 b4a8d7c7
01f0  173db359 810db42e 3b5cbdb7 ad6cbac0
0200  2083b8ed b6b3bf9a 0ce2b603 9ad2b174
0210  3947d5ea af77d29d 1526db04 8316dc73
0220  120b63e3 843b6494 3e6a6d0d a85a6a7a
0230  0bcf0ee4 9dff0993 27ae000a b19e077d
0240  44930ff0 d2a30887 68f2011e fec20669
0250  5d5762f7 cb676580 71366c19 e7066b6e
0260  761bd4fe e02bd389 5a7ada10 cc4add67
0270  6fdfb9f9 f9efbe8e 43beb717 d58eb060
0280  e8a3d6d6 7e93d1a1 c4c2d838 52f2df4f
0290  f167bbd1 6757bca6 dd06b53f 4b36b248
02a0  da2b0dd8 4c1b0aaf f64a0336 607a0441
02b0  c3ef60df 55df67a8 ef8e6e31 79be6946
02c0  8cb361cb 1a8366bc a0d26f25 36e26852
02d0  95770ccc 03470bbb b9160222 2f260555
02e0  be3bbac5 280bbdb2 925ab42b 046ab35c
02f0  a7ffd7c2 31cfd0b5 8b9ed92c 1daede5b
0300  b0c2649b 26f263ec 9ca36a75 0a936d02
0310  a906099c 3f360eeb 85670772 13570005
0320  824abf95 147ab8e2 ae2bb17b 381bb60c
0330  9b8ed292 0dbed5e5 b7efdc7c 21dfdb0b
0340  d4d2d386 42e2d4f1 f8b3dd68 6e83da1f
0350  cd16be81 5b26b9f6 e177b06f 7747b718
0360  e65a0888 706a0fff ca3b0666 5c0b0111
0370  ff9e658f 69ae62f8 d3ff6b61 45cf6c16
0380  78e20aa0 eed20dd7 5483044e c2b30339
0390  612667a7 f71660d0 4d476949 db776e3e
03a0  4a6ad1ae dc5ad6d9 660bdf40 f03bd837
03b0  53aebca9 c59ebbde 7fcfb247 e9ffb530
03c0  1cf2bdbd 8ac2baca 3093b353 a6a3b424
03d0  0536d0ba 9306d7cd 2957de54 bf67d923
03e0  2e7a66b3 b84a61c4 021b685d 942b6f2a
03f0  37be0bb4 a18e0cc3 1bdf055a 8def022d

Look closely at the table’s second word. Its numeric value is 0x77073096, but its four bytes in little-endian storage are 96 30 07 77. This is the same distinction we made for packet fields. A value’s printed hexadecimal notation and its byte representation in memory are different views. The table’s storage byte order follows the target; the protocol’s byte order follows the protocol contract.

During a runtime CRC update, the CPU calculates an index, loads one 32-bit word and combines it with the shifted register. That table fits in 1024 bytes of data. Cache behavior still matters, and the next register depends on the previous one, so the loop has a dependency chain. Comptime removes initialization; it does not remove these runtime loads or their dependencies.

Nor is every declared constant guaranteed to survive in a binary. If the program only computes the CRC of a known string during compilation, the backend might retain only the final checksum. If no runtime code references a codec, it may not be emitted. Debug information can still describe names and types even when the runtime program contains no reflection machinery for them.

Section placement is a toolchain decision too. An ELF build commonly places constant table data in a read-only section such as .rodata, while other object formats use different names. The linker may merge constants, discard unreferenced material or place data according to a linker script. The useful invariant is that the runtime algorithm can access the required constant words; a particular section label is not part of the Zig language contract.

The specialization bill

ChoiceCompilation paysRuntime pays
One schema-specific codecAnalyze and generate operations for that schema.Direct loads, shifts, stores and length validation.
Many distinct schemasMore specializations and potentially more machine code.Specific operations for each schema; larger code may affect instruction caches.
Runtime schema interpreterCompile a shared interpreter and schema representation.Walk metadata and branch on field categories for each message.
Comptime CRC tableEvaluate the recurrence and materialize constant data.Use table lookups; no table initialization on startup.

C++ template instantiation and Rust monomorphization make a related trade: concrete types can produce concrete machine code. Zig’s distinctive part is how directly ordinary functions and first-class compile-time types express that construction. It does not escape the code-size consequences of specialization. Shared non-generic byte-processing routines can keep the number of generated combinations under control.

Before tuning the compiler budget, inspect what you are generating. A boolean parameter with two values can double specializations; several independent policies can multiply them further. Keep a policy at runtime when its branch is cheap and variation does not justify separate code. Keep it at comptime when it changes types, eliminates substantial work or makes invalid combinations unrepresentable.

Compile failures deserve tests as well. Try a signed field, a floating-point field and a format string with a missing argument in separate negative fixtures. Check that compilation fails for the intended reason, rather than because the fixture itself is malformed. Keep positive tests alongside them so a checker that rejects every input cannot pass unnoticed. For a generic library, the supported set of instantiations is part of its public behavior.

Make the boundary testable

The supplied protocol.zig includes the constructor, CRC builder, checker, small program and tests. basics.zig contains the introductory examples. With Zig 0.17.1 available, run the commands below from their directory. The tests verify the exact three wire bytes, a round trip, truncated and trailing input, standard CRC values and repeated type identity. The browser model additionally checks every table entry and the other packet widths.

Reproduce with Zig 0.17.1 · local symbol numbers may change between builds
zig test protocol.zig
zig test basics.zig
zig run protocol.zig
zig build-obj assembly.zig -target x86_64-linux-gnu -O ReleaseFast \
  -fllvm -fomit-frame-pointer -fstrip -femit-asm=release.s -femit-bin=release.o
objdump -s -j .rodata release.o
Executable checks supplied with the protocol
test "wire format, round trip and strict length" {
    const bytes = Wire.encode(.{ .id = 0x1234, .kind = 7 });
    try std.testing.expectEqualSlices(u8, &.{ 0x34, 0x12, 0x07 }, &bytes);
    const value = try Wire.decode(&bytes);
    try std.testing.expectEqual(@as(u16, 0x1234), value.id);
    try std.testing.expectEqual(@as(u8, 7), value.kind);
    try std.testing.expectError(error.BadLength, Wire.decode(&.{ 0x34, 0x12 }));
    try std.testing.expectError(error.BadLength, Wire.decode(&.{ 0x34, 0x12, 7, 0 }));
}

test "CRC-32 standard check value and table entries" {
    try std.testing.expectEqual(@as(u32, 0xcbf43926), crc32("123456789"));
    try std.testing.expectEqual(@as(u32, 0), crc32(""));
    try std.testing.expectEqual(@as(u32, 0x77073096), crc_table[1]);
    try std.testing.expectEqual(@as(u32, 0x2d02ef8d), crc_table[255]);
}

test "type identity and format acceptance" {
    try std.testing.expect(Packet(Header) == Packet(Header));
    checkFormat("{{id={d}, kind={x}}}", &.{ u16, u8 });
    checkFormat("{s}", &.{[]const u8});
}

For compiler-output comparisons, retain the toolchain version, target triple, optimization mode and backend flags beside the assembly. Test the wire contract independently of that output. A better optimizer is allowed to change every instruction while preserving the same three bytes and the same handling of invalid input.

The sensor message has now crossed the whole boundary. A known struct type selected a codec. Compiler-side loops built a CRC table. A known format string selected compatible formatting operations. The executable keeps the concrete work that depends on future messages. That is the practical power of comptime: the schema can be a program, and the running program can contain only the consequences it needs.

Check yourselfA runtime CRC function indexes crc_table using incoming bytes. Which work has compilation eliminated?

Choose the boundary deliberately: compute stable structure while building, then leave a small, explicit program to handle changing data.

End of Zig comptime · 8 levels, Idea to Machine

Where to next

Practical notes

  1. Note3 min read

    Cross-compile C and Zig with Zig 0.17.1

    Select the target explicitly with zig cc -target or a build script using standardTargetOptions. Verify the file format separately from whether the artifact runs on the target.

Browse all 34 divesAll topics