zig/test/behavior/union_with_members.zig
Andrew Kelley 81a3910e44 Sema: improve union support
* reduce number of branches in zirCmpEq
 * implement equality comparison for enums and unions
 * fix coercion from union to its tag type resulting in the wrong type
 * fix method calls of unions
 * implement peer type resolution for unions, enums, and enum literals
 * fix union tag type memory in the wrong arena
2021-12-28 20:20:30 -07:00

29 lines
786 B
Zig

const std = @import("std");
const expect = std.testing.expect;
const mem = std.mem;
const fmt = std.fmt;
const ET = union(enum) {
SINT: i32,
UINT: u32,
pub fn print(a: *const ET, buf: []u8) anyerror!usize {
return switch (a.*) {
ET.SINT => |x| fmt.formatIntBuf(buf, x, 10, .lower, fmt.FormatOptions{}),
ET.UINT => |x| fmt.formatIntBuf(buf, x, 10, .lower, fmt.FormatOptions{}),
};
}
};
test "enum with members" {
const a = ET{ .SINT = -42 };
const b = ET{ .UINT = 42 };
var buf: [20]u8 = undefined;
try expect((a.print(buf[0..]) catch unreachable) == 3);
try expect(mem.eql(u8, buf[0..3], "-42"));
try expect((b.print(buf[0..]) catch unreachable) == 2);
try expect(mem.eql(u8, buf[0..2], "42"));
}