All files reader.ts

100% Statements 31/31
100% Branches 6/6
100% Functions 11/11
100% Lines 29/29

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      1x 5x 5x 5x   5x   1x 2658x     1x 201x 201x     1x 113x     1x 3x     1x 795x 795x     1x 926x         1x 812x 3x   809x   32833x         1x 577x 576x 576x   1x  
/**
 * Read bytes from a Uint8Array.
 */
export class Reader {
  private _offset = 0
  private currentClamp = 0
  private textDecoder = new (typeof TextDecoder !== "undefined" ? TextDecoder : require("text-encoding").TextDecoder)()
 
  public constructor(private readonly array: Uint8Array) {}
 
  public get offset(): number {
    return this._offset
  }
 
  public skip(amount: number): this {
    this._offset += amount
    return this
  }
 
  public clamp(): void {
    this.currentClamp = this._offset
  }
 
  public unclamp(): void {
    this.currentClamp = 0
  }
 
  public jump(offset: number): this {
    this._offset = offset + this.currentClamp
    return this
  }
 
  public eof(): boolean {
    return this.offset >= this.array.length
  }
 
  public peek(amount: number): Uint8Array
  public peek(amount: number, encoding: "utf8"): string
  public peek(amount: number, encoding?: "utf8"): Uint8Array | string {
    if (this.eof()) {
      throw new Error("EOF")
    }
    const data = this.array.slice(this.offset, this.offset + amount)
    // There may be nil bytes used as padding which we'll remove.
    return encoding ? this.textDecoder.decode(data.filter((byte) => byte !== 0x00)) : data
  }
 
  public read(amount: number): Uint8Array
  public read(amount: number, encoding: "utf8"): string
  public read(amount: number, encoding?: "utf8"): Uint8Array | string {
    const data = this.peek(amount, encoding as any) // eslint-disable-line @typescript-eslint/no-explicit-any
    this._offset += amount
    return data
  }
}