nakarte

Source code of https://map.sikmir.ru (fork)
git clone git://git.sikmir.ru/nakarte
Log | Files | Refs | LICENSE

binary-stream.js (2098B)


      1 import utf8 from 'utf8';
      2 
      3 class BinStream {
      4     constructor(size, 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 old_buffer = 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(old_buffer);
     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     writeString(s, zeroTerminated) {
     68         s = utf8.encode(s);
     69         for (let i = 0; i < s.length; i++) {
     70             this.writeUint8(s.charCodeAt(i));
     71         }
     72         if (zeroTerminated) {
     73             this.writeUint8(0);
     74         }
     75     }
     76 
     77     tell() {
     78         return this._pos;
     79     }
     80 
     81     seek(pos) {
     82         this._pos = pos;
     83     }
     84 
     85     getBuffer() {
     86         return this.dv.buffer.slice(0, this.size);
     87     }
     88 }
     89 
     90 export {BinStream};