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_with_default_ctx()
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(
50 false,
51 include_bytes!("../../../plugins/bin/test_plugin.wasm"),
52 )
53 .await
54 .unwrap();
55
56 let plugin = TestPlugin {
57 noop: runtime.function("noop").unwrap(),
58 constant: runtime.function("constant").unwrap(),
59 identity: runtime.function("identity").unwrap(),
60 add: runtime.function("add").unwrap(),
61 swap: runtime.function("swap").unwrap(),
62 sort: runtime.function("sort").unwrap(),
63 print: runtime.function("print").unwrap(),
64 and_back: runtime.function("and_back").unwrap(),
65 imports: runtime.function("imports").unwrap(),
66 half_async: runtime.function("half_async").unwrap(),
67 echo_async: runtime.function("echo_async").unwrap(),
68 };
69
70 let unsorted = vec![1, 3, 4, 2, 5];
71 let sorted = vec![1, 2, 3, 4, 5];
72
73 assert_eq!(runtime.call(&plugin.noop, ()).await.unwrap(), ());
74 assert_eq!(runtime.call(&plugin.constant, ()).await.unwrap(), 27);
75 assert_eq!(runtime.call(&plugin.identity, 58).await.unwrap(), 58);
76 assert_eq!(runtime.call(&plugin.add, (3, 4)).await.unwrap(), 7);
77 assert_eq!(runtime.call(&plugin.swap, (1, 2)).await.unwrap(), (2, 1));
78 assert_eq!(runtime.call(&plugin.sort, unsorted).await.unwrap(), sorted);
79 assert_eq!(runtime.call(&plugin.print, "Hi!".into()).await.unwrap(), ());
80 assert_eq!(runtime.call(&plugin.and_back, 1).await.unwrap(), 8);
81 assert_eq!(runtime.call(&plugin.imports, 1).await.unwrap(), 8);
82 assert_eq!(runtime.call(&plugin.half_async, 4).await.unwrap(), 2);
83 assert_eq!(
84 runtime
85 .call(&plugin.echo_async, "eko".into())
86 .await
87 .unwrap(),
88 "eko\n"
89 );
90 }
91 .block_on()
92 }
93}