UNPKG

blitflash

Version:

A JavaScript implementation of the 32blit flash tools

65 lines (64 loc) 2.28 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RandomAccessReader = void 0; class RandomAccessReader { constructor(buffer) { this.buffer = buffer; this.textdecoder = new TextDecoder(); this.currentPos = 0; this.dataview = new DataView(buffer); } read(length) { if (this.currentPos + length > this.dataview.byteLength) { throw new Error(`Tried to read beyond length. pos: ${this.currentPos}, buffer byteLength: ${this.dataview.byteLength}, length: ${length} `); } const result = this.buffer.slice(this.currentPos, this.currentPos + length); this.currentPos += length; return result; } readUint8() { if (this.currentPos + 1 >= this.dataview.byteLength) { throw new Error('Tried to read beyond length.'); } const value = this.dataview.getUint8(this.currentPos); this.currentPos += 1; return value; } readUint16(littleEndian) { if (this.currentPos + 2 >= this.dataview.byteLength) { throw new Error('Tried to read beyond length.'); } const value = this.dataview.getUint16(this.currentPos, littleEndian); this.currentPos += 2; return value; } readUint32(littleEndian) { if (this.currentPos + 4 >= this.dataview.byteLength) { throw new Error('Tried to read beyond length.'); } const value = this.dataview.getUint32(this.currentPos, littleEndian); this.currentPos += 4; return value; } readString(length) { const data = new Uint8Array(this.read(length)); let end = data.findIndex((value) => value === 0); if (end === -1) { end = length; } return this.textdecoder.decode(data.slice(0, end)); } getPos() { return this.currentPos; } setPos(newPos) { if (newPos >= this.dataview.byteLength) { throw new Error('Cant set position beyond length.'); } this.currentPos = newPos; } byteLength() { return this.dataview.byteLength; } } exports.RandomAccessReader = RandomAccessReader;