"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.VarIntProcessor = void 0;
exports.serializeVarint = serializeVarint;
const util_1 = require("../../util");
const msb = 0x80;
const dropMsb = 0x7f;
const maxSize = Math.floor((8 * 8 + 7) / 7);
class VarIntProcessor {
    constructor() {
        this.buf = new Uint8Array(maxSize);
        this.i = 0;
    }
    push(b) {
        if (this.i >= maxSize) {
            throw new Error('Unterminated varint');
        }
        this.buf[this.i] = b;
        this.i += 1;
    }
    finished() {
        return this.i > 0 && (this.buf[this.i - 1] & msb) === 0;
    }
    decode() {
        let result = 0;
        let shift = 0;
        let success = false;
        for (let i = 0; i < this.i; i++) {
            const b = this.buf[i];
            const msbDropped = b & dropMsb;
            result |= msbDropped << shift;
            shift += 7;
            if ((b & msb) == 0 || shift > 9 * 7) {
                success = (b & msb) === 0;
                break;
            }
        }
        if (success) {
            return result;
        }
        else {
            console.error((0, util_1.asError)(this.buf));
            return null;
        }
    }
}
exports.VarIntProcessor = VarIntProcessor;
function serializeVarint(int) {
    const buf = new Uint8Array(maxSize);
    let n = int;
    let i = 0;
    while (n >= msb) {
        buf[i] = msb | n;
        i += 1;
        n >>= 7;
    }
    buf[i] = n;
    i += 1;
    return buf.slice(0, i).buffer;
}
//# sourceMappingURL=varint.js.map