const std = @import("std"); const gc = @import("../gc.zig"); const value = @import("../value.zig"); const Alloc = std.mem.Allocator; const Value = value.Value; // Zig API /// 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 putStr(self: *@This(), s: []const u8) void { std.debug.assert(s.len <= 255); @memcpy(self.bufU8()[8 .. 8 + s.len], s); } pub fn str(self: *@This()) []const u8 { const buf = self.bufU8(); return buf[8 .. 8 + self.meta.len]; } }; pub fn new(alloc: Alloc, hash: u64, s: []const u8) !Istr { const aln = std.mem.Alignment.of(Istr); const ptr = try alloc.alignedAlloc(u8, aln, 8 + s.len); const istr: Istr = @ptrCast(ptr); istr.hash = hash; istr.putStr(s); return istr; } pub fn check(v: Value) ?Istr { if (v.getPtr(.istr)) |p| { return @ptrCast(p); } return null; } pub fn assert(v: Value) Istr { return check(v) orelse { v.dump(); @panic("not istr"); }; } pub fn isValidIstr(s: []const u8) bool { return s.len <= 255; } fn assertValidIstr(s: []const u8) void { if (!isValidIstr(s)) { std.debug.print("invalid istr: {s}\n", .{s}); @panic("invalid istr"); } } pub fn intern(s: []const u8) !Value { assertValidIstr(s); return gc.internString(s); } // Zisp API pub fn pred(v: Value) Value { return value.boole.pack(check(v) != null); } pub fn len(v: Value) Value { const istr = assert(v); return value.fixnum.pack(@intCast(istr.len())); }