Modules

Flat_Pool

moduleSource

Available on macOS, Linux, Windows

#import "Flat_Pool";

A bump allocator over one contiguous range of reserved address space.

Use it when allocations never move and everything is dropped together: get hands out memory, reset takes it all back.

Example
pool: Flat_Pool;
defer fini(*pool);
list := cast(*u8) get(*pool, 100);
list[99] = 1;
assert(list[99] == 1);

Doesn't run in the browser (skipped on wasm).

Module parameters#

DEFAULT_VIRTUAL_MEMORY_RESERVE := 256 * 1024 * 1024
The address space a pool reserves when init is not given a size, in bytes.
OVERWRITE_ALL_POOLS_ON_RESET := false
Fills reset memory with 0xcc for every pool.

Procedures#

(pool: *Flat_Pool, reserve := DEFAULT_VIRTUAL_MEMORY_RESERVE)

Reserves reserve bytes of address space for the pool (256 MiB by default) and sets it up. No memory is used until get touches pages.

pool: Flat_Pool;
init(*pool, 1024 * 1024);
defer fini(*pool);
assert(get(*pool, 16) != null);

Doesn't run in the browser (skipped on wasm).

(pool: *Flat_Pool, nbytes: s64) -> *void

Returns nbytes bytes from the pool, aligned to its alignment. The memory is not cleared. Running out of the reserved range fails an assert.

pool: Flat_Pool;
defer fini(*pool);
a := cast(*int) get(*pool, size_of(int));
a.* = 3;
assert(a.* == 3);

Doesn't run in the browser (skipped on wasm).

(pool: *Flat_Pool, overwrite_memory := false)

Rewinds the pool to the start, keeping its committed pages for reuse. Pointers from get are invalid afterwards.

pool: Flat_Pool;
defer fini(*pool);
first := get(*pool, 32);
reset(*pool);
assert(get(*pool, 32) == first);

Doesn't run in the browser (skipped on wasm).

(mode: Allocator_Mode, requested_size: s64, old_size: s64, old_memory: *void, allocator_data: *void) -> *void

The Allocator_Proc for a flat pool: use it as Allocator.{ flat_pool_allocator_proc, *pool }. Allocate and resize take memory from the pool, free does nothing.

pool: Flat_Pool;
defer fini(*pool);
context.allocator = Allocator.{ flat_pool_allocator_proc, *pool };
numbers := NewArray(4, int);
assert(numbers.count == 4);

Doesn't run in the browser (skipped on wasm).

()

A small demonstration: initialize, allocate, reset with overwrite, finalize. It exists as a smoke test and is not part of the API.

Types#

:: struct

A bump allocator over one contiguous range of reserved address space, committed page by page as it is used.

alignment: s32
current_point: *u8
memory_base: *u8
first_uncommitted_page: *u8
address_limit: *u8
pool: Flat_Pool;
init(*pool, 1024 * 1024);
defer fini(*pool);

first := cast(*int) get(*pool, size_of(int));
first.* = 7;
for 0..9999 get(*pool, 64); // growing never moves `first`
assert(first.* == 7);

reset(*pool);
assert(get(*pool, size_of(int)) == first); // the same memory comes back

Doesn't run in the browser (skipped on wasm).

Constants#