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
|
const builtin = @import("builtin");
const std = @import("std");
const value = @import("value.zig");
const ptr = value.ptr;
const seq = value.seq;
const Value = value.Value;
const Zptr = value.Zptr;
pub const alloc = std.heap.smp_allocator;
// Cons cells
const ConsPool = std.heap.MemoryPool([2]Value);
var cons_pool: ConsPool = undefined;
var need_init = true;
pub fn cons(v1: Value, v2: Value) *[2]Value {
if (need_init) {
cons_pool = ConsPool.initCapacity(alloc, 64) catch @panic("OOM");
need_init = false;
}
const mem = cons_pool.create(alloc) catch @panic("OOM");
mem[0] = v1;
mem[1] = v2;
return mem;
}
// Interned strings
const istr_ctx = std.hash_map.StringContext{};
var istr_pool = std.hash_map.StringHashMap(*seq.Header).init(alloc);
pub fn internString(str: []const u8) Value {
const gop = istr_pool.getOrPutAdapted(
str,
istr_ctx,
) catch @panic("OOM");
if (gop.found_existing) {
const p: *seq.Header = gop.value_ptr.*;
return ptr.pack(p, .seq);
}
std.debug.assert(str.len <= std.math.maxInt(u48));
const header: seq.Header = .{
.type = .string,
.info = .{ .string = .{
.enc = .utf8,
.interned = true,
} },
.size = @intCast(str.len),
};
const h_align: std.mem.Alignment = @enumFromInt(@alignOf(seq.Header));
const h_size = @sizeOf(seq.Header);
const size = str.len + h_size;
const mem = alloc.alignedAlloc(u8, h_align, size) catch @panic("OOM");
const h_bytes: [h_size]u8 = @bitCast(header);
@memcpy(mem[0..h_size], &h_bytes);
@memcpy(mem[h_size..size], str);
gop.key_ptr.* = alloc.dupe(u8, str) catch @panic("OOM");
gop.value_ptr.* = @ptrCast(mem.ptr);
return ptr.pack(mem.ptr, .seq);
}
|