Tutorial · Chapter 8 of 23

Plan RAM and reuse scratch storage

Give one sector record a byte layout and decide when its encoded bytes can be reused.

Jump to a section

Name the space before allocating from it

A C64 address can belong to the loaded program, system workspace, I/O, or RAM reserved for your data. Here, reserve 16 visible bytes at $9000 for staging. The region is a compile-time ownership declaration. The arena manages allocations within that region at runtime. Its optional result handles a request that does not fit.

A sector record has two bytes of visits and one byte of flags. The encoder uses @sizeOf and @offsetOf to tie the staging layout to the type. It writes a word low byte first. An independent data format can use explicit offsets when the encoding must remain stable across source changes.

Encode and reuse one small record buffer

survey-buffer.zp64
const c64 = @import("c64");

const Sector = struct { visits: u16, flags: u8 };

memory {
    region staging_ram: c64 at 0x9000 size 16;
    arena scratch in staging_ram;
}

fn show(sector: Sector) void {
    if (scratch.allocBytes(@sizeOf(Sector))) |bytes| {
        const word = sector.visits;
        const low = word & 0x00ff;
        const high = word >> 8;
        bytes[0] = low;
        bytes[1] = high;
        bytes[@offsetOf(Sector, "flags")] = sector.flags;
        c64.console.print("RECORD {x} {x} {x}\n", .{ bytes[0], bytes[1], bytes[2] });
        scratch.reset();
    } else {
        c64.console.print("SCRATCH FULL\n", .{});
    }
}

export fn main() void {
    c64.console.clear();
    show(Sector{ .visits = 0x0102, .flags = 4 });
    show(Sector{ .visits = 0x0103, .flags = 4 });
}

Open the complete source

Expect RECORD 02 01 04, then RECORD 03 01 04. The first two bytes change with the visit count. The flags stay the same. Each call finishes reading its buffer before resetting the arena. The next allocation can start at the same address because no old pointer remains in use.

Choose a lifetime that matches the work

An arena suits scratch data that expires together. If independently managed objects must remain live while others are freed, use a fixed-block pool. A far arena applies the reset model to REU addresses, where explicit copies replace C64 pointer access. The arena guide compares the three allocation results and their release rules.

Try shrinking the staging reservation to two bytes. The record still needs three. Both calls should print SCRATCH FULL. Restore the reservation before moving on to the larger REU table.