~alva/zig-bare

9536ed48134b4bb888c6060615055ff22d8bd651 — Alva 4 months ago c78b4b2
Tests for bare unions
2 files changed, 28 insertions(+), 7 deletions(-)

M src/bare.zig
M src/test.zig
M src/bare.zig => src/bare.zig +3 -3
@@ 348,12 348,12 @@ pub const Writer = struct {
        const ti = @typeInfo(T).Union;

        if (ti.tag_type) |TT| {
            const tag = @as(TT, value);
            try self.writeVarUint(@enumToInt(tag), stream);
            const tag = @enumToInt(value);
            try self.writeVarUint(tag, stream);

            inline for (ti.fields) |f| {
                if (f.enum_field) |ef| {
                    if (tag == @intToEnum(TT, ef.value))
                    if (tag == ef.value)
                        try self.writeAllowVoid(@field(value, f.name), stream);
                }
            }

M src/test.zig => src/test.zig +25 -4
@@ 225,6 225,17 @@ test "read tagged union" {
    expectEqual(Foo{ .c = 42 }, res);
}

test "read untagged union" {
    try testCompileError(
        \\pub fn main() void {
        \\  const Foo = union { a: u8, b: void };
        \\  var fbs = io.fixedBufferStream("lol");
        \\  _ = try Reader.init(testing.allocator).read(Foo, fbs.inStream());
        \\}
        , "only tagged unions are supported"
    );
}

test "read void" {
    try testCompileError(
        \\pub fn main() void {


@@ 467,6 478,17 @@ test "write tagged union with void member active" {
    expectEqualSlices(u8, fbs.getWritten(), expected[0..]);
}

test "write untagged union" {
    try testCompileError(
        \\pub fn main() void {
        \\  const Foo = union { a: u8, b: void };
        \\  var fbs = io.fixedBufferStream("lol");
        \\  _ = try Writer.init().write(Foo{ .a = 2 }, fbs.outStream());
        \\}
        , "only tagged unions are supported"
    );
}

test "write void" {
    try testCompileError(
        \\pub fn main() void {


@@ 722,7 744,6 @@ fn testCompileError(comptime code: []const u8, comptime expected_error: []const 
    try proc.spawn();
    const stderr = try proc.stderr.?.inStream().readAllAlloc(testing.allocator, 0x1000);
    const term = try proc.wait();
//    warn("{}\n", .{ t });
    defer testing.allocator.free(stderr);
    try checkErrorMessage(stderr, expected_error);
    expectEqual(term.Exited, 1);


@@ 735,8 756,8 @@ fn checkErrorMessage(haystack: []const u8, message: []const u8) !void {
        return;
    };
    const errorslice = haystack[idx + errorstart.len..];
    if (!mem.startsWith(u8, errorslice, message)) {
    const starts_with = mem.startsWith(u8, errorslice, message);
    if (!starts_with)
        warn("\nunexpected output: {}\n", .{ errorslice });
        expect(false);
    }
    expect(starts_with);
}