blob: 1159cc77f085736511fc54f5721e25ca75854a33 (
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
74
75
76
77
78
79
80
81
82
83
84
85
86
|
const std = @import("std");
const gc = @import("../gc.zig");
const value = @import("../value.zig");
const Alloc = std.mem.Allocator;
const IstrSet = gc.IstrSet;
const Value = value.Value;
// Zig API
/// Pointer to an interned string. First byte is length.
pub const IstrPtr = *align(@alignOf(value.Zptr)) IstrHead;
pub const IstrHead = packed struct(u8) {
len: u8,
fn bufU8(self: *@This()) [*]u8 {
return @ptrCast(self);
}
pub fn putStr(self: *@This(), s: []const u8) void {
std.debug.assert(s.len <= 255);
const buf = self.bufU8();
const start = @sizeOf(IstrHead);
@memcpy(buf[start .. start + s.len], s);
}
pub fn str(self: *@This()) []const u8 {
const buf = self.bufU8();
const start = @sizeOf(IstrHead);
const len: usize = self.len;
return buf[start .. start + len];
}
};
pub fn check(v: Value) ?IstrPtr {
if (v.getPtr(.istr)) |p| {
return @ptrCast(p);
}
return null;
}
pub fn assert(v: Value) IstrPtr {
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 {
return internInSet(gc.mainIstrSet(), s);
}
pub fn internInSet(set: *IstrSet, s: []const u8) !Value {
assertValidIstr(s);
const istr = try set.add(s);
return value.ptr.pack(@ptrCast(istr), .istr);
}
pub fn getStr(v: Value) []const u8 {
return assert(v).str();
}
// Zisp API
pub fn pred(v: Value) Value {
return value.boole.pack(check(v) != null);
}
pub fn getLen(v: Value) Value {
const istr = assert(v);
return value.fixnum.pack(@intCast(istr.len));
}
|