buffer-reader.ts
1 const emptyBuffer = Buffer.allocUnsafe(0) 2 3 export class BufferReader { 4 private buffer: Buffer = emptyBuffer 5 6 // TODO(bmc): support non-utf8 encoding? 7 private encoding: string = 'utf-8' 8 9 constructor(private offset: number = 0) {} 10 11 public setBuffer(offset: number, buffer: Buffer): void { 12 this.offset = offset 13 this.buffer = buffer 14 } 15 16 public int16(): number { 17 const result = this.buffer.readInt16BE(this.offset) 18 this.offset += 2 19 return result 20 } 21 22 public byte(): number { 23 const result = this.buffer[this.offset] 24 this.offset++ 25 return result 26 } 27 28 public int32(): number { 29 const result = this.buffer.readInt32BE(this.offset) 30 this.offset += 4 31 return result 32 } 33 34 public uint32(): number { 35 const result = this.buffer.readUInt32BE(this.offset) 36 this.offset += 4 37 return result 38 } 39 40 public string(length: number): string { 41 const result = this.buffer.toString(this.encoding, this.offset, this.offset + length) 42 this.offset += length 43 return result 44 } 45 46 public cstring(): string { 47 const start = this.offset 48 let end = start 49 // eslint-disable-next-line no-empty 50 while (this.buffer[end++] !== 0) {} 51 this.offset = end 52 return this.buffer.toString(this.encoding, start, end - 1) 53 } 54 55 public bytes(length: number): Buffer { 56 const result = this.buffer.slice(this.offset, this.offset + length) 57 this.offset += length 58 return result 59 } 60 }