1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
|
//! 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);
}
|