UNPKG

@devgrid/smartbuffer

Version:
1,984 lines • 74.8 kB
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SmartBuffer = exports.isSmartBuffer = void 0;
const long_1 = __importDefault(require("long"));
const utfx = __importStar(require("utfx"));
const buffer_1 = require("buffer");
const EMPTY_BUFFER = buffer_1.Buffer.allocUnsafe(0);
const _isString = (value) => typeof value === 'string' || value instanceof String;
const stringSource = (s) => {
    let i = 0;
    return () => (i < s.length ? s.charCodeAt(i++) : null);
};
const stringDestination = () => {
    const cs = [];
    const ps = [];
    return (...args) => {
        if (args.length === 0) {
            return `${ps.join('')}${String.fromCharCode(...cs)}`;
        }
        if (cs.length + args.length > 1024) {
            ps.push(String.fromCharCode(...cs));
            cs.length = 0;
        }
        cs.push(...args);
    };
};
const isSmartBuffer = (obj) => obj instanceof SmartBuffer;
exports.isSmartBuffer = isSmartBuffer;
class SmartBuffer {
    static { this.EMPTY_BUFFER = EMPTY_BUFFER; }
    static { this.DEFAULT_CAPACITY = 64; }
    static { this.DEFAULT_NOASSERT = false; }
    static { this.MAX_VARINT32_BYTES = 5; }
    static { this.MAX_VARINT64_BYTES = 10; }
    static { this.METRICS_CHARS = 'c'; }
    static { this.METRICS_BYTES = 'b'; }
    constructor(capacity, noAssert = SmartBuffer.DEFAULT_NOASSERT) {
        this.woffset = 0;
        this.roffset = 0;
        let lCapacity = capacity === void 0 || Number.isNaN(capacity) ? SmartBuffer.DEFAULT_CAPACITY : capacity;
        if (!noAssert) {
            lCapacity |= 0;
            if (lCapacity < 0) {
                throw new TypeError('Illegal capacity');
            }
            noAssert = Boolean(noAssert);
        }
        this.buffer = lCapacity === 0 ? EMPTY_BUFFER : buffer_1.Buffer.allocUnsafe(lCapacity);
        this.noAssert = noAssert;
    }
    get length() {
        return this.woffset - this.roffset;
    }
    get capacity() {
        return this.buffer.length;
    }
    readBitSet(offset) {
        let loffset = offset ?? this.roffset;
        const ret = this.readVarint32(loffset);
        const bits = ret.value;
        let bytes = bits >> 3;
        let bit = 0;
        const value = [];
        let k;
        loffset += ret.length;
        while (bytes--) {
            k = this.readInt8(loffset++);
            value[bit++] = Boolean(k & 0x01);
            value[bit++] = Boolean(k & 0x02);
            value[bit++] = Boolean(k & 0x04);
            value[bit++] = Boolean(k & 0x08);
            value[bit++] = Boolean(k & 0x10);
            value[bit++] = Boolean(k & 0x20);
            value[bit++] = Boolean(k & 0x40);
            value[bit++] = Boolean(k & 0x80);
        }
        if (bit < bits) {
            let m = 0;
            k = this.readInt8(loffset++);
            while (bit < bits) {
                value[bit++] = Boolean((k >> m++) & 1);
            }
        }
        if (offset === void 0) {
            this.roffset = loffset;
        }
        return value;
    }
    read(length, offset) {
        let loffset = offset ?? this.roffset;
        if (!this.noAssert) {
            if (typeof loffset !== 'number' || loffset % 1 !== 0) {
                throw new TypeError(`Illegal offset: ${loffset} (not an integer)`);
            }
            loffset >>>= 0;
            if (loffset < 0 || loffset + length > this.buffer.length) {
                throw new TypeError(`Illegal offset: 0 <= ${loffset} (${length}) <= ${this.buffer.length}`);
            }
        }
        const slice = this.slice(offset, loffset + length);
        if (offset === void 0) {
            this.roffset += length;
        }
        return slice;
    }
    readInt8(offset) {
        const loffset = this._checkRead(1, offset);
        let value = this.buffer[loffset];
        if ((value & 0x80) === 0x80) {
            value = -(0xff - value + 1);
        }
        return value;
    }
    readUInt8(offset) {
        const loffset = this._checkRead(1, offset);
        return this.buffer[loffset];
    }
    readInt16LE(offset) {
        const loffset = this._checkRead(2, offset);
        let value = 0;
        value = this.buffer[loffset];
        value |= this.buffer[loffset + 1] << 8;
        if ((value & 0x8000) === 0x8000) {
            value = -(0xffff - value + 1);
        }
        return value;
    }
    readInt16BE(offset) {
        const loffset = this._checkRead(2, offset);
        let value = 0;
        value = this.buffer[loffset] << 8;
        value |= this.buffer[loffset + 1];
        if ((value & 0x8000) === 0x8000) {
            value = -(0xffff - value + 1);
        }
        return value;
    }
    readUInt16LE(offset) {
        const loffset = this._checkRead(2, offset);
        let value = 0;
        value = this.buffer[loffset];
        value |= this.buffer[loffset + 1] << 8;
        return value;
    }
    readUInt16BE(offset) {
        const loffset = this._checkRead(2, offset);
        let value = 0;
        value = this.buffer[loffset] << 8;
        value |= this.buffer[loffset + 1];
        return value;
    }
    readUInt24BE(offset) {
        const loffset = this._checkRead(3, offset);
        let value = 0;
        value = this.buffer[loffset] << 16;
        value |= this.buffer[loffset + 1] << 8;
        value |= this.buffer[loffset + 2];
        value |= 0;
        return value;
    }
    readInt32LE(offset) {
        const loffset = this._checkRead(4, offset);
        let value = 0;
        value = this.buffer[loffset + 2] << 16;
        value |= this.buffer[loffset + 1] << 8;
        value |= this.buffer[loffset];
        value += (this.buffer[loffset + 3] << 24) >>> 0;
        value |= 0;
        return value;
    }
    readInt32BE(offset) {
        const loffset = this._checkRead(4, offset);
        let value = 0;
        value = this.buffer[loffset + 1] << 16;
        value |= this.buffer[loffset + 2] << 8;
        value |= this.buffer[loffset + 3];
        value += (this.buffer[loffset] << 24) >>> 0;
        value |= 0;
        return value;
    }
    readUInt32LE(offset) {
        const loffset = this._checkRead(4, offset);
        let value = 0;
        value = this.buffer[loffset + 2] << 16;
        value |= this.buffer[loffset + 1] << 8;
        value |= this.buffer[loffset];
        value += (this.buffer[loffset + 3] << 24) >>> 0;
        return value;
    }
    readUInt32BE(offset) {
        const loffset = this._checkRead(4, offset);
        let value = 0;
        value = this.buffer[loffset + 1] << 16;
        value |= this.buffer[loffset + 2] << 8;
        value |= this.buffer[loffset + 3];
        value += (this.buffer[loffset] << 24) >>> 0;
        return value;
    }
    readInt64LE(offset) {
        const loffset = this._checkRead(8, offset);
        let lo = 0;
        let hi = 0;
        lo = this.buffer[loffset + 2] << 16;
        lo |= this.buffer[loffset + 1] << 8;
        lo |= this.buffer[loffset];
        lo += (this.buffer[loffset + 3] << 24) >>> 0;
        hi = this.buffer[loffset + 6] << 16;
        hi |= this.buffer[loffset + 5] << 8;
        hi |= this.buffer[loffset + 4];
        hi += (this.buffer[loffset + 7] << 24) >>> 0;
        return new long_1.default(lo, hi, false);
    }
    readInt64BE(offset) {
        const loffset = this._checkRead(8, offset);
        let lo = 0;
        let hi = 0;
        hi = this.buffer[loffset + 1] << 16;
        hi |= this.buffer[loffset + 2] << 8;
        hi |= this.buffer[loffset + 3];
        hi += (this.buffer[loffset] << 24) >>> 0;
        lo = this.buffer[loffset + 5] << 16;
        lo |= this.buffer[loffset + 6] << 8;
        lo |= this.buffer[loffset + 7];
        lo += (this.buffer[loffset + 4] << 24) >>> 0;
        return new long_1.default(lo, hi, false);
    }
    readUInt64LE(offset) {
        const loffset = this._checkRead(8, offset);
        let lo = 0;
        let hi = 0;
        lo = this.buffer[loffset + 2] << 16;
        lo |= this.buffer[loffset + 1] << 8;
        lo |= this.buffer[loffset];
        lo += (this.buffer[loffset + 3] << 24) >>> 0;
        hi = this.buffer[loffset + 6] << 16;
        hi |= this.buffer[loffset + 5] << 8;
        hi |= this.buffer[loffset + 4];
        hi += (this.buffer[loffset + 7] << 24) >>> 0;
        return new long_1.default(lo, hi, true);
    }
    readUInt64BE(offset) {
        const loffset = this._checkRead(8, offset);
        let lo = 0;
        let hi = 0;
        hi = this.buffer[loffset + 1] << 16;
        hi |= this.buffer[loffset + 2] << 8;
        hi |= this.buffer[loffset + 3];
        hi += (this.buffer[loffset] << 24) >>> 0;
        lo = this.buffer[loffset + 5] << 16;
        lo |= this.buffer[loffset + 6] << 8;
        lo |= this.buffer[loffset + 7];
        lo += (this.buffer[loffset + 4] << 24) >>> 0;
        return new long_1.default(lo, hi, true);
    }
    readBigIntBE(offset) {
        const loffset = this._checkRead(8, offset);
        let value = (BigInt(this.buffer[loffset]) << 56n) |
            (BigInt(this.buffer[loffset + 1]) << 48n) |
            (BigInt(this.buffer[loffset + 2]) << 40n) |
            (BigInt(this.buffer[loffset + 3]) << 32n) |
            (BigInt(this.buffer[loffset + 4]) << 24n) |
            (BigInt(this.buffer[loffset + 5]) << 16n) |
            (BigInt(this.buffer[loffset + 6]) << 8n) |
            BigInt(this.buffer[loffset + 7]);
        if (value & (1n << 63n)) {
            value -= 1n << 64n;
        }
        return value;
    }
    readUBigIntBE(offset) {
        const loffset = this._checkRead(8, offset);
        const value = (BigInt(this.buffer[loffset]) << 56n) |
            (BigInt(this.buffer[loffset + 1]) << 48n) |
            (BigInt(this.buffer[loffset + 2]) << 40n) |
            (BigInt(this.buffer[loffset + 3]) << 32n) |
            (BigInt(this.buffer[loffset + 4]) << 24n) |
            (BigInt(this.buffer[loffset + 5]) << 16n) |
            (BigInt(this.buffer[loffset + 6]) << 8n) |
            BigInt(this.buffer[loffset + 7]);
        return value;
    }
    readBigIntLE(offset) {
        const loffset = this._checkRead(8, offset);
        let value = (BigInt(this.buffer[loffset]) << 0n) |
            (BigInt(this.buffer[loffset + 1]) << 8n) |
            (BigInt(this.buffer[loffset + 2]) << 16n) |
            (BigInt(this.buffer[loffset + 3]) << 24n) |
            (BigInt(this.buffer[loffset + 4]) << 32n) |
            (BigInt(this.buffer[loffset + 5]) << 40n) |
            (BigInt(this.buffer[loffset + 6]) << 48n) |
            (BigInt(this.buffer[loffset + 7]) << 56n);
        if (value & (1n << 63n)) {
            value -= 1n << 64n;
        }
        return value;
    }
    readUBigIntLE(offset) {
        const loffset = this._checkRead(8, offset);
        const value = (BigInt(this.buffer[loffset + 7]) << 56n) |
            (BigInt(this.buffer[loffset + 6]) << 48n) |
            (BigInt(this.buffer[loffset + 5]) << 40n) |
            (BigInt(this.buffer[loffset + 4]) << 32n) |
            (BigInt(this.buffer[loffset + 3]) << 24n) |
            (BigInt(this.buffer[loffset + 2]) << 16n) |
            (BigInt(this.buffer[loffset + 1]) << 8n) |
            BigInt(this.buffer[loffset]);
        return value;
    }
    readFloatLE(offset) {
        const loffset = this._checkRead(4, offset);
        return this.buffer.readFloatLE(loffset);
    }
    readFloatBE(offset) {
        const loffset = this._checkRead(4, offset);
        return this.buffer.readFloatBE(loffset);
    }
    readDoubleLE(offset) {
        const loffset = this._checkRead(8, offset);
        return this.buffer.readDoubleLE(loffset);
    }
    readDoubleBE(offset) {
        const loffset = this._checkRead(8, offset);
        return this.buffer.readDoubleBE(loffset);
    }
    write(source, offset, length, encoding = 'utf8') {
        let loffset = offset === void 0 ? this.woffset : offset;
        const result = loffset >>> 0;
        if (!this.noAssert) {
            if (typeof loffset !== 'number' || loffset % 1 !== 0) {
                throw new TypeError(`Illegal offset: ${loffset} (not an integer)`);
            }
            if (loffset < 0 || loffset + 0 > this.buffer.length) {
                throw new RangeError(`Illegal offset: 0 <= ${loffset} (0) <= ${this.buffer.length}`);
            }
        }
        let llength;
        const isString = _isString(source);
        if (isString) {
            llength = length || buffer_1.Buffer.byteLength(source);
        }
        else {
            if (!(source instanceof SmartBuffer)) {
                source = SmartBuffer.wrap(source, encoding);
            }
            llength = source.woffset - source.roffset;
        }
        if (llength <= 0) {
            return this;
        }
        loffset += llength;
        let capacity = this.buffer.length;
        if (loffset > capacity) {
            this.resize((capacity *= 2) > loffset ? capacity : loffset);
        }
        if (isString) {
            this.buffer.write(source, result);
        }
        else {
            source.buffer.copy(this.buffer, result, source.roffset, source.woffset);
            source.roffset += llength;
        }
        if (offset === void 0) {
            this.woffset += llength;
        }
        return this;
    }
    writeBitSet(value, offset) {
        let loffset = offset ?? this.woffset;
        if (!this.noAssert) {
            if (!Array.isArray(value)) {
                throw new TypeError('Illegal BitSet: Not an array');
            }
            if (typeof loffset !== 'number' || loffset % 1 !== 0) {
                throw new TypeError(`Illegal offset: ${loffset} (not an integer)`);
            }
            loffset >>>= 0;
            if (loffset < 0 || loffset + 0 > this.buffer.length) {
                throw new RangeError(`Illegal offset: 0 <= ${loffset} (0) <= ${this.buffer.length}`);
            }
        }
        const start = loffset;
        const bits = value.length;
        let bytes = bits >> 3;
        let bit = 0;
        let k;
        loffset += this.writeVarint32(bits, loffset);
        while (bytes--) {
            k =
                (!!value[bit++] & 1) |
                    (!!value[bit++] << 1) |
                    (!!value[bit++] << 2) |
                    (!!value[bit++] << 3) |
                    (!!value[bit++] << 4) |
                    (!!value[bit++] << 5) |
                    (!!value[bit++] << 6) |
                    (!!value[bit++] << 7);
            this.writeInt8(k, loffset++);
        }
        if (bit < bits) {
            let m = 0;
            k = 0;
            while (bit < bits) {
                k = k | (!!value[bit++] << m++);
            }
            this.writeInt8(k, loffset++);
        }
        if (offset === void 0) {
            this.woffset = loffset;
            return this;
        }
        return loffset - start;
    }
    writeBuffer(buf, offset) {
        if (buf.length === 0) {
            return this;
        }
        const relative = offset === void 0;
        const loffset = relative ? this.woffset : offset;
        const targetEnd = loffset + buf.length;
        let capacity = this.buffer.length;
        if (targetEnd > capacity) {
            capacity *= 2;
            this.resize(capacity > targetEnd ? capacity : targetEnd);
        }
        buf.copy(this.buffer, loffset);
        if (relative) {
            this.woffset = targetEnd;
        }
        return this;
    }
    writeInt8(value, offset) {
        const iValue = value | 0;
        const loffset = this._checkWrite(iValue, 1, offset);
        this.buffer[loffset] = iValue;
        return this;
    }
    writeUInt8(value, offset) {
        const uValue = value >>> 0;
        const loffset = this._checkWrite(uValue, 1, offset);
        this.buffer[loffset] = uValue;
        return this;
    }
    writeInt16LE(value, offset) {
        const iValue = value | 0;
        const loffset = this._checkWrite(iValue, 2, offset);
        this.buffer[loffset + 1] = iValue >>> 8;
        this.buffer[loffset] = iValue;
        return this;
    }
    writeInt16BE(value, offset) {
        const iValue = value | 0;
        const loffset = this._checkWrite(iValue, 2, offset);
        this.buffer[loffset] = iValue >>> 8;
        this.buffer[loffset + 1] = iValue;
        return this;
    }
    writeUInt16LE(value, offset) {
        const uValue = value >>> 0;
        const loffset = this._checkWrite(uValue, 2, offset);
        this.buffer[loffset + 1] = uValue >>> 8;
        this.buffer[loffset] = uValue;
        return this;
    }
    writeUInt16BE(value, offset) {
        const uValue = value >>> 0;
        const loffset = this._checkWrite(uValue, 2, offset);
        this.buffer[loffset] = uValue >>> 8;
        this.buffer[loffset + 1] = uValue;
        return this;
    }
    writeUInt24BE(value, offset) {
        const uValue = value >>> 0;
        const loffset = this._checkWrite(uValue, 3, offset);
        this.buffer[loffset] = uValue >>> 16;
        this.buffer[loffset + 1] = uValue >>> 8;
        this.buffer[loffset + 2] = uValue;
        return this;
    }
    writeInt32LE(value, offset) {
        const iValue = value | 0;
        const loffset = this._checkWrite(iValue, 4, offset);
        this.buffer[loffset + 3] = iValue >>> 24;
        this.buffer[loffset + 2] = iValue >>> 16;
        this.buffer[loffset + 1] = iValue >>> 8;
        this.buffer[loffset] = iValue;
        return this;
    }
    writeInt32BE(value, offset) {
        const iValue = value | 0;
        const loffset = this._checkWrite(iValue, 4, offset);
        this.buffer[loffset] = iValue >>> 24;
        this.buffer[loffset + 1] = iValue >>> 16;
        this.buffer[loffset + 2] = iValue >>> 8;
        this.buffer[loffset + 3] = iValue;
        return this;
    }
    writeUInt32LE(value, offset) {
        const uValue = value >>> 0;
        offset = this._checkWrite(uValue, 4, offset);
        this.buffer[offset + 3] = uValue >>> 24;
        this.buffer[offset + 2] = uValue >>> 16;
        this.buffer[offset + 1] = uValue >>> 8;
        this.buffer[offset] = uValue;
        return this;
    }
    writeUInt32BE(value, offset) {
        const uValue = value >>> 0;
        offset = this._checkWrite(uValue, 4, offset);
        this.buffer[offset] = uValue >>> 24;
        this.buffer[offset + 1] = uValue >>> 16;
        this.buffer[offset + 2] = uValue >>> 8;
        this.buffer[offset + 3] = uValue;
        return this;
    }
    writeInt64LE(value, offset) {
        const [lvalue, loffset] = this._checkWriteLong(value, offset);
        const lo = lvalue.low;
        const hi = lvalue.high;
        this.buffer[loffset + 3] = lo >>> 24;
        this.buffer[loffset + 2] = lo >>> 16;
        this.buffer[loffset + 1] = lo >>> 8;
        this.buffer[loffset] = lo;
        this.buffer[loffset + 7] = hi >>> 24;
        this.buffer[loffset + 6] = hi >>> 16;
        this.buffer[loffset + 5] = hi >>> 8;
        this.buffer[loffset + 4] = hi;
        return this;
    }
    writeInt64BE(value, offset) {
        const [lvalue, loffset] = this._checkWriteLong(value, offset);
        const lo = lvalue.low;
        const hi = lvalue.high;
        this.buffer[loffset] = hi >>> 24;
        this.buffer[loffset + 1] = hi >>> 16;
        this.buffer[loffset + 2] = hi >>> 8;
        this.buffer[loffset + 3] = hi;
        this.buffer[loffset + 4] = lo >>> 24;
        this.buffer[loffset + 5] = lo >>> 16;
        this.buffer[loffset + 6] = lo >>> 8;
        this.buffer[loffset + 7] = lo;
        return this;
    }
    writeUInt64LE(value, offset) {
        const [lvalue, loffset] = this._checkWriteLong(value, offset);
        const lo = lvalue.low;
        const hi = lvalue.high;
        this.buffer[loffset + 3] = lo >>> 24;
        this.buffer[loffset + 2] = lo >>> 16;
        this.buffer[loffset + 1] = lo >>> 8;
        this.buffer[loffset] = lo;
        this.buffer[loffset + 7] = hi >>> 24;
        this.buffer[loffset + 6] = hi >>> 16;
        this.buffer[loffset + 5] = hi >>> 8;
        this.buffer[loffset + 4] = hi;
        return this;
    }
    writeUInt64BE(value, offset) {
        const [lvalue, loffset] = this._checkWriteLong(value, offset);
        const lo = lvalue.low;
        const hi = lvalue.high;
        this.buffer[loffset] = hi >>> 24;
        this.buffer[loffset + 1] = hi >>> 16;
        this.buffer[loffset + 2] = hi >>> 8;
        this.buffer[loffset + 3] = hi;
        this.buffer[loffset + 4] = lo >>> 24;
        this.buffer[loffset + 5] = lo >>> 16;
        this.buffer[loffset + 6] = lo >>> 8;
        this.buffer[loffset + 7] = lo;
        return this;
    }
    writeBigIntBE(value, offset) {
        const loffset = this._checkWrite(Number(value), 8, offset);
        const isNegative = value < 0n;
        if (isNegative) {
            value = (1n << 64n) + value;
        }
        this.buffer[loffset] = Number((BigInt(value) >> 56n) & BigInt(0xff));
        this.buffer[loffset + 1] = Number((BigInt(value) >> 48n) & BigInt(0xff));
        this.buffer[loffset + 2] = Number((BigInt(value) >> 40n) & BigInt(0xff));
        this.buffer[loffset + 3] = Number((BigInt(value) >> 32n) & BigInt(0xff));
        this.buffer[loffset + 4] = Number((BigInt(value) >> 24n) & BigInt(0xff));
        this.buffer[loffset + 5] = Number((BigInt(value) >> 16n) & BigInt(0xff));
        this.buffer[loffset + 6] = Number((BigInt(value) >> 8n) & BigInt(0xff));
        this.buffer[loffset + 7] = Number(BigInt(value) & BigInt(0xff));
        return this;
    }
    writeUBigIntBE(value, offset) {
        const loffset = this._checkWrite(Number(value), 8, offset);
        this.buffer[loffset] = Number((BigInt(value) >> 56n) & BigInt(0xff));
        this.buffer[loffset + 1] = Number((BigInt(value) >> 48n) & BigInt(0xff));
        this.buffer[loffset + 2] = Number((BigInt(value) >> 40n) & BigInt(0xff));
        this.buffer[loffset + 3] = Number((BigInt(value) >> 32n) & BigInt(0xff));
        this.buffer[loffset + 4] = Number((BigInt(value) >> 24n) & BigInt(0xff));
        this.buffer[loffset + 5] = Number((BigInt(value) >> 16n) & BigInt(0xff));
        this.buffer[loffset + 6] = Number((BigInt(value) >> 8n) & BigInt(0xff));
        this.buffer[loffset + 7] = Number(BigInt(value) & BigInt(0xff));
        return this;
    }
    writeBigIntLE(value, offset) {
        const loffset = this._checkWrite(Number(value), 8, offset);
        const isNegative = value < 0n;
        if (isNegative) {
            value = (1n << 64n) + value;
        }
        this.buffer[loffset] = Number(value & 0xffn);
        this.buffer[loffset + 1] = Number((BigInt(value) >> 8n) & 0xffn);
        this.buffer[loffset + 2] = Number((BigInt(value) >> 16n) & 0xffn);
        this.buffer[loffset + 3] = Number((BigInt(value) >> 24n) & 0xffn);
        this.buffer[loffset + 4] = Number((BigInt(value) >> 32n) & 0xffn);
        this.buffer[loffset + 5] = Number((BigInt(value) >> 40n) & 0xffn);
        this.buffer[loffset + 6] = Number((BigInt(value) >> 48n) & 0xffn);
        this.buffer[loffset + 7] = Number((BigInt(value) >> 56n) & 0xffn);
        return this;
    }
    writeUBigIntLE(value, offset) {
        const loffset = this._checkWrite(Number(value), 8, offset);
        this.buffer[loffset] = Number(value & 0xffn);
        this.buffer[loffset + 1] = Number((BigInt(value) >> 8n) & 0xffn);
        this.buffer[loffset + 2] = Number((BigInt(value) >> 16n) & 0xffn);
        this.buffer[loffset + 3] = Number((BigInt(value) >> 24n) & 0xffn);
        this.buffer[loffset + 4] = Number((BigInt(value) >> 32n) & 0xffn);
        this.buffer[loffset + 5] = Number((BigInt(value) >> 40n) & 0xffn);
        this.buffer[loffset + 6] = Number((BigInt(value) >> 48n) & 0xffn);
        this.buffer[loffset + 7] = Number((BigInt(value) >> 56n) & 0xffn);
        return this;
    }
    writeFloatLE(value, offset) {
        const loffset = this._checkWrite(value, 4, offset, true);
        this.buffer.writeFloatLE(value, loffset);
        return this;
    }
    writeFloatBE(value, offset) {
        const loffset = this._checkWrite(value, 4, offset, true);
        this.buffer.writeFloatBE(value, loffset);
        return this;
    }
    writeDoubleLE(value, offset) {
        const loffset = this._checkWrite(value, 8, offset, true);
        this.buffer.writeDoubleLE(value, loffset);
        return this;
    }
    writeDoubleBE(value, offset) {
        const loffset = this._checkWrite(value, 8, offset, true);
        this.buffer.writeDoubleBE(value, loffset);
        return this;
    }
    _checkRead(bytes, offset) {
        const loffset = offset ?? this.roffset;
        if (offset === void 0) {
            this.roffset += bytes;
        }
        if (!this.noAssert) {
            if (typeof loffset !== 'number' || loffset % 1 !== 0) {
                throw new TypeError(`Illegal offset: ${loffset} (not an integer)`);
            }
            if (loffset < 0 || loffset + bytes > this.buffer.length) {
                throw new RangeError(`Illegal offset: 0 <= ${loffset} (${bytes}) <= ${this.buffer.length}`);
            }
        }
        return loffset;
    }
    _checkWrite(value, bytes, offset, isFloat = false) {
        let loffset = (offset ?? this.woffset) >>> 0;
        if (offset === void 0) {
            this.woffset += bytes;
        }
        const result = (loffset >>>= 0);
        if (!this.noAssert) {
            if (typeof value !== 'number' || (!isFloat && value % 1 !== 0)) {
                throw new TypeError(`Illegal value: ${value} (not an integer)`);
            }
            if (typeof loffset !== 'number' || loffset % 1 !== 0) {
                throw new TypeError(`Illegal offset: ${offset} (not an integer)`);
            }
            if (loffset < 0 || loffset + 0 > this.buffer.length) {
                throw new RangeError(`Illegal offset: 0 <= ${loffset} (0) <= ${this.buffer.length}`);
            }
        }
        loffset += bytes;
        let capacity = this.buffer.length;
        if (loffset > capacity) {
            this.resize((capacity *= 2) > loffset ? capacity : loffset);
        }
        return result;
    }
    _checkWriteLong(value, offset) {
        let loffset = offset ?? this.woffset;
        if (offset === void 0) {
            this.woffset += 8;
        }
        const result = (loffset >>>= 0);
        if (!this.noAssert) {
            if (typeof value === 'number') {
                value = long_1.default.fromNumber(value);
            }
            else if (_isString(value)) {
                value = long_1.default.fromString(value);
            }
            else if (!(typeof value === 'object' && value instanceof long_1.default)) {
                throw new TypeError(`Illegal value: ${value} (not an integer or Long)`);
            }
            if (typeof loffset !== 'number' || loffset % 1 !== 0) {
                throw new TypeError(`Illegal offset: ${loffset} (not an integer)`);
            }
            if (loffset < 0 || loffset + 0 > this.buffer.length) {
                throw new RangeError(`Illegal offset: 0 <= ${loffset} (0) <= ${this.buffer.length}`);
            }
        }
        if (typeof value === 'number') {
            value = long_1.default.fromNumber(value);
        }
        else if (_isString(value)) {
            value = long_1.default.fromString(value);
        }
        loffset += 8;
        let capacity = this.buffer.length;
        if (loffset > capacity) {
            this.resize((capacity *= 2) > loffset ? capacity : loffset);
        }
        return [value, result];
    }
    writeVarint32(value, offset) {
        let loffset = offset ?? this.woffset;
        if (!this.noAssert) {
            if (typeof value !== 'number' || value % 1 !== 0) {
                throw new TypeError(`Illegal value: ${value} (not an integer)`);
            }
            value |= 0;
            if (typeof loffset !== 'number' || loffset % 1 !== 0) {
                throw new TypeError(`Illegal offset: ${loffset} (not an integer)`);
            }
            loffset >>>= 0;
            if (loffset < 0 || loffset + 0 > this.buffer.length) {
                throw new RangeError(`Illegal offset: 0 <= ${loffset} (0) <= ${this.buffer.length}`);
            }
        }
        const size = SmartBuffer.calculateVarint32(value);
        let b;
        loffset += size;
        let capacity10 = this.buffer.length;
        if (loffset > capacity10) {
            this.resize((capacity10 *= 2) > loffset ? capacity10 : loffset);
        }
        loffset -= size;
        value >>>= 0;
        while (value >= 0x80) {
            b = (value & 0x7f) | 0x80;
            this.buffer[loffset++] = b;
            value >>>= 7;
        }
        this.buffer[loffset++] = value;
        if (offset === void 0) {
            this.woffset = loffset;
            return this;
        }
        return size;
    }
    writeVarint32ZigZag(value, offset) {
        return this.writeVarint32(SmartBuffer.zigZagEncode32(value), offset);
    }
    readVarint32(offset) {
        let loffset = offset ?? this.roffset;
        if (!this.noAssert) {
            if (typeof loffset !== 'number' || loffset % 1 !== 0) {
                throw new TypeError(`Illegal offset: ${loffset} (not an integer)`);
            }
            loffset >>>= 0;
            if (loffset < 0 || loffset + 1 > this.buffer.length) {
                throw new RangeError(`Illegal offset: 0 <= ${loffset} (1) <= ${this.buffer.length}`);
            }
        }
        let c = 0;
        let value = 0 >>> 0;
        let b;
        do {
            if (!this.noAssert && loffset > this.buffer.length) {
                const err = new Error('Truncated');
                Object.defineProperty(err, 'truncated', {
                    enumerable: true,
                    value: true,
                });
                throw err;
            }
            b = this.buffer[loffset++];
            if (c < 5) {
                value |= (b & 0x7f) << (7 * c);
            }
            ++c;
        } while ((b & 0x80) !== 0);
        value |= 0;
        if (offset === void 0) {
            this.roffset = loffset;
            return value;
        }
        return { value, length: c };
    }
    readVarint32ZigZag(offset) {
        let val = this.readVarint32(offset);
        if (typeof val === 'object') {
            val.value = SmartBuffer.zigZagDecode32(val.value);
        }
        else {
            val = SmartBuffer.zigZagDecode32(val);
        }
        return val;
    }
    writeVarint64(value, offset) {
        let loffset = offset === void 0 ? this.woffset : offset;
        if (!this.noAssert) {
            if (typeof value === 'number') {
                value = long_1.default.fromNumber(value);
            }
            else if (_isString(value)) {
                value = long_1.default.fromString(value);
            }
            else if (!(typeof value === 'object' && value instanceof long_1.default)) {
                throw new TypeError(`Illegal value: ${value} (not an integer or Long)`);
            }
            if (typeof loffset !== 'number' || loffset % 1 !== 0) {
                throw new TypeError(`Illegal offset: ${loffset} (not an integer)`);
            }
            loffset >>>= 0;
            if (loffset < 0 || loffset + 0 > this.buffer.length) {
                throw new RangeError(`Illegal offset: 0 <= ${loffset} (0) <= ${this.buffer.length}`);
            }
        }
        if (typeof value === 'number') {
            value = long_1.default.fromNumber(value, false);
        }
        else if (_isString(value)) {
            value = long_1.default.fromString(value, false);
        }
        else if (value.unsigned !== false) {
            value = value.toSigned();
        }
        const size = SmartBuffer.calculateVarint64(value);
        const part0 = value.toInt() >>> 0;
        const part1 = value.shru(28).toInt() >>> 0;
        const part2 = value.shru(56).toInt() >>> 0;
        loffset += size;
        let capacity11 = this.buffer.length;
        if (loffset > capacity11) {
            this.resize((capacity11 *= 2) > loffset ? capacity11 : loffset);
        }
        loffset -= size;
        switch (size) {
            case 10:
                this.buffer[loffset + 9] = (part2 >>> 7) & 0x01;
            case 9:
                this.buffer[loffset + 8] = size !== 9 ? part2 | 0x80 : part2 & 0x7f;
            case 8:
                this.buffer[loffset + 7] = size !== 8 ? (part1 >>> 21) | 0x80 : (part1 >>> 21) & 0x7f;
            case 7:
                this.buffer[loffset + 6] = size !== 7 ? (part1 >>> 14) | 0x80 : (part1 >>> 14) & 0x7f;
            case 6:
                this.buffer[loffset + 5] = size !== 6 ? (part1 >>> 7) | 0x80 : (part1 >>> 7) & 0x7f;
            case 5:
                this.buffer[loffset + 4] = size !== 5 ? part1 | 0x80 : part1 & 0x7f;
            case 4:
                this.buffer[loffset + 3] = size !== 4 ? (part0 >>> 21) | 0x80 : (part0 >>> 21) & 0x7f;
            case 3:
                this.buffer[loffset + 2] = size !== 3 ? (part0 >>> 14) | 0x80 : (part0 >>> 14) & 0x7f;
            case 2:
                this.buffer[loffset + 1] = size !== 2 ? (part0 >>> 7) | 0x80 : (part0 >>> 7) & 0x7f;
            case 1:
                this.buffer[loffset] = size !== 1 ? part0 | 0x80 : part0 & 0x7f;
        }
        if (offset === void 0) {
            this.woffset += size;
            return this;
        }
        return size;
    }
    writeVarint64ZigZag(value, offset) {
        return this.writeVarint64(SmartBuffer.zigZagEncode64(value), offset);
    }
    readVarint64(offset) {
        let loffset = offset === void 0 ? this.roffset : offset;
        if (!this.noAssert) {
            if (typeof loffset !== 'number' || loffset % 1 !== 0) {
                throw new TypeError(`Illegal offset: ${loffset} (not an integer)`);
            }
            loffset >>>= 0;
            if (loffset < 0 || loffset + 1 > this.buffer.length) {
                throw new RangeError(`Illegal offset: 0 <= ${loffset} (1) <= ${this.buffer.length}`);
            }
        }
        const start = loffset;
        let part0 = 0;
        let part1 = 0;
        let part2 = 0;
        let b = 0;
        b = this.buffer[loffset++];
        part0 = b & 0x7f;
        if (b & 0x80) {
            b = this.buffer[loffset++];
            part0 |= (b & 0x7f) << 7;
            if (b & 0x80 || (this.noAssert && b === void 0)) {
                b = this.buffer[loffset++];
                part0 |= (b & 0x7f) << 14;
                if (b & 0x80 || (this.noAssert && b === void 0)) {
                    b = this.buffer[loffset++];
                    part0 |= (b & 0x7f) << 21;
                    if (b & 0x80 || (this.noAssert && b === void 0)) {
                        b = this.buffer[loffset++];
                        part1 = b & 0x7f;
                        if (b & 0x80 || (this.noAssert && b === void 0)) {
                            b = this.buffer[loffset++];
                            part1 |= (b & 0x7f) << 7;
                            if (b & 0x80 || (this.noAssert && b === void 0)) {
                                b = this.buffer[loffset++];
                                part1 |= (b & 0x7f) << 14;
                                if (b & 0x80 || (this.noAssert && b === void 0)) {
                                    b = this.buffer[loffset++];
                                    part1 |= (b & 0x7f) << 21;
                                    if (b & 0x80 || (this.noAssert && b === void 0)) {
                                        b = this.buffer[loffset++];
                                        part2 = b & 0x7f;
                                        if (b & 0x80 || (this.noAssert && b === void 0)) {
                                            b = this.buffer[loffset++];
                                            part2 |= (b & 0x7f) << 7;
                                            if (b & 0x80 || (this.noAssert && b === void 0)) {
                                                throw new RangeError('Buffer overrun');
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        const value = long_1.default.fromBits(part0 | (part1 << 28), (part1 >>> 4) | (part2 << 24), false);
        if (offset === void 0) {
            this.roffset = loffset;
            return value;
        }
        return { value, length: loffset - start };
    }
    readVarint64ZigZag(offset) {
        let val = this.readVarint64(offset);
        if (typeof val === 'object' && val.value instanceof long_1.default) {
            val.value = SmartBuffer.zigZagDecode64(val.value);
        }
        else {
            val = SmartBuffer.zigZagDecode64(val);
        }
        return val;
    }
    writeCString(str, offset) {
        let loffset = offset === void 0 ? this.woffset : offset;
        let i;
        let k = str.length;
        if (!this.noAssert) {
            if (!_isString(str)) {
                throw new TypeError('Illegal str: Not a string');
            }
            for (i = 0; i < k; ++i) {
                if (str.charCodeAt(i) === 0) {
                    throw new TypeError('Illegal str: Contains NULL-characters');
                }
            }
            if (typeof loffset !== 'number' || loffset % 1 !== 0) {
                throw new TypeError(`Illegal offset: ${loffset} (not an integer)`);
            }
            loffset >>>= 0;
            if (loffset < 0 || loffset + 0 > this.buffer.length) {
                throw new RangeError(`Illegal offset: 0 <= ${loffset} (0) <= ${this.buffer.length}`);
            }
        }
        k = buffer_1.Buffer.byteLength(str, 'utf8');
        loffset += k + 1;
        let capacity12 = this.buffer.length;
        if (loffset > capacity12) {
            this.resize((capacity12 *= 2) > loffset ? capacity12 : loffset);
        }
        loffset -= k + 1;
        loffset += this.buffer.write(str, loffset, k, 'utf8');
        this.buffer[loffset++] = 0;
        if (offset === void 0) {
            this.woffset = loffset;
            return this;
        }
        return k;
    }
    readCString(offset) {
        let loffset = offset === void 0 ? this.roffset : offset;
        if (!this.noAssert) {
            if (typeof loffset !== 'number' || loffset % 1 !== 0) {
                throw new TypeError(`Illegal offset: ${offset} (not an integer)`);
            }
            loffset >>>= 0;
            if (loffset < 0 || loffset + 1 > this.buffer.length) {
                throw new RangeError(`Illegal offset: 0 <= ${loffset} (1) <= ${this.buffer.length}`);
            }
        }
        const start = loffset;
        let temp;
        do {
            if (loffset >= this.buffer.length) {
                throw new RangeError(`Index out of range: ${loffset} <= ${this.buffer.length}`);
            }
            temp = this.buffer[loffset++];
        } while (temp !== 0);
        const str = this.buffer.toString('utf8', start, loffset - 1);
        if (offset === void 0) {
            this.roffset = loffset;
            return str;
        }
        return { string: str, length: loffset - start };
    }
    writeString(str, offset) {
        let loffset = offset === void 0 ? this.woffset : offset;
        if (!this.noAssert) {
            if (typeof loffset !== 'number' || loffset % 1 !== 0) {
                throw new TypeError(`Illegal offset: ${loffset} (not an integer)`);
            }
            loffset >>>= 0;
            if (loffset < 0 || loffset + 0 > this.buffer.length) {
                throw new RangeError(`Illegal offset: 0 <= ${loffset} (0) <= ${this.buffer.length}`);
            }
        }
        const k = buffer_1.Buffer.byteLength(str, 'utf8');
        loffset += k;
        let capacity14 = this.buffer.length;
        if (loffset > capacity14) {
            capacity14 *= 2;
            this.resize(capacity14 > loffset ? capacity14 : loffset);
        }
        loffset -= k;
        loffset += this.buffer.write(str, loffset, k, 'utf8');
        if (offset === void 0) {
            this.woffset = loffset;
            return this;
        }
        return k;
    }
    readString(length, metrics, offset) {
        if (typeof metrics === 'number') {
            offset = metrics;
            metrics = undefined;
        }
        let loffset = offset === void 0 ? this.roffset : offset;
        if (metrics === void 0) {
            metrics = SmartBuffer.METRICS_CHARS;
        }
        if (!this.noAssert) {
            if (typeof length !== 'number' || length % 1 !== 0) {
                throw new TypeError(`Illegal length: ${length} (not an integer)`);
            }
            length |= 0;
            if (typeof loffset !== 'number' || loffset % 1 !== 0) {
                throw new TypeError(`Illegal offset: ${loffset} (not an integer)`);
            }
            loffset >>>= 0;
            if (loffset < 0 || loffset + 0 > this.buffer.length) {
                throw new RangeError(`Illegal offset: 0 <= ${loffset} (0) <= ${this.buffer.length}`);
            }
        }
        let i = 0;
        const start = loffset;
        let temp;
        let sd;
        if (metrics === SmartBuffer.METRICS_CHARS) {
            sd = stringDestination();
            utfx.decodeUTF8(() => (i < length && loffset < this.buffer.length ? this.buffer[loffset++] : null), (cp) => {
                ++i;
                utfx.UTF8toUTF16(cp, sd);
            });
            if (i !== length) {
                throw new RangeError(`Illegal range: Truncated data, ${i} == ${length}`);
            }
            if (offset === void 0) {
                this.roffset = loffset;
                return sd();
            }
            return { string: sd(), length: loffset - start };
        }
        else if (metrics === SmartBuffer.METRICS_BYTES) {
            if (!this.noAssert) {
                if (typeof loffset !== 'number' || loffset % 1 !== 0) {
                    throw new TypeError(`Illegal offset: ${loffset} (not an integer)`);
                }
                loffset >>>= 0;
                if (loffset < 0 || loffset + length > this.buffer.length) {
                    throw new RangeError(`Illegal offset: 0 <= ${loffset} (${length}) <= ${this.buffer.length}`);
                }
            }
            temp = this.buffer.toString('utf8', loffset, loffset + length);
            if (offset === void 0) {
                this.roffset += length;
                return temp;
            }
            return { string: temp, length };
        }
        throw new TypeError(`Unsupported metrics: ${metrics}`);
    }
    writeVString(str, offset) {
        let loffset = offset ?? this.woffset;
        if (!this.noAssert) {
            if (!_isString(str)) {
                throw new TypeError('Illegal str: Not a string');
            }
            if (typeof loffset !== 'number' || loffset % 1 !== 0) {
                throw new TypeError(`Illegal offset: ${loffset} (not an integer)`);
            }
            loffset >>>= 0;
            if (loffset < 0 || loffset + 0 > this.buffer.length) {
                throw new RangeError(`Illegal offset: 0 <= ${loffset} (0) <= ${this.buffer.length}`);
            }
        }
        const start = loffset;
        const k = buffer_1.Buffer.byteLength(str, 'utf8');
        const l = SmartBuffer.calculateVarint32(k);
        loffset += l + k;
        let capacity15 = this.buffer.length;
        if (loffset > capacity15) {
            this.resize((capacity15 *= 2) > loffset ? capacity15 : loffset);
        }
        loffset -= l + k;
        loffset += this.writeVarint32(k, loffset);
        loffset += this.buffer.write(str, loffset, k, 'utf8');
        if (offset === void 0) {
            this.woffset = loffset;
            return this;
        }
        return loffset - start;
    }
    readVString(offset) {
        let loffset = offset ?? this.roffset;
        if (!this.noAssert) {
            if (typeof loffset !== 'number' || loffset % 1 !== 0) {
                throw new TypeError(`Illegal offset: ${loffset} (not an integer)`);
            }
            loffset >>>= 0;
            if (loffset < 0 || loffset + 1 > this.buffer.length) {
                throw new RangeError(`Illegal offset: 0 <= ${loffset} (1) <= ${this.buffer.length}`);
            }
        }
        const start = loffset;
        const len = this.readVarint32(loffset);
        const str = this.readString(len.value, SmartBuffer.METRICS_BYTES, (loffset += len.length));
        loffset += str.length;
        if (offset === void 0) {
            this.roffset = loffset;
            return str.string;
        }
        return { string: str.string, length: loffset - start };
    }
    appendTo(target, offset) {
        target.write(this, offset);
        return this;
    }
    assert(assert) {
        this.noAssert = !assert;
        return this;
    }
    reset(resetWOffset = false) {
        this.roffset = 0;
        if (resetWOffset) {
            this.woffset = 0;
        }
        return this;
    }
    clone(copy = false) {
        const bb = new SmartBuffer(0, this.noAssert);
        if (copy) {
            const buffer = buffer_1.Buffer.allocUnsafe(this.buffer.length);
            this.buffer.copy(buffer);
            bb.buffer = buffer;
        }
        else {
            bb.buffer = this.buffer;
        }
        bb.roffset = this.roffset;
        bb.woffset = this.woffset;
        return bb;
    }
    compact(begin, end) {
        let lbegin = begin === void 0 ? this.roffset : begin;
        let lend = end === void 0 ? this.buffer.length : end;
        if (!this.noAssert) {
            if (typeof lbegin !== 'number' || lbegin % 1 !== 0) {
                throw new TypeError('Illegal begin: Not an integer');
            }
            lbegin >>>= 0;
            if (typeof lend !== 'number' || lend % 1 !== 0) {
                throw new TypeError('Illegal end: Not an integer');
            }
            lend >>>= 0;
            if (lbegin < 0 || lbegin > lend || lend > this.buffer.length) {
                throw new RangeError(`Illegal range: 0 <= ${lbegin} <= ${lend} <= ${this.buffer.length}`);
            }
        }
        if (lbegin === 0 && lend === this.buffer.length) {
            return this;
        }
        const len = lend - lbegin;
        if (len === 0) {
            this.buffer = EMPTY_BUFFER;
            this.roffset = 0;
            this.woffset = 0;
            return this;
        }
        const buffer = buffer_1.Buffer.allocUnsafe(len);
        this.buffer.copy(buffer, 0, lbegin, lend);
        this.buffer = buffer;
        this.woffset -= this.roffset;
        this.roffset = 0;
        return this;
    }
    copy(begin, end) {
        let lbegin = begin === void 0 ? this.roffset : begin;
        let lend = end === void 0 ? this.woffset : end;
        if (!this.noAssert) {
            if (typeof lbegin !== 'number' || lbegin % 1 !== 0) {
                throw new TypeError('Illegal begin: Not an integer');
            }
            lbegin >>>= 0;
            if (typeof lend !== 'number' || lend % 1 !== 0) {
                throw new TypeError('Illegal end: Not an integer');
            }
            lend >>>= 0;
            if (lbegin < 0 || lbegin > lend || lend > this.buffer.length) {
                throw new RangeError(`Illegal range: 0 <= ${lbegin} <= ${lend} <= ${this.buffer.length}`);
            }
        }
        if (lbegin === lend) {
            return new SmartBuffer(0, this.noAssert);
        }
        const capacity = lend - lbegin;
        const bb = new SmartBuffer(capacity, this.noAssert);
        bb.roffset = 0;
        bb.woffset = 0;
        this.copyTo(bb, 0, lbegin, lend);
        return bb;
    }
    copyTo(target, targetOffset, sourceStart, sourceEnd) {
        if (!this.noAssert) {
            if (!(target instanceof SmartBuffer)) {
                throw new TypeError("'target' is not a SmartBuffer");
            }
        }
        const ltargetOffset = targetOffset === void 0 ? target.woffset : targetOffset | 0;
        const lsourceStart = sourceStart === void 0 ? this.roffset : sourceStart | 0;
        const lsourceEnd = sourceEnd === void 0 ? this.woffset : sourceEnd | 0;
        if (ltargetOffset < 0 || ltargetOffset > target.buffer.length) {
            throw new RangeError(`Illegal target range: 0 <= ${ltargetOffset} <= ${target.buffer.length}`);
        }
        if (lsourceStart < 0 || lsourceEnd > this.buffer.length) {
            throw new RangeError(`Illegal source range: 0 <= ${lsourceStart} <= ${this.buffer.length}`);
        }
        const len = lsourceEnd - lsourceStart;
        if (len === 0) {
            return target;
        }
        target.ensureCapacity(ltargetOffset + len);
        this.buffer.copy(target.buffer, ltargetOffset, lsourceStart, lsourceEnd);
        if (sourceStart === void 0) {
            this.roffset += len;
        }
        if (targetOffset === void 0) {
            target.woffset += len;
        }
        return this;
    }
    ensureCapacity(capacity) {
        let current = this.buffer.length;
        if (current < capacity) {
            return this.resize((current *= 2) > capacity ? current : capacity);
        }
        return this;
    }
    fill(value, begin, end) {
        let lbegin = begin === void 0 ? this.woffset : begin;
        if (_isString(value) && value.length > 0) {
            value = value.charCodeAt(0);
        }
        let lend = end === void 0
            ? this.buffer.length
            : end;
        if (!this.noAssert) {
            if (typeof value !== 'number' || value % 1 !== 0) {
                throw new TypeError(`Illegal value: ${value} (not an integer)`);
            }
            value |= 0;
            if (typeof lbegin !== 'number' || lbegin % 1 !== 0) {
                throw new TypeError('Illegal begin: Not an integer');
            }
            lbegin >>>= 0;
            if (typeof lend !== 'number' || lend % 1 !== 0) {
                throw new TypeError('Illegal end: Not an integer');
            }
            lend >>>= 0;
            if (lbegin < 0 || lbegin > lend || lend > this.buffer.length) {
                throw new RangeError(`Illegal range: 0 <= ${lbegin} <= ${lend} <= ${this.buffer.length}`);
            }
        }
        if (lbegin >= lend) {
            return this;
        }
        this.buffer.fill(value, lbegin, lend);
        if (begin === void 0) {
            this.woffset = lend;
        }
        return this;
    }
    prepend(source, offset, encoding) {
        let loffset = offset === void 0 ? this.roffset : offset;
        if (!this.noAssert) {
            if (typeof loffset !== 'number' || loffset % 1 !== 0) {
                throw new TypeError(`Illegal offset: ${loffset} (not an integer)`);
            }
            loffset >>>= 0;
            if (loffset < 0 || loffset + 0 > this.buffer.length) {
                throw new RangeError(`Illegal offset: 0 <= ${loffset} (0) <= ${this.buffer.length}`);
            }
        }
        if (!(source instanceof SmartBuffer)) {
            source = SmartBuffer.wrap(source, encoding);
        }
        const len = source.buffer.length - source.roffset;
        if (len <= 0) {
            return this;
        }
        const diff = len - loffset;
        if (diff > 0) {
            const buffer = buffer_1.Buffer.allocUnsafe(this.buffer.length + diff);
            this.buffer.copy(buffer, len, loffset, this.buffer.length);
            this.buffer = buffer;
            this.roffset += diff;
            this.woffset += diff;
            loffset += diff;
        }
        source.buffer.copy(this.buffer, loffset - len, source.roffset, source.buffer.length);
        source.roffset = source.buffer.length;
        if (offset === void 0) {
            this.roffset -= len;
        }
        return this;
    }
    prependTo(target, offset) {
        target.prepend(this, offset);
        return this;
    }
    resize(capacity) {
        if (!this.noAssert) {
            if (typeof capacity !== 'number' || capacity % 1 !== 0) {
                throw new TypeError(`'capacity' is not an integer: ${capacity}`);
            }
            capacity |= 0;
            if (capacity < 0) {
                throw new TypeError(`Not valid capacity value: 0 <= ${capacity}`);
            }
        }
        if (this.buffer.length < capacity) {
            const buffer = buffer_1.Buffer.allocUnsafe(capacity);
            this.buffer.copy(buffer);
            this.buffer = buffer;
        }
        return this;
    }
    reverse(begin, end) {
        let lbegin = begin === void 0 ? this.roffset : begin;
        let lend = end === void 0 ? this.woffset : end;
        if (!this.noAssert) {
            if (typeof lbegin !== 'number' || lbegin % 1 !== 0) {
                throw new TypeError('Illegal begin: Not an integer');
            }
            lbegin >>>= 0;
            if (typeof lend !== 'number' || lend % 1 !== 0) {
                throw new TypeError('Illegal end: Not an integer');
            }
            lend >>>= 0;
            if (lbegin < 0 || lbegin > lend || lend > this.buffer.length) {
                throw new RangeError(`Illegal range: 0 <= ${lbegin} <= ${lend} <= ${this.buffer.length}`);
            }
        }
        if (lbegin === lend) {
            return this;
        }
        Array.prototype.reverse.call(this.buffer.slice(lbegin, lend));
        return this;
    }
    skipRead(length) {
        if (!this.noAssert) {
            if (typeof length !== 'number' || length % 1 !== 0) {
                throw new TypeError(`Illegal length: ${length} (not an integer)`);
            }
            length |= 0;
        }
        const offset = this.roffset + length;
        if (!this.noAssert) {
            if (offset < 0 || offset > this.buffer.length) {
                throw new RangeError(`Illegal length: 0 <= ${this.roffset} + ${length} <= ${this.buffer.length}`);
            }
        }
        this.roffset = offset;
        return this;
    }
    skipWrite(length) {
        if (!this.noAssert) {
            if (typeof length !== 'number' || length % 1 !== 0) {
                throw new TypeError(`Illegal length: ${length} (not an integer)`);
            }
            length |= 0;
        }
        const offset = this.woffset + length;
        if (!this.noAssert) {
            if (offset < 0 || offset > this.buffer.length) {
                throw new RangeError(`Illegal length: 0 <= ${this.woffset} + ${length} <= ${this.buffer.length}`);
            }
        }
        this.woffset = offset;
        return this;
    }
    slice(begin, end) {
        let lbegin = begin === void 0 ? this.roffset : begin;
        let lend = end === void 0 ? this.woffset : end;
        if (!this.noAssert) {
            if (typeof lbegin !== 'number' || lbegin % 1 !== 0) {
                throw new TypeError('Illegal begin: Not an integer');
            }
            lbegin >>>= 0;
            if (typeof end !== 'number' || lend % 1 !== 0) {
                throw new TypeError('Illegal end: Not an integer');
            }
            lend >>>= 0;
            if (lbegin < 0 || lbegin > lend || lend > this.buffer.length) {
                throw new RangeError(`Illegal range: 0 <= ${lbegin} <= ${lend} <= ${this.buffer.length}`);
            }
        }
        const bb = new SmartBuffer(lend - lbegin);
        bb.buffer = this.buffer.slice(begin, lend);
        bb.woffset = bb.capacity;
        return bb;
    }
    toBuffer(forceCopy = false, begin, end) {
        let lbegin = begin === void 0 ? this.roffset : begin;
        let lend = end === void 0 ? this.woffset : end;
        lbegin >>>= 0;
        lend >>>= 0;
        if (!this.noAssert) {
            if (typeof lbegin !== 'number' || lbegin % 1 !== 0) {
                throw new TypeError('Illegal begin: Not an integer');
            }
            if (typeof lend !== 'number' || lend % 1 !== 0) {
                throw new TypeError('Illegal end: Not an integer');
            }
            if (lbegin < 0 || lbegin > lend || lend > this.buffer.length) {
                throw new RangeError(`Illegal range: 0 <= ${lbegin} <= ${lend} <= ${this.buffer.length}`);
            }
        }
        if (forceCopy) {
            const buffer = buffer_1.Buffer.allocUnsafe(lend - lbegin);
            this.buffer.copy(buffer, 0, lbegin, end);
            return buffer;
        }
        if (lbegin === 0 && lend === this.buffer.length) {
            return this.buffer;
        }
        return this.buffer.slice(lbegin, lend);
    }
    toArrayBuffer() {
        let offset = this.roffset;
        let limit = this.woffset;
        if (!this.noAssert) {
            if (offset === void 0 || offset % 1 !== 0) {
                throw new TypeError('Illegal offset: Not an integer');
            }
            offset >>>= 0;
            if (typeof limit !== 'number' || limit % 1 !== 0) {
                throw new TypeError('Illegal limit: Not an integer');
            }
            limit >>>= 0;
            if (offset < 0 || offset > limit || limit > this.buffer.length) {
                throw new RangeError(`Illegal range: 0 <= ${offset} <= ${limit} <= ${this.buffer.length}`);
            }
        }
        const ab = new ArrayBuffer(limit - offset);
        const dst = new Uint8Array(ab);
        this.buffer.copy(dst);
        return ab;
    }
    toString(encoding, begin, end) {
        if (encoding === void 0) {
            return `ByteArrayNB(roffset=${this.roffset},woffset=${this.woffset},capacity=${this.capacity})`;
        }
        switch (encoding) {
            case 'utf8':
                return this.toUTF8(begin, end);
            case 'base64':
                return this.toBase64(begin, end);
            case 'hex':
                return this.toHex(begin, end);
            case 'binary':
                return this.toBinary(begin, end);
            case 'debug':
                return this.toDebug();
            default:
                throw new TypeError(`Unsupported encoding: ${encoding}`);
        }
    }
    toBase64(begin, end) {
        let lbegin = begin === void 0 ? this.roffset : begin;
        let lend = end === void 0 ? this.woffset : end;
        lbegin |= 0;
        lend |= 0;
        if (lbegin < 0 || lend > this.buffer.length || lbegin > lend) {
            throw new RangeError('begin, end');
        }
        return this.buffer.toString('base64', lbegin, lend);
    }
    toBinary(begin, end) {
        let lbegin = begin === void 0 ? this.roffset : begin;
        let lend = end === void 0 ? this.woffset : end;
        lbegin |= 0;
        lend |= 0;
        if (lbegin < 0 || lend > this.capacity || lbegin > lend) {
            throw new RangeError('begin, end');
        }
        return this.buffer.toString('binary', lbegin, lend);
    }
    toDebug(columns = false) {
        let i = -1;
        const k = this.buffer.length;
        let b;
        let hex = '';
        let asc = '';
        let out = '';
        while (i < k) {
            if (i !== -1) {
                b = this.buffer[i];
                if (b < 0x10) {
                    hex += `0${b.toString(16).toUpperCase()}`;
                }
                else {
                    hex += b.toString(16).toUpperCase();
                }
                if (columns) {
                    asc += b > 32 && b < 127 ? String.fromCharCode(b) : '.';
                }
            }
            ++i;
            if (columns) {
                if (i > 0 && i % 16 === 0 && i !== k) {
                    while (hex.length < 3 * 16 + 3) {
                        hex += ' ';
                    }
                    out += `${hex + asc}\n`;
                    hex = asc = '';
                }
            }
            if (i === this.roffset && this.roffset === this.woffset && this.woffset === this.buffer.length) {
                hex += '|';
            }
            else if (i === this.roffset && this.roffset === this.woffset) {
                hex += '^';
            }
            else if (i === this.roffset && this.roffset === this.buffer.length) {
                hex += '[';
            }
            else if (i === this.woffset && this.woffset === this.buffer.length) {
                hex += ']';
            }
            else if (i === this.roffset) {
                hex += '<';
            }
            else if (i === this.woffset) {
                hex += '>';
            }
            else if (i === this.buffer.length) {
                hex += '*';
            }
            else {
                hex += columns || (i !== 0 && i !== k) ? ' ' : '';
            }
        }
        if (columns && hex !== ' ') {
            while (hex.length < 3 * 16 + 3) {
                hex += ' ';
            }
            out += `${hex + asc}\n`;
        }
        return columns ? out : hex;
    }
    toHex(begin, end) {
        let lbegin = begin === void 0 ? this.roffset : begin;
        let lend = end === void 0 ? this.woffset : end;
        if (!this.noAssert) {
            if (typeof lbegin !== 'number' || lbegin % 1 !== 0) {
                throw new TypeError('Illegal begin: Not an integer');
            }
            lbegin >>>= 0;
            if (typeof lend !== 'number' || lend % 1 !== 0) {
                throw new TypeError('Illegal end: Not an integer');
            }
            lend >>>= 0;
            if (lbegin < 0 || lbegin > lend || lend > this.buffer.length) {
                throw new RangeError(`Illegal range: 0 <= ${lbegin} <= ${lend} <= ${this.buffer.length}`);
            }
        }
        return this.buffer.toString('hex', lbegin, lend);
    }
    toUTF8(begin, end) {
        let lbegin = begin === void 0 ? this.roffset : begin;
        let lend = end === void 0 ? this.woffset : end;
        if (!this.noAssert) {
            if (typeof lbegin !== 'number' || lbegin % 1 !== 0) {
                throw new TypeError('Illegal begin: Not an integer');
            }
            lbegin >>>= 0;
            if (typeof lend !== 'number' || lend % 1 !== 0) {
                throw new TypeError('Illegal end: Not an integer');
            }
            lend >>>= 0;
            if (lbegin < 0 || lbegin > lend || lend > this.buffer.length) {
                throw new RangeError(`Illegal range: 0 <= ${lbegin} <= ${lend} <= ${this.buffer.length}`);
            }
        }
        return this.buffer.toString('utf8', lbegin, lend);
    }
    static alloc(capacity, noAssert = SmartBuffer.DEFAULT_NOASSERT) {
        return new SmartBuffer(capacity, noAssert);
    }
    static concat(buffers, encoding, noAssert = SmartBuffer.DEFAULT_NOASSERT) {
        let capacity = 0;
        const k = buffers.length;
        let i = 0;
        let length;
        for (; i < k; ++i) {
            if (!(buffers[i] instanceof SmartBuffer)) {
                buffers[i] = SmartBuffer.wrap(buffers[i], encoding);
            }
            length = buffers[i].woffset - buffers[i].roffset;
            if (length > 0) {
                capacity += length;
            }
        }
        if (capacity === 0) {
            return new SmartBuffer(0, noAssert);
        }
        const bb = new SmartBuffer(capacity, noAssert);
        let bi;
        i = 0;
        while (i < k) {
            bi = buffers[i++];
            length = bi.woffset - bi.roffset;
            if (length <= 0) {
                continue;
            }
            bi.buffer.copy(bb.buffer, bb.woffset, bi.roffset, bi.woffset);
            bb.woffset += length;
        }
        bb.roffset = 0;
        return bb;
    }
    static wrap(buffer, encoding, noAssert) {
        if (_isString(buffer)) {
            if (encoding === void 0) {
                encoding = 'utf8';
            }
            switch (encoding) {
                case 'base64':
                    return SmartBuffer.fromBase64(buffer);
                case 'hex':
                    return SmartBuffer.fromHex(buffer);
                case 'binary':
                    return SmartBuffer.fromBinary(buffer);
                case 'utf8':
                    return SmartBuffer.fromUTF8(buffer);
                case 'debug':
                    return SmartBuffer.fromDebug(buffer);
                default:
                    throw new TypeError(`Unsupported encoding: ${encoding}`);
            }
        }
        let bb;
        if (buffer instanceof SmartBuffer) {
            bb = buffer.clone();
            return bb;
        }
        let b;
        if (buffer instanceof Uint8Array) {
            b = buffer_1.Buffer.from(buffer);
            buffer = b;
        }
        else if (buffer instanceof ArrayBuffer) {
            b = buffer_1.Buffer.from(buffer);
            buffer = b;
        }
        else if (!(buffer instanceof buffer_1.Buffer)) {
            if (!Array.isArray(buffer)) {
                throw new TypeError('Illegal buffer');
            }
            buffer = buffer_1.Buffer.from(buffer);
        }
        bb = new SmartBuffer(0, noAssert);
        if (buffer.length > 0) {
            bb.buffer = buffer;
            bb.woffset = buffer.length;
        }
        return bb;
    }
    static calculateVarint32(value) {
        value = value >>> 0;
        if (value < 1 << 7) {
            return 1;
        }
        else if (value < 1 << 14) {
            return 2;
        }
        else if (value < 1 << 21) {
            return 3;
        }
        else if (value < 1 << 28) {
            return 4;
        }
        return 5;
    }
    static zigZagEncode32(n) {
        return (((n |= 0) << 1) ^ (n >> 31)) >>> 0;
    }
    static zigZagDecode32(n) {
        return ((n >>> 1) ^ -(n & 1)) | 0;
    }
    static calculateVarint64(value) {
        let lValue;
        if (typeof value === 'number') {
            lValue = long_1.default.fromNumber(value);
        }
        else if (_isString(value)) {
            lValue = long_1.default.fromString(value);
        }
        else {
            lValue = value;
        }
        const part0 = lValue.toInt() >>> 0;
        const part1 = lValue.shru(28).toInt() >>> 0;
        const part2 = lValue.shru(56).toInt() >>> 0;
        if (part2 === 0) {
            if (part1 === 0) {
                if (part0 < 1 << 14) {
                    return part0 < 1 << 7 ? 1 : 2;
                }
                return part0 < 1 << 21 ? 3 : 4;
            }
            if (part1 < 1 << 14) {
                return part1 < 1 << 7 ? 5 : 6;
            }
            return part1 < 1 << 21 ? 7 : 8;
        }
        return part2 < 1 << 7 ? 9 : 10;
    }
    static zigZagEncode64(value) {
        let lValue;
        if (typeof value === 'number') {
            lValue = long_1.default.fromNumber(value, false);
        }
        else if (_isString(value)) {
            lValue = long_1.default.fromString(value, false);
        }
        else if (value.unsigned !== false) {
            lValue = value.toSigned();
        }
        else {
            lValue = value;
        }
        return lValue.shl(1).xor(lValue.shr(63)).toUnsigned();
    }
    static zigZagDecode64(value) {
        let lValue;
        if (typeof value === 'number') {
            lValue = long_1.default.fromNumber(value, false);
        }
        else if (_isString(value)) {
            lValue = long_1.default.fromString(value, false);
        }
        else if (value.unsigned !== false) {
            lValue = value.toSigned();
        }
        else {
            lValue = value;
        }
        return lValue.shru(1).xor(lValue.and(long_1.default.ONE).toSigned().negate()).toSigned();
    }
    static calculateUTF8Chars(str) {
        return utfx.calculateUTF16asUTF8(stringSource(str))[0];
    }
    static calculateString(str) {
        if (!_isString(str)) {
            throw new TypeError(`Illegal argument: ${typeof str}`);
        }
        return buffer_1.Buffer.byteLength(str, 'utf8');
    }
    static fromBase64(str) {
        return SmartBuffer.wrap(buffer_1.Buffer.from(str, 'base64'));
    }
    static btoa(str) {
        return SmartBuffer.fromBinary(str).toBase64();
    }
    static atob(b64) {
        return SmartBuffer.fromBase64(b64).toBinary();
    }
    static fromBinary(str) {
        return SmartBuffer.wrap(buffer_1.Buffer.from(str, 'binary'));
    }
    static fromDebug(str, noAssert = SmartBuffer.DEFAULT_NOASSERT) {
        const k = str.length;
        const bb = new SmartBuffer(((k + 1) / 3) | 0, noAssert);
        let i = 0;
        let j = 0;
        let ch;
        let b;
        let rs = false;
        let hw = false;
        let hr = false;
        let hl = false;
        let fail = false;
        while (i < k) {
            switch ((ch = str.charAt(i++))) {
                case '|':
                    if (!noAssert) {
                        if (hr || hw || hl) {
                            fail = true;
                            break;
                        }
                        hr = hw = hl = true;
                    }
                    bb.roffset = bb.woffset = j;
                    rs = false;
                    break;
                case ']':
                    if (!noAssert) {
                        if (hw || hl) {
                            fail = true;
                            break;
                        }
                        hw = hl = true;
                    }
                    bb.woffset = j;
                    rs = false;
                    break;
                case '^':
                    if (!noAssert) {
                        if (hr || hw) {
                            fail = true;
                            break;
                        }
                        hr = hw = true;
                    }
                    bb.roffset = bb.woffset = j;
                    rs = false;
                    break;
                case '<':
                    if (!noAssert) {
                        if (hr) {
                            fail = true;
                            break;
                        }
                        hr = true;
                    }
                    bb.roffset = j;
                    rs = false;
                    break;
                case '*':
                    if (!noAssert) {
                        if (hl) {
                            fail = true;
                            break;
                        }
                        hl = true;
                    }
                    rs = false;
                    break;
                case '>':
                    if (!noAssert) {
                        if (hw) {
                            fail = true;
                            break;
                        }
                        hw = true;
                    }
                    bb.woffset = j;
                    rs = false;
                    break;
                case ' ':
                    rs = false;
                    break;
                default:
                    if (!noAssert) {
                        if (rs) {
                            fail = true;
                            break;
                        }
                    }
                    b = parseInt(ch + str.charAt(i++), 16);
                    if (!noAssert) {
                        if (isNaN(b) || b < 0 || b > 255) {
                            throw new RangeError('Not a debug encoded string');
                        }
                    }
                    bb.buffer[j++] = b;
                    rs = true;
            }
            if (fail) {
                throw new RangeError(`Invalid symbol at ${i}`);
            }
        }
        if (!noAssert) {
            if (!hr || !hw || !hl) {
                throw new RangeError(`Missing roffset or woffset or limit: ${str}`);
            }
            if (j < bb.buffer.length) {
                throw new RangeError(`Not a debug encoded string (is it hex?) ${j} < ${k}`);
            }
        }
        return bb;
    }
    static fromHex(str, noAssert = SmartBuffer.DEFAULT_NOASSERT) {
        if (!noAssert) {
            if (!_isString(str)) {
                throw new TypeError('Illegal str: Not a string');
            }
            if (str.length % 2 !== 0) {
                throw new TypeError('Illegal str: Length not a multiple of 2');
            }
        }
        const bb = new SmartBuffer(0, true);
        bb.buffer = buffer_1.Buffer.from(str, 'hex');
        bb.woffset = bb.buffer.length;
        return bb;
    }
    static fromUTF8(str, noAssert = SmartBuffer.DEFAULT_NOASSERT) {
        if (!noAssert) {
            if (!_isString(str)) {
                throw new TypeError('Illegal str: Not a string');
            }
        }
        const bb = new SmartBuffer(0, noAssert);
        bb.buffer = buffer_1.Buffer.from(str, 'utf8');
        bb.woffset = bb.buffer.length;
        return bb;
    }
}
exports.SmartBuffer = SmartBuffer;
//# sourceMappingURL=index.js.map