memory
overview
void has two memory modes:
- manual — used in the bootstrap compiler. the programmer manages allocation and deallocation explicitly.
- borrow checker — planned for the self-hosted rewrite. eliminates use-after-free and data races at compile time.
allocators
default heap allocator
import std.mem.HeapAlloc;
let allocator: HeapAlloc = HeapAlloc.new();
let buffer: Option[*int32] = allocator.alloc(1024); // size in bytes
let buffer = match buffer {
Some(ptr) => {ptr},
None => {panic("allocation failed!")}
}
// do something
allocator.drop(buffer);
uses a basic HeapAlloc. simple but less efficient for bulk allocations.
arena allocator
import std.mem.ArenaAlloc;
let arena: ArenaAlloc = ArenaAlloc.new();
let mut b = Array.new([1, 2, 3], arena);
// ... use b ...
arena.drop(); // frees everything allocated in this arena at once
arena allocators are efficient for short-lived groups of allocations —
all memory is freed in a single call to arena.drop().
borrow checker
the borrow checker is planned for the self-hosted rewrite stage. it will enforce:
- single ownership
- no use-after-free
- no data races