std/arena

The std/arena module provides a fast "bump" allocator for bulk memory allocations. All memory allocated within an arena is freed at once when the arena itself is destroyed or reset.

Overview

Usage

import "std/arena.zc"
import "std/io.zc"

struct Node {
    val: int;
}

fn main() {
    // Create arena with 1KB capacity
    let a = Arena::new(1024);
    
    // Fast allocations
    let n1 = a.alloc<Node>();
    let n2 = a.alloc<Node>();
    
    // Duplicate string into arena memory
    let s = a.dup_str("Hello World");
    
    println(f"Arena used: {a.bytes_used()} bytes");
    
    // Everything is freed automatically when 'a' goes out of scope
}

Struct Definition

struct Arena {
    data: void*;
    capacity: usize;
    used: usize;
}

Methods

Construction

MethodSignatureDescription
newArena::new(cap: usize) -> ArenaCreates a new arena with the specified capacity.

Allocation

MethodSignatureDescription
alloc<T>alloc<T>(self) -> T*Allocates and zero-initializes memory for a type T.
alloc_n<T>alloc_n<T>(self, count: usize) -> T*Allocates memory for an array of count elements of type T.
alloc_bytesalloc_bytes(self, size: usize) -> void*Raw byte allocation (aligned to 8 bytes).
dup_strdup_str(self, src: char*) -> char*Duplicates a C string into the arena.

Query & Control

MethodSignatureDescription
bytes_usedbytes_used(self) -> usizeReturns the total bytes currently allocated.
bytes_freebytes_free(self) -> usizeReturns the remaining capacity.
savesave(self) -> usizeReturns a "checkpoint" representating current usage.
restorerestore(self, mark: usize)Partially frees back to a previous checkpoint.
resetreset(self)Frees all allocations by resetting usage to zero (buffer is kept).

Memory Management

MethodSignatureDescription
freefree(self)Explicitly frees the underlying arena buffer.
Traitimpl Drop for ArenaAutomatically calls free() when the arena goes out of scope.