Arenas, pools, and records

Choose a visible-RAM arena, a fixed-block pool, or an REU arena and work with structured data.

Choose storage by lifetime

DeclarationAllocation resultRelease
Near arena in C64 RAMOptional many-item byte pointerReset the entire arena
Fixed-block pool in C64 RAMOptional many-item byte pointer to one blockFree a block or reset the pool
Far arena in REU RAMOptional opaque far handleReset the entire arena

Handle allocation failure before use. Byte counts can use supported expressions. A zero-byte request fails. Arena reset reclaims the space and makes previous allocations stale. The compiler does not track all aliases held by application code.

Heap and REU reservations

Use a near arena for work done together

A near arena advances a cursor through its region. Use it for temporary work that can be discarded together. In this example, an allocation writes two bytes and reset lets the next allocation start again at $9000.

34_near_heap_arena.zp64
const c64 = @import("c64");

memory {
    region main_ram: c64 at 0x9000 size 0x0100;

    arena near_heap in main_ram;
}

export fn main() void {
    c64.console.clear();
    c64.console.print("NEAR HEAP ARENA\n", .{});

    const first = near_heap.allocBytes(8);
    if (first) |first_buf| {
        first_buf[0] = 0x48;
        first_buf[1] = 0x50;
        if (first_buf[0] == 0x48 and first_buf[1] == 0x50) {
            c64.console.print("ALLOC OK\n", .{});
        }
    }

    near_heap.reset();
    const again = near_heap.allocBytes(1);
    if (again) |again_buf| {
        if (@intFromPtr(again_buf) == 0x9000) {
            c64.console.print("RESET OK\n", .{});
            c64.vic.border = 5;
        }
    }
}

Open the complete source

Store a structured record in a byte allocation

allocBytes returns bytes. This example uses @sizeOf to request enough space for an Actor and @offsetOf to encode and decode its fields. Normal typed code works with the reconstructed record. Use explicit low and high bytes when encoding a word. A near allocation does not supply a general typed allocator or an integer-to-struct-pointer cast.

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

const Actor = struct {
    x: u8,
    hp: u8,
    facing: u8,
};

memory {
    region work_ram: c64 at 0x9000 size 0x0100;
    arena frame in work_ram;
}

fn storeActor(bytes: [*]u8, actor: Actor) void {
    bytes[@offsetOf(Actor, "x")] = actor.x;
    bytes[@offsetOf(Actor, "hp")] = actor.hp;
    bytes[@offsetOf(Actor, "facing")] = actor.facing;
}

fn loadActor(bytes: [*]u8) Actor {
    return Actor{
        .x = bytes[@offsetOf(Actor, "x")],
        .hp = bytes[@offsetOf(Actor, "hp")],
        .facing = bytes[@offsetOf(Actor, "facing")],
    };
}

export fn main() void {
    c64.console.clear();
    if (frame.allocBytes(@sizeOf(Actor))) |bytes| {
        storeActor(bytes, Actor{ .x = 12, .hp = 5, .facing = 1 });
        const actor = loadActor(bytes);
        c64.console.print("X {x} HP {x} FACE {x}\n", .{ actor.x, actor.hp, actor.facing });
    }
    frame.reset();
}

Open the complete source

Expect X 0C HP 05 FACE 01. For typed records that live in an REU, see the nested record example.

Reuse fixed-size blocks

A pool divides visible RAM into equal blocks. This one has four 16-byte blocks. An allocation consumes a whole block even when it requests fewer bytes. The demo frees the first block and checks that the next allocation gets it back. Pass only a live pointer from that pool to free. Keep using the pointer only while its block is owned by that allocation.

35_fixed_heap_blocks.zp64
const c64 = @import("c64");

memory {
    region sprites_ram: c64 at 0x9200 size 0x0040;

    pool sprites in sprites_ram block 16;
}

export fn main() void {
    c64.console.clear();
    c64.console.print("FIXED HEAP BLOCKS\n", .{});

    const first = sprites.allocBytes(8);
    const second = sprites.allocBytes(8);
    if (first) |first_buf| {
        first_buf[0] = 0x46;
        first_buf[1] = 0x48;
        sprites.free(first_buf);
    }
    if (second) |second_buf| {
        second_buf[0] = 0x42;
    }

    const reused = sprites.allocBytes(4);
    if (reused) |reused_buf| {
        if (@intFromPtr(reused_buf) == 0x9200) {
            reused_buf[2] = 0x52;
            c64.console.print("FREE REUSE OK\n", .{});
        }
    }

    sprites.reset();
    const reset_block = sprites.allocBytes(1);
    if (reset_block) |reset_buf| {
        if (@intFromPtr(reset_buf) == 0x9200) {
            c64.console.print("RESET OK\n", .{});
            c64.vic.border = 5;
        }
    }
}

Open the complete source

Size a pool for reusable objects

Suppose you need at most four live messages and each encoded message fits in 16 bytes. Reserve 64 bytes and choose a block size of 16. A six-byte message uses one block, with ten bytes of spare capacity in that block. A seventeen-byte message fails even if the pool is otherwise empty. Choose an arena if the messages can all expire together. Choose a pool if you need to return one block while the other messages stay live.

Give a fixed pool a region whose size divides exactly into blocks. Keep it in visible RAM and outside the assembled PRG, stack, and other claims. Allocate record bytes as in the near arena example, using @sizeOf and an explicit byte layout. Keep the block pointer alive until you have finished every read or write, then return it to its own pool.

Allocate, exhaust, free, and reuse blocks · Rejected uneven block layout · Rejected per-allocation free on an arena

Plan for exhaustion and reuse

Each allocator returns an optional. A failed request gives you a chance to retry after a reset, fall back to another buffer, or report that the requested work does not fit. Resetting an arena is a lifetime decision: finish using every pointer and view from that arena first. Freeing a pool block gives only that block back. A request larger than one pool block cannot span multiple blocks.

Near arena allocation and reset fixture · Pool exhaustion and reuse fixture · Far allocation, transfer, and reset fixture

Use a far arena for bulk data

A far arena allocates in the REU address space. Its handle carries a far address and length. Read and write through copyFromC64, copyToC64, or a typed view. A far handle cannot be cast to a near pointer. The example copies bytes through two screen RAM locations.

36_far_reu_arena.zp64
const c64 = @import("c64");
const ZeroPage = @import("ZeroPage");

memory {
    region assets_ram: reu at 0x010000 size 0x0100;

    arena assets in assets_ram;
}

fn poke(addr: u16, value: u8) void {
    const ptr: *volatile u8 = @ptrFromInt(addr);
    ptr.* = value;
}

fn peek(addr: u16) u8 {
    const ptr: *volatile u8 = @ptrFromInt(addr);
    return ptr.*;
}

export fn main() void {
    c64.console.clear();
    c64.console.print("FAR REU ARENA\n", .{});

    poke(0x0500, 'O');
    poke(0x0501, 'K');
    poke(0x0528, '.');
    poke(0x0529, '.');

    const maybe_far = assets.allocBytes(2);
    if (maybe_far) |far| {
        ZeroPage.reu.copyFromC64(far, 0x0500, 2);
        ZeroPage.reu.copyToC64(far, 0x0528, 2);
        if (peek(0x0528) == 'O' and peek(0x0529) == 'K') {
            c64.console.print("FAR COPY OK\n", .{});
            c64.vic.border = 5;
        } else {
            c64.console.print("FAR COPY BAD\n", .{});
            c64.vic.border = 2;
        }
    } else {
        c64.console.print("FAR ALLOC BAD\n", .{});
        c64.vic.border = 2;
    }
}

Continue to typed far records and materialized views.