const std = @import("std"); const gc = @import("../gc.zig"); const value = @import("../value.zig"); 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 { return @ptrCast(self); } pub fn len(self: *@This()) u8 { return self.buf()[0]; } pub fn str(self: *@This()) []u8 { const end = 1 + self.len(); return self.buf()[1..end]; } 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 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())); }