/** Sequential little-endian reader over a byte array, with the format's variable-length integers. */ import { BlkFormatError } from '../errors.ts'; export class ByteReader { readonly bytes: Uint8Array; offset = 0; constructor(bytes: Uint8Array) { this.bytes = bytes; } get remaining(): number { return this.bytes.length - this.offset; } u8(): number { this.require(1); return this.bytes[this.offset++]!; } take(length: number): Uint8Array { this.require(length); const slice = this.bytes.subarray(this.offset, this.offset + length); this.offset += length; return slice; } /** Unsigned LEB128: 7 bits per byte, least significant group first, high bit = more bytes follow. */ varUint(): number { let value = 0; for (let shift = 0; shift < 35; shift += 7) { const byte = this.u8(); value += (byte & 0x7f) * 2 ** shift; if ((byte & 0x80) === 0) return value; } throw new BlkFormatError(`variable-length integer at offset ${this.offset} is too long`); } private require(length: number): void { if (length > this.remaining) { throw new BlkFormatError(`unexpected end of data: need ${length} bytes at offset ${this.offset}, have ${this.remaining}`); } } }