"use strict";
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
var encoder = new TextEncoder();
var WasmInstance = /** @class */ (function () {
    function WasmInstance(exports, fs) {
        this.result = undefined;
        this.exports = exports;
        this.fs = fs;
    }
    WasmInstance.prototype.stringToCharStar = function (str) {
        // Caller MUST free the returned char* from stringToU8 using this.exports.c_free, e.g., as done in callWithString here.
        var strAsArray = encoder.encode(str);
        var len = strAsArray.length + 1;
        var ptr = this.exports.c_malloc(len);
        var array = new Int8Array(this.exports.memory.buffer, ptr, len);
        array.set(strAsArray);
        array[len - 1] = 0;
        return ptr;
    };
    WasmInstance.prototype.callWithString = function (name, str) {
        var _a;
        var args = [];
        for (var _i = 2; _i < arguments.length; _i++) {
            args[_i - 2] = arguments[_i];
        }
        this.result = undefined;
        var ptr = this.stringToCharStar(str);
        var r;
        try {
            var f = this.exports[name];
            if (f == null) {
                throw Error("no function ".concat(name, " defined in wasm module"));
            }
            // @ts-ignore
            r = f.apply(void 0, __spreadArray([ptr], __read(args), false));
        }
        finally {
            // @ts-ignore
            this.exports.c_free(ptr);
        }
        return (_a = this.result) !== null && _a !== void 0 ? _a : r;
    };
    return WasmInstance;
}());
exports.default = WasmInstance;
//# sourceMappingURL=instance.js.map