blob: dec3b098194d11a1b6d294d596cac456929c2523 (
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
|
const std = @import("std");
const gc = @import("../gc.zig");
const value = @import("../value.zig");
const Value = value.Value;
// Zig API
/// Pointer to an interned string.
///
/// First 64 bits are a cached hash, of which the lowest 8 bits are actually the
/// length of the string: u64hash = (real_u64hash << 1) | u8length
pub const Istr = *align(8) packed union {
hash: u64,
meta: packed struct(u64) {
len: u8,
_: u56,
},
fn bufU8(self: *@This()) [*]u8 {
return @ptrCast(self);
}
pub fn new(alloc: *Allocator, hash: u64, s: []const u8) Istr {
const istr: Istr = @ptrCast(alloc.alloc(u8, 8 + s.len));
istr.hash = hash;
istr.putStr(s);
return istr;
}
pub fn putStr(self: *@This(), s: []const u8) void {
std.debug.assert(s.len <= 255);
@memcpy(istr.bufU8()[8 .. 8 + s.len], s);
}
pub fn str(self: *@This()) []const u8 {
const buf = self.bufU8();
const len = self.meta.len;
return buf[8 .. 8 + len];
}
};
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()));
}
|