|
| 1 | +(function () { |
| 2 | + const code = document.getElementById("code"); |
| 3 | + |
| 4 | + const run = document.getElementById("run"); |
| 5 | + run.onclick = formatCode; |
| 6 | + |
| 7 | + let wasm_promise = fetch("./zabi_wasm.wasm"); |
| 8 | + var wasm_exports = null; |
| 9 | + |
| 10 | + const text_decoder = new TextDecoder(); |
| 11 | + const text_encoder = new TextEncoder(); |
| 12 | + |
| 13 | + // Convenience function to prepare a typed byte array |
| 14 | + // from a pointer and a length into WASM memory. |
| 15 | + function getView(ptr, len) { |
| 16 | + return new Uint8Array(wasm_exports.memory.buffer, ptr, len); |
| 17 | + } |
| 18 | + |
| 19 | + // JS strings are UTF-16 and have to be encoded into an |
| 20 | + // UTF-8 typed byte array in WASM memory. |
| 21 | + function encodeString(str) { |
| 22 | + const capacity = str.length * 2 + 5; // As per MDN |
| 23 | + const ptr = wasm_exports.malloc(capacity); |
| 24 | + const { written } = text_encoder.encodeInto(str, getView(ptr, capacity)); |
| 25 | + return [ptr, written, capacity]; |
| 26 | + } |
| 27 | + |
| 28 | + // Decodes the string type produced from zig. |
| 29 | + function decodeString(ptr, len) { |
| 30 | + if (len === 0) return ""; |
| 31 | + return text_decoder.decode( |
| 32 | + new Uint8Array(wasm_exports.memory.buffer, ptr, len), |
| 33 | + ); |
| 34 | + } |
| 35 | + |
| 36 | + // Unwraps the string type produced from zig. |
| 37 | + function unwrapString(bigint) { |
| 38 | + const ptr = Number(bigint & 0xffffffffn); |
| 39 | + const len = Number(bigint >> 32n); |
| 40 | + |
| 41 | + return decodeString(ptr, len); |
| 42 | + } |
| 43 | + |
| 44 | + function formatCode() { |
| 45 | + const source = code.value; |
| 46 | + const [ptr, len] = encodeString(source); |
| 47 | + |
| 48 | + const result = wasm_exports.formatSolidity(ptr, len); |
| 49 | + |
| 50 | + const str = unwrapString(result); |
| 51 | + document.getElementById("result").textContent = str; |
| 52 | + } |
| 53 | + |
| 54 | + // Instantiate WASM module and run our test code. |
| 55 | + WebAssembly.instantiateStreaming(wasm_promise, { |
| 56 | + env: { |
| 57 | + // We export this function to WASM land. |
| 58 | + log: (ptr, len) => { |
| 59 | + const msg = decodeString(ptr, len); |
| 60 | + console.log(msg); |
| 61 | + }, |
| 62 | + panic: function (ptr, len) { |
| 63 | + const msg = decodeString(ptr, len); |
| 64 | + throw new Error("panic: " + msg); |
| 65 | + }, |
| 66 | + }, |
| 67 | + }).then((wasm_binary) => { |
| 68 | + wasm_exports = wasm_binary.instance.exports; |
| 69 | + window.wasm = wasm_binary; // for debugging |
| 70 | + }); |
| 71 | +})(); |
0 commit comments