-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsumtype_example.d
80 lines (64 loc) · 2.13 KB
/
sumtype_example.d
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
/+ dub.sdl:
dependency "sumtype" version="~>1.1.0"
dependency "sbin" path=".."
+/
import sumtype;
import sbin;
struct Foo { string name; }
alias TUnion = SumType!( typeof(null), int, string, Foo );
static assert (isTagged!(TUnion).any);
static assert (isTagged!(TUnion).isSumType);
struct Bar
{
int someInt;
TUnion[] data;
}
void barTest()
{
auto bar = Bar(77, [TUnion(42), TUnion("Hello"), TUnion(Foo("ABC")), TUnion(null)]);
auto sdbar_data = bar.sbinSerialize;
assert (sdbar_data.length == int.sizeof + 1 /+ length packed to 1 byte +/ +
byte.sizeof + int.sizeof + // count
byte.sizeof + 1 /+ length packed to 1 byte +/ + 5 + // str
byte.sizeof + 1 /+ length packed to 1 byte +/ + 3 + // Foo
byte.sizeof /+ length packed to 1 byte +/ // null
);
assert (sdbar_data == [77, 0, 0, 0, 4, 1, 42, 0, 0, 0, 2, 5, 72, 101, 108, 108, 111, 3, 3, 65, 66, 67, 0]);
auto sdbar = sdbar_data.sbinDeserialize!Bar;
assert (sdbar.someInt == 77);
assert (sdbar.data.length == 4);
assert (sdbar.data[0].typeIndex == 1);
assert (sdbar.data[0].match!((int v) => v, _ => 0 ) == 42);
// deserialize to new memory
assert (bar.data[1].match!((string v) => v.ptr, _ => null) !=
sdbar.data[1].match!((string v) => v.ptr, _ => null));
assert (sdbar.data[1].typeIndex == 2);
assert (sdbar.data[1].match!((string v) => v, _ => "") == "Hello");
assert (sdbar.data[2].typeIndex == 3);
assert (sdbar.data[2].match!((Foo v) => v, _ => Foo.init) == Foo("ABC"));
assert (bar.data[2].match!((Foo v) => v.name.ptr, _ => null) !=
sdbar.data[2].match!((Foo v) => v.name.ptr, _ => null));
assert (sdbar.data[3].typeIndex == 0);
}
alias UT3 = SumType!(typeof(null), byte, This[]);
void ut3Test()
{
auto val1 = UT3([
UT3(42),
UT3(null),
UT3([
UT3(null),
UT3(65)
]),
UT3(12)
]);
auto data = sbinSerialize(val1);
assert (data == [2, 4, 1, 42, 0, 2, 2, 0, 1, 65, 1, 12]);
auto val2 = sbinDeserialize!UT3(data);
assert (val1 == val2);
}
void main()
{
barTest();
ut3Test();
}