summaryrefslogtreecommitdiff
path: root/src/zisp/gc.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/zisp/gc.zig')
-rw-r--r--src/zisp/gc.zig60
1 files changed, 39 insertions, 21 deletions
diff --git a/src/zisp/gc.zig b/src/zisp/gc.zig
index d778b77..cf2d32f 100644
--- a/src/zisp/gc.zig
+++ b/src/zisp/gc.zig
@@ -3,15 +3,11 @@ const std = @import("std");
const value = @import("value.zig");
+const ptr = value.ptr;
const seq = value.seq;
const Value = value.Value;
-
-/// A "heap value" that could be a Value or object header.
-pub const Hval = union {
- value: Value,
- seq_header: seq.Header,
-};
+const Zptr = value.Zptr;
pub const alloc = std.heap.smp_allocator;
@@ -28,20 +24,42 @@ pub fn cons(v1: Value, v2: Value) *[2]Value {
// Interned strings
-var istr_pool = std.hash_map.StringHashMap(void).init(alloc);
-
-pub fn intern(header: seq.Header, str: []const u8) *seq.Header {
- const hs = @sizeOf(seq.Header);
- const size = str.len + hs;
- const copy = alloc.alloc(u8, size) catch @panic("OOM");
- const header_bytes: [hs]u8 = @bitCast(header);
- @memcpy(copy[0..hs], &header_bytes);
- @memcpy(copy[hs..size], str);
- const entry = istr_pool.getOrPutValue(copy, {}) catch @panic("OOM");
- return @ptrCast(entry.key_ptr);
-}
+const istr_ctx = std.hash_map.StringContext{};
+var istr_pool = std.hash_map.StringHashMap(*seq.Header).init(alloc);
+
+pub fn internString(str: []const u8) Value {
+ const gop = istr_pool.getOrPutAdapted(
+ str,
+ istr_ctx,
+ ) catch @panic("OOM");
+ if (gop.found_existing) {
+ const p: *seq.Header = gop.value_ptr.*;
+ return ptr.pack(p, .seq);
+ }
+
+ std.debug.assert(str.len <= std.math.maxInt(u48));
+
+ const header: seq.Header = .{
+ .type = .string,
+ .info = .{ .string = .{
+ .enc = .utf8,
+ .interned = true,
+ } },
+ .size = @intCast(str.len),
+ };
+
+ const h_align = @alignOf(seq.Header);
+ const h_size = @sizeOf(seq.Header);
+ const size = str.len + h_size;
+
+ const mem = alloc.alignedAlloc(u8, h_align, size) catch @panic("OOM");
+
+ const h_bytes: [h_size]u8 = @bitCast(header);
+ @memcpy(mem[0..h_size], &h_bytes);
+ @memcpy(mem[h_size..size], str);
+
+ gop.key_ptr.* = alloc.dupe(u8, str) catch @panic("OOM");
+ gop.value_ptr.* = @ptrCast(mem.ptr);
-pub fn istrHeader(ptr: *Hval) *seq.Header {
- const entry_key: *[]u8 = @ptrCast(ptr);
- return @alignCast(@ptrCast(entry_key.ptr));
+ return ptr.pack(mem.ptr, .seq);
}