Skip to content

Commit 667aab7

Browse files
committed
refactor: use peekByte for non-destructive null checking
Update unpackNull to peek at header byte before consuming, enabling non-destructive type checking. Simplifies optional handling in unpackAny by eliminating error-based control flow. Removes unused isNullError helper.
1 parent ca17cb3 commit 667aab7

2 files changed

Lines changed: 9 additions & 12 deletions

File tree

src/any.zig

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ const NonOptional = @import("utils.zig").NonOptional;
55

66
const packNull = @import("null.zig").packNull;
77
const unpackNull = @import("null.zig").unpackNull;
8-
const isNullError = @import("null.zig").isNullError;
98

109
const getBoolSize = @import("bool.zig").getBoolSize;
1110
const packBool = @import("bool.zig").packBool;
@@ -142,12 +141,10 @@ pub fn unpackAny(reader: *std.Io.Reader, allocator: std.mem.Allocator, comptime
142141
}
143142
},
144143
.optional => |opt_info| {
145-
return unpackAny(reader, allocator, opt_info.child) catch |err| {
146-
if (isNullError(err)) {
147-
return null;
148-
}
149-
return err;
144+
unpackNull(reader) catch {
145+
return try unpackAny(reader, allocator, opt_info.child);
150146
};
147+
return null;
151148
},
152149
else => {},
153150
}

src/null.zig

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,12 @@ pub fn packNull(writer: *std.Io.Writer) !void {
1313
}
1414

1515
pub fn unpackNull(reader: *std.Io.Reader) !void {
16-
const header = try reader.takeByte();
17-
_ = try maybeUnpackNull(header, ?void);
16+
const header = try reader.peekByte();
17+
if (header == hdrs.NIL) {
18+
reader.toss(1);
19+
return;
20+
}
21+
return error.InvalidFormat;
1822
}
1923

2024
pub fn maybePackNull(writer: *std.Io.Writer, comptime T: type, value: T) !?NonOptional(T) {
@@ -29,10 +33,6 @@ pub fn maybePackNull(writer: *std.Io.Writer, comptime T: type, value: T) !?NonOp
2933
return value;
3034
}
3135

32-
pub fn isNullError(err: anyerror) bool {
33-
return err == error.Null;
34-
}
35-
3636
pub fn maybeUnpackNull(header: u8, comptime T: type) !T {
3737
switch (header) {
3838
hdrs.NIL => return if (isOptional(T)) null else error.Null,

0 commit comments

Comments
 (0)