index.js (2142B)
1 import utf8 from 'utf8'; 2 3 class BinStream { 4 constructor(littlEndian) { 5 this.maxSize = 1024; 6 this.dv = new DataView(new ArrayBuffer(this.maxSize)); 7 this._pos = 0; 8 this.size = 0; 9 this.littlEndian = littlEndian; 10 } 11 12 grow() { 13 this.maxSize *= 2; 14 const oldBuffer = this.dv.buffer; 15 this.dv = new DataView(new ArrayBuffer(this.maxSize)); 16 const newAr = new Uint8Array(this.dv.buffer); 17 const oldAr = new Uint8Array(oldBuffer); 18 for (let i = 0; i < oldAr.length; i++) { 19 newAr[i] = oldAr[i]; 20 } 21 } 22 23 checkSize(size) { 24 if (this._pos + size >= this.maxSize) { 25 this.grow(); 26 } 27 const newPos = this._pos + size; 28 this.size = newPos > this.size ? newPos : this.size; 29 } 30 31 writeUint8(value) { 32 this.checkSize(1); 33 this.dv.setUint8(this._pos, value); 34 this._pos += 1; 35 } 36 37 writeInt8(value) { 38 this.checkSize(1); 39 this.dv.setInt8(this._pos, value); 40 this._pos += 1; 41 } 42 43 writeInt16(value) { 44 this.checkSize(2); 45 this.dv.setInt16(this._pos, value, this.littlEndian); 46 this._pos += 2; 47 } 48 49 writeUint16(value) { 50 this.checkSize(2); 51 this.dv.setUint16(this._pos, value, this.littlEndian); 52 this._pos += 2; 53 } 54 55 writeInt32(value) { 56 this.checkSize(4); 57 this.dv.setInt32(this._pos, value, this.littlEndian); 58 this._pos += 4; 59 } 60 61 writeUint32(value) { 62 this.checkSize(4); 63 this.dv.setUint32(this._pos, value, this.littlEndian); 64 this._pos += 4; 65 } 66 67 writeBinaryString(s) { 68 for (let i = 0; i < s.length; i++) { 69 this.writeUint8(s.charCodeAt(i)); 70 } 71 } 72 73 writeString(s, zeroTerminated) { 74 this.writeBinaryString(utf8.encode(s)); 75 if (zeroTerminated) { 76 this.writeUint8(0); 77 } 78 } 79 80 tell() { 81 return this._pos; 82 } 83 84 seek(pos) { 85 this._pos = pos; 86 } 87 88 getBuffer() { 89 return this.dv.buffer.slice(0, this.size); 90 } 91 } 92 93 export {BinStream};