1 module tests.encode_decode; 2 3 import unit_threaded; 4 import unit_threaded.io; 5 import cerealed.cerealiser; 6 import cerealed.decerealiser; 7 import core.exception; 8 9 10 private void implEncDec(T)(T[] values) { 11 auto enc = Cerealiser(); 12 import std.stdio; 13 foreach(b; values) { 14 writelnUt("Encoding ", b); 15 enc ~= b; 16 } 17 auto dec = Decerealiser(enc.bytes); 18 writelnUt("Decoding to match ", values); 19 writelnUt("Bytes: ", enc.bytes); 20 foreach(b; values) shouldEqual(dec.value!T, b); 21 dec.value!ubyte.shouldThrow!RangeError; //no more bytes 22 } 23 24 void testEncDecBool() { 25 implEncDec([ true, true, false, false, true]); 26 } 27 28 29 private void implEncDecValues(T, alias arr)() { 30 T[] values = arr; 31 implEncDec(values); 32 } 33 34 void testEncDecByte() { 35 implEncDecValues!(byte, [ 1, 3, -2, 5, -4 ]); 36 } 37 38 void testEncDecUByte() { 39 implEncDecValues!(ubyte, [ 1, 255, 12 ]); 40 } 41 42 void testEncDecShort() { 43 implEncDecValues!(short, [ 1, -2, -32768, 5 ]); 44 } 45 46 void testEncDecUShort() { 47 implEncDecValues!(short, [ 1, -2, 32767, 5 ]); 48 } 49 50 void testEncDecInt() { 51 implEncDecValues!(int, [ 1, -2, -1_000_000, 2_000_000 ]); 52 } 53 54 void testEncDecUInt() { 55 implEncDecValues!(uint, [ 1, -2, 1_000_000, 2_000_000 ]); 56 } 57 58 void testEncDecLong() { 59 implEncDecValues!(long, [ 5_000_000, 2, -3, -5_000_000_000, 1 ]); 60 } 61 62 void testEncDecULong() { 63 implEncDecValues!(ulong, [ 5_000_000, 2, 7_000_000_000, 1 ]); 64 } 65 66 void testEncDecFloat() { 67 implEncDec([ 2.0f, -4.3f, 3.1415926f ]); //don't add a value without 'f'! 68 } 69 70 void testEncDecDouble() { 71 implEncDec([ 2.0, -9.0 ]); 72 } 73 74 void testEncDecChars() { 75 char c = 5; 76 wchar w = 300; 77 dchar d = 1_000_000; 78 auto enc = Cerealiser(); 79 enc ~= c; enc ~= w; enc ~= d; 80 auto dec = Decerealiser(enc.bytes); 81 dec.value!char.shouldEqual(c); 82 dec.value!wchar.shouldEqual(w); 83 dec.value!dchar.shouldEqual(d); 84 dec.value!ubyte.shouldThrow!RangeError; //no more bytes 85 } 86 87 void testEncDecArray() { 88 auto enc = Cerealiser(); 89 const ints = [ 2, 6, 9]; 90 enc ~= ints; 91 auto dec = Decerealiser(enc.bytes); 92 dec.value!(int[]).shouldEqual(ints); 93 dec.value!ubyte.shouldThrow!RangeError; //no more bytes 94 } 95 96 void testEncDecAssocArray() { 97 auto enc = Cerealiser(); 98 const intToInts = [ 1:2, 3:6, 9:18]; 99 enc ~= intToInts; 100 auto dec = Decerealiser(enc.bytes); 101 dec.value!(int[int]).shouldEqual(intToInts); 102 dec.value!ubyte.shouldThrow!RangeError; //no more bytes 103 }