Webassembly实践 - rust to wasm

目标

利用rust现有的lib - blake2b-simd, 生成js可调用的工具类函数。避免用js转译rust代码带来的资源消耗。

环境

  • rustc rustup cargo (rust-lang 的开发编译工具)
  • nodejs (发布wasm-pack生成的package)

安装 wasm-pack

cargo install wasm-pack

使用cargo创建项目

cargo new --lib blake2b-wasm

cd到blake2b-wasm目录

编辑Cargo.toml

[package]
name = "blake2b-wasm"
version = "0.1.0"
authors = ["foo "]
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.rs

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)

你可能感兴趣的:(javascript,html5,node.js,rust,rust-lang)