-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtest_enum.zig
136 lines (117 loc) · 2.62 KB
/
test_enum.zig
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
const expect = @import("std").testing.expect;
const mem = @import("std").mem;
const Type = enum {
ok,
not_ok,
};
test "Type enum" {
try expect(@typeInfo(Type).Enum.tag_type == u1);
const c = Type.ok;
try expect(@TypeOf(c) == Type);
}
const Value = enum(u2) {
zero,
one,
two,
};
test "enum ordinal value" {
try expect(@intFromEnum(Value.zero) == 0);
try expect(@intFromEnum(Value.one) == 1);
try expect(@intFromEnum(Value.two) == 2);
}
const Value2 = enum(u32) {
hundred = 100,
thousand = 1000,
million = 1000000,
};
test "enum ordinal value 2" {
try expect(@intFromEnum(Value2.hundred) == 100);
try expect(@intFromEnum(Value2.thousand) == 1000);
try expect(@intFromEnum(Value2.million) == 1000000);
}
const Suit = enum {
clubs, //梅花
spades, //黑桃
diamonds, //钻石
hearts, //红心
// 不写pub也可以
pub fn isClubs(self: Suit) bool {
return self == Suit.clubs;
}
};
test "enum method" {
const p = Suit.spades;
try expect(!p.isClubs());
try expect(!Suit.isClubs(p));
}
const Foo = enum {
string,
number,
none,
};
test "enum switch" {
const p = Foo.number;
const what_is_it = switch (p) {
Foo.string => "this is a string",
Foo.number => "this is a number",
Foo.none => "this is a none",
};
try expect(mem.eql(u8, what_is_it, "this is a number"));
}
const Small = enum {
one,
two,
three,
four,
};
test "tag @typeInfo @tagName" {
try expect(@typeInfo(Small).Enum.tag_type == u2);
try expect(@typeInfo(Small).Enum.fields.len == 4);
try expect(mem.eql(u8, @typeInfo(Small).Enum.fields[1].name, "two"));
try expect(mem.eql(u8, @tagName(Small.three), "three"));
}
// C-ABI-compatible enum
const Foo2 = enum(c_int) { a, b, c };
export fn entry(foo: Foo2) void {
_ = foo;
}
const Color = enum {
auto,
off,
on,
};
test "enum literals" {
const color: Color = .auto;
const color2 = Color.auto;
try expect(color == color2);
}
test "switch using enum literals" {
const color = Color.on;
const result = switch (color) {
.auto => false,
.on => true,
.off => false,
};
try expect(result);
}
// Non-exhaustive enum
const Number = enum(u8) {
one,
two,
three,
_,
};
test "switch on non-exhaustive enum" {
const number = Number.one;
const result = switch (number) {
.one => true,
.two, .three => false,
_ => false,
};
try expect(result);
const is_one = switch (number) {
.one => true,
else => false,
};
try expect(is_one);
}