"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BufferWriter = void 0;
const primitive_types_1 = require("./primitive-types");
class BufferWriter {
    get capacity() {
        return this._capacity;
    }
    get length() {
        return this._length;
    }
    get currentOffset() {
        return this._offset;
    }
    toBuffer() {
        return this._wb.slice(0, this.length);
    }
    constructor(cap = 0x40) {
        this._capacity = cap;
        this._wb = Buffer.allocUnsafe(cap);
        this._wb.fill(0);
        this._offset = 0;
        this._length = 0;
    }
    guard(len2write) {
        if (this._offset + len2write > this._capacity) {
            this._capacity = (this._offset + len2write) * 2;
            const wb1 = Buffer.allocUnsafe(this._capacity);
            this._wb.copy(wb1, 0, 0, this._length);
            wb1.fill(0, this._length, this._capacity);
            this._wb = wb1;
        }
        if (this._offset + len2write > this._length) {
            this._length = this._offset + len2write;
        }
    }
    shrinkToFit() {
        this._capacity = this._length;
        const wb1 = Buffer.allocUnsafe(this._capacity);
        this._wb.copy(wb1, 0, 0, this._length);
        this._wb = wb1;
    }
    seek(offset) {
        const oldOffset = this._offset;
        this._offset = offset;
        return oldOffset;
    }
    bytes(b) {
        this.guard(b.length);
        for (let index = 0, len = b.length; index < len; ++index) {
            this._wb.writeUInt8(b.readUInt8(index), this._offset);
            this._offset += primitive_types_1.SizeofUInt8;
        }
    }
    int8(n) {
        this.guard(primitive_types_1.SizeofUInt8);
        this._wb.writeInt8(n, this._offset);
        this._offset += primitive_types_1.SizeofUInt8;
    }
    int16(n) {
        this.guard(primitive_types_1.SizeofUInt16);
        this._wb.writeInt16BE(n, this._offset);
        this._offset += primitive_types_1.SizeofUInt16;
    }
    int32(n) {
        this.guard(primitive_types_1.SizeofUInt32);
        this._wb.writeInt32BE(n, this._offset);
        this._offset += primitive_types_1.SizeofUInt32;
    }
    uint8(n) {
        this.guard(primitive_types_1.SizeofUInt8);
        this._wb.writeUInt8(n, this._offset);
        this._offset += primitive_types_1.SizeofUInt8;
    }
    uint16(n) {
        this.guard(primitive_types_1.SizeofUInt16);
        this._wb.writeUInt16BE(n, this._offset);
        this._offset += primitive_types_1.SizeofUInt16;
    }
    uint32(n) {
        this.guard(primitive_types_1.SizeofUInt32);
        this._wb.writeUInt32BE(n, this._offset);
        this._offset += primitive_types_1.SizeofUInt32;
    }
}
exports.BufferWriter = BufferWriter;
//# sourceMappingURL=buffer-writer.js.map