Webassembly practice - rust to wasm

Keywords: node.js npm

target

Using the existing lib - blake2b-simd of rust, js callable tool class functions are generated. Avoid the resource consumption caused by using js to translate the rust code.

Environmental Science

  • Rustc rustup cargo (development and compilation tool of rust Lang)
  • nodejs (publish the package generated by wasm pack)

Install wasm pack

cargo install wasm-pack

Create a project with cargo

cargo new --lib blake2b-wasm

cd to blake2b wasm directory

Edit Cargo.toml

[package]
name = "blake2b-wasm"
version = "0.1.0"
authors = ["foo <foo@example.com>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
crate-type = ["cdylib"]

[dependencies]
wasm-bindgen = "0.2"
blake2b_simd = "0.5.8"

Edit lib.rs under src directory

use blake2b_simd::{blake2b, Params};
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn blake2b_encode(input: &[u8], length: usize) -> String {
  if length == 0 {
    return blake2b(input).to_hex().to_string()
  }
  let hash = Params::new().hash_length(length).hash(input);
  hash.to_hex().to_string()
}


#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn it_works() {
    let expected = "ca002330e69d3e6b84a46a56a6533fd79d51d97a3bb7cad6c2ff43b354185d6d\
                    c1e723fb3db4ae0737e120378424c714bb982d9dc5bbd7a0ab318240ddd18f8d";
    let hash = blake2b(b"foo");
    assert_eq!(expected, &hash.to_hex());
  }
}

Perform unit tests

cargo test 

If you see the following results, you can compile the web assembly next.

Finished dev [unoptimized + debuginfo] target(s) in 0.09s
     Running target/debug/deps/blake2b_wasm-8c79ae2ec6adeb5b

running 1 test
test tests::it_works ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

Using wasm pack to package source files into wasm format

wasm-pack build --scope foo --target nodejs

After compilation, pkg directory will be generated, which can be directly published to npm for use.
If you want to use it on a browser, compile with -- target browser
You can also specify the generated directory, - D browser ﹣ PKG

If we have installed nodejs before, we can create a test.js file in this directory to test the wasm package we just compiled.

test.js

const { blake2b_encode } = require('./pkg')
const assert = require('assert')

const encodeString = blake2b_encode(Buffer.from("foo"))
const expectedString = "ca002330e69d3e6b84a46a56a6533fd79d51d97a3bb7cad6c2ff43b354185d6dc1e723fb3db4ae0737e120378424c714bb982d9dc5bbd7a0ab318240ddd18f8d"
assert.equal(encodeString, expectedString)

Posted by Fearpig on Wed, 30 Oct 2019 07:01:55 -0700