38 lines
1.1 KiB
Zig
38 lines
1.1 KiB
Zig
//! Simple bump allocator arena.
|
|
|
|
const phys_memory = @import("mem/phys.zig");
|
|
const log = @import("debug.zig").log;
|
|
const mem = @import("mem.zig");
|
|
|
|
/// Bump allocator implementation.
|
|
pub const Arena = struct {
|
|
phys_base: mem.PhysicalAddress,
|
|
capacity: usize,
|
|
len: usize,
|
|
|
|
/// Creates a new `Arena` of given `cap`acity.
|
|
///
|
|
/// Requires initialized physical memory management.
|
|
pub fn init(cap: usize) ?Arena {
|
|
const phys_base = phys_memory.alloc_pages(cap / mem.vmm.PAGE_SIZE) orelse return null;
|
|
return .{ .phys_base = phys_base, .capacity = cap, .len = 0 };
|
|
}
|
|
|
|
/// Allocates an object of type `T` within this arena.
|
|
///
|
|
/// # Panics
|
|
///
|
|
/// Panics if the arena runs out of memory.
|
|
pub fn create(self: *@This(), comptime T: type) *T {
|
|
if (self.len + @sizeOf(T) > self.capacity) {
|
|
log.panic("Out of memory. Cannot allocate {} bytes", .{@sizeOf(T)});
|
|
}
|
|
|
|
const v = self.phys_base.add(self.len).virtualize();
|
|
const ptr = @as(*T, @ptrFromInt(v));
|
|
self.len += @sizeOf(T);
|
|
|
|
return ptr;
|
|
}
|
|
};
|