Minimal Rust & WebAssembly example

Click the button to run the WebAssembly code.

Based on an example by Steve Klabnik.


The Code

Download add.rs
Download add.wat (WebAssembly text format)

#[no_mangle]
pub extern "C" fn add_one(x: i32) -> i32 {
    x + 1
}

Compile this code as follows:

rustup update
rustup target add wasm32-unknown-unknown --toolchain nightly
rustc +nightly --target wasm32-unknown-unknown -O --crate-type=cdylib add.rs -o add.big.wasm

Reduce the size by removing unused stuff from the module:

cargo install --git https://github.com/alexcrichton/wasm-gc 
wasm-gc add.big.wasm add.wasm

The JavaScript code loads the WebAssembly module and has access to the exported function.

fetch('add.wasm')
.then(response => response.arrayBuffer())
.then(bytes => WebAssembly.instantiate(bytes, {}))
.then(results => {
    alert(results.instance.exports.add_one(41));
});

The readable Webassembly looks like this:

(module
  (type (;0;) (func (param i32) (result i32)))
  (type (;1;) (func))
  (func (;0;) (type 0) (param i32) (result i32)
    get_local 0
    i32.const 1
    i32.add)
  (func (;1;) (type 1))
  (table (;0;) 0 anyfunc)
  (memory (;0;) 17)
  (export "memory" (memory 0))
  (export "add_one" (func 0))
  (export "rust_eh_personality" (func 1))
  (data (i32.const 4) "\10\00\10\00"))