blob: 90eccb63e9dd51d355c4bcd2f2c33a7868129034 (
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
|
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 str(self: *@This()) []const u8 {
const start = @sizeOf(IstrHead);
const len: usize = self.len;
return self.bufU8()[start .. start + len];
}
pub fn putStr(self: *@This(), s: []const u8) void {
const start = @sizeOf(IstrHead);
self.len = @intCast(s.len);
@memcpy(self.bufU8()[start .. start + s.len], s);
}
};
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 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 pack(istr: IstrPtr) Value {
return value.ptr.pack(@ptrCast(istr), .istr);
}
pub fn getOrNew(s: []const u8) !Value {
return getOrNewInSet(gc.mainIstrSet(), s);
}
pub fn getOrNewInSet(set: *IstrSet, s: []const u8) !Value {
assertValidIstr(s);
return pack(try set.getOrNew(s));
}
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));
}
// TODO: Zisp representation of IstrSet & ability to intern in given IstrSet
pub fn intern(v: Value) Value {
const istr = assert(v);
const set = gc.mainIstrSet();
return pack(set.getOrPut(istr));
}
|