65 lines
1.5 KiB
JavaScript
65 lines
1.5 KiB
JavaScript
/* Minimal stateful binary reader over a Uint8Array, similar in spirit to jBinary/binary-parser readers. */
|
|
export class BinaryReader {
|
|
constructor(data) {
|
|
if (!(data instanceof Uint8Array))
|
|
throw new TypeError("Uint8Array required");
|
|
this.data = data;
|
|
this.view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
|
this.pos = 0;
|
|
}
|
|
get remaining() {
|
|
return this.data.length - this.pos;
|
|
}
|
|
seek(pos) {
|
|
this.pos = pos;
|
|
return this;
|
|
}
|
|
skip(n) {
|
|
this.pos += n;
|
|
return this;
|
|
}
|
|
readUint8() {
|
|
const v = this.view.getUint8(this.pos);
|
|
this.pos += 1;
|
|
return v;
|
|
}
|
|
readInt8() {
|
|
const v = this.view.getInt8(this.pos);
|
|
this.pos += 1;
|
|
return v;
|
|
}
|
|
readUint16LE() {
|
|
const v = this.view.getUint16(this.pos, true);
|
|
this.pos += 2;
|
|
return v;
|
|
}
|
|
readUint16BE() {
|
|
const v = this.view.getUint16(this.pos, false);
|
|
this.pos += 2;
|
|
return v;
|
|
}
|
|
readUint32LE() {
|
|
const v = this.view.getUint32(this.pos, true);
|
|
this.pos += 4;
|
|
return v;
|
|
}
|
|
readUint32BE() {
|
|
const v = this.view.getUint32(this.pos, false);
|
|
this.pos += 4;
|
|
return v;
|
|
}
|
|
readBytes(n) {
|
|
const v = this.data.slice(this.pos, this.pos + n);
|
|
this.pos += n;
|
|
return v;
|
|
}
|
|
readCString(maxLen = this.remaining) {
|
|
const start = this.pos;
|
|
let end = start;
|
|
while (end < start + maxLen && this.data[end] !== 0) end++;
|
|
const text = new TextDecoder().decode(this.data.slice(start, end));
|
|
this.pos = Math.min(end + 1, this.data.length);
|
|
return text;
|
|
}
|
|
}
|