@kikuchan/binary-reader
Version:
binary-reader
2 lines (1 loc) • 1.53 kB
JavaScript
"use strict";export class BinaryReader{#t;#e;constructor(t){t instanceof ArrayBuffer?this.#t=new DataView(t):this.#t=new DataView(t.buffer,t.byteOffset,t.byteLength),this.#e=0}get position(){return this.#e}get size(){return this.#t.byteLength}get remain(){return this.size-this.position}eof(){return this.remain<=0}seek(t){return this.#e=t,this}skip(t){return this.#e+=Math.min(t??1,this.size-this.#e),this}align(t){return this.position%t?this.skip(t-this.position%t):this}peekBuffer(t){t===void 0&&(t=this.remain);const e=this.#t.byteOffset+this.position;return this.#t.buffer.slice(e,e+t)}readByte(){const t=this.#t.getUint8(this.position);return this.skip(1),t}readLe16(){const t=this.#t.getUint16(this.position,!0);return this.skip(2),t}readLe32(){const t=this.#t.getUint32(this.position,!0);return this.skip(4),t}readLe64(){const t=this.#t.getBigUint64(this.position,!0);return this.skip(8),t}readBe16(){const t=this.#t.getUint16(this.position,!1);return this.skip(2),t}readBe32(){const t=this.#t.getUint32(this.position,!1);return this.skip(4),t}readBe64(){const t=this.#t.getBigUint64(this.position,!1);return this.skip(8),t}readBytes(t){const e=this.peekBuffer(t);return e&&this.skip(e.byteLength),e}#i(){const t=this.remain;for(let e=0;e<t;e++)if(this.#t.getUint8(this.position+e)===0)return e}readString(t,e){const r=this.remain;let i=0;if(t===void 0&&(t=this.#i(),i=1),t===void 0||r<t)return;const s=this.peekBuffer(t);try{const n=new TextDecoder(e??"utf-8",{fatal:!0}).decode(s);return this.skip(t+i),n}catch{return}}}