Skip to content

Commit b13ba39

Browse files
improve host function API
1 parent d0c2134 commit b13ba39

7 files changed

Lines changed: 265 additions & 256 deletions

File tree

src/bin/utils/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ pub fn compile_wat(wat_path: &Path) -> Result<Vec<u8>, Box<dyn std::error::Error
4242
}
4343

4444
/// Loads and compiles a resource WAT file
45+
#[allow(dead_code)]
4546
pub fn load_resource_module(name: &str) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
4647
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
4748
.join("src/bin/resources")

src/bin/wagmi_example_host.rs

Lines changed: 40 additions & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use std::rc::Rc;
22
use std::cell::RefCell;
33
use std::collections::HashMap;
4-
use wagmi::{Module, Instance, Imports, ExportValue, WasmValue, RuntimeFunction, RuntimeType, Signature, ValType};
4+
use wagmi::{Module, Instance, Imports, ExportValue, WasmValue, RuntimeFunction, ValType};
55

66
mod utils;
77
use utils::load_resource_module;
@@ -11,89 +11,51 @@ struct HostState {
1111
last_printed: RefCell<Option<i32>>,
1212
}
1313

14-
fn create_host_print(state: Rc<HostState>) -> RuntimeFunction {
15-
let signature = Signature {
16-
params: vec![ValType::I32],
17-
result: None,
18-
};
19-
20-
let host_fn = Rc::new(move |args: &mut [WasmValue]| {
21-
let value = args[0].as_i32();
22-
println!(" [Host Print] Value: {}", value);
23-
*state.last_printed.borrow_mut() = Some(value);
24-
*state.call_count.borrow_mut() += 1;
25-
});
26-
27-
RuntimeFunction {
28-
ty: RuntimeType::from_signature(&signature),
29-
pc_start: None,
30-
locals_count: 0,
31-
owner: None,
32-
owner_idx: None,
33-
host: Some(host_fn),
34-
}
35-
}
36-
37-
fn create_host_random() -> RuntimeFunction {
38-
let signature = Signature {
39-
params: vec![],
40-
result: Some(ValType::I32),
41-
};
42-
43-
let host_fn = Rc::new(move |args: &mut [WasmValue]| {
44-
use std::time::{SystemTime, UNIX_EPOCH};
45-
let seed = SystemTime::now()
46-
.duration_since(UNIX_EPOCH)
47-
.unwrap()
48-
.subsec_nanos() as i32;
49-
let random = (seed ^ 0x5DEECE66Di64 as i32) % 100;
50-
println!(" [Host Random] Generated: {}", random);
51-
args[0] = WasmValue::from_i32(random);
52-
});
53-
54-
RuntimeFunction {
55-
ty: RuntimeType::from_signature(&signature),
56-
pc_start: None,
57-
locals_count: 0,
58-
owner: None,
59-
owner_idx: None,
60-
host: Some(host_fn),
61-
}
62-
}
63-
64-
fn create_host_add() -> RuntimeFunction {
65-
let signature = Signature {
66-
params: vec![ValType::I32, ValType::I32],
67-
result: Some(ValType::I32),
68-
};
69-
70-
let host_fn = Rc::new(move |args: &mut [WasmValue]| {
71-
let a = args[0].as_i32();
72-
let b = args[1].as_i32();
73-
let result = a + b;
74-
println!(" [Host Add] {} + {} = {}", a, b, result);
75-
args[0] = WasmValue::from_i32(result);
76-
});
77-
78-
RuntimeFunction {
79-
ty: RuntimeType::from_signature(&signature),
80-
pc_start: None,
81-
locals_count: 0,
82-
owner: None,
83-
owner_idx: None,
84-
host: Some(host_fn),
85-
}
86-
}
87-
8814
fn main() -> Result<(), Box<dyn std::error::Error>> {
8915
let host_state = Rc::new(HostState {
9016
call_count: RefCell::new(0),
9117
last_printed: RefCell::new(None),
9218
});
9319

94-
let print_fn = create_host_print(host_state.clone());
95-
let random_fn = create_host_random();
96-
let add_fn = create_host_add();
20+
let state_clone = host_state.clone();
21+
let print_fn = RuntimeFunction::new_host(
22+
vec![ValType::I32], // params
23+
None, // no result
24+
move |args| {
25+
let value = args[0].as_i32();
26+
println!(" [Host Print] Value: {}", value);
27+
*state_clone.last_printed.borrow_mut() = Some(value);
28+
*state_clone.call_count.borrow_mut() += 1;
29+
None
30+
}
31+
);
32+
33+
let random_fn = RuntimeFunction::new_host(
34+
vec![], // no params
35+
Some(ValType::I32), // returns i32
36+
|_args| {
37+
use std::time::{SystemTime, UNIX_EPOCH};
38+
let seed = SystemTime::now()
39+
.duration_since(UNIX_EPOCH)
40+
.unwrap()
41+
.subsec_nanos() as i32;
42+
let random = (seed ^ 0x5DEECE66Di64 as i32) % 100;
43+
println!(" [Host Random] Generated: {}", random);
44+
Some(WasmValue::from_i32(random))
45+
}
46+
);
47+
48+
let add_fn = RuntimeFunction::new_host(
49+
vec![ValType::I32, ValType::I32], // two i32 params
50+
Some(ValType::I32), // returns i32
51+
|args| {
52+
let a = args[0].as_i32();
53+
let b = args[1].as_i32();
54+
let result = a + b;
55+
println!(" [Host Add] {} + {} = {}", a, b, result);
56+
Some(WasmValue::from_i32(result))
57+
}
58+
);
9759

9860
let mut imports = Imports::new();
9961
let mut host_module = HashMap::new();

src/bin/wagmi_inspect.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
148148
for (name, export) in exports {
149149
match export {
150150
ExportValue::Function(func) => {
151-
println!(" {} : function (params: {}, result: {})", name, func.ty.n_params(), if func.ty.has_result() { "yes" } else { "no" });
151+
println!(" {} : function (params: {}, result: {})", name, func.ty().n_params(), if func.ty().has_result() { "yes" } else { "no" });
152152
}
153153
ExportValue::Table(table) => {
154154
let t = table.borrow();

src/bin/wagmi_run.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -134,13 +134,13 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
134134
for (name, export) in &instance.exports {
135135
if let ExportValue::Function(func) = export {
136136
print!(" {} (", name);
137-
let n_params = func.ty.n_params();
137+
let n_params = func.ty().n_params();
138138
for i in 0..n_params {
139139
if i > 0 { print!(", "); }
140140
print!("param{}", i);
141141
}
142142
print!(")");
143-
if func.ty.has_result() {
143+
if func.ty().has_result() {
144144
print!(" -> result");
145145
}
146146
println!();
@@ -168,11 +168,11 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
168168
wasm_args.push(parse_value(arg_str)?);
169169
}
170170

171-
if wasm_args.len() != func.ty.n_params() as usize {
171+
if wasm_args.len() != func.ty().n_params() as usize {
172172
return Err(format!(
173173
"Function '{}' expects {} arguments, but {} provided",
174174
func_name,
175-
func.ty.n_params(),
175+
func.ty().n_params(),
176176
wasm_args.len()
177177
).into());
178178
}

0 commit comments

Comments
 (0)