summaryrefslogtreecommitdiff
path: root/src/zisp/value/istr.zig
blob: 528280a47c879d9881cd651da3376fc6755ca589 (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
//! Intermediate-length String
//!
//! Length up to 255, stored in pointer.  Typically interned in an IstrPool.

const std = @import("std");

const Alloc = std.mem.Allocator;

const gc = @import("../gc.zig");
const value = @import("../value.zig");

const IstrPool = gc.IstrPool;
const Value = value.Value;

pub const max_len = 255;

// Zig API

pub fn check(v: Value) bool {
    return v.isIstr();
}

pub fn assert(v: Value) void {
    if (!check(v)) {
        v.dump();
        @panic("not istr");
    }
}

pub fn isValidIstr(s: []const u8) bool {
    return s.len <= max_len;
}

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 getOrNew(s: []const u8) !IstrPtr {
    return getOrNewInPool(gc.mainIstrPool(), s);
}

pub fn getOrNewInPool(pool: *IstrPool, s: []const u8) !IstrPtr {
    assertValidIstr(s);
    return try pool.getOrNew(s);
}

pub fn pack(istr: IstrPtr) Value {
    const ptr = @intFromPtr(istr);
    return .{ .istr = .{ .ptr = @intCast(ptr) } };
}

pub fn unpack(v: Value) IstrPtr {
    return @ptrFromInt(v.istr.ptr);
}

pub fn getBytes(v: Value) []const u8 {
    assert(v);
    return unpack(v).bytes();
}

// Zisp API

pub fn pred(v: Value) Value {
    return value.boole.pack(check(v));
}

pub fn getLen(v: Value) Value {
    assert(v);
    const istr: IstrPtr = @ptrFromInt(v.istr.ptr);
    return value.fixnum.pack(istr.len);
}

// TODO: Zisp representation of IstrPool & ability to intern in given IstrPool

pub fn intern(v: Value) Value {
    const istr = assert(v);
    const pool = gc.mainIstrPool();
    return pack(pool.getOrPut(istr));
}