Minimal Rust & WebAssembly example

Click the button to run the WebAssembly code.

Based on an example by Steve Klabnik.

The Code

Download add.wat (WebAssembly text format)

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 -o add.big.wasm

Reduce the size by removing unused stuff from the module:

cargo install --git 
wasm-gc add.big.wasm add.wasm

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

.then(response => response.arrayBuffer())
.then(bytes => WebAssembly.instantiate(bytes, {}))
.then(results => {

The readable Webassembly looks like this:

  (type (;0;) (func (param i32) (result i32)))
  (type (;1;) (func))
  (func (;0;) (type 0) (param i32) (result i32)
    get_local 0
    i32.const 1
  (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"))