UNPKG

lifehash

Version:

TypeScript/JavaScript implementation of LifeHash, a visual hash algorithm

46 lines (45 loc) 1.09 kB
export class BitEnumerator { constructor(data) { this.data = data; this.index = 0; this.mask = 128; } has_next() { return this.mask !== 0 || this.index !== this.data.length - 1; } next() { if (!this.has_next()) { throw new Error('BitEnumerator underflow.'); } if (this.mask === 0) { this.mask = 128; this.index += 1; } const b = (this.data[this.index] & this.mask) !== 0; this.mask >>= 1; return b; } next_configurable(bitMask, bits) { let val = 0; let m = bitMask; for (let i = 0; i < bits; i += 1) { if (this.next()) { val |= m; } m >>= 1; } return val; } next_uint2() { return this.next_configurable(2, 2); } next_uint8() { return this.next_configurable(128, 8); } next_uint16() { return this.next_configurable(32768, 16); } next_frac() { return this.next_uint16() / 65535.0; } }