All files / src/parsers binary-reader.ts

51.42% Statements 18/35
0% Branches 0/1
60% Functions 6/10
51.42% Lines 18/35

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 721x   1x 2x   2x     12x 12x 12x 12x                                   26x 26x 26x 26x       2x 2x 2x 2x                                 12x       40x                      
import base58 from 'bs58';
 
export class BinaryReader {
  private offset = 0;
 
  constructor(private buffer: Buffer) {}
 
  readFixedArray(length: number): Buffer {
    this.checkBounds(length);
    const array = this.buffer.slice(this.offset, this.offset + length);
    this.offset += length;
    return array;
  }
 
  readU8(): number {
    this.checkBounds(1);
    const value = this.buffer.readUInt8(this.offset);
    this.offset += 1;
    return value;
  }
 
  readU16(): number {
    this.checkBounds(2);
    const value = this.buffer.readUint16LE(this.offset);
    this.offset += 2;
    return value;
  }
 
  readU64(): bigint {
    this.checkBounds(8);
    const value = this.buffer.readBigUInt64LE(this.offset);
    this.offset += 8;
    return value;
  }
 
  readI64(): bigint {
    this.checkBounds(8);
    const value = this.buffer.readBigInt64LE(this.offset);
    this.offset += 8;
    return value;
  }
 
  readString(): string {
    // Read 4-byte (32-bit) length instead of 1 byte
    const length = this.buffer.readUInt32LE(this.offset);
    this.offset += 4;
 
    this.checkBounds(length);
    const strBuffer = this.buffer.slice(this.offset, this.offset + length);
    const content = strBuffer.toString('utf8');
    this.offset += length;
 
    return content;
  }
 
  readPubkey(): string {
    return base58.encode(Buffer.from(this.readFixedArray(32)));
  }
 
  private checkBounds(length: number) {
    Iif (this.offset + length > this.buffer.length) {
      throw new Error(
        `Buffer overflow: trying to read ${length} bytes at offset ${this.offset} in buffer of length ${this.buffer.length}`
      );
    }
  }
 
  getOffset(): number {
    return this.offset;
  }
}