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
|
//! 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]);
}
|