From b84ed4f563b3536365f7d3cc4d068407e98685b3 Mon Sep 17 00:00:00 2001 From: Taylan Kammer Date: Sat, 20 Jun 2026 22:53:50 +0200 Subject: It's a revolution baby. --- src/zisp/gc/ListPool.zig | 69 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 src/zisp/gc/ListPool.zig (limited to 'src/zisp/gc/ListPool.zig') diff --git a/src/zisp/gc/ListPool.zig b/src/zisp/gc/ListPool.zig new file mode 100644 index 0000000..6c34074 --- /dev/null +++ b/src/zisp/gc/ListPool.zig @@ -0,0 +1,69 @@ +//! 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 Value = value.Value; + +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; + +// Initial capacity of ArrayList of pointers to filled blocks. Also 512, since +// pointers are 8 bytes as well. +const def_full_blocks_cap = 512; + +const Block = [block_value_cap]Value; + +alloc: Alloc, + +current_block: *Block, +current_index: usize, + +full_blocks: ArrayList(*Block), + +pub fn init(alloc: Alloc) !Self { + return .{ + .alloc = alloc, + .current_block = try alloc.create(Block), + .current_index = 0, + .full_blocks = try .initCapacity(alloc, def_full_blocks_cap), + }; +} + +pub fn deinit(self: *Self) void { + self.alloc.destroy(self.current_block); + for (self.full_blocks) |block| self.alloc.destroy(block); + self.full_blocks.deinit(self.alloc); +} + +fn newBlock(self: *Self) !void { + try self.full_blocks.append(self.alloc, self.current_block); + self.current_block = try self.alloc.create(Block); + self.current_index = 0; +} + +pub fn create(self: *Self, len: u3) ![*]Value { + std.debug.assert(len != 0); + + if (len > block_value_cap - self.current_index) { + try self.newBlock(); + } + + defer self.current_index += len; + return @ptrCast(&self.current_block[self.current_index]); +} -- cgit v1.2.3