Skip to content

Instantly share code, notes, and snippets.

@tpmccallum
Created November 13, 2019 04:44
Show Gist options
  • Select an option

  • Save tpmccallum/1da587b4f681223343a3b88ff89a422e to your computer and use it in GitHub Desktop.

Select an option

Save tpmccallum/1da587b4f681223343a3b88ff89a422e to your computer and use it in GitHub Desktop.
Executing Rust code, as WebAssembly (Wasm) in your browser, in under 5 minutes.

Run all of the following Ubuntu system set up commands (update, install Apache2 and Rust)

sudo apt-get update
sudo apt-get -y upgrade
sudo apt-get -y install apache2
sudo chown -R $USER:$USER /var/www/html
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
rustup target add wasm32-wasi
rustup override set nightly

Create a quick Rust project

cd ~
cargo new --lib triple
cd triple

Configure rust by adding this config to the lib section of the Cargo.toml file

[lib]
name = "triple_lib"
path = "src/triple.rs"
crate-type =["cdylib"]

Finish configuring Rust by creating a new file at ~/.cargo.config and adding the following config to it

[build]
target = "wasm32-wasi"

Write a quick Rust program and save it as triple.rs (in the ~/triple/src directory)

#[no_mangle]
pub extern fn triple(x: i32) -> i32 {
    return 3 * x;
}

Build the Rust code into Wasm

cargo build --release

Copy the Wasm file to the Apache2 server area

cp -rp ~/triple/target/wasm32-wasi/release/triple_lib.wasm /var/www/html/triple.wasm

Create a new file called triple.html in the var/www/html/ directory and fill it with the following code.

<html>
	<head>
		<script>
    if (!('WebAssembly' in window)) {
      alert('you need a browser with wasm support enabled :(');
    }
(async () => {
  const response = await fetch('triple.wasm');
  const buffer = await response.arrayBuffer();
  const module = await WebAssembly.compile(buffer);
  const instance = await WebAssembly.instantiate(module);
  const exports = instance.exports;
  const triple = exports.triple;
  var buttonOne = document.getElementById('buttonOne');
        buttonOne.value = 'Triple the number';
        buttonOne.addEventListener('click', function() {
          var input = 1;
          alert(input + ' tripled equals ' + triple(input));
        }, false);
})();    

  </script>
	</head>
	<body>
		<input type="button" id="buttonOne" value="Loading ..."/>
	</body>
</html>

Visit your machine's IP at the triple web page and click the "Triple the number" button.

http://12.345.456.78/triple.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment