-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathindex.html
executable file
·92 lines (78 loc) · 2.03 KB
/
index.html
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<h1>500!</h1>
<p id="factorial500"></p>
<h1>string_to_int('42')</h1>
<p id="stringToInt"></p>
<h1>Control</h1>
<p>
<button onclick="wasm.instance.exports.debug_dump_memory();">
Dump memory
</button>
</p>
<script>
let wasm;
function get_memory() {
return new Uint8Array(wasm.instance.exports.memory.buffer);
}
const decoder = new TextDecoder("utf-8");
const encoder = new TextEncoder("utf-8");
function charPtrToString(str) {
const memory = get_memory();
let length=0;
for (; memory[str + length] !== 0 ;++length) {}
return decoder.decode(memory.subarray(str, str + length));
}
function stringToCharPtr(str) {
const data = encoder.encode(str + "\x00");
const ptr = wasm.instance.exports.get_memory_for_string(data.length + 1);
const memory = get_memory();
memory.subarray(ptr).set(data);
return ptr;
}
function freeCharPtr(ptr) {
wasm.instance.exports.free_memory_for_string(ptr);
}
// If the Webassemby module had been linked with
//
// --import-memory
//
// its memory will be provided with
//
// const wasmMemory = new WebAssembly.Memory({initial:10, maximum:100});
// const memory = new Uint8Array(wasmMemory.buffer);
//
// But this module is providing its own memory and exporting it.
let printString = function(str) {
console.log(str);
};
const importObject = {
env: {
print_string: function(str) {
printString(charPtrToString(str));
}
}
};
WebAssembly.instantiateStreaming(fetch('library.wasm'), importObject)
.then(function(obj) {
wasm = obj;
const s = stringToCharPtr('42');
document.getElementById("stringToInt").innerHTML = "" + wasm.instance.exports.string_to_int(s);
freeCharPtr(s);
wasm.instance.exports.factorial(50);
wasm.instance.exports.factorial(100);
wasm.instance.exports.factorial(200);
const oldPrintString = printString;
printString = function(str) {
document.getElementById("factorial500").innerHTML += str;
}
wasm.instance.exports.factorial(500);
printString = oldPrintString;
});
</script>
</body>
</html>