|
| 1 | +import { getNumber, getStruct } from "../fixtures.mjs"; |
| 2 | +import fs from "fs/promises"; |
| 3 | + |
| 4 | +/** @returns {Promise<import("../bench.mjs").Exports>} */ |
| 5 | +export async function init() { |
| 6 | + const source = await fs.readFile("./zig/zig-out/bin/zig.wasm"); |
| 7 | + const { instance: { exports } } = await WebAssembly.instantiate(source, { |
| 8 | + x: { |
| 9 | + getNumber, |
| 10 | + getStruct: () => toCString(JSON.stringify(getStruct())), |
| 11 | + } |
| 12 | + }); |
| 13 | + memory = exports.memory, cached = new Uint8Array(memory.buffer); |
| 14 | + |
| 15 | + return { |
| 16 | + echoNumber: exports.echoNumber, |
| 17 | + echoStruct: () => JSON.parse(fromCString(exports.echoStruct())), |
| 18 | + fi: exports.fi |
| 19 | + }; |
| 20 | +} |
| 21 | + |
| 22 | +let memory, cached; |
| 23 | +const encoder = new TextEncoder("utf-8"); |
| 24 | +const decoder = new TextDecoder("utf-8"); |
| 25 | + |
| 26 | +function toCString(str) { |
| 27 | + const memory = getMemoryCached(); |
| 28 | + const { written } = encoder.encodeInto(str, memory); |
| 29 | + memory[written] = 0; // appending null terminator |
| 30 | + return 0; // naive: always writing to the start of the wasm memory |
| 31 | +} |
| 32 | + |
| 33 | +function fromCString(ptr) { |
| 34 | + const memory = getMemoryCached(); |
| 35 | + let len = 0; |
| 36 | + while (memory[ptr + len] !== 0) len++; |
| 37 | + const bytes = memory.subarray(ptr, ptr + len); |
| 38 | + return decoder.decode(bytes); |
| 39 | +} |
| 40 | + |
| 41 | +function getMemoryCached() { |
| 42 | + if (cached.buffer.byteLength === memory.buffer.byteLength) return cached; |
| 43 | + return cached = new Uint8Array(memory.buffer); |
| 44 | +} |
0 commit comments