-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
76 lines (73 loc) · 1.53 KB
/
index.js
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
(() => {
const memory = new WebAssembly.Memory({
initial: Math.ceil((64 * 1024 * 1024) / (64 * 1024))
});
let ex;
function makeString(str) {
const ptr = malloc(str.length + 1);
for (let i = 0; i != str.length; ++i)
ex.writeUint8(ptr + i, str.charCodeAt(i));
ex.writeUint8(ptr + str.length, 0);
return ptr;
}
function getString(addr) {
let str = '';
let i = 0;
while (true) {
const c = ex.readUint8(addr + i++);
if (c == 0)
break;
str += String.fromCharCode(c);
}
return str;
}
if (typeof window === 'undefined') {
const fs = require('fs');
ex = {
...new WebAssembly.Instance(
new WebAssembly.Module(fs.readFileSync('utils.wasm')),
{
env: {
memory
}
}
).exports
};
module.exports = ex;
Object.assign(ex, {
makeString,
getString
});
} else {
ex = new Promise((res, rej) => {
fetch('utils.wasm')
.then(r => r.arrayBuffer())
.then(buf => {
res({
...new WebAssembly.Instance(
new WebAssembly.Module(buf),
{
env: {
memory
}
}
).exports
});
})
.catch(rej);
});
Object.assign(window, {
wasc: ex
});
ex.then(res => {
ex = res;
Object.assign(window, {
wasc: ex
});
Object.assign(ex, {
makeString,
getString
});
});
}
})();