DEV Community

Cover image for Web Assembly With Rust
Praveen Chaudhary
Praveen Chaudhary

Posted on

Web Assembly With Rust

It is a universal binary code that is designed for the web.

Wasm uses a low virtual machine with linear memory. It executes safely inside the sandbox.

Wasm Chain

Image Source :→ Tapadoo

When should we use WASM?

Whenever we need to do the heavy computation, we should use wasm as they are efficient and fast.

But why Rust?

You can choose any language that you wish to, but Rust provides low-level control over the memory and is free from non-deterministic garbage collection.

Let's create our Fibonacci wasm package

1. Creating/ Initializing our first lib

Make sure rust is installed. You can install it from here if not installed.

$  cargo new fibonacci-wasm --lib
Enter fullscreen mode Exit fullscreen mode

2. Writing our Fibonacci function in Rust

It's pretty easy to write a function.

pub fn fibonacci(n: i64) -> i64 {
    if n == 0 {
        return 0;
    } else if n == 1 {
        return 1;
    } else {
        let mut a = 0;
        let mut b = 1;
        for _i in 2..n {
            let c = a + b;
            a = b;
            b = c;
        }
        return b;
    }
}
Enter fullscreen mode Exit fullscreen mode

Apart from this, you can do whatever you can do in the browser like consoling, alerting etc.

  • You can use the web_sys which provides the web browser APIs in the Rust code.
  • web_sys is a part of wasm-bindgen which extends the functionality that you can do with the Rust code.
  • For JS bindings you can use the js_sys which provides binding to JavaScript’s standard, built-in objects, including their methods and properties

You can use the web_sys and js_sys to do whatever you thought of doing in the browser.

3. Let's create JS binding with our Rust code

It is a difficult part but we have crate/library to do this.

We will be using it to Facilitate high-level interactions between Wasm modules and JavaScript.

Binding our rust code with js is simple with the help of the wasm_bindgen macro.

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn fibonacci(n: i64) -> i64 {
    ....
}
Enter fullscreen mode Exit fullscreen mode

Most of the things are done.

4. Let's compile and generate wasm package with wasm-pack

wasm-pack -> one-stop solution for working with rust-generated wasm code with the javascript.

YOu can use the wasm-pack to easily publish to npm registry or use it inside in node_modules folder.

You can install wasm-pack here.

$ wasm-pack build --target web
Enter fullscreen mode Exit fullscreen mode

Now you can find a new folder created with the name pkg.

You can just import WebAssembly modules the same way you would import JavaScript modules.

5. Testing our package in the browser

  • Create a basic Html page and in the body, section adds the script tag with type module.

    <script type="module">
    
  • Importing the wasm package.

        <script type="module">
        import init, { fibonacci } from "./pkg/fibonacci_wasm.js";
        ....
        </script>
    
  • Initializing our wasm code

    <script type="module">
      import init, { fibonacci } from "./pkg/fibonacci_wasm.js";
    
      await init();
      ....
    </script>
    
  • Running our Fibonacci function

    <script type="module">
      import init, { fibonacci } from "./pkg/fibonacci_wasm.js";
    
      await init();
      console.log(fibonacci(10));
    </script>
    

Results

wasm Fibonacci results

Resources

  1. iJS 2021: WebAssembly, Rust, and TypeScript – a Match Made in Heaven

Feel free to ask queries and make pull requests for changes and suggestions in GitHub.

Source Code

Github

Happy Hacking

Rustaceans!

Top comments (0)