1 module hunt.serialization.BinaryDeserializer;
2 
3 import hunt.serialization.Common;
4 import hunt.serialization.Specify;
5 import std.traits;
6 
7 /**
8  * 
9  */
10 struct BinaryDeserializer {
11 
12     private {
13         const(ubyte)[] _buffer;
14     }
15 
16     this(ubyte[] buffer) {
17         this._buffer = buffer;
18     }
19 
20     const(ubyte[]) bytes() const nothrow {
21         return _buffer;
22     }
23 
24     ulong bytesLeft() const {
25         return _buffer.length;
26     }
27 
28     T iArchive(SerializationOptions options, T)()
29             if (!isDynamicArray!T && !isAssociativeArray!T && !is(T == class) && __traits(compiles, T())) {
30         T obj;
31         specify!(options)(this, obj);
32         return obj;
33     }
34 
35     T iArchive(SerializationOptions options, T)()
36             if (!isDynamicArray!T && !isAssociativeArray!T && !is(T == class)
37                 && !__traits(compiles, T())) {
38         T obj = void;
39         specify!(options)(this, obj);
40         return obj;
41     }
42 
43     T iArchive(SerializationOptions options, T, A...)(A args) if (is(T == class)) {
44         T obj = new T(args);
45         specify!(options)(this, obj);
46         return obj;
47     }
48 
49     T iArchive(SerializationOptions options, T)() if (isDynamicArray!T || isAssociativeArray!T) {
50         return iArchive!(options, T, ushort)();
51     }
52 
53     T iArchive(SerializationOptions options, T, U)() if (isDynamicArray!T || isAssociativeArray!T) {
54         T obj;
55         specify!(options)(this, obj);
56         return obj;
57     }
58 
59     void putUbyte(ref ubyte val) {
60         val = _buffer[0];
61         _buffer = _buffer[1 .. $];
62     }
63 
64     void putClass(SerializationOptions options, T)(T val) if (is(T == class)) {
65         specifyClass!(options)(this, val);
66     }
67 
68     deprecated("Using take instead.")
69     alias putRaw = take;
70 
71     const(ubyte)[] take(size_t length) {
72         const(ubyte)[] res = _buffer[0 .. length];
73         _buffer = _buffer[length .. $];
74         return res;
75     }
76 
77     // T takeAs(T, SerializationOptions options)() 
78     //     if (!is(T == enum) && (isSigned!T || isBoolean!T || is(T == char) || isFloatingPoint!T)) {
79     //     T r;
80     //     // T* val = &r;
81 
82     //     // ubyte val0 = (val >> 24);
83     //     // ubyte val1 = cast(ubyte)(val >> 16);
84     //     // ubyte val2 = cast(ubyte)(val >> 8);
85     //     // ubyte val3 = val & 0xff;
86     //     // putUbyte(val0);
87     //     // putUbyte(val1);
88     //     // putUbyte(val2);
89     //     // putUbyte(val3);
90     //     // val = (val0 << 24) + (val1 << 16) + (val2 << 8) + val3;
91     //     return r;
92     // }
93 
94     // T takeAs(T, SerializationOptions options)() {
95     //     return T.init;
96     // }
97 
98     bool isNullObj() {
99         return _buffer[0 .. 4] == NULL ? true : false;
100     }
101 }