zig/test/cases/enum.zig

139 lines
2.4 KiB
Zig
Raw Normal View History

2017-01-05 16:57:48 +08:00
const assert = @import("std").debug.assert;
const mem = @import("std").mem;
2017-01-05 16:57:48 +08:00
2017-05-24 09:38:31 +08:00
test "enum type" {
2016-12-20 14:50:32 +08:00
const foo1 = Foo.One {13};
const foo2 = Foo.Two { Point { .x = 1234, .y = 5678, }};
const bar = Bar.B;
assert(bar == Bar.B);
assert(@memberCount(Foo) == 3);
assert(@memberCount(Bar) == 4);
assert(@sizeOf(Foo) == @sizeOf(FooNoVoid));
2016-12-20 14:50:32 +08:00
assert(@sizeOf(Bar) == 1);
}
2017-05-24 09:38:31 +08:00
test "enum as return value" {
switch (returnAnInt(13)) {
Foo.One => |value| assert(value == 13),
else => unreachable,
}
}
2016-12-20 14:50:32 +08:00
const Point = struct {
x: u64,
y: u64,
};
const Foo = enum {
One: i32,
Two: Point,
Three: void,
};
const FooNoVoid = enum {
One: i32,
Two: Point,
};
2016-12-20 14:50:32 +08:00
const Bar = enum {
A,
B,
C,
D,
};
fn returnAnInt(x: i32) -> Foo {
Foo.One { x }
}
2017-05-24 09:38:31 +08:00
test "constant enum with payload" {
2016-12-22 14:20:08 +08:00
var empty = AnEnumWithPayload.Empty;
var full = AnEnumWithPayload.Full {13};
shouldBeEmpty(empty);
shouldBeNotEmpty(full);
}
2017-03-26 15:39:18 +08:00
fn shouldBeEmpty(x: &const AnEnumWithPayload) {
switch (*x) {
2016-12-22 14:20:08 +08:00
AnEnumWithPayload.Empty => {},
else => unreachable,
2016-12-22 14:20:08 +08:00
}
}
2017-03-26 15:39:18 +08:00
fn shouldBeNotEmpty(x: &const AnEnumWithPayload) {
switch (*x) {
AnEnumWithPayload.Empty => unreachable,
2016-12-22 14:20:08 +08:00
else => {},
}
}
const AnEnumWithPayload = enum {
Empty,
Full: i32,
};
2016-12-26 15:36:04 +08:00
const Number = enum {
Zero,
One,
Two,
Three,
Four,
};
2017-05-24 09:38:31 +08:00
test "enum to int" {
2016-12-26 15:36:04 +08:00
shouldEqual(Number.Zero, 0);
shouldEqual(Number.One, 1);
shouldEqual(Number.Two, 2);
shouldEqual(Number.Three, 3);
shouldEqual(Number.Four, 4);
}
fn shouldEqual(n: Number, expected: usize) {
assert(usize(n) == expected);
}
2016-12-26 16:44:59 +08:00
2017-05-24 09:38:31 +08:00
test "int to enum" {
2016-12-27 05:34:18 +08:00
testIntToEnumEval(3);
}
fn testIntToEnumEval(x: i32) {
assert(IntToEnumNumber(x) == IntToEnumNumber.Three);
}
const IntToEnumNumber = enum {
Zero,
One,
Two,
Three,
Four,
};
2017-05-24 09:38:31 +08:00
test "@enumTagName" {
assert(mem.eql(u8, testEnumTagNameBare(BareNumber.Three), "Three"));
comptime assert(mem.eql(u8, testEnumTagNameBare(BareNumber.Three), "Three"));
}
fn testEnumTagNameBare(n: BareNumber) -> []const u8 {
return @enumTagName(n);
}
const BareNumber = enum {
One,
Two,
Three,
};
test "enum alignment" {
2017-08-27 01:51:51 +08:00
comptime {
assert(@alignOf(AlignTestEnum) >= @alignOf([9]u8));
assert(@alignOf(AlignTestEnum) >= @alignOf(u64));
2017-08-27 01:51:51 +08:00
}
}
const AlignTestEnum = enum {
A: [9]u8,
B: u64,
};