summaryrefslogtreecommitdiff
path: root/src/zisp/gc/IstrSet.zig
blob: a97c258d1c9e0a54824db71092d146ca06d10747 (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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
//!
//! Efficient hash set for short(ish) strings.
//!
//! Layout: []Bucket
//!
//! * Bucket: [2]Sector
//!
//! * Sector: [32]u8 or [4]u64
//!
//! The parser interns strings up to 255 bytes in length, using the `Istr` heap
//! representation, which has an 8-byte metadata prefix.  Therefore, strings of
//! up to 24 bytes can fit into a 32-byte sector as an immediate Istr, so the
//! pointer to the sector becomes the Istr pointer itself.
//!
//! The 8-byte header of an Istr is a u64 hash, but its lowest 8 bits are also
//! the length of the string: u64hash = (real_u64hash << 8) | u8length
//!
//! Note that the empty string is never interned since strings up to 6 bytes in
//! length are packed directly into a NaN value.  Thus, checking if a sector is
//! empty is a matter of checking its first 8 bytes as a u64 value, which would
//! hold the Istr header, which cannot be zero, because the lowest 8 bits are
//! the length of the string.
//!
//! If the length value is greater than 24, meaning the Istr can't actually fit
//! here, that means the next 8 bytes of the sector are actually a pointer to
//! the Istr elsewhere on the heap, and another 16 bytes are unused.
//!

const std = @import("std");

const Alloc = std.mem.Allocator;

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

const IstrPtr = value.istr.IstrPtr;

const Set = @This();

const bucket_sectors = 2;
const sector_u64_cnt = 4;

const sector_size = sector_u64_cnt * 8;

// Empirically, 32 is the sweet spot; perhaps because it corresponds to 4 KiB;
// this was however tested with strings from /dev/random, which also tended to
// be on the shorter end.  TODO: Re-test with various data.
const max_probe_length = 32;

// Really just a fall-back to ensure we don't fill to 100% because our resize
// logic needs to find at least one empty sector.
const max_fill_percent = 95;

const Bucket = [bucket_sectors][sector_u64_cnt]u64;

const SectorPtr = *align(8) SectorHead;

const SectorHead = packed union {
    hash: u64,
    meta: packed struct(u64) {
        len: u8,
        _: u56,
    },

    fn bufU64(self: SectorPtr) [*]u64 {
        return @ptrCast(self);
    }

    fn getIstrPtr(self: SectorPtr) IstrPtr {
        if (self.meta.len <= sector_size - @sizeOf(SectorHead)) {
            return @ptrCast(self);
        } else {
            return @ptrFromInt(self.bufU64()[1]);
        }
    }

    pub fn match(self: SectorPtr, hash: u64, s: []const u8) ?IstrPtr {
        if (self.hash != hash) {
            return null;
        }
        const istr = self.getIstrPtr();
        if (std.hash_map.eqlString(s, istr.str())) {
            return istr;
        } else {
            return null;
        }
    }

    pub fn insert(
        self: SectorPtr,
        alloc: Alloc,
        hash: u64,
        s: []const u8,
    ) !IstrPtr {
        self.hash = hash;
        if (s.len <= sector_size - @sizeOf(SectorHead)) {
            const istr: IstrPtr = @ptrCast(self);
            istr.putStr(s);
            return istr;
        } else {
            const istr = try value.istr.new(alloc, hash, s);
            self.bufU64()[1] = @intFromPtr(istr);
            return istr;
        }
    }

    pub fn copy(self: SectorPtr, dest: SectorPtr) void {
        const end = sector_u64_cnt;
        @memcpy(dest.bufU64()[0..end], self.bufU64()[0..end]);
    }
};

buckets: []Bucket = undefined,

used_sectors: usize = 0,
used_threshold: usize = undefined,

const default_bcount = 512;

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

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

fn allocBuckets(self: *Set, alloc: Alloc, bcount: usize) !void {
    self.buckets = try alloc.alloc(Bucket, bcount);
    @memset(self.buckets, std.mem.zeroes(Bucket));
    self.used_threshold = bcount * bucket_sectors * max_fill_percent / 100;
}

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

fn sector(bs: []Bucket, b_idx: usize, s_idx: usize) SectorPtr {
    return @ptrCast(&bs[b_idx][s_idx]);
}

/// Add, or get existing, string.
pub fn add(self: *Set, alloc: Alloc, s: []const u8) !IstrPtr {
    std.debug.assert(s.len < 256);

    const idx_mask = self.buckets.len - 1;

    const real_hash = std.hash_map.hashString(s);
    const hash = (real_hash << 8) | s.len;

    const idx_init = @as(usize, @truncate(hash & idx_mask));

    var idx = idx_init;
    const s_idx = b: while (true) : (idx = (idx +% 1) & idx_mask) {
        inline for (0..bucket_sectors) |si| {
            const sec = sector(self.buckets, idx, si);
            if (sec.hash == 0) break :b si;
            if (sec.match(hash, s)) |istr| return istr;
        }
    };

    if (idx -% idx_init >= max_probe_length) {
        try self.resize(alloc);
        return self.add(alloc, s);
    }

    self.used_sectors += 1;
    if (self.used_sectors >= self.used_threshold) {
        try self.resize(alloc);
        return self.add(alloc, s);
    }

    const sec = sector(self.buckets, idx, s_idx);
    return sec.insert(alloc, hash, s);
}

fn resize(self: *Set, alloc: Alloc) !void {
    const old_bc = self.buckets.len;
    const old_bs = self.buckets;

    const new_bc = old_bc << 1;

    try self.allocBuckets(alloc, new_bc);
    defer alloc.free(old_bs);

    const new_bs = self.buckets;

    const old_mask = old_bc - 1;
    const new_mask = new_bc - 1;

    // Make sure we're not in the middle of a cluster
    var idx = b: for (old_bs, 0..) |_, idx| {
        inline for (0..bucket_sectors) |s_idx| {
            const sec = sector(old_bs, idx, s_idx);
            if (sec.hash == 0) break :b (idx +% 1) & old_mask;
        }
    } else unreachable; // Resize strategy guarantees empty slots

    const idx_last = (idx -% 1) & old_mask;

    while (idx != idx_last) : (idx = (idx +% 1) & old_mask) {
        // Need to walk destinations sector by sector, since strings grouped in
        // one sector in the old buckets may be split across buckets in the new
        // array.

        const bucket_size = sector_size * bucket_sectors;
        const new_bs_base = @intFromPtr(new_bs.ptr);

        var dest_lo = new_bs_base + (bucket_size * idx);
        var dest_hi = new_bs_base + (bucket_size * (idx + old_bc));

        // Start copying cluster
        b: while (idx != idx_last) : (idx = (idx +% 1) & old_mask) {
            inline for (0..bucket_sectors) |s_idx| {
                const sec = sector(old_bs, idx, s_idx);
                if (sec.hash == 0) break :b;
                const new_idx = sec.hash & new_mask;
                var dest: SectorPtr = undefined;
                if (new_idx < old_bc) {
                    dest = @ptrFromInt(dest_lo);
                    dest_lo += sector_size;
                } else {
                    dest = @ptrFromInt(dest_hi);
                    dest_hi += sector_size;
                }
                sec.copy(dest);
            }
        }
    }
}