Module coca::arena

source · []
Expand description

Arena-based memory management.

An arena controls a contiguous region of memory, partitioning it by simply incrementing a pointer. Once such an allocation goes out of scope, the memory cannot be reused until the entire region is cleared in aggregate. This scheme has minimal run-time overhead, at the cost of internal memory fragmentation.

In order to guarantee safety, Arena cannot implement a clear method. Instead, the underlying region is reset by dropping the arena, and may then be freed or reused safely; you’ll get an error if a Box<'_, T> pointing into it still lives. So this won’t compile:

use core::mem::MaybeUninit;
use coca::arena::{Arena, Box};

let bad_array = {
    let mut backing_region = [MaybeUninit::uninit(); 256];
    let mut arena = Arena::from(&mut backing_region[..]);
    arena.array_default::<i32>(10)
};

This makes it wasteful to mix long-lived allocations with short-lived ones in the same arena. One solution is to construct a temporary sub-arena using the remaining memory. Sub-arenas may be nested arbitrarily, resulting in stack-like behavior, which is sufficient for many allocation patterns.

Note that this is legal but strongly discouraged:

// callers must drop the return value before they can allocate from `arena` again!
fn semi_bad_array<'a>(arena: &'a mut Arena) -> Box<'a, [i32]> {
    let mut sub = arena.make_sub_arena();
    sub.array_default(10)
}

A Box should not outlive the arena it was allocated from. If temporary allocations are required where an arena allocated value is to be returned, consider using Arena::try_reserve.

Memory Profiling

During development, it is common practice to provide arenas with more memory than is assumed necessary, and track their peak utilization to aid in determining a more appropriate size for deployment.

To accommodate this, the profile feature enables the Arena::utilization method and its return type, UtilizationProfile. Note that this requires an allocation for some meta data when creating an arena from a buffer, which may panic on buffers smaller than 40 bytes (the exact threshold depends on your target platform’s pointer size and the alignment of the passed buffer). This does not apply to creating sub-arenas.

Structs

A memory arena, also known as a region-based allocator, or bump allocator.

A pointer type providing ownership of an arena allocation.

A summary of all allocations from an arena and all its sub-arenas from it since its creation.

Implementor of core::fmt::Write backed by an Arena. Primarily intended for use in expansions of fmt!.