| 24 | * The buffer must remain valid and unmodified for the reader's lifetime. |
| 25 | */ |
| 26 | export class BinaryReader { |
| 27 | private readonly bytes: Uint8Array; |
| 28 | private readonly dv: DataView; |
| 29 | private off = 0; |
| 30 | |
| 31 | constructor(bytes: Uint8Array) { |
| 32 | this.bytes = bytes; |
| 33 | this.dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); |
| 34 | } |
| 35 | |
| 36 | get offset(): number { |
| 37 | return this.off; |
| 38 | } |
| 39 | |
| 40 | get byteLength(): number { |
| 41 | return this.bytes.byteLength; |
| 42 | } |
| 43 | |
| 44 | get remaining(): number { |
| 45 | return this.byteLength - this.off; |
| 46 | } |
| 47 | |
| 48 | /** Validate that offset is 4-byte aligned; throws ZR_MISALIGNED on violation. */ |
| 49 | ensureAligned4(offset: number = this.off): void { |
| 50 | if ((offset & 3) !== 0) { |
| 51 | throw new ZrBinaryError({ |
| 52 | code: "ZR_MISALIGNED", |
| 53 | offset, |
| 54 | detail: "offset must be 4-byte aligned", |
| 55 | }); |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | /** Advance cursor by len bytes without reading; validates bounds first. */ |
| 60 | skip(len: number): void { |
| 61 | if (!Number.isInteger(len) || len < 0) { |
| 62 | throw new Error(`BinaryReader.skip: len must be a non-negative integer (got ${String(len)})`); |
| 63 | } |
| 64 | this.ensureAvailable(len); |
| 65 | this.off += len; |
| 66 | } |
| 67 | |
| 68 | /** Read unsigned 8-bit integer, advancing cursor by 1 byte. */ |
| 69 | readU8(): number { |
| 70 | this.ensureAvailable(1); |
| 71 | const v = this.dv.getUint8(this.off); |
| 72 | this.off += 1; |
| 73 | return v; |
| 74 | } |
| 75 | |
| 76 | /** Read unsigned 32-bit integer (little-endian), advancing cursor by 4 bytes. */ |
| 77 | readU32(): number { |
| 78 | this.ensureAvailable(4); |
| 79 | const v = this.dv.getUint32(this.off, true); |
| 80 | this.off += 4; |
| 81 | return v; |
| 82 | } |
| 83 |
nothing calls this directly
no outgoing calls
no test coverage detected