1 module utils.binary.funcs; 2 3 import 4 std.mmfile, 5 6 utils.except, 7 utils.binary; 8 9 // ----------------------------------------- READ FUNCTIONS ----------------------------------------- 10 11 auto binaryRead(T)(in void[] data, bool canRest = false, string f = __FILE__, uint l = __LINE__) 12 { 13 auto r = data.BinaryReader!MemoryReader; 14 auto v = r.read!T(f, l); 15 16 !r.reader.length || canRest || throwError!`not all the buffer was parsed, %s bytes rest`(f, l, r.reader.length); 17 return v; 18 } 19 20 auto binaryReadFile(T)(string name, string f = __FILE__, uint l = __LINE__) 21 { 22 auto m = new MmFile(name); 23 24 try 25 { 26 return m[].binaryRead!T(false, f, l); 27 } 28 finally 29 { 30 m.destroy; 31 } 32 } 33 34 // ----------------------------------------- WRITE FUNCTIONS ----------------------------------------- 35 36 const(void)[] binaryWrite(T)(auto ref in T data, string f = __FILE__, uint l = __LINE__) 37 { 38 return BinaryReader!AppendWriter().write(data, f, l).reader.data; 39 } 40 41 void binaryWrite(T)(void[] buf, auto ref in T data, bool canRest = false, string f = __FILE__, uint l = __LINE__) 42 { 43 auto r = buf.BinaryReader!MemoryReader; 44 r.write(data, f, l); 45 46 !r.reader.length || canRest || throwError!`not all the buffer was used, %u bytes rest`(f, l, r.reader.length); 47 } 48 49 void binaryWriteFile(T)(string name, auto ref in T data, string f = __FILE__, uint l = __LINE__) 50 { 51 auto len = binaryWriteLen(data, f, l); 52 auto m = new MmFile(name, MmFile.Mode.readWriteNew, len, null); 53 54 try 55 { 56 binaryWrite(m[], data, false, f, l); 57 } 58 finally 59 { 60 m.destroy; 61 } 62 } 63 64 // ----------------------------------------- OTHER FUNCTIONS ----------------------------------------- 65 66 auto binaryWriteLen(T)(auto ref in T data, string f = __FILE__, uint l = __LINE__) 67 { 68 struct LengthCalc 69 { 70 bool write(in ubyte[] v) 71 { 72 length += v.length; 73 return true; 74 } 75 76 bool wskip(uint cnt) 77 { 78 length += cnt; 79 return true; 80 } 81 82 uint length; 83 } 84 85 return BinaryReader!LengthCalc().write(data, f, l).reader.length; 86 }