summaryrefslogtreecommitdiff
path: root/src/zisp/value/sstr.zig
diff options
context:
space:
mode:
authorTaylan Kammer <taylan.kammer@gmail.com>2025-03-30 18:34:00 +0200
committerTaylan Kammer <taylan.kammer@gmail.com>2025-03-30 18:34:00 +0200
commit3d05c94b9d8aa964e4ff848c95d5999cec170e04 (patch)
tree2864753404e8c9cb9fa8bce537772a29b90d1cbd /src/zisp/value/sstr.zig
parent9340f3c44ca0d9d4fdee905fc6e8b428824b9185 (diff)
Big cleanup.
Diffstat (limited to 'src/zisp/value/sstr.zig')
-rw-r--r--src/zisp/value/sstr.zig78
1 files changed, 78 insertions, 0 deletions
diff --git a/src/zisp/value/sstr.zig b/src/zisp/value/sstr.zig
new file mode 100644
index 0000000..b02fd3d
--- /dev/null
+++ b/src/zisp/value/sstr.zig
@@ -0,0 +1,78 @@
+const std = @import("std");
+
+const value = @import("../value.zig");
+
+const ShortString = value.ShortString;
+const OtherTag = value.OtherTag;
+const Value = value.Value;
+
+// Zig API
+
+pub fn check(v: Value) bool {
+ return v.isOtherTag(.sstr) or v.isOtherTag(.qstr);
+}
+
+pub fn assert(v: Value) void {
+ if (!check(v)) {
+ v.dump();
+ @panic("not sstr");
+ }
+}
+
+pub fn checkQuoted(v: Value) bool {
+ return v.isOtherTag(.qstr);
+}
+
+// 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");
+ }
+}
+
+// Different ways of doing the following have been tested, including manual
+// shifting and bit masking, but memcpy always wins easily according to our
+// micro-benchmarks, under both ReleaseSafe and ReleaseFast.
+
+// Note: rune.zig uses equivalent code; probably good to keep in sync.
+
+pub fn pack(s: []const u8) Value {
+ return _pack(s, .sstr);
+}
+
+pub fn packQuoted(s: []const u8) Value {
+ return _pack(s, .qstr);
+}
+
+fn _pack(s: []const u8, tag: OtherTag) Value {
+ assertValidSstr(s);
+ var v = Value{ .sstr = .{ .string = 0, .tag = tag } };
+ 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);
+ inline for (0..6) |i| {
+ if (s[i] == 0) return .{ .buffer = s, .len = i };
+ }
+ return .{ .buffer = s, .len = 6 };
+}
+
+// No Zisp API for sstr specifically, since it's a string. See string.zig.