Wow, I’ve learned more about WebAssembly in the past week, and it makes me very excited! Rust has a built in targeter for wasm in its compiler. Wasm functions can be imported into the JavaScript runtime. Vice versa, JavaScript functions can be imported into the WebAssembly runtime.

First and foremost, last week’s post a rusty web part one, was a little wrong and mislead. The tutorial I followed was only just pulling from the JavaScript file that was made at compilation. I thought something seemed weird, because it seemed like nothing was invoking the functions I made in Rust. Hopefully what follows will clear it up some more!

There is a built in wasm targeter that is in the Rust compiler. This was very interesting. So I tried it out! I wrote out some code and I compiled it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#[no_mangle]

pub extern fn fibonacci(x: i32) -> i32 {
    if x <= 2 {
        return 1;
    } else {
        return fibonacci(x - 1) + fibonacci(x - 2);
    }
}

#[no_mangle]

pub extern fn add(x: i32, y: i32) -> i32 {
    return x + y;
}

Command to Compile to Wasm

cargo +nightly build --target wasm32-unknown-unknown --release

This Rust code is basically the same as last weeks. What surprised menu greatly, is that this code was compiled in like 2 seconds using the Rust compiler! Last weeks compilation took 90 seconds through emcc. The only difference between the two compilation steps was that emcc ouptutted a wasm file as well as a js file. The Rust compiler outputted just a wasm file.

Now here is the part that is different than last week. The way to import a wasm file is through a network request. I decided to use a fetch API, in order to get the wasm file.

1
2
3
4
5
6
7
fetch("demo.wasm")
  .then((response) => response.arrayBuffer())
  .then((bytes) => WebAssembly.instantiate(bytes, {}))
  .then((results) => {
    console.log(results.instance.exports.fibonacci(23));
    console.log(results.instance.exports.add(23, 89));
  });

This bit of JavaScript code made more sense than last week. Download the file through a network request, instantiate the wasm file bytes through JavaScript API, then the exported functions are accessed. Simple! Fantastic!

I have not learned more about calling JavaScript from Rust yet, but looking at the syntax now, it seems very similar to what I did last week. Good to know how to put the two together!