Don't like this style? Click here to change it! blue.css

LOGIN:
Welcome .... Click here to logout

Rust + WASI / Component Model Lab

In this lab you will take a real open-source Rust project that generates procedural world maps, compile it to a WebAssembly component using WASI, and run it both natively and as a sandboxed WASM binary.

Why Rust + WASI matters

Project

We are using rhysd/world-map-gen, a small Rust library and CLI that generates random maps with altitude and land types (sea, forest, mountain, town, etc.).

Step 0 — Install the tools

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source "$HOME/.cargo/env"
rustup target add wasm32-wasip2
curl https://wasmtime.dev/install.sh -sSf | bash

Step 1 — Clone and run natively

git clone https://github.com/rhysd/world-map-gen.git
cd world-map-gen
cargo build --release
cargo run --release -- --help
cargo run --release -- -s 42 -w 40 -h 20

Look around in the src/ directory. The interesting modules are gen, board, and draw.

Step 2 — Compile to a WASI component

cargo build --target wasm32-wasip2 --release

The output is at:

target/wasm32-wasip2/release/world-map-gen.wasm

Run it with Wasmtime:

wasmtime run target/wasm32-wasip2/release/world-map-gen.wasm -- -s 1337 -w 30 -h 15

The output should match the native run. You have just turned the same Rust code into a portable, sandboxed component.

Step 3 — Optional: make a thin wrapper

If you want a smaller teaching binary, create a new project that depends on the library:

cargo new map-wasi
cd map-wasi
cargo add world-map-gen@0.1

Replace src/main.rs with:

use world_map_gen::gen;

fn main() {
    let seed = std::env::args().nth(1).and_then(|s| s.parse().ok()).unwrap_or(42);
    let board = gen::generate(40, 20, seed);
    println!("{}", board);
}

Then build and run:

cargo build --target wasm32-wasip2 --release
wasmtime run target/wasm32-wasip2/release/map-wasi.wasm 999

Step 4 — Run it as a service (optional)

You can also wrap the generator in an HTTP component (using Spin or Wasmtime’s serve command) so it answers HTTP requests. The original repository already contains a browser demo in the www/ directory if you want to see the same logic running in the browser via wasm-bindgen.

What to notice

Lab checklist

  1. Successfully run the project natively.
  2. Produce a .wasm with the wasm32-wasip2 target.
  3. Run that binary with wasmtime and confirm the output matches.
  4. (Optional) Create the thin wrapper or serve it over HTTP.