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

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

const ShortString = value.ShortString;
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");
    }
}

// For now, ignore encoding, just treat it as []u8.

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 v = Value{ .sstr = .{ .string = 0 } };
    const dest: [*]u8 = @ptrCast(&v.sstr.string);
    @memcpy(dest, s);
    return v;
}

pub fn unpack(v: Value) ShortString {
    assert(v);
    const s: [6]u8 = @bitCast(v.sstr.string);
    const l = value.sstrLen(v.bits);
    return .{ .buffer = s, .len = l };
}

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