1use std::cell::RefCell;
8use std::ffi::{CStr, CString, NulError, c_char, c_int, c_void};
9use std::panic::{AssertUnwindSafe, catch_unwind};
10use std::ptr::NonNull;
11
12use crate::ffi;
13
14pub trait Router: 'static {
20 fn query(&mut self, logical_name: &str) -> bool;
27
28 fn write(&mut self, _logical_name: &str, _text: &str) {}
30
31 fn read(&mut self, _logical_name: &str) -> Option<u8> {
33 None
34 }
35
36 fn unread(&mut self, _logical_name: &str, _byte: u8) -> bool {
38 false
39 }
40
41 fn exit(&mut self, _exit_code: i32) {}
44}
45
46#[derive(Debug, Clone, PartialEq, Eq)]
48pub enum RouterError {
49 InteriorNul,
51 DuplicateName,
54 NotFound,
56}
57
58impl From<NulError> for RouterError {
59 fn from(_: NulError) -> Self {
60 Self::InteriorNul
61 }
62}
63
64impl std::fmt::Display for RouterError {
65 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66 match self {
67 Self::InteriorNul => formatter.write_str("router name contains a NUL byte"),
68 Self::DuplicateName => formatter.write_str("a CLIPS router already uses this name"),
69 Self::NotFound => formatter.write_str("CLIPS router was not found"),
70 }
71 }
72}
73
74impl std::error::Error for RouterError {}
75
76struct RouterContext {
77 router: RefCell<Box<dyn Router>>,
78}
79
80pub(crate) struct RouterEntry {
85 name: CString,
86 _context: Box<RouterContext>,
87}
88
89impl RouterEntry {
90 pub(crate) fn register<R: Router>(
91 environment: NonNull<ffi::Environment>,
92 name: &str,
93 priority: i32,
94 router: R,
95 ) -> Result<Self, RouterError> {
96 let name = CString::new(name)?;
97 let context = Box::new(RouterContext {
98 router: RefCell::new(Box::new(router)),
99 });
100 let context_ptr = (&*context as *const RouterContext)
101 .cast_mut()
102 .cast::<c_void>();
103 let added = unsafe {
104 ffi::AddRouter(
105 environment.as_ptr(),
106 name.as_ptr(),
107 priority,
108 Some(query_trampoline),
109 Some(write_trampoline),
110 Some(read_trampoline),
111 Some(unread_trampoline),
112 Some(exit_trampoline),
113 context_ptr,
114 )
115 };
116 added
117 .then_some(Self {
118 name,
119 _context: context,
120 })
121 .ok_or(RouterError::DuplicateName)
122 }
123
124 pub(crate) fn name(&self) -> &CStr {
125 &self.name
126 }
127
128 pub(crate) fn activate(
129 &self,
130 environment: NonNull<ffi::Environment>,
131 ) -> Result<(), RouterError> {
132 unsafe { ffi::ActivateRouter(environment.as_ptr(), self.name.as_ptr()) }
133 .then_some(())
134 .ok_or(RouterError::NotFound)
135 }
136
137 pub(crate) fn deactivate(
138 &self,
139 environment: NonNull<ffi::Environment>,
140 ) -> Result<(), RouterError> {
141 unsafe { ffi::DeactivateRouter(environment.as_ptr(), self.name.as_ptr()) }
142 .then_some(())
143 .ok_or(RouterError::NotFound)
144 }
145
146 pub(crate) fn unregister(
148 self,
149 environment: NonNull<ffi::Environment>,
150 ) -> Result<(), (Self, RouterError)> {
151 if unsafe { ffi::DeleteRouter(environment.as_ptr(), self.name.as_ptr()) } {
152 Ok(())
153 } else {
154 Err((self, RouterError::NotFound))
155 }
156 }
157}
158
159unsafe fn context<'a>(raw: *mut c_void) -> Option<&'a RouterContext> {
160 NonNull::new(raw.cast::<RouterContext>()).map(|pointer| unsafe { pointer.as_ref() })
161}
162
163unsafe fn text<'a>(raw: *const c_char) -> Option<&'a str> {
164 (!raw.is_null())
165 .then(|| unsafe { CStr::from_ptr(raw) })
166 .and_then(|value| value.to_str().ok())
167}
168
169unsafe extern "C" fn query_trampoline(
170 _environment: *mut ffi::Environment,
171 logical_name: *const c_char,
172 raw_context: *mut c_void,
173) -> bool {
174 catch_unwind(AssertUnwindSafe(|| {
175 let (Some(context), Some(logical_name)) =
176 (unsafe { (context(raw_context), text(logical_name)) })
177 else {
178 return false;
179 };
180 context
181 .router
182 .try_borrow_mut()
183 .map(|mut router| router.query(logical_name))
184 .unwrap_or(false)
185 }))
186 .unwrap_or(false)
187}
188
189unsafe extern "C" fn write_trampoline(
190 _environment: *mut ffi::Environment,
191 logical_name: *const c_char,
192 output: *const c_char,
193 raw_context: *mut c_void,
194) {
195 let _ = catch_unwind(AssertUnwindSafe(|| {
196 let (Some(context), Some(logical_name), Some(output)) =
197 (unsafe { (context(raw_context), text(logical_name), text(output)) })
198 else {
199 return;
200 };
201 if let Ok(mut router) = context.router.try_borrow_mut() {
202 router.write(logical_name, output);
203 }
204 }));
205}
206
207unsafe extern "C" fn read_trampoline(
208 _environment: *mut ffi::Environment,
209 logical_name: *const c_char,
210 raw_context: *mut c_void,
211) -> c_int {
212 catch_unwind(AssertUnwindSafe(|| {
213 let (Some(context), Some(logical_name)) =
214 (unsafe { (context(raw_context), text(logical_name)) })
215 else {
216 return -1;
217 };
218 context
219 .router
220 .try_borrow_mut()
221 .ok()
222 .and_then(|mut router| router.read(logical_name))
223 .map_or(-1, c_int::from)
224 }))
225 .unwrap_or(-1)
226}
227
228unsafe extern "C" fn unread_trampoline(
229 _environment: *mut ffi::Environment,
230 logical_name: *const c_char,
231 character: c_int,
232 raw_context: *mut c_void,
233) -> c_int {
234 catch_unwind(AssertUnwindSafe(|| {
235 let (Some(context), Some(logical_name), Ok(byte)) = (
236 unsafe { context(raw_context) },
237 unsafe { text(logical_name) },
238 u8::try_from(character),
239 ) else {
240 return -1;
241 };
242 if context
243 .router
244 .try_borrow_mut()
245 .map(|mut router| router.unread(logical_name, byte))
246 .unwrap_or(false)
247 {
248 character
249 } else {
250 -1
251 }
252 }))
253 .unwrap_or(-1)
254}
255
256unsafe extern "C" fn exit_trampoline(
257 _environment: *mut ffi::Environment,
258 exit_code: c_int,
259 raw_context: *mut c_void,
260) {
261 let _ = catch_unwind(AssertUnwindSafe(|| {
262 let Some(context) = (unsafe { context(raw_context) }) else {
263 return;
264 };
265 if let Ok(mut router) = context.router.try_borrow_mut() {
266 router.exit(exit_code);
267 }
268 }));
269}