Webassembly and Rust

We gave an intro to webassembly in the previous blog (https://medium.com/@jain.sm/web-assembly-introduction-8a745501bba0). There we took an example of a c program which could be compiled to wasm format and executed in the browser. Today we extend the ambit a bit and take an example of a simple Rust program and launch it via the browser.

The prerequisite here is to have the Rust environment installed alongside the Cargo package manager for Rust. Also nodejs and npm should be installed beforehand.

The workflow here would be to

1. Write a simple Rust program which will have functions which can be invoked from java script as well as they can invoke the javascript functions

2. Compile the rust program to wasm

3. Package the wasm alongside other js artifacts into an npm module

4. Publish the npm module for consumption from a node program

Use cargo to generate the first rust library named sample-wasm

cargo new — lib sample-wasm

This generates the artifacts

Modify the lib.rs file to add the code

The code above has two functions. The alert function is defined as an external function which means its defined outside the rust environment. In this case it’s the javascript function alert which the Rust code can invoke.

The other function is the greet function which is the function which can be invoked by the javascript runtime. We use the wasm_bindgen to provide this interface beteen javascript and rust runtimes.

We open the cargo.toml file and edit it to include the dependency for wasm-bindgen.

Also crate type has to be cdylib

Once done then we build the npm. We need to download wasm-pack to generate the npm (https://rustwasm.github.io/wasm-pack/installer/)

wasm-pack build — scope smjain

This generate the pkg directory with all needed artifacts of the npm package

Now we can publish the package using npm publish.

I published this into the npm registry (https://www.npmjs.com/package/@smjain/first-wasm)

Now we create a simple nodejs program using webpack and consume the npm module

Create package.json file as below

We can see we have defined a dependency on the npm module we just created

Create a webpack.config.js file

Create an index.html file

And finally create the referred index.js file

We can see we invoke the rust function greet here within the js file and pass a string to it. Internally the rust function invokes the js function alert to display the message as an alert

Start the server

Now open the page in browser

The example above displays the powerful paradigm of webassembly and via this and previous blog we are able to demonstrate use cases of compiling c as well as rust to web assembly and rendering them in the chrome browser.

Example above is taken from the mozzila website (https://developer.mozilla.org/en-US/docs/WebAssembly/Rust_to_wasm)