zig/test/cases/union.zig

78 lines
1.3 KiB
Zig
Raw Normal View History

2017-10-26 22:22:48 -07:00
const assert = @import("std").debug.assert;
const Value = enum {
Int: u64,
Array: [9]u8,
};
const Agg = struct {
val1: Value,
val2: Value,
};
const v1 = Value.Int { 1234 };
const v2 = Value.Array { []u8{3} ** 9 };
const err = (%Agg)(Agg {
.val1 = v1,
.val2 = v2,
});
const array = []Value { v1, v2, v1, v2};
test "unions embedded in aggregate types" {
switch (array[1]) {
Value.Array => |arr| assert(arr[4] == 3),
else => unreachable,
}
switch((%%err).val1) {
Value.Int => |x| assert(x == 1234),
else => unreachable,
}
}
2017-11-14 20:53:53 -08:00
const Foo = union {
float: f64,
int: i32,
};
test "basic unions" {
var foo = Foo { .int = 1 };
assert(foo.int == 1);
2017-11-16 18:15:15 -08:00
foo = Foo {.float = 12.34};
2017-11-14 20:53:53 -08:00
assert(foo.float == 12.34);
}
test "init union with runtime value" {
var foo: Foo = undefined;
setFloat(&foo, 12.34);
assert(foo.float == 12.34);
setInt(&foo, 42);
assert(foo.int == 42);
}
fn setFloat(foo: &Foo, x: f64) {
*foo = Foo { .float = x };
}
fn setInt(foo: &Foo, x: i32) {
*foo = Foo { .int = x };
}
const FooExtern = extern union {
float: f64,
int: i32,
};
test "basic extern unions" {
var foo = FooExtern { .int = 1 };
assert(foo.int == 1);
foo.float = 12.34;
assert(foo.float == 12.34);
}