Hello web is working!!

This commit is contained in:
Brian Carroll 2021-09-18 23:52:18 +01:00
parent e0af849518
commit c20a2e5740
3 changed files with 44 additions and 19 deletions

View file

@ -0,0 +1 @@
hello-world

View file

@ -0,0 +1,12 @@
<html>
<body>
<div id="output"></div>
<script src="platform/host.js"></script>
<script>
roc_web_platform_run(
"./hello-world.wasm",
document.getElementById("output")
);
</script>
</body>
</html>

View file

@ -1,31 +1,43 @@
const test_decoder = true; const test_decoder = true;
function run() { async function roc_web_platform_run(wasm_filename, dom_node) {
const memory = new Uint8Array(1024);
const decoder = new TextDecoder(); const decoder = new TextDecoder();
let memory_bytes;
let exit_code;
function js_display_roc_string(str_bytes, str_len) { function js_display_roc_string(str_bytes, str_len) {
const utf8_bytes = memory.subarray(str_bytes, str_bytes + str_len); const utf8_bytes = memory_bytes.subarray(str_bytes, str_bytes + str_len);
const js_string = decoder.decode(utf8_bytes); const js_string = decoder.decode(utf8_bytes);
console.log(js_string); dom_node.textContent = js_string;
} }
if (test_decoder) { const importObj = {
const testAddress = 123; wasi_snapshot_preview1: {
const testString = "Hello, world"; proc_exit: (code) => {
if (code !== 0) {
console.error(`Exited with code ${code}`);
}
exit_code = code;
},
},
env: {
js_display_roc_string,
},
};
const utf8Encoder = new TextEncoder(); const wasm = await WebAssembly.instantiateStreaming(
const targetBytes = memory.subarray( fetch(wasm_filename),
testAddress, importObj
testAddress + testString.length );
);
const { read, written } = utf8Encoder.encodeInto(testString, targetBytes); memory_bytes = new Uint8Array(wasm.instance.exports.memory.buffer);
if (written !== read) {
throw new Error("Not enough space"); try {
wasm.instance.exports._start();
} catch (e) {
const is_ok = e.message === "unreachable" && exit_code === 0;
if (!is_ok) {
console.error(e);
} }
js_display_roc_string(testAddress, testString.length);
} }
} }
run();