//! Intermediate-length String //! //! Length up to 255, stored in pointer. Typically interned in an IstrPool. const std = @import("std"); const Alloc = std.mem.Allocator; const gc = @import("../gc.zig"); const value = @import("../value.zig"); const IstrPool = gc.IstrPool; const Value = value.Value; pub const max_len = 255; // Zig API pub fn check(v: Value) bool { return v.isIstr(); } pub fn assert(v: Value) void { if (!check(v)) { v.dump(); @panic("not istr"); } } pub fn isValidIstr(s: []const u8) bool { return s.len <= max_len; } fn assertValidIstr(s: []const u8) void { if (!isValidIstr(s)) { std.debug.print("invalid istr: {s}\n", .{s}); @panic("invalid istr"); } } pub fn new(alloc: Alloc, s: []const u8) !IstrPtr { const algn = std.mem.Alignment.of(IstrPtr); const size = @sizeOf(IstrHead) + s.len; const istr: IstrPtr = @ptrCast(try alloc.alignedAlloc(u8, algn, size)); istr.putStr(s); return istr; } pub fn getOrNew(s: []const u8) !IstrPtr { return getOrNewInPool(gc.mainIstrPool(), s); } pub fn getOrNewInPool(pool: *IstrPool, s: []const u8) !IstrPtr { assertValidIstr(s); return try pool.getOrNew(s); } pub fn pack(istr: IstrPtr) Value { const ptr = @intFromPtr(istr); return .{ .istr = .{ .ptr = @intCast(ptr) } }; } pub fn unpack(v: Value) IstrPtr { return @ptrFromInt(v.istr.ptr); } pub fn getBytes(v: Value) []const u8 { assert(v); return unpack(v).bytes(); } // Zisp API pub fn pred(v: Value) Value { return value.boole.pack(check(v)); } pub fn getLen(v: Value) Value { assert(v); const istr: IstrPtr = @ptrFromInt(v.istr.ptr); return value.fixnum.pack(istr.len); } // TODO: Zisp representation of IstrPool & ability to intern in given IstrPool pub fn intern(v: Value) Value { const istr = assert(v); const pool = gc.mainIstrPool(); return pack(pool.getOrPut(istr)); }