//! List array pool //! //! Strategy: To ensure list arrays are allocated sequentially without any //! padding, we allocate memory in large blocks, and whenever a list array with //! a certain length is to be allocated, we check if the current block still has //! enough room; otherwise we allocate the next block. //! //! This is only used for lists up to 7 elements. Starting at 8, they can't //! share a cache line with other list elements anyway. const std = @import("std"); const Alloc = std.mem.Allocator; const ArrayList = std.ArrayListUnmanaged; const value = @import("../value.zig"); const seg_stack = @import("seg_stack.zig"); const Value = value.Value; const SegStack = seg_stack.SegStack; const Self = @This(); /// How many Value elements fit in a block. A good value should be 512, since /// each Value is 8 bytes: 512 * 8 = 4 KiB const block_value_cap = 512; const Block = [block_value_cap]Value; alloc: Alloc, current_block: *Block, current_index: usize = 0, full_list: SegStack(*Block, 4096), free_lists: [7]SegStack([*]Value, 512), pub fn init(alloc: Alloc) !Self { return .{ .alloc = alloc, .current_block = try alloc.create(Block), .full_list = try .init(alloc), .free_lists = .{ try .init(alloc), try .init(alloc), try .init(alloc), try .init(alloc), try .init(alloc), try .init(alloc), try .init(alloc), }, }; } pub fn deinit(self: *Self) void { for (self.free_lists) |l| l.deinit(self.alloc); while (self.full_list.pop(self.alloc)) |block| self.alloc.destroy(block); self.full_list.deinit(self.alloc); self.alloc.destroy(self.current_block); } fn newBlock(self: *Self) !void { try self.full_list.push(self.alloc, self.current_block); self.current_block = try self.alloc.create(Block); self.current_index = 0; } fn popFree(self: *Self, len: u3) ?[*]Value { return self.free_lists[len - 1].pop(self.alloc); } fn pushFree(self: *Self, len: u3, ptr: [*]Value) !void { try self.free_lists[len - 1].push(self.alloc, ptr); } pub fn allocVals(self: *Self, len: u3) ![*]Value { std.debug.assert(len != 0); if (self.popFree(len)) |ptr| return ptr; if (len > block_value_cap - self.current_index) { try self.newBlock(); } defer self.current_index += len; return @ptrCast(&self.current_block[self.current_index]); } pub fn freeVals(self: *Self, len: u3, ptr: [*]Value) !void { std.debug.assert(len != 0); try self.pushFree(len, ptr); } pub fn freeList(self: *Self, list: Value) !void { const len = value.list.getLenTag(list); const ptr = value.list.getValPtr(list); try self.freeVals(len, ptr); }