| 406 | } |
| 407 | |
| 408 | export class Bitstream { |
| 409 | /** Current offset in bits. */ |
| 410 | pos = 0; |
| 411 | |
| 412 | constructor(public bytes: Uint8Array) {} |
| 413 | |
| 414 | seekToByte(byteOffset: number) { |
| 415 | this.pos = 8 * byteOffset; |
| 416 | } |
| 417 | |
| 418 | private readBit() { |
| 419 | const byteIndex = Math.floor(this.pos / 8); |
| 420 | const byte = this.bytes[byteIndex] ?? 0; |
| 421 | const bitIndex = 0b111 - (this.pos & 0b111); |
| 422 | const bit = (byte & (1 << bitIndex)) >> bitIndex; |
| 423 | |
| 424 | this.pos++; |
| 425 | return bit; |
| 426 | } |
| 427 | |
| 428 | readBits(n: number) { |
| 429 | if (n === 1) { |
| 430 | return this.readBit(); |
| 431 | } |
| 432 | |
| 433 | let result = 0; |
| 434 | |
| 435 | for (let i = 0; i < n; i++) { |
| 436 | result <<= 1; |
| 437 | result |= this.readBit(); |
| 438 | } |
| 439 | |
| 440 | return result; |
| 441 | } |
| 442 | |
| 443 | writeBits(n: number, value: number) { |
| 444 | const end = this.pos + n; |
| 445 | |
| 446 | for (let i = this.pos; i < end; i++) { |
| 447 | const byteIndex = Math.floor(i / 8); |
| 448 | let byte = this.bytes[byteIndex]; |
| 449 | const bitIndex = 0b111 - (i & 0b111); |
| 450 | |
| 451 | byte &= ~(1 << bitIndex); |
| 452 | byte |= ((value & (1 << (end - i - 1))) >> (end - i - 1)) << bitIndex; |
| 453 | this.bytes[byteIndex] = byte; |
| 454 | } |
| 455 | |
| 456 | this.pos = end; |
| 457 | }; |
| 458 | |
| 459 | readAlignedByte() { |
| 460 | // Ensure we're byte-aligned |
| 461 | if (this.pos % 8 !== 0) { |
| 462 | throw new Error('Bitstream is not byte-aligned.'); |
| 463 | } |
| 464 | |
| 465 | const byteIndex = this.pos / 8; |
nothing calls this directly
no outgoing calls
no test coverage detected