1 module libs.marshal.binary_demarshaller; 2 3 import std.conv, std.algorithm, std.bitmanip; 4 import std.stdio; 5 6 package interface IBinaryDemarshalerStorageStrategy 7 { 8 package: 9 immutable(ubyte[]) GetBuffer(); 10 void SetBuffer(immutable(ubyte[]) data); 11 12 T ReadVal(T)(); 13 } 14 15 public class InvalidFormattingException : Exception 16 { 17 this(string s) { super(s); } 18 } 19 20 package class BinaryDemarshallerStorageStrategy : IBinaryDemarshalerStorageStrategy 21 { 22 package: 23 this() {} 24 25 this(const(ubyte[]) data) 26 { 27 SetBuffer(data); 28 } 29 30 final const(ubyte[]) GetBuffer() 31 { 32 return m_buffer.idup; 33 } 34 35 final void SetBuffer(const(ubyte)[] data) 36 { 37 m_buffer = data.dup; 38 m_cursor = 0; 39 } 40 41 T ReadVal(T)() 42 { 43 T retval = m_buffer.peek!T(m_cursor); 44 m_cursor += T.sizeof; 45 // writefln("ReadVal!(%s) = %s", T.stringof, to!string(retval)); 46 return retval; 47 } 48 49 private: 50 51 ubyte[] m_buffer; 52 int m_cursor = 0; 53 54 unittest { 55 BinaryDemarshallerStorageStrategy tm = new BinaryDemarshallerStorageStrategy; 56 tm.SetBuffer([0, 0, 0, 10, 65, 51, 51, 51]); 57 58 auto i = tm.ReadVal!int(); 59 auto f = tm.ReadVal!float(); 60 61 assert( i == 10 ); 62 assert( f == 11.2f ); 63 64 } 65 }