-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmir_algebraic_example.d
More file actions
67 lines (55 loc) · 1.86 KB
/
mir_algebraic_example.d
File metadata and controls
67 lines (55 loc) · 1.86 KB
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
/+ dub.sdl:
dependency "mir-core" version="~>1.1.54"
dependency "sbin" path=".."
+/
import mir.algebraic;
import sbin;
struct Foo { string name; }
alias TUnion = Algebraic!(
TaggedType!(typeof(null), "nil"),
TaggedType!(int, "count"),
TaggedType!(string, "str"),
TaggedType!(Foo, "foo"),
);
static assert (isTagged!(TUnion).any);
static assert (isTagged!(TUnion).isMirAlgebraic);
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].kind == TUnion.Kind.count);
assert (sdbar.data[0].get!int == 42);
//assert (sdbar.data[0].count == 42);
// deserialize to new memory
assert (bar.data[1].get!string.ptr !=
sdbar.data[1].get!string.ptr);
assert (sdbar.data[1].kind == TUnion.Kind.str);
assert (sdbar.data[1].get!string == "Hello");
//assert (sdbar.data[1].str == "Hello");
assert (sdbar.data[2].kind == TUnion.Kind.foo);
assert (sdbar.data[2].get!Foo == Foo("ABC"));
//assert (sdbar.data[2].foo == Foo("ABC"));
assert (sdbar.data[2].get!Foo.name.ptr !=
bar.data[2].get!Foo.name.ptr);
assert (sdbar.data[3].isNull);
}
void main()
{
barTest();
}