1个不稳定版本
0.1.0 | 2023年10月3日 |
---|
#598 in WebAssembly
16KB
152 代码行
rust-purewasm
rust-purewasm 是一个为Rust提供的 purewasm 库。
⚠ 开发中
rust-purewasm 是一个Rust库,旨在使用WebAssembly (Wasm) 构建纯函数。WebAssembly 是一种可移植的二进制中间语言,它能够在虚拟机中执行代码。它提供了一个安全沙箱环境,代码可以在其中运行,其指令集限于纯函数及其自身内存上的数值操作。尽管 WebAssembly 常用于网络技术,但它也适合在各种环境中开发确定性的(纯)函数。
然而,WebAssembly 在支持复杂数据类型方面存在局限性。尽管有这种局限性,purewasm 通过对内存做出假设,并提供了JSON和CBOR编解码器的编码解码功能来努力克服它。
运行时
purewasm 的运行时组件负责执行 WebAssembly 模块。它遵循以下步骤
- 使用指定的编解码器(如JSON或CBOR)将输入数据编码为字节。
- 分配内存以存储输入字节。
- 将输入的指针和长度传递给 WebAssembly 模块。
Wasm 模块
purewasm 的 wasm 模块组件负责处理输入数据,准备输出数据,并将其指针和长度返回给运行时。它执行以下任务
- 使用提供的指针和长度检索输入字节。
- 将输入数据从指定的编解码器(如JSON或CBOR)解码为适当的数据类型。
- 处理输入并准备输出数据。
- 使用指定的编解码器将输出数据编码为字节。
- 将输出数据的指针和长度返回给运行时。
一个 purewasm 函数只接受一个输入,并只返回一个输出。以下是一个示例,说明如何在Rust中定义一个可以作为WebAssembly模块使用的函数,它可以与JSON和CBOR编解码器一起使用
fn example(ptr: i32, len: i32) -> (i32, i32) {
// ...
}
安装
cargo install rust-purewasm
用法
模块
purewasm = { version = "0.1.0", features = ["bindgen-json"] }
#![no_main]
#![cfg_attr(not(test), no_std)]
extern crate alloc;
use purewasm::bindgen::prelude::*;
use serde::{Serialize, Deserialize};
use alloc::{format, string::String};
#[derive(Debug, Serialize, Deserialize)]
pub struct Input {
pub code: i32,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CustomResult {
pub msg: String,
}
#[purewasm_bindgen]
pub fn handle_example(input: Input) -> PureResult<CustomResult> {
Ok(CustomResult {
msg: format!("The input code is {}", input.code),
})
}
运行时(wasmtime)
purewasm = { version = "0.1.0", features = ["wasmtime"] }
use purewasm::wasmtime::PureModule;
fn main() {
let wasm_file = "../target/wasm32-unknown-unknown/release/purewasm_json_module.wasm";
let input = serde_json::to_vec(&serde_json::json!({"code": 6})).unwrap();
let mut module = PureModule::from_file(wasm_file);
let result = module.call_fn("handle_example", &input);
let result: serde_json::Value = serde_json::from_slice(&result).unwrap();
println!("Result: {:?}", result);
}
查看 cbor 示例
许可证
APACHE 2.0
依赖项
~0.4–15MB
~156K SLoC