diff options
Diffstat (limited to 'src/zisp/value')
| -rw-r--r-- | src/zisp/value/istr.zig | 38 |
1 files changed, 24 insertions, 14 deletions
diff --git a/src/zisp/value/istr.zig b/src/zisp/value/istr.zig index 2ca2dad..dec3b09 100644 --- a/src/zisp/value/istr.zig +++ b/src/zisp/value/istr.zig @@ -7,27 +7,37 @@ const Value = value.Value; // Zig API -/// Pointer to beginning of an interned string with a 1-byte length prefix and -/// 8-byte hash cache suffix. Aligned to 8 bytes, like all Zisp heap pointers. -pub const Istr = *align(8) struct { - fn buf(self: *@This()) [*]u8 { +/// Pointer to an interned string. +/// +/// First 64 bits are a cached hash, of which the lowest 8 bits are actually the +/// length of the string: u64hash = (real_u64hash << 1) | u8length +pub const Istr = *align(8) packed union { + hash: u64, + meta: packed struct(u64) { + len: u8, + _: u56, + }, + + fn bufU8(self: *@This()) [*]u8 { return @ptrCast(self); } - pub fn len(self: *@This()) u8 { - return self.buf()[0]; + pub fn new(alloc: *Allocator, hash: u64, s: []const u8) Istr { + const istr: Istr = @ptrCast(alloc.alloc(u8, 8 + s.len)); + istr.hash = hash; + istr.putStr(s); + return istr; } - pub fn str(self: *@This()) []u8 { - const end = 1 + self.len(); - return self.buf()[1..end]; + pub fn putStr(self: *@This(), s: []const u8) void { + std.debug.assert(s.len <= 255); + @memcpy(istr.bufU8()[8 .. 8 + s.len], s); } - pub fn getHash(self: *@This()) u64 { - // Hash stored in the next naturally aligned u64 - const hash_idx = ((self.len() + 8) & -8) / 8; - const buf: [*]u64 = @ptrCast(self); - return buf[hash_idx]; + pub fn str(self: *@This()) []const u8 { + const buf = self.bufU8(); + const len = self.meta.len; + return buf[8 .. 8 + len]; } }; |
