利用rust現有的lib - blake2b-simd, 生成js可調用的工具類函數。避免用js轉譯rust代碼帶來的資源消耗。
安裝 wasm-packhtml
cargo install wasm-pack
使用cargo建立項目node
cargo new --lib blake2b-wasm
cd到blake2b-wasm目錄web
編輯Cargo.tomlshell
[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"
編輯src目錄下的lib.rsnpm
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()); } }
執行單元測試瀏覽器
cargo test
若是看到如下結果,說明能夠進行下一步編譯webassembly函數
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
使用wasm-pack把源文件打包爲 wasm 格式工具
wasm-pack build --scope foo --target nodejs
編譯完成後會生成pkg目錄,這個能夠直接發佈到npm上使用
若是但願在瀏覽器上使用,編譯時使用 --target browser
也能夠指定生成的目錄, -d browser_pkg單元測試
若是咱們以前已經把nodejs安裝好了,能夠在此目錄下建立一個test.js文件來測試咱們剛纔編譯的wasm包測試
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)