Skip to content

Instantly share code, notes, and snippets.

@kbknapp
Created May 4, 2018 14:34
Show Gist options
  • Save kbknapp/4a335c5381c24eccae4e2b63bf4f4c02 to your computer and use it in GitHub Desktop.
Save kbknapp/4a335c5381c24eccae4e2b63bf4f4c02 to your computer and use it in GitHub Desktop.

wasm32-unknown-unknown

Setup

  1. Use nightly with rustup
$ rustup update nightly
$ rustup target add wasm32-unknown-unknown --toolchain nightly 
  1. Add the target wasm32-unknown-unknown
  2. Install wasm-gc
$ cargo install --git https://github.com/alexcrichton/wasm-gc 
$ wasm-gc .\add.wasm small-add.wasm
  1. Compile as a cdylib
$ rustc +nightly --target wasm32-unknown-unknown -O .\lib.rs --crate-type=cdylib 

Or using cargo and Cargo.toml

[lib]
path = "src/lib.rs"
crate-type = ["cdylib"]
  1. Run wasm-gc to compress the code size
$ wasm-gc TARGET.wasm small-TARGET.wasm

Example

Rust Code:

// add.rs
#![feature(lang_items)]
#![no_std]

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


// needed for no_std if no_std is requirement
#[lang = "panic_fmt"]
#[no_mangle]
pub extern fn rust_begin_panic(_msg: core::fmt::Arguments,
                               _file: &'static str,
                               _line: u32,
                               _column: u32) 
                               -> ! 
{
    loop {}
}

HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
      <meta charset="utf-8">
      <title>wasm wasm wasm</title>
      <script>
        fetch('small-add.wasm').then(response =>
          response.arrayBuffer()
        ).then(bytes =>
          WebAssembly.instantiate(bytes, {})
        ).then(results => {
          alert(results.instance.exports.add_one(41));
        });
      </script>
  </head>
</html>

Run:

$ python -m SimpleHTTPServer

Open browser to http://localhost:8000/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment