authorgravatar for twostepted@gmail.comTravis Staloch <twostepted@gmail.com> 2023-10-26 21:12:47-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2023-10-27 05:50:33-04:00
log8f48533691e93538846993f78f732272a03a600b
tree0d0d29c5019b4a64c3d3dd71c41fa3e2fc5dc6f3
parent29b05897a5e25e699f176b37ba558eea2694136b

GenericReader error set fixes

add error.EndOfStream to readEnum() and isBytes() so that users can catch these errors. this also prevents them from panicing with 'invalid error value' on EndOfStream. test both methods.

2 files changed, 15 insertions(+), 2 deletions(-)

lib/std/io.zig+2-2
......@@ -308,7 +308,7 @@ pub fn GenericReader(
308308 return @errorCast(self.any().skipBytes(num_bytes, options));
309309 }
310310
311 pub inline fn isBytes(self: Self, slice: []const u8) Error!bool {
311 pub inline fn isBytes(self: Self, slice: []const u8) NoEofError!bool {
312312 return @errorCast(self.any().isBytes(slice));
313313 }
314314
......@@ -320,7 +320,7 @@ pub fn GenericReader(
320320 return @errorCast(self.any().readStructBig(T));
321321 }
322322
323 pub const ReadEnumError = Error || error{
323 pub const ReadEnumError = NoEofError || error{
324324 /// An integer was read, but it did not match any of the tags in the supplied enum.
325325 InvalidValue,
326326 };
lib/std/io/test.zig+13
......@@ -182,3 +182,16 @@ test "updateTimes" {
182182 try expect(stat_new.atime < stat_old.atime);
183183 try expect(stat_new.mtime < stat_old.mtime);
184184}
185
186test "GenericReader methods can return error.EndOfStream" {
187 // https://github.com/ziglang/zig/issues/17733
188 var fbs = std.io.fixedBufferStream("");
189 try std.testing.expectError(
190 error.EndOfStream,
191 fbs.reader().readEnum(enum(u8) { a, b }, .Little),
192 );
193 try std.testing.expectError(
194 error.EndOfStream,
195 fbs.reader().isBytes("foo"),
196 );
197}