@pkmn/engine 0.1.0-dev.2c13d3ec → 0.1.0-dev.305a932f

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,60 @@
1
+ const std = @import("std");
2
+
3
+ const expect = std.testing.expect;
4
+ const assert = std.debug.assert;
5
+
6
+ // TODO: ziglang/zig#104
7
+ pub fn Optional(comptime T: type) type {
8
+ const fields = std.meta.fields(switch (@typeInfo(T)) {
9
+ .Bool => enum { false, true },
10
+ else => T,
11
+ });
12
+
13
+ var enumFields: [fields.len + 1]std.builtin.Type.EnumField = undefined;
14
+ var decls = [_]std.builtin.Type.Declaration{};
15
+
16
+ enumFields[0] = .{ .name = "None", .value = 0 };
17
+ inline for (fields, 1..) |field, i| {
18
+ assert(!std.mem.eql(u8, field.name, "None"));
19
+ enumFields[i] = .{
20
+ .name = field.name,
21
+ .value = i,
22
+ };
23
+ }
24
+
25
+ return @Type(.{
26
+ .Enum = .{
27
+ .tag_type = std.math.IntFittingRange(0, fields.len + 1),
28
+ .fields = &enumFields,
29
+ .decls = &decls,
30
+ .is_exhaustive = true,
31
+ },
32
+ });
33
+ }
34
+
35
+ test Optional {
36
+ try expect(@bitSizeOf(Optional(bool)) == 2);
37
+
38
+ const a: Optional(bool) = .true;
39
+ try expect(a != .None);
40
+ try expect(a == .true);
41
+ try expect(a != .false);
42
+
43
+ const b: Optional(bool) = .None;
44
+ try expect(b == .None);
45
+ try expect(b != .true);
46
+ try expect(b != .false);
47
+
48
+ const Player = @import("./data.zig").Player;
49
+ try expect(@bitSizeOf(Optional(Player)) == 2);
50
+
51
+ const p: Optional(Player) = .P2;
52
+ try expect(p != .None);
53
+ try expect(p != .P1);
54
+ try expect(p == .P2);
55
+
56
+ const q: Optional(Player) = .None;
57
+ try expect(q == .None);
58
+ try expect(q != .P1);
59
+ try expect(q != .P2);
60
+ }