summaryrefslogtreecommitdiff
path: root/src/zisp/value/sstr.zig
blob: 2c4db4b5d0d62dafa70f55d6fe3e0b116360276c (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
const std = @import("std");

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

const Value = value.Value;

// Zig API

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

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

pub fn isValidSstr(s: []const u8) bool {
    if (s.len > 6) return false;
    for (s) |c| if (c == 0) return false;
    return true;
}

fn assertValidSstr(s: []const u8) void {
    if (!isValidSstr(s)) {
        std.debug.print("invalid sstr: {s}\n", .{s});
        @panic("invalid sstr");
    }
}

pub fn pack(s: []const u8) Value {
    assertValidSstr(s);
    var buf: [6]u8 = @splat(0);
    @memcpy(buf[0..s.len], s);
    return .{ .sstr = .{ .string = @bitCast(buf) } };
}

pub fn unpack(v: *const Value) []const u8 {
    assert(v.*);
    const buf = v.bytes();
    const len = value.sstrLen(v.bits);
    return buf[0..len];
}

// No Zisp API for sstr specifically, since it's a string.  See string.zig.