1 module tests.pointers; 2 3 import unit_threaded; 4 import cerealed; 5 import core.exception; 6 7 8 private struct InnerStruct { 9 ubyte b; 10 ushort s; 11 } 12 13 private struct OuterStructWithPointerToStruct { 14 ushort s; 15 InnerStruct* inner; 16 ubyte b; 17 } 18 19 void testStructWithPointerToStruct() { 20 auto enc = Cerealiser(); 21 //outer not const because not copyable from const 22 auto outer = OuterStructWithPointerToStruct(3, new InnerStruct(7, 2), 5); 23 enc ~= outer; 24 25 const bytes = [ 0, 3, 7, 0, 2, 5]; 26 enc.bytes.shouldEqual(bytes); 27 28 auto dec = Decerealiser(bytes); 29 const decOuter = dec.value!OuterStructWithPointerToStruct; 30 31 //can't compare the two structs directly since the pointers 32 //won't match but the values will. 33 decOuter.s.shouldEqual(outer.s); 34 shouldEqual(*decOuter.inner, *outer.inner); 35 decOuter.inner.shouldNotEqual(outer.inner); //ptrs shouldn't match 36 decOuter.b.shouldEqual(outer.b); 37 38 dec.value!ubyte.shouldThrow!RangeError; //no bytes 39 } 40 41 42 private class InnerClass { 43 ushort s; 44 ubyte b; 45 this() {} //needed for decerealisation 46 this(ushort s, ubyte b) { this.s = s; this.b = b; } 47 override string toString() const { //so it can be used in shouldEqual 48 import std.conv; 49 return text("InnerClass(", s, ", ", b, ")"); 50 } 51 52 } 53 54 private struct OuterStructWithClass { 55 ushort s; 56 InnerClass inner; 57 ubyte b; 58 } 59 60 void testStructWithClassReference() { 61 auto enc = Cerealiser(); 62 auto outer = OuterStructWithClass(2, new InnerClass(3, 5), 8); 63 enc ~= outer; 64 65 const bytes = [ 0, 2, 0, 3, 5, 8]; 66 enc.bytes.shouldEqual(bytes); 67 68 auto dec = Decerealiser(bytes); 69 const decOuter = dec.value!OuterStructWithClass; 70 71 //can't compare the two structs directly since the pointers 72 //won't match but the values will. 73 decOuter.s.shouldEqual(outer.s); 74 decOuter.inner.shouldEqual(outer.inner); 75 shouldNotEqual(&decOuter.inner, &outer.inner); //ptrs shouldn't match 76 decOuter.b.shouldEqual(outer.b); 77 } 78 79 void testPointerToInt() { 80 auto enc = Cerealiser(); 81 auto i = new int; *i = 4; 82 enc ~= i; 83 const bytes = [0, 0, 0, 4]; 84 enc.bytes.shouldEqual(bytes); 85 86 auto dec = Decerealiser(bytes); 87 shouldEqual(*dec.value!(int*), *i); 88 }