aboutsummaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authornsfisis <nsfisis@gmail.com>2026-01-26 23:42:01 +0900
committernsfisis <nsfisis@gmail.com>2026-01-26 23:42:01 +0900
commit225cb99c09ec01fac5cfecf858040f53ee5cc32b (patch)
tree53ef2ecb5d9ff6800e9ac8893187cbd3a8b4460e
parentc2a92de7fa1af4fc058f8e5e8317fb67a6df18ef (diff)
downloadzgjq-225cb99c09ec01fac5cfecf858040f53ee5cc32b.tar.gz
zgjq-225cb99c09ec01fac5cfecf858040f53ee5cc32b.tar.zst
zgjq-225cb99c09ec01fac5cfecf858040f53ee5cc32b.zip
refactor isFalsy/isTruthy
-rw-r--r--src/jq/execute.zig14
-rw-r--r--src/jv/ops.zig32
2 files changed, 34 insertions, 12 deletions
diff --git a/src/jq/execute.zig b/src/jq/execute.zig
index 0565004..282a35c 100644
--- a/src/jq/execute.zig
+++ b/src/jq/execute.zig
@@ -187,12 +187,7 @@ pub const Runtime = struct {
std.debug.assert(self.values.ensureSize(1));
const value = self.values.pop();
- const is_falsy = switch (value) {
- .null => true,
- .bool => |b| !b,
- else => false,
- };
- if (is_falsy) {
+ if (jv.ops.isFalsy(value)) {
self.pc += offset - 1;
}
// FIXME: optimize pop and push
@@ -334,12 +329,7 @@ pub const Runtime = struct {
_ = self.values.pop();
const lhs = self.values.pop();
const rhs = self.values.pop();
- const is_falsy = switch (lhs) {
- .null => true,
- .bool => |b| !b,
- else => false,
- };
- try self.values.push(if (is_falsy) rhs else lhs);
+ try self.values.push(if (jv.ops.isFalsy(lhs)) rhs else lhs);
},
.@"const" => |idx| {
std.debug.assert(self.values.ensureSize(1));
diff --git a/src/jv/ops.zig b/src/jv/ops.zig
index 3c702c8..21f9efb 100644
--- a/src/jv/ops.zig
+++ b/src/jv/ops.zig
@@ -186,3 +186,35 @@ test "compare different types" {
try std.testing.expectError(error.InvalidType, compare(.{ .integer = 1 }, .{ .string = "1" }, .eq));
try std.testing.expectError(error.InvalidType, compare(.null, .{ .integer = 0 }, .eq));
}
+
+pub fn isFalsy(value: Value) bool {
+ return switch (value) {
+ .null => true,
+ .bool => |b| !b,
+ else => false,
+ };
+}
+
+pub fn isTruthy(value: Value) bool {
+ return !isFalsy(value);
+}
+
+test "isFalsy" {
+ try std.testing.expect(isFalsy(.null));
+ try std.testing.expect(isFalsy(.{ .bool = false }));
+ try std.testing.expect(!isFalsy(.{ .bool = true }));
+ try std.testing.expect(!isFalsy(.{ .integer = 0 }));
+ try std.testing.expect(!isFalsy(.{ .integer = 1 }));
+ try std.testing.expect(!isFalsy(.{ .string = "" }));
+ try std.testing.expect(!isFalsy(.{ .string = "hello" }));
+}
+
+test "isTruthy" {
+ try std.testing.expect(!isTruthy(.null));
+ try std.testing.expect(!isTruthy(.{ .bool = false }));
+ try std.testing.expect(isTruthy(.{ .bool = true }));
+ try std.testing.expect(isTruthy(.{ .integer = 0 }));
+ try std.testing.expect(isTruthy(.{ .integer = 1 }));
+ try std.testing.expect(isTruthy(.{ .string = "" }));
+ try std.testing.expect(isTruthy(.{ .string = "hello" }));
+}