summaryrefslogtreecommitdiff
path: root/src/zisp/value/istr.zig
blob: 2ca2dadbb406146795722885ffc32d7055bfe67e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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()));
}