~alva/zig-bare

3302303980ad9c02da032c04447af3a0cc1fc133 — ugla a month ago e901850 0.5.0
Handle reading of invalid enum values
2 files changed, 13 insertions(+), 3 deletions(-)

M src/bare.zig
M src/test.zig
M src/bare.zig => src/bare.zig +1 -3
@@ 117,10 117,8 @@ pub const Reader = struct {
    }

    fn readEnum(self: *Self, comptime T: type, reader: anytype) !T {
        // TODO: Check that value is valid enum value?
        // TODO: Is there a nicer way?
        const TT = @TagType(T);
        return @intToEnum(T, @intCast(TT, try self.readVarUint(reader)));
        return meta.intToEnum(T, @intCast(TT, try self.readVarUint(reader)));
    }

    fn readOptional(self: *Self, comptime T: type, reader: anytype) !T {

M src/test.zig => src/test.zig +12 -0
@@ 139,6 139,18 @@ test "read enum" {
    expectEqual(res, .c);
}

test "read invalid enum value" {
    const Foo = enum {
        a = 2,
        b = 1,
        c = 0,
    };
    expectError(
        error.InvalidEnumTag,
        Reader.init(testing.allocator).read(Foo, io.fixedBufferStream("\x03").reader())
    );
}

test "read optional u8 value" {
    const res = try Reader.init(testing.allocator).read(?u8, io.fixedBufferStream("\x01\x2a").reader());
    expectEqual(res, 42);