summaryrefslogtreecommitdiff
path: root/src/zisp/gc/IstrPool.zig
blob: 81b4632de4d68f1f26fd173574bdff35b00bac8e (plain)
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
//! Interned string pool
//!
//! This is a fairly standard open-address linear-search hash-set, specialized
//! for our istr data type, not supporting removal.

// TODO: Allocate the strings in tight blocks just like ListPool.

// TODO: Vector instructions.

const std = @import("std");

const Alloc = std.mem.Allocator;

const gc = @import("../gc.zig");
const value = @import("../value.zig");

const Value = value.Value;

const Self = @This();

const max_fill_percent = 80;

/// Fingerprint: 8 bit length, 24 bits from the real u64 hash.
const Fp = packed union(u32) {
    info: packed struct(u32) {
        // Put length first; allows more optimal instructions.
        len: u8,
        fp: u24,
    },
    bits: u32,
};

const Bucket = packed struct(u64) {
    // Put fp first; allows more optimal instructions.
    fp: Fp = .{ .bits = 0 },
    idx: u32 = 0,

    pub fn empty(self: Bucket) bool {
        // On x64 this is just checking an 8-bit low virtual register thanks to
        // fp.info.len being the lowest 8 bits.
        return self.fp.info.len == 0;
    }

    pub fn getIstr(self: Bucket) Value {
        return .{ .istr = .{ .idx = self.idx, .len = self.fp.info.len } };
    }

    pub fn putIstr(self: *Bucket, v: Value, fp: Fp) void {
        self.idx = v.istr.idx;
        self.fp = fp;
    }
};

alloc: Alloc,
buckets: []Bucket = undefined,

used_buckets: usize = 0,
used_threshold: usize = undefined,

const test_stdlib_impl = false;

const default_bcount = 512;

pub fn init(alloc: Alloc) !Self {
    return initCustom(alloc, default_bcount);
}

pub fn initCustom(alloc: Alloc, bcount: usize) !Self {
    if (test_stdlib_impl) {
        try map.ensureTotalCapacity(alloc, 512);
        return Self{ .alloc = alloc };
    }
    std.debug.assert(@popCount(bcount) == 1); // Must be power of 2.
    var self = Self{ .alloc = alloc };
    try self.allocBuckets(bcount);
    return self;
}

fn allocBuckets(self: *Self, bcount: usize) !void {
    self.buckets = try self.alloc.alloc(Bucket, bcount);
    @memset(self.buckets, Bucket{});
    self.used_threshold = bcount * max_fill_percent / 100;
}

pub fn deinit(self: *Self) void {
    self.alloc.free(self.buckets);
}

/// Get the istr with the given string contents, or alloc and store a new one.
pub fn getOrNew(self: *Self, s: []const u8) !Value {
    std.debug.assert(s.len <= 255);
    if (test_stdlib_impl) {
        return self.addStdlib(s);
    }
    return self.getOrPutOrNew(s.ptr, @intCast(s.len), null);
}

/// Get the canonical istr with the same contents, or store this one as it.
pub fn getOrPut(self: *Self, v: Value) !Value {
    const sptr = gc.istrPtrFromIdx(v.istr.idx);
    const len = v.istr.len;
    return self.getOrPutOrNew(sptr, len, v);
}

fn getOrPutOrNew(self: *Self, sptr: [*]const u8, len: u8, put: ?Value) !Value {
    if (self.used_buckets > self.used_threshold) {
        try self.resize();
    }

    const hash = hashBytes(sptr, len);
    const fp = makeHashFp(hash, len);

    const idx_mask = self.buckets.len - 1;
    const idx_start = hash & idx_mask;

    var idx = idx_start;
    while (true) : (idx = (idx + 1) & idx_mask) {
        const bucket = &self.buckets[idx];
        if (bucket.empty()) {
            self.used_buckets += 1;
            const v = put orelse try self.newIstr(sptr, len);
            bucket.putIstr(v, fp);
            return v;
        }
        if (bucket.fp.bits == fp.bits) {
            const ptr = gc.istrPtrFromIdx(bucket.idx);
            if (eqBytes(sptr, ptr, len)) return bucket.getIstr();
        }
    }
}

fn newIstr(self: *Self, sptr: [*]const u8, len: u8) !Value {
    // TODO: Alloc manually in slabs, like ListPool FlexiBlock.
    const s = try self.alloc.alloc(u8, len);
    @memcpy(s, sptr[0..len]);
    const idx = gc.istrIdxFromPtr(s.ptr);
    return .{ .istr = .{ .idx = idx, .len = len } };
}

fn resize(self: *Self) !void {
    const old_buckets = self.buckets;
    try self.allocBuckets(old_buckets.len << 1);
    defer self.alloc.free(old_buckets);
    const new_buckets = self.buckets;

    const idx_mask = new_buckets.len - 1;
    for (old_buckets) |old| {
        if (old.empty()) continue;
        const len = old.fp.info.len;
        const ptr = gc.istrPtrFromIdx(old.idx);
        var idx = hashBytes(ptr, len) & idx_mask;
        while (!new_buckets[idx].empty()) idx = (idx + 1) & idx_mask;
        new_buckets[idx] = old;
    }
}

fn hashBytes(s: [*]const u8, len: u8) u64 {
    // TODO: Can do better than this.
    return std.hash_map.hashString(s[0..len]);
}

fn eqBytes(s1: [*]const u8, s2: [*]const u8, len: u8) bool {
    // TODO: Can do better than this.
    return std.hash_map.eqlString(s1[0..len], s2[0..len]);
}

fn makeHashFp(hash: u64, len: u8) Fp {
    //
    // Should compile to just two instructions; e.g. on x64:
    //
    //     shl edi, 8
    //
    //     lea eax, [rdi + rsi]
    //
    return .{ .info = .{ .len = len, .fp = @truncate(hash) } };
}

// Using stdlib, to compare

const str_ctx = std.hash_map.StringContext{};

const Map = std.hash_map.StringHashMapUnmanaged(Value);
var map: Map = .empty;

pub fn addStdlib(self: *Self, s: []const u8) !Value {
    const gop = map.getOrPutAdapted(self.alloc, s, str_ctx) catch @panic("OOM");
    if (gop.found_existing) {
        return gop.value_ptr.*;
    }

    const istr = try self.newIstr(s);
    gop.key_ptr.* = istr.bytes();
    gop.value_ptr.* = istr;
    return istr;
}