Guide · Chapter 2 of 14

Lay out records and pass them between functions

Choose a representation, inspect its byte layout, and decide which code owns the data.

Jump to a section

Calculate a record's offsets

Consider a header you want to copy to a buffer or inspect in the monitor. The compiler lays out fields in declaration order and aligns them to one byte. A two-byte field can start at an odd offset. This is the ZeroPage target layout. Use its layout queries when you write code that depends on these offsets.

Header definitions from the layout fixture
const Cell = enum(u8) { empty, x, o };
const Header = struct { tag: u8, word: u16, cell: Cell, ok: bool };
const Nested = struct { a: u8, header: Header, tail: u16 };
const Board = struct { cells: [3]Cell, checksum: u16 };
const Maybe = struct { maybe_byte: ?u8, maybe_word: ?u16, maybe_ptr: ?*Header };
const Event = union(enum) { none, key: u8, word: u16, ptr: *Header };
Field in HeaderOffsetSize
tag01
word12
cell31
ok41

With tag = 0x07, word = 0x1234, cell = .x, and ok = true, the bytes are 07 34 12 01 01. @offsetOf(Nested, "header.word") gives 2 because the nested header starts at offset 1. A [2]Header occupies 10 bytes and the second record begins at offset 5. The layout fixture checks these sizes and offsets independently of screen I/O.

The runnable layout example prints the header size and a nested field offset.

Full layout fixture · Value representation

Choose a snapshot or an in-place update

Imagine saving a snapshot before playing a move. A by-value copy preserves the old board and lets you return a changed record. For a single live game, a pointer makes changes directly to the record the caller owns. Use the value form when an independent snapshot is part of the design. Use the pointer form when the caller wants to observe the mutation.

Return a changed value

From the struct value demo
fn applyMove(game: Game, index: u8, mark: Cell) Game {
    game.board.cells[index] = mark;
    game.history[game.move_count] = index;
    game.move_count = game.move_count + 1;
    return game;
}

Change the caller's record

From the struct pointer fixture
fn setCell(board: *Board, index: u8, cell: Cell) void {
    board.cells[index] = cell;
}

Both forms use the same field and index syntax. A pointer argument here has two bytes. A record argument carries all the flattened fields. Passing a large record by value can increase storage and copy work. Check the assembled output when the difference matters. Bound the runtime index before calling either helper.

Snapshot and value-return example · Nested fields and in-place updates · Game state case study

Distinguish a pointer, an optional pointer, and a pointer field

*Board refers to one record. Field access through that pointer uses board.score. For scalar pointers, ptr.* reads or writes the value. [*]u8 is a many-item pointer and ptr[i] indexes it. Supply a valid address and an index in range. A nullable pointer ?*Board occupies two bytes, with address zero representing null.

Optional pointer and payload capture
fn firstCell(board: ?*Board) u8 {
    if (board) |ptr| {
        return ptr.cells[0];
    } else {
        return 0;
    }
}

The captured *Board can still refer to mutable data. The optional changes whether the address is available. A pointer field embedded in a copied record keeps its two address bytes, and both copies can refer to the same target. A record copy gives you an independent set of fields while pointed-to data can remain shared.

Use @ptrFromInt for supported scalar addresses such as hardware registers. Form a typed struct pointer using &record or the address of a supported nested field. Integer-to-struct casts, volatile struct pointers, and pointer-to-pointer types are outside this subset.

Optional pointer branches and updates · Two-byte pointer fields across copies and calls

Copy a record that contains an address

Predict what changes when advance copies a Link. The tag is copied by value. Changing the callee's tag changes the returned record, while the original keeps tag 1. The pointer's two address bytes are also copied by value. Both initially address the same byte at $c150, so incrementing through the copied pointer is visible through the original.

record-alias.zp64
const c64 = @import("c64");

const Link = struct { tag: u8, target: *u8 };

fn advance(link: Link) Link {
    link.tag += 1;
    const target: *u8 = link.target;
    target.* = target.* + 1;
    return link;
}

export fn main() void {
    c64.console.clear();

    const first_ptr: *u8 = @ptrFromInt(0xc150);
    const second_ptr: *u8 = @ptrFromInt(0xc1f0);
    first_ptr.* = 5;
    second_ptr.* = 9;
    const original = Link{ .tag = 1, .target = first_ptr };
    var result = advance(original);
    c64.console.print("TAGS {x} {x}\n", .{ original.tag, result.tag });
    const old_target: *u8 = original.target;
    const shared_target: *u8 = result.target;
    c64.console.print("SHARED {x} {x}\n", .{ old_target.*, shared_target.* });

    result.target = second_ptr;
    const new_target: *u8 = result.target;
    new_target.* = new_target.* + 1;
    c64.console.print("SPLIT {x} {x}\n", .{ old_target.*, new_target.* });
    if (original.tag == 1 and result.tag == 2 and first_ptr.* == 6 and second_ptr.* == 10) {
        c64.vic.border = 5;
    } else {
        c64.vic.border = 2;
    }
}

Open the complete source

Expect TAGS 01 02, SHARED 06 06, then SPLIT 06 0A. Assigning a new address to result.target changes that field only. The next write goes to $c1f0, where the value becomes $0a. The preview accepts an explicit load followed by a store through a single-item pointer, as in target.* = target.* + 1.

If a snapshot needs independent pointed-to bytes, copy the data into storage you own and set the snapshot's pointer to that storage. A by-value record assignment copies the addresses. Host assertions for copied pointer bytes · Trace the aggregate return storage

Pass a base address and an index

A many-item pointer carries a base address, with no array length alongside it. The indexing demo takes the address of the first scalar element, passes through the supported integer conversion, and constructs a many-item pointer. Mutating element 1 through that pointer changes values[1]. Use a fixed array and its .len while you own the table. If you pass a pointer to another function, pass or otherwise establish the available length as part of the function's contract.

From the indexed pointer demo
var values = [_]u8{ 1, 2, 3, 4 };
const value_ptr: [*]u8 = @ptrFromInt(@intFromPtr(&values[0]));
value_ptr[1] = 0x20;
value_ptr[1] += 0x0a;
value_ptr[2] = value_ptr[1] + 1;

The demo also passes a many-item volatile pointer to a screen-writing helper. Use a literal target base for hardware and add an index through the pointer operand. Pointer arithmetic, comparison, and slice formation are outside the supported subset. A mutable scalar or a literal-index scalar array element can supply an address. For an indexed update whose index calculation has side effects, the compiler evaluates the index before loading a direct many-item pointer's value. It captures a struct pointer before evaluating an index into one of its array fields. Keep index calculations simple unless the order is part of what you intend to test.

Runnable local and volatile pointer example · Index evaluation and pending values · Supported pointer forms

Choose a representation for a missing value or a variant

A scalar optional uses a presence byte followed by its payload. The byte value zero and the absence of a byte are separate cases. A tagged union has a tag and a fixed payload area. Use an optional for a value that may be absent. Use a tagged union for a value whose payload depends on which event or state you received.

One payload that can be absent

Optional scalar · example excerpt
if (maybe_score) |score| {
    c64.console.print("SCORE {x16}
", .{score});
} else {
    c64.console.print("NO SCORE
", .{});
}

Payload selected by a tag

Tagged union · example excerpt
switch (event) {
    .key => |key| handleKey(key),
    .none => {},
}

The union payload becomes available inside the matching switch branch. Captures are read-only. Supported union payloads include scalar, enum, pointer, and payloadless alternatives. The far-record API uses a smaller field subset. Use plain fixed-layout fields when a record must also work in a typed REU view.

Absent and present scalar values · Tagged payload fixtures · Far-record field rules

Use widths to express intent

Widen a byte before arithmetic when the result needs to survive a carry out of bit 7. For example, a word made from byte 9 plus 0x0100 is 0x0109. An explicit type also helps at the boundary between a fixed address and a volatile pointer.

Widening and a target address from the cast demo
const word: u16 = @as(u16, values[3]) + @as(u16, 0x0100);
const screen: [*]volatile u8 = @ptrFromInt(0x04c0);

ZeroPage supports fitting literals, unsigned widening, and exact enum or pointer contexts with @as. Its casts cover the documented target subset. Use explicit data conversion when encoding bytes or moving between different record types. Read @offsetOf as a layout query. It gives a byte offset and does not create or validate an address.

Complete cast and MMIO demo · Accepted cast cases · Rejected out-of-range literal