1 /** 2 Copyright: Copyright (c) 2016-2018 Andrey Penechko. 3 License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0). 4 Authors: Andrey Penechko. 5 */ 6 module voxelman.utils.filewriter; 7 8 import std.stdio : File; 9 10 struct FileWriter 11 { 12 File file; 13 14 enum CAPACITY = 4096; 15 ubyte[CAPACITY] buffer; 16 size_t length; 17 18 void put(ubyte[] data ...) 19 { 20 size_t cap = capacity; 21 if (data.length > cap) 22 { 23 size_t writeOffset; 24 25 // fill buffer till CAPACITY 26 if (length > 0) 27 { 28 buffer[length..$] = data[0..cap]; 29 file.rawWrite(buffer); 30 writeOffset = cap; 31 } 32 33 size_t writeLength = ((data.length - writeOffset) / CAPACITY) * CAPACITY; 34 size_t writeTo = writeOffset+writeLength; 35 if (writeLength) 36 file.rawWrite(data[writeOffset..writeTo]); 37 38 size_t writeLater = data.length - writeTo; 39 if (writeLater) 40 { 41 buffer[0..writeLater] = data[writeTo..$]; 42 length = writeLater; 43 } 44 else 45 { 46 length = 0; 47 } 48 } 49 else 50 { 51 buffer[length..length+data.length] = data; 52 length += data.length; 53 } 54 } 55 56 void flush() { 57 if (length) { 58 file.rawWrite(buffer[0..length]); 59 length = 0; 60 } 61 } 62 63 size_t capacity() { return CAPACITY - length; } 64 }