Skip to content
CryoCryo home
Stdliballoc

arena

import std::alloc::arena; · source

Arena

type struct Arena {
    head:       Chunk*;
    current:    Chunk*;
    chunk_size: u64;

    static new() -> Arena;
    static with_chunk_size(chunk_size: u64) -> Arena;
    reset(mut &this) -> void;
    capacity(&this) -> u64;
    used(&this) -> u64;
    bump(mut &this, size: u64, align: u64) -> void*;
    owns(&this, ptr: void*) -> boolean;
    grow(mut &this, ptr: void*, old_size: u64, new_size: u64, align: u64) -> void*;
    release(mut &this) -> void;
}
const DEFAULT_CHUNK_SIZE: u64 = 1048576;

Bump allocation, bulk release. An arena hands out memory by bumping an offset into a chunk. Allocation is O(1), individual deallocation is unsupported, and everything comes back at once through reset (keep the chunks, reuse the space) or drop (return the chunks to the OS).

The shape it fits is "allocate a pile of things with related lifetimes, then throw them away together" — compiler passes, per-request handlers, parse trees. Long-lived caches are not that shape.

import std::alloc::arena;

mut a: Arena = Arena::new();
mut nodes: Array<Node, Arena> = Array<Node, Arena>::new_in(a);
// ... build the tree ...
a.reset();      // everything above is invalid now; capacity is reused
MethodNotes
new()Chunks of DEFAULT_CHUNK_SIZE (1 MiB).
with_chunk_size(chunk_size)A hint about typical allocation size, not a cap — a larger request gets its own chunk sized to fit.
reset()Rewind every chunk to zero. Invalidates every pointer handed out.
release()Return every chunk to the OS. This is what drop calls.
capacity() / used()Bytes held in chunks / bytes handed out.
bump(size, align)void*, null on OOM or a zero-sized request.
grow(ptr, old_size, new_size, align)Extends in place when ptr is the most recent allocation in the frontier chunk; otherwise copies, stranding the old block until reset.
owns(ptr)Whether the pointer lies in a chunk this arena owns.

Repeated reset is where an arena earns its keep — the same memory gets reused instead of round-tripping through the platform allocator.

Each chunk's data buffer is mapped straight from the OS, so releasing it returns the pages immediately and RSS drops at the call, with none of the main-heap retention you get from freeing many small malloc blocks. The mapping is demand-paged, so untouched pages cost nothing and a small arena stays cheap despite the 1 MiB nominal chunk.

Trait implementations

implement trait Allocator for struct Arena   // std::alloc::arena_alloc

implement trait Drop for struct Arena   // std::alloc::arena_alloc

Arena implements Allocator, so it drops into any allocator-generic type. Its deallocate is a no-op by design; reallocate tries grow first.