Files
CWasm/data/wasm_functions.js

54 lines
1.5 KiB
JavaScript

import { appGlobals } from './globals.js'
export async function loadWasmModule(filePath, environment)
{
let result = null;
try
{
const fetchPromise = fetch(filePath);
const wasmModule = await WebAssembly.instantiateStreaming(
fetchPromise,
{ env: environment }
);
result = wasmModule.instance;
}
catch (exception)
{
console.error("Failed to load WASM module from \"" + filePath + "\":", exception);
}
return result;
}
//TODO: We should do some performance measurements of wasmPntrToJsString vs wasmPntrAndLengthToJsString!
export function wasmPntrToJsString(ptr)
{
let cIndex = ptr;
while (cIndex < appGlobals.memDataView.byteLength)
{
let byteValue = appGlobals.memDataView.getUint8(cIndex, true);
if (byteValue == 0) { break; }
cIndex++;
}
return appGlobals.textDecoder.decode(
appGlobals.memDataView.buffer.slice(ptr, cIndex)
);
}
export function wasmPntrAndLengthToJsString(ptr, length)
{
return appGlobals.textDecoder.decode(
appGlobals.memDataView.buffer.slice(ptr, ptr + length)
);
}
export function jsStringToWasmPntr(arenaPntr, jsString, addNullTerm)
{
let encodedBytes = appGlobals.textEncoder.encode(jsString);
let memPntr = appGlobals.wasmModule.exports.cAllocMem(arenaPntr, encodedBytes.length + (addNullTerm ? 1 : 0), 0);
if (memPntr == 0) { return memPntr; }
const writeArray = new Uint8Array(appGlobals.wasmModule.exports.memory.buffer);
writeArray.set(encodedBytes, memPntr);
if (addNullTerm) { writeArray[encodedBytes.length] = 0; }
return memPntr;
}