1 module as.stream; 2 import as.def; 3 import core.stdc..string : memcpy; 4 import core.stdc.stdlib : free; 5 6 struct BinaryStream { 7 private: 8 size_t readOffset; 9 10 package(as): 11 asIBinaryStream* stream; 12 13 public: 14 15 /** 16 Creates a new stream 17 */ 18 static BinaryStream* create() { 19 BinaryStream* bstr = new BinaryStream; 20 bstr.stream = asStream_Create(&binaryRead, &binaryWrite, bstr); 21 return bstr; 22 } 23 24 /** 25 Destructor 26 */ 27 ~this() { 28 free(stream); 29 } 30 31 /** 32 Rewinds back to the beginning of the buffer 33 */ 34 void rewind() { 35 readOffset = 0; 36 } 37 38 /** 39 Gets how far has been read in to the buffer 40 */ 41 size_t tell() { 42 return readOffset; 43 } 44 45 /** 46 The buffer 47 */ 48 ubyte[] buffer; 49 } 50 51 package(as) { 52 extern(C): 53 int binaryRead(void* ptr, asUINT size, void* param) { 54 BinaryStream* stream = cast(BinaryStream*)param; 55 56 assert(size <= stream.buffer.length, "Tried copying contents larger than buffer"); 57 58 // Copy stream data to ptr 59 memcpy(ptr, &stream.buffer[stream.readOffset], size); 60 61 // Increase read offset 62 stream.readOffset += size; 63 64 // No errors 65 return 0; 66 } 67 68 int binaryWrite(const(void)* ptr, asUINT size, void* param) { 69 BinaryStream* stream = cast(BinaryStream*)param; 70 71 // Resize data to fit 72 size_t start = stream.buffer.length; 73 stream.buffer.length += size; 74 75 // Get the stream data 76 memcpy(&stream.buffer[start], ptr, size); 77 78 // No errors 79 return 0; 80 } 81 }