-
Notifications
You must be signed in to change notification settings - Fork 0
/
bundle.js
55 lines (47 loc) · 1.61 KB
/
bundle.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
function fetchAndInstantiate(url, importObject = {}) {
return fetch(url)
.then(response => response.arrayBuffer())
.then(bytes => WebAssembly.instantiate(bytes, importObject))
.then(results => results.instance);
}
function copyCStr(module, ptr) {
let orig_ptr = ptr;
const collectCString = function* () {
let memory = new Uint8Array(module.memory.buffer);
while (memory[ptr] !== 0) {
if (memory[ptr] === undefined) { throw new Error("Tried to read undef mem") }
yield memory[ptr]
ptr += 1
}
}
const buffer_as_u8 = new Uint8Array(collectCString())
const utf8Decoder = new TextDecoder("UTF-8");
const buffer_as_utf8 = utf8Decoder.decode(buffer_as_u8);
module.dealloc_str(orig_ptr);
return buffer_as_utf8
}
function getStr(module, ptr, len) {
const getData = function* (ptr, len) {
let memory = new Uint8Array(module.memory.buffer);
for (let index = 0; index < len; index++) {
if (memory[ptr] === undefined) { throw new Error(`Tried to read undef mem at ${ptr}`) }
yield memory[ptr + index]
}
}
const buffer_as_u8 = new Uint8Array(getData(ptr / 8, len / 8));
const utf8Decoder = new TextDecoder("UTF-8");
const buffer_as_utf8 = utf8Decoder.decode(buffer_as_u8);
return buffer_as_utf8;
}
function newString(module, str) {
const utf8Encoder = new TextEncoder("UTF-8");
let string_buffer = utf8Encoder.encode(str)
let len = string_buffer.length
let ptr = module.alloc(len + 1)
let memory = new Uint8Array(module.memory.buffer);
for (i = 0; i < len; i++) {
memory[ptr + i] = string_buffer[i]
}
memory[ptr + len] = 0;
return ptr
}