1pub mod plugin;
2pub use plugin::*;
3
4#[cfg(test)]
5mod tests {
6 use super::*;
7 use pollster::FutureExt as _;
8
9 #[test]
10 pub fn test_plugin() {
11 pub struct TestPlugin {
12 noop: WasiFn<(), ()>,
13 constant: WasiFn<(), u32>,
14 identity: WasiFn<u32, u32>,
15 add: WasiFn<(u32, u32), u32>,
16 swap: WasiFn<(u32, u32), (u32, u32)>,
17 sort: WasiFn<Vec<u32>, Vec<u32>>,
18 print: WasiFn<String, ()>,
19 and_back: WasiFn<u32, u32>,
20 imports: WasiFn<u32, u32>,
21 half_async: WasiFn<u32, u32>,
22 echo_async: WasiFn<String, String>,
23 }
24
25 async {
26 let mut runtime = PluginBuilder::new_default()
27 .unwrap()
28 .host_function("mystery_number", |input: u32| input + 7)
29 .unwrap()
30 .host_function("import_noop", |_: ()| ())
31 .unwrap()
32 .host_function("import_identity", |input: u32| input)
33 .unwrap()
34 .host_function("import_swap", |(a, b): (u32, u32)| (b, a))
35 .unwrap()
36 .host_function_async("import_half", |a: u32| async move { a / 2 })
37 .unwrap()
38 .host_function_async("command_async", |command: String| async move {
39 let mut args = command.split(' ');
40 let command = args.next().unwrap();
41 smol::process::Command::new(command)
42 .args(args)
43 .output()
44 .await
45 .ok()
46 .map(|output| output.stdout)
47 })
48 .unwrap()
49 .init(PluginBinary::Wasm(
50 include_bytes!("../../../plugins/bin/test_plugin.wasm").as_ref(),
51 ))
52 .await
53 .unwrap();
54
55 let plugin = TestPlugin {
56 noop: runtime.function("noop").unwrap(),
57 constant: runtime.function("constant").unwrap(),
58 identity: runtime.function("identity").unwrap(),
59 add: runtime.function("add").unwrap(),
60 swap: runtime.function("swap").unwrap(),
61 sort: runtime.function("sort").unwrap(),
62 print: runtime.function("print").unwrap(),
63 and_back: runtime.function("and_back").unwrap(),
64 imports: runtime.function("imports").unwrap(),
65 half_async: runtime.function("half_async").unwrap(),
66 echo_async: runtime.function("echo_async").unwrap(),
67 };
68
69 let unsorted = vec![1, 3, 4, 2, 5];
70 let sorted = vec![1, 2, 3, 4, 5];
71
72 runtime.call(&plugin.noop, ()).await.unwrap();
73 assert_eq!(runtime.call(&plugin.constant, ()).await.unwrap(), 27);
74 assert_eq!(runtime.call(&plugin.identity, 58).await.unwrap(), 58);
75 assert_eq!(runtime.call(&plugin.add, (3, 4)).await.unwrap(), 7);
76 assert_eq!(runtime.call(&plugin.swap, (1, 2)).await.unwrap(), (2, 1));
77 assert_eq!(runtime.call(&plugin.sort, unsorted).await.unwrap(), sorted);
78 runtime.call(&plugin.print, "Hi!".into()).await.unwrap();
79 assert_eq!(runtime.call(&plugin.and_back, 1).await.unwrap(), 8);
80 assert_eq!(runtime.call(&plugin.imports, 1).await.unwrap(), 8);
81 assert_eq!(runtime.call(&plugin.half_async, 4).await.unwrap(), 2);
82 assert_eq!(
83 runtime
84 .call(&plugin.echo_async, "eko".into())
85 .await
86 .unwrap(),
87 "eko\n"
88 );
89 }
90 .block_on()
91 }
92}