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;
function run() {
const memory = new Uint8Array(1024);
async function roc_web_platform_run(wasm_filename, dom_node) {
const decoder = new TextDecoder();
let memory_bytes;
let exit_code;
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);
console.log(js_string);
dom_node.textContent = js_string;
}
if (test_decoder) {
const testAddress = 123;
const testString = "Hello, world";
const importObj = {
wasi_snapshot_preview1: {
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 targetBytes = memory.subarray(
testAddress,
testAddress + testString.length
);
const { read, written } = utf8Encoder.encodeInto(testString, targetBytes);
if (written !== read) {
throw new Error("Not enough space");
const wasm = await WebAssembly.instantiateStreaming(
fetch(wasm_filename),
importObj
);
memory_bytes = new Uint8Array(wasm.instance.exports.memory.buffer);
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();