WebAssembly

WHAT

WASM is a binary instruction format for a stack-based virtual machine. It’s designed as a portable target for compilation of high-level languages like C++, enabling deployment on the web for client and server applications. It defines an Abstract Syntax Tree (AST) which gets stored in a binary format

Brief:

How it works:

  1. Dev code in C++
  2. Compile with WA support into WA byte-code files
  3. Browser JS Engine translates WASM into machine code and runs it

Logic Flow

DEMO - Counting

  1. Create a couple of C funcs
  2. Compile C code to wasm file; multiple ways for this process
  3. Web application JS can fetch wasm file and call C funcs (which is now in wasm binary format)
  4. Lastly, user click triggers JS calling the C func and uses the output to update DOM
# file dir
node_modules
index.c
index.css
index.html
index.js
index.wasm
<body>
    <h1>
        Web Assembly Demo
    </h1>
    <button id="btn-doit">
        Do it!
    </button>
    <div class="display-area" id="display-area-doit">
        <p>
            0
        </p>
    </div>
    
    <button id="btn-count">
        Count
    </button>
    <div class="display-area", id="display-area-count">
        <p>
            0
        </p>
    </div>
    
    <script src="index.js"></script>
</body>
// index.c
static int count = 0;

int CCount(int increaseValue) {
    count = increaseValue + count;
    return count;
}

int CDoit() {
    return 42;
}
fetch('index.wasm').then(response =>
                        response.arrayBuffer()
                        ).then(bytes =>
                              WebAssembly.instantiate(bytes, importObject)
                              ).then(results => {
    // Get access to WASM code
    const wasmExports = results.instance.exports;
    
    doItButton.onclick = ()=> {
        doItDisplayArea.innerText = wasmExports.CCount();
    }
    
    counterButton.onclick = ()=> {
        counterDisplayArea.innerText = wasmExports.CDoit(1);
    }

WHY

WASM-RUST Web App

Flow

Live update possible (Rust, C++) have live-reloading and hot-module-replacement auto-display changes

Support means:

Mainly due to WASM supports ONLY flat linear memoary - good for C++/Rust but other needs GC to run

Demo - updating click with Rust-Wasm func rather than JS

Tutorial (https://medium.com/tech-lah/webassembly-part-ii-a-wasm-with-rust-2356dbc6526e)


code · notebook · prose · gallery · qui et quoi? · main