weirdnet_code_spaces/
host.rs1use crate::abi::{CALL_ERROR, CALL_OK, WnBuf, WnHost, WnStr};
5use std::ffi::c_void;
6
7pub trait Host {
9 fn call(&mut self, method: &str, request: &str) -> Result<String, String>;
12}
13
14pub unsafe fn run_with(abi_version: u32, run: crate::abi::PluginRun, host: &mut dyn Host) -> i32 {
23 let mut h: &mut dyn Host = host;
24 let table = WnHost { abi_version, ctx: &mut h as *mut &mut dyn Host as *mut c_void, call: host_call, free: host_free };
25 unsafe { run(&table) }
27}
28
29fn reply(out: *mut WnBuf, s: String) {
30 let b = s.into_bytes().into_boxed_slice();
31 let len = b.len();
32 let ptr = Box::into_raw(b) as *mut u8;
33 unsafe { *out = WnBuf { ptr, len, cap: len } };
35}
36
37unsafe extern "C" fn host_call(ctx: *mut c_void, method: WnStr, request: WnStr, out: *mut WnBuf) -> i32 {
39 if ctx.is_null() || out.is_null() {
40 return CALL_ERROR;
41 }
42 let (host, method, request) = unsafe { (&mut *(ctx as *mut &mut dyn Host), method.as_bytes(), request.as_bytes()) };
44 let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| -> Result<String, String> {
45 let method = std::str::from_utf8(method).map_err(|_| "invalid host method: not UTF-8".to_string())?;
46 let text = std::str::from_utf8(request).map_err(|_| "invalid request: not UTF-8".to_string())?;
47 host.call(method, text)
48 }));
49 match res {
50 Ok(Ok(s)) => {
51 reply(out, s);
52 CALL_OK
53 }
54 Ok(Err(e)) => {
55 reply(out, e);
56 CALL_ERROR
57 }
58 Err(_) => {
59 reply(out, "the host failed on this call".into());
60 CALL_ERROR
61 }
62 }
63}
64
65unsafe extern "C" fn host_free(_ctx: *mut c_void, buf: WnBuf) {
67 if !buf.ptr.is_null() {
68 drop(unsafe { Box::from_raw(std::ptr::slice_from_raw_parts_mut(buf.ptr, buf.len)) });
70 }
71}
72
73#[cfg(test)]
74mod tests {
75 use super::*;
76 use crate::abi::{RUN_ERROR, RUN_OK};
77
78 struct Echo(Vec<String>);
79 impl Host for Echo {
80 fn call(&mut self, method: &str, request: &str) -> Result<String, String> {
81 self.0.push(format!("{method}:{request}"));
82 match method {
83 "boom" => panic!("no"),
84 "fail" => Err("nope".into()),
85 _ => Ok(format!("[{request}]")),
86 }
87 }
88 }
89
90 fn call(h: &WnHost, m: &[u8], r: &str) -> (i32, String) {
91 let mut out = WnBuf::EMPTY;
92 let m = WnStr { ptr: m.as_ptr(), len: m.len() };
93 unsafe {
95 let c = (h.call)(h.ctx, m, WnStr::new(r), &mut out);
96 let t = String::from_utf8(out.as_slice().to_vec()).unwrap();
97 (h.free)(h.ctx, out);
98 (c, t)
99 }
100 }
101
102 impl WnBuf {
103 fn as_slice(&self) -> &[u8] {
104 unsafe { std::slice::from_raw_parts(self.ptr, self.len) }
106 }
107 }
108
109 unsafe extern "C" fn plugin(h: *const WnHost) -> i32 {
110 let h = unsafe { &*h };
112 assert_eq!(h.abi_version, 7);
113 assert_eq!(call(h, b"echo", "{}"), (CALL_OK, "[{}]".into()));
114 assert_eq!(call(h, b"fail", "x"), (CALL_ERROR, "nope".into()));
115 assert_eq!(call(h, b"boom", ""), (CALL_ERROR, "the host failed on this call".into()));
116 assert_eq!(call(h, &[0xff], ""), (CALL_ERROR, "invalid host method: not UTF-8".into()));
117 if h.ctx.is_null() { RUN_ERROR } else { RUN_OK }
118 }
119
120 #[test]
121 fn calls_reach_the_host_and_errors_come_back() {
122 let mut e = Echo(vec![]);
123 std::panic::set_hook(Box::new(|_| {}));
124 let code = unsafe { run_with(7, plugin, &mut e) };
126 let _ = std::panic::take_hook();
127 assert_eq!(code, RUN_OK);
128 assert_eq!(e.0, vec!["echo:{}", "fail:x", "boom:"]);
129 }
130}