<!doctype html>
<title>WASM Test</title>
<script>
function fetchAndInstantiateWasm (url, imports) {
return fetch(url)
.then(res => {
if (res.ok)
return res.arrayBuffer();
throw new Error(`Unable to fetch Web Assembly file ${url}.`);
})
.then(bytes => WebAssembly.compile(bytes))
.then(module => WebAssembly.instantiate(module, imports || {}))
.then(instance => instance.exports);
}
let mem;
function writeString (str, offset) {
const strBuf = new TextEncoder().encode(str);
const outBuf = new Uint8Array(mem.buffer, offset, strBuf.length);
for (let i = 0; i < strBuf.length; i++) {
outBuf[i] = strBuf[i];
}
}
fetchAndInstantiateWasm('https://cdn.rawgit.com/guybedford/wasm-intro/dc93a5f3/5-writing-wasm-memory/program.wasm', {
env: {
consoleLog (offset, len) {
const strBuf = new Uint8Array(mem.buffer, offset, len);
console.log(new TextDecoder().decode(strBuf));
}
}
})
.then(m => {
mem = m.memory;
writeString("Hello Web Assembly", m.getInStrOffset());
m.toLowerCase();
});
</script>
void consoleLog (char* offset, int len);
char inStr[20];
char outStr[20];
char* getInStrOffset () {
return &inStr[0];
}
void toLowerCase () {
for (int i = 0; i < 20; i++) {
char c = inStr[i];
if (c > 64 && c < 91) {
c = c + 32;
}
outStr[i] = c;
}
consoleLog(&outStr[0], 20);
}