Recently I have been learning more about Rust and experimenting with WebAssembly. I came up with this fibonacci calculator example to demonstrate how simple it is to offload complex computations to a client machine. As our personal devices become even more powerful it seems reasonable that we will see an effort to move computation from the server to the client. So with that in mind I hope you enjoy this demo.
Fibonacci Calculator:
Calculate fibonacci in the browser in real time. Built for the Web in Rust and Wasm. *Numbers above onhundredthousand will produce a noticable lag (on my machine 😁)*
Fibonacci:
0
Rust code with WASM bindings: src/lib.rs. This is a
straightforward iterative approach for calculating fibonacci. The
num::BigUint library is used for large integer support. See
that the return value is a string so that we can pass the result to
javascript without loss of precision.
use wasm_bindgen::prelude::*;
use num::{BigUint, Zero, One};
use std::mem::replace;
#[wasm_bindgen] pub fn fibonacci(n: usize) -> String {
let mut f0: BigUint = Zero::zero();
let mut f1: BigUint = One::one();
for _ in 0..n {
let f2 = f0 + &f1;
f0 = replace(&mut f1, f2);
}
f0.to_string()
}
Update the cargo.toml config file with the following. Notice
the wasm-bindgen and num dependencies.
Additionally the cdylib type is important.
[package]
name = "fibonacci"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
num = "0.4"
wasm-bindgen = "0.2"
After running wasm-pack build --target web you will get a
pkg directory with the following contents:
fibonacci.d.ts
fibonacci.js
fibonacci_bg.wasm
fibonacci_bg.wasm.d.ts
package.json
Then to load the rust-wasm fibonacci implementation in the browser we use:
<script type="module">
import init, { fibonacci } from "./pkg/fibonacci.js";
init().then(() => (window.fibonacci = fibonacci));
</script>
And the fibonacci input at the top of this page looks like:
<input
type="number"
min="0"
max="1000000"
value="0"
style="font-size: 2em; display: inline"
oninput="document.getElementById('target').innerText = fibonacci(value);"
/>
<div style="height: 80%; overflow: auto">
<p
id="target"
style="word-wrap: break-word; font-size: 2em; font-family: monospace"
>
0
</p>
</div>
Additional resources and in-depth documentation can be found here: