summaryrefslogtreecommitdiff
path: root/src/zisp/value/list.zig
blob: a78d274e182a7a5e4274ff50b1af160b89a43684 (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
//! List array

const std = @import("std");

const Alloc = std.mem.Allocator;

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

const ListPool = gc.ListPool;
const Value = value.Value;

// Zig API

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

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

pub fn new(alloc: Alloc, pool: ?*ListPool, vals: []const Value) !Value {
    var len_tagged_ptr: u48 = undefined;
    if (vals.len < 8 and pool != null) {
        const ptr = try pool.?.allocVals(@intCast(vals.len));
        for (vals, 0..) |v, i| ptr[i] = v;
        len_tagged_ptr = @intCast(@intFromPtr(ptr) | vals.len);
    } else {
        const ptr = try alloc.alloc(Value, vals.len + 1);
        for (vals, 0..) |v, i| ptr[i] = v;
        ptr[vals.len] = value.none;
        len_tagged_ptr = @intCast(@intFromPtr(ptr.ptr));
    }
    return .{ .list = .{ .len_tagged_ptr = len_tagged_ptr } };
}

pub fn free(alloc: Alloc, pool: ?*ListPool, list: Value) !void {
    const len = getLenTag(list);
    const ptr = getValPtr(list);
    if (len == 0 or pool == null) {
        const full_len = findFullLen(list);
        alloc.free(ptr[0..full_len]);
    } else {
        try pool.?.freeVals(len, ptr);
    }
}

pub fn getLenTag(v: Value) u3 {
    return @truncate(v.bits);
}

pub fn getValPtr(v: Value) [*]Value {
    return @ptrFromInt(v.bits & 0x0000fffffffffff8);
}

pub fn findFullLen(v: Value) usize {
    std.debug.assert(getLenTag(v) == 0);
    const ptr: [*]u64 = @ptrCast(getValPtr(v));
    var i: usize = 8;
    while (true) : (i += 8) {
        const vals: @Vector(8, u64) = (ptr + i)[0..8].*;
        const mask: @Vector(8, u64) = @splat(value.none.bits);
        const results: u8 = @bitCast(vals == mask);
        if (results != 0) return i + @clz(results);
    }
}

// Zisp API

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

pub fn getLength(v: Value) Value {
    assert(v);
    const len = findFullLen(v);
    return value.fixnum.pack(@intCast(len));
}