Compiling from Rust
Rust has first-class WebAssembly support: no garbage collector, a small runtime, and an official ecosystem (wasm-bindgen, wasm-pack, web-sys) that generates the JavaScript glue for you.
Targets
| Target | Use it for |
|---|---|
wasm32-unknown-unknown |
browsers and JS hosts: no OS assumptions, imports are whatever you declare |
wasm32-wasip1 / wasm32-wasip2 |
WASI runtimes (Wasmtime, Wasmer) and the component model |
wasm32-unknown-emscripten |
interop with Emscripten-compiled C libraries |
rustup target add wasm32-unknown-unknown
cargo build --target wasm32-unknown-unknown --releaseA plain exported function
// src/lib.rs (Cargo.toml: [lib] crate-type = ["cdylib"])
#[no_mangle]
pub extern "C" fn clamp_percent(value: i32) -> i32 {
value.clamp(0, 100)
}
#[no_mangle]
pub extern "C" fn checked_ratio(a: u32, b: u32) -> u32 {
a / b // panics when b == 0
}#[no_mangle] extern "C" exports the function under its plain name. In release mode, the compiled code is
essentially this:
(module
(import "console" "log" (func $log (param i32)))
(func $clamp_percent (export "clamp_percent") (param $v i32) (result i32)
;; v.clamp(0, 100) compiles to two selects, no branches
(select
(local.tee $v (select (local.get $v) (i32.const 0) (i32.gt_s (local.get $v) (i32.const 0))))
(i32.const 100)
(i32.lt_s (local.get $v) (i32.const 100))))
(func $checked_ratio (export "checked_ratio") (param $a i32) (param $b i32) (result i32)
;; Rust checks for division by zero itself and panics; with panic = "abort" the panic is a trap
(if (i32.eqz (local.get $b)) (then (unreachable)))
(i32.div_u (local.get $a) (local.get $b)))
(func (export "main")
(call $log (call $clamp_percent (i32.const 150)))
(call $log (call $clamp_percent (i32.const -20)))
(call $log (call $clamp_percent (i32.const 64)))
(call $log (call $checked_ratio (i32.const 90) (i32.const 4)))
(call $log (call $checked_ratio (i32.const 1) (i32.const 0)))))100
0
64
22
RuntimeError: unreachable
Note that u32 and i32 are both i32 in Wasm: the compiler chose div_u because the Rust type is unsigned.
wasm-bindgen and wasm-pack
Raw exports only speak numbers. wasm-bindgen lets you write natural Rust signatures with strings, structs, closures and JS objects, and generates the glue on both sides:
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = console)]
fn log(s: &str); // import console.log
}
#[wasm_bindgen]
pub fn greet(name: &str) -> String {
log("greet was called");
format!("Hello, {name}!")
}cargo install wasm-pack
wasm-pack build --target web # -> pkg/: my_crate_bg.wasm + my_crate.js + my_crate.d.tsimport init, { greet } from './pkg/my_crate.js';
await init(); // fetches and instantiates the .wasm
console.log(greet('Ada')); // "Hello, Ada!"What the glue does
Behind greet(name) the generated JS performs the same steps you wrote by hand in Passing Strings & Arrays.
This simulation shows the sequence of calls the glue makes (the "Wasm side" is a JS stand-in so we can trace it):
// A stand-in for the exports wasm-bindgen generates (__wbindgen_malloc, greet, __wbindgen_free)
const memory = new Uint8Array(256);
let top = 16;
const trace = [];
const wasm = {
__wbindgen_malloc(len) { trace.push(`malloc(${len}) -> ${top}`); const p = top; top += len; return p; },
__wbindgen_free(ptr, len) { trace.push(`free(${ptr}, ${len})`); },
greet(ptr, len) { // Rust: format!("Hello, {name}!")
const name = new TextDecoder().decode(memory.subarray(ptr, ptr + len));
const out = new TextEncoder().encode(`Hello, ${name}!`);
const outPtr = this.__wbindgen_malloc(out.length);
memory.set(out, outPtr);
trace.push(`greet(${ptr}, ${len}) -> [${outPtr}, ${out.length}]`);
return [outPtr, out.length]; // returned as a (ptr, len) pair
},
};
// The generated JS wrapper, simplified
function greet(name) {
const bytes = new TextEncoder().encode(name);
const ptr = wasm.__wbindgen_malloc(bytes.length);
memory.set(bytes, ptr);
const [outPtr, outLen] = wasm.greet(ptr, bytes.length);
try {
return new TextDecoder().decode(memory.subarray(outPtr, outPtr + outLen));
} finally {
wasm.__wbindgen_free(outPtr, outLen); // Rust's String is freed after copying
}
}
console.log(greet('Ada'));
console.log(greet('Grace'));
console.log(trace.join('\n'));Hello, Ada!
Hello, Grace!
malloc(3) -> 16
malloc(11) -> 19
greet(16, 3) -> [19, 11]
free(19, 11)
malloc(5) -> 30
malloc(13) -> 35
greet(30, 5) -> [35, 13]
free(35, 13)
web-sys and js-sys
The web-sys crate exposes the whole Web platform (DOM, fetch, canvas, WebGL) as typed Rust bindings, and
js-sys covers JavaScript built-ins (Array, Promise, Date). Every call is still an import underneath:
Rust can only touch the page through the host.
use wasm_bindgen::prelude::*;
#[wasm_bindgen(start)]
pub fn start() -> Result<(), JsValue> {
let page = web_sys::window().unwrap().document().unwrap();
let p = page.create_element("p")?;
p.set_text_content(Some("Created from Rust"));
page.body().unwrap().append_child(&p)?;
Ok(())
}Size tips
A minimal Rust module can be under 1 KB, but format!, panics with messages and the default allocator add tens
of kilobytes. In Cargo.toml:
[profile.release]
opt-level = "z" # optimise for size
lto = true # whole-program optimisation
codegen-units = 1
panic = "abort" # no unwinding machinery
strip = trueThen run wasm-opt -Oz (Binaryen) on the output; wasm-pack does this automatically.
Test yourself
Which target do you use for a Rust library running in the browser?
x86_64-unknown-linux-gnuwasm32-unknown-unknownwasm32-wasip2aarch64-apple-darwin
What does a Rust panic become with panic = "abort"?
- A JavaScript exception with the message
- A trap (
unreachable) - A return value of -1
- An infinite loop
What does wasm-bindgen generate for a function taking &str?
- Nothing, Wasm supports strings
- JS glue that encodes the string to UTF-8, copies it into Wasm memory and passes (ptr, len)
- A WebAssembly string type
- A JSON conversion