Level 3 · Systems· Lesson 10 of 11 · 30 min
WebAssembly
Compiling Rust for the browser and beyond — linear memory, the raw ABI used by this site's lab, wasm-bindgen, and WASI.
What WebAssembly is
WebAssembly (Wasm) is a compact binary instruction format for a sandboxed stack machine. Browsers run it at near-native speed next to JavaScript; standalone runtimes (Wasmtime, Wasmer) run it on servers, at the edge, and as a plugin format. Rust is one of its best-supported source languages because Rust needs no garbage collector and no large runtime.
A module:
- exports and imports functions whose parameters and results are numbers:
i32,i64,f32,f64; - owns one linear memory — a resizable array of bytes that the host can read and write;
- cannot touch anything else unless the host passes it in as an import.
Everything richer than a number — strings, structs, arrays — is a convention built on “a pointer and a length into linear memory”.
The raw approach
The Wasm Lab on this site is built this way, with no tooling beyond cargo. The crate is in wasm-labs/ in the repository.
# Cargo.toml
[lib]
crate-type = ["cdylib"]
[profile.release]
opt-level = 3
lto = true
panic = "abort"
strip = true
// src/lib.rs (excerpt)
/// Allocate `len` bytes in linear memory and return the pointer to JavaScript.
#[unsafe(no_mangle)]
pub extern "C" fn buf_alloc(len: usize) -> *mut u8 {
let mut v = Vec::<u8>::with_capacity(len);
let p = v.as_mut_ptr();
std::mem::forget(v); // ownership passes to the caller
p
}
/// # Safety
/// `ptr` must come from `buf_alloc(len)`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn buf_free(ptr: *mut u8, len: usize) {
drop(unsafe { Vec::from_raw_parts(ptr, 0, len) });
}
/// Count primes below `n` with a sieve.
#[unsafe(no_mangle)]
pub extern "C" fn count_primes(n: u32) -> u32 {
let n = n as usize;
if n < 2 { return 0; }
let mut composite = vec![false; n];
let mut count = 0;
for i in 2..n {
if !composite[i] {
count += 1;
// usize is 32 bits on wasm32: a plain `i * i` would wrap for i > 65535.
let mut j = i.saturating_mul(i);
while j < n { composite[j] = true; j += i; }
}
}
count
}
This is exactly the FFI lesson again: extern "C", unmangled names, raw pointers, explicit ownership transfer. Build it with:
rustup target add wasm32-unknown-unknown
cargo build --release --target wasm32-unknown-unknown
and load it from JavaScript:
const { instance } = await WebAssembly.instantiateStreaming(fetch('/wasm/labs.wasm'));
const { memory, buf_alloc, mandelbrot, count_primes } = instance.exports;
console.log(count_primes(1_000_000)); // numbers pass straight through
const len = 720 * 480 * 4;
const ptr = buf_alloc(len); // an integer: an offset into linear memory
mandelbrot(ptr, 720, 480, -0.6, 0, 0.0044, 300); // Rust writes RGBA bytes there
// Create the view AFTER the call: growing memory detaches older views.
const pixels = new Uint8ClampedArray(memory.buffer, ptr, len);
ctx.putImageData(new ImageData(pixels.slice(), 720, 480), 0, 0);
Open the lab, then read src/pages/[...locale]/labs.astro and wasm-labs/src/lib.rs side by side. The whole compiled module is about 16 KiB.
wasm-bindgen: the ergonomic approach
Hand-writing pointer conventions does not scale. wasm-bindgen generates the glue in both directions, and the wasm-pack tool builds and packages the result for npm or a bundler.
// crate: wasm-bindgen
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = console)]
fn log(s: &str); // import a JavaScript function
}
#[wasm_bindgen]
pub fn greet(name: &str) -> String {
log(&format!("greet called with {name}"));
format!("Hello, {name}!")
}
#[wasm_bindgen]
pub struct Counter {
count: u32,
}
#[wasm_bindgen]
impl Counter {
#[wasm_bindgen(constructor)]
pub fn new() -> Counter {
Counter { count: 0 }
}
pub fn increment(&mut self) -> u32 {
self.count += 1;
self.count
}
}
From JavaScript this is greet("Ferris") and new Counter().increment(); strings are copied in and out of linear memory for you. The companion crates js-sys and web-sys expose the JavaScript standard library and the DOM, and frameworks such as Leptos, Yew and Dioxus build whole front ends on top of them.
Practical constraints
- The boundary has a cost. Each call crosses between two worlds, and strings must be transcoded (UTF-8 ↔ UTF-16) and copied. Design chunky interfaces: one call that processes a buffer, not a million calls that process a byte.
- Threads are opt-in.
std::thread::spawndoes not work onwasm32-unknown-unknown. Parallelism uses Web Workers with shared memory, behind cross-origin isolation headers. - No blocking. The browser’s main thread must not block; I/O is asynchronous.
wasm-bindgen-futuresbridges Rust futures and JavaScript promises. - Size matters. Use
opt-level = "s"or"z", LTO,panic = "abort", and runwasm-opt. Avoid pulling formatting machinery into tiny modules.twiggyshows what is taking space. - Panics. Install
console_error_panic_hookduring development so panics print a message instead of an opaqueunreachabletrap. - 32-bit.
usizeis 32 bits; a module can address at most 4 GiB.
Is it faster than JavaScript? For tight numeric loops over typed memory, usually, by a modest factor — JavaScript JITs are excellent. Try the lab’s benchmarks in two different browsers. The stronger arguments are predictable performance (no JIT warm-up, no GC pauses), reusing existing Rust libraries on the web, and the sandbox.
Beyond the browser: WASI and components
WASI is a standard system interface, so std::fs, std::env and friends work outside a browser:
rustup target add wasm32-wasip1
cargo build --release --target wasm32-wasip1
wasmtime run --dir . target/wasm32-wasip1/release/app.wasm
The host decides which directories and capabilities the module receives — a capability-based sandbox. The Component Model (the wasm32-wasip2 target, with interfaces described in WIT) adds rich, typed interfaces between modules written in different languages, which makes Wasm a serious plugin and serverless format.
Exercises
- Build
wasm-labsyourself withnpm run build:wasm. Add an exported functionsum_bytes(ptr, len) -> u32, call it from the browser console with a buffer you fill from JavaScript. - Port the lab’s
count_primestowasm-bindgenand compare the generated JavaScript glue with the hand-written loader. - Write a WASI program that counts lines in a file, run it with Wasmtime, and observe what happens when you omit
--dir. - Measure the cost of the boundary: call a trivial exported
add(a, b)ten million times from JavaScript, and compare with one call that loops ten million times inside Rust.
Check your understanding
Pick an answer to see the explanation.
1.How does JavaScript read a byte buffer produced by a Rust WebAssembly module without a bindings generator?
2.Why must JavaScript re-create its typed-array view after calling into a module that may allocate?
3.Which target would you choose for a command-line tool that runs in Wasmtime with file access?