1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
const addr = "http://localhost:6969/ws";
let ws = new WebSocket(addr);
ws.binaryType = "arraybuffer";
let wasmModule;
let wasmInstance;
let isCompiling = false;
ws.onmessage = async (message) => {
if (!wasmInstance) {
if (isCompiling) return;
isCompiling = true;
try {
const { instance, module } = await WebAssembly.instantiate(message.data);
wasmInstance = instance;
wasmModule = module;
ws.send(JSON.stringify({
success: true,
message: "WASM module loaded successfully.",
}));
} catch (err) {
ws.send(JSON.stringify({
success: false,
message: "WASM module loaded successfully.",
}));
} finally {
isCompiling = false;
}
return;
}
try {
const exports = wasmInstance.exports;
const inputPtr = passArrayBufferToWasm(exports, message.data);
const outputPtr = exports.entry(inputPtr);
const resultString = getStringFromWasm(exports.memory, outputPtr);
ws.send(JSON.stringify({
success: true,
message: resultString,
}));
exports.deallocate(inputPtr);
exports.deallocate(outputPtr);
} catch (error) {
console.error(error);
ws.send(JSON.stringify({
success: true,
message: `Failed to run wasm: ${error.message}`
}));
}
};
function passArrayBufferToWasm(exports, arrayBuffer) {
const srcBytes = new Uint8Array(arrayBuffer);
const len = srcBytes.length;
const ptr = exports.allocate(len + 1);
const heap = new Uint8Array(exports.memory.buffer);
heap.set(srcBytes, ptr);
heap[ptr + len] = 0;
return ptr;
}
function getStringFromWasm(memory, ptr) {
const bytes = new Uint8Array(memory.buffer);
let endPtr = ptr;
while (endPtr < bytes.length && bytes[endPtr] !== 0) {
endPtr++;
}
return new TextDecoder("utf-8").decode(bytes.slice(ptr, endPtr));
}
|