-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathwasm-rust.rs
207 lines (173 loc) · 6.06 KB
/
wasm-rust.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
use std::hint::black_box;
use eyre::{eyre, Result};
use tinywasm::{Extern, FuncContext, Imports, MemoryStringExt, Module, Store};
/// Examples of using WebAssembly compiled from Rust with tinywasm.
///
/// These examples are meant to be run with `cargo run --example wasm-rust <example>`.
/// For example, `cargo run --example wasm-rust hello`.
///
/// To run these, you first need to compile the Rust examples to WebAssembly:
///
/// ```sh
/// ./examples/rust/build.sh
/// ```
///
/// This requires the `wasm32-unknown-unknown` target, `binaryen`, and `wabt` to be installed:
///
/// `rustup target add wasm32-unknown-unknown`.
/// <https://github.com/WebAssembly/wabt>
/// <https://github.com/WebAssembly/binaryen>
///
fn main() -> Result<()> {
pretty_env_logger::init();
if !std::path::Path::new("./examples/rust/out/").exists() {
return Err(eyre!("No WebAssembly files found. See examples/wasm-rust.rs for instructions."));
}
let args = std::env::args().collect::<Vec<_>>();
if args.len() < 2 {
println!("Usage: cargo run --example wasm-rust <rust_example>");
println!("Available examples:");
println!(" hello");
println!(" printi32");
println!(" fibonacci - calculate fibonacci(30)");
println!(" tinywasm - run printi32 inside of tinywasm inside of itself");
println!(" argon2id - run argon2id(1000, 2, 1)");
return Ok(());
}
match args[1].as_str() {
"hello" => hello()?,
"printi32" => printi32()?,
"fibonacci" => fibonacci()?,
"tinywasm" => tinywasm()?,
"tinywasm_no_std" => tinywasm_no_std()?,
"argon2id" => argon2id()?,
"all" => {
println!("Running all examples");
println!("\nhello.wasm:");
hello()?;
println!("\nprinti32.wasm:");
printi32()?;
println!("\nfibonacci.wasm:");
fibonacci()?;
println!("\ntinywasm.wasm:");
tinywasm()?;
println!("\ntinywasm_no_std.wasm:");
tinywasm_no_std()?;
println!("argon2id.wasm:");
argon2id()?;
}
_ => {}
}
Ok(())
}
fn tinywasm() -> Result<()> {
let module = Module::parse_file("./examples/rust/out/tinywasm.opt.wasm")?;
let mut store = Store::default();
let mut imports = Imports::new();
imports.define("env", "printi32", Extern::typed_func(|_: FuncContext<'_>, _x: i32| Ok(())))?;
let instance = module.instantiate(&mut store, Some(black_box(imports)))?;
let hello = instance.exported_func::<(), ()>(&store, "hello")?;
hello.call(&mut store, black_box(()))?;
hello.call(&mut store, black_box(()))?;
hello.call(&mut store, black_box(()))?;
Ok(())
}
fn tinywasm_no_std() -> Result<()> {
let module = Module::parse_file("./examples/rust/out/tinywasm_no_std.wasm")?;
let mut store = Store::default();
let mut imports = Imports::new();
imports.define("env", "printi32", Extern::typed_func(|_: FuncContext<'_>, _x: i32| Ok(())))?;
let instance = module.instantiate(&mut store, Some(black_box(imports)))?;
let hello = instance.exported_func::<(), ()>(&store, "hello")?;
hello.call(&mut store, black_box(()))?;
hello.call(&mut store, black_box(()))?;
hello.call(&mut store, black_box(()))?;
Ok(())
}
fn hello() -> Result<()> {
let module = Module::parse_file("./examples/rust/out/hello.opt.wasm")?;
let mut store = Store::default();
let mut imports = Imports::new();
imports.define(
"env",
"print_utf8",
Extern::typed_func(|mut ctx: FuncContext<'_>, args: (i64, i32)| {
let mem = ctx.exported_memory("memory")?;
let ptr = args.0 as usize;
let len = args.1 as usize;
let string = mem.load_string(ptr, len)?;
println!("{string}");
Ok(())
}),
)?;
let instance = module.instantiate(&mut store, Some(imports))?;
let arg_ptr = instance.exported_func::<(), i32>(&store, "arg_ptr")?.call(&mut store, ())?;
let arg = b"world";
instance.exported_memory_mut(&mut store, "memory")?.store(arg_ptr as usize, arg.len(), arg)?;
let hello = instance.exported_func::<i32, ()>(&store, "hello")?;
hello.call(&mut store, arg.len() as i32)?;
Ok(())
}
fn printi32() -> Result<()> {
let module = Module::parse_file("./examples/rust/out/print.opt.wasm")?;
let mut store = Store::default();
let mut imports = Imports::new();
imports.define(
"env",
"printi32",
Extern::typed_func(|_: FuncContext<'_>, x: i32| {
println!("{x}");
Ok(())
}),
)?;
let instance = module.instantiate(&mut store, Some(imports))?;
let add_and_print = instance.exported_func::<(i32, i32), ()>(&store, "add_and_print")?;
add_and_print.call(&mut store, (1, 2))?;
Ok(())
}
fn fibonacci() -> Result<()> {
let module = Module::parse_file("./examples/rust/out/fibonacci.opt.wasm")?;
let mut store = Store::default();
let instance = module.instantiate(&mut store, None)?;
let fibonacci = instance.exported_func::<i32, i32>(&store, "fibonacci_recursive")?;
let n = 26;
let result = fibonacci.call(&mut store, n)?;
println!("fibonacci({n}) = {result}");
Ok(())
}
fn argon2id() -> Result<()> {
let module = Module::parse_file("./examples/rust/out/argon2id.opt.wasm")?;
let mut store = Store::default();
let instance = module.instantiate(&mut store, None)?;
let argon2id = instance.exported_func::<(i32, i32, i32), i32>(&store, "argon2id")?;
argon2id.call(&mut store, (1000, 2, 1))?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_hello() {
hello().unwrap();
}
#[test]
fn test_printi32() {
printi32().unwrap();
}
#[test]
fn test_fibonacci() {
fibonacci().unwrap();
}
#[test]
fn test_tinywasm() {
tinywasm().unwrap();
}
#[test]
fn test_tinywasm_no_std() {
tinywasm_no_std().unwrap();
}
#[test]
fn test_argon2id() {
argon2id().unwrap();
}
}