use std::cell::RefCell;
use std::ffi::{CStr, CString, NulError, c_char, c_int, c_void};
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::ptr::NonNull;
use crate::ffi;
pub trait Router: 'static {
fn query(&mut self, logical_name: &str) -> bool;
fn write(&mut self, _logical_name: &str, _text: &str) {}
fn read(&mut self, _logical_name: &str) -> Option<u8> {
None
}
fn unread(&mut self, _logical_name: &str, _byte: u8) -> bool {
false
}
fn exit(&mut self, _exit_code: i32) {}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RouterError {
InteriorNul,
DuplicateName,
NotFound,
}
impl From<NulError> for RouterError {
fn from(_: NulError) -> Self {
Self::InteriorNul
}
}
impl std::fmt::Display for RouterError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::InteriorNul => formatter.write_str("router name contains a NUL byte"),
Self::DuplicateName => formatter.write_str("a CLIPS router already uses this name"),
Self::NotFound => formatter.write_str("CLIPS router was not found"),
}
}
}
impl std::error::Error for RouterError {}
struct RouterContext {
router: RefCell<Box<dyn Router>>,
}
pub(crate) struct RouterEntry {
name: CString,
_context: Box<RouterContext>,
}
impl RouterEntry {
pub(crate) fn register<R: Router>(
environment: NonNull<ffi::Environment>,
name: &str,
priority: i32,
router: R,
) -> Result<Self, RouterError> {
let name = CString::new(name)?;
let context = Box::new(RouterContext {
router: RefCell::new(Box::new(router)),
});
let context_ptr = (&*context as *const RouterContext)
.cast_mut()
.cast::<c_void>();
let added = unsafe {
ffi::AddRouter(
environment.as_ptr(),
name.as_ptr(),
priority,
Some(query_trampoline),
Some(write_trampoline),
Some(read_trampoline),
Some(unread_trampoline),
Some(exit_trampoline),
context_ptr,
)
};
added
.then_some(Self {
name,
_context: context,
})
.ok_or(RouterError::DuplicateName)
}
pub(crate) fn name(&self) -> &CStr {
&self.name
}
pub(crate) fn activate(
&self,
environment: NonNull<ffi::Environment>,
) -> Result<(), RouterError> {
unsafe { ffi::ActivateRouter(environment.as_ptr(), self.name.as_ptr()) }
.then_some(())
.ok_or(RouterError::NotFound)
}
pub(crate) fn deactivate(
&self,
environment: NonNull<ffi::Environment>,
) -> Result<(), RouterError> {
unsafe { ffi::DeactivateRouter(environment.as_ptr(), self.name.as_ptr()) }
.then_some(())
.ok_or(RouterError::NotFound)
}
pub(crate) fn unregister(
self,
environment: NonNull<ffi::Environment>,
) -> Result<(), (Self, RouterError)> {
if unsafe { ffi::DeleteRouter(environment.as_ptr(), self.name.as_ptr()) } {
Ok(())
} else {
Err((self, RouterError::NotFound))
}
}
}
unsafe fn context<'a>(raw: *mut c_void) -> Option<&'a RouterContext> {
NonNull::new(raw.cast::<RouterContext>()).map(|pointer| unsafe { pointer.as_ref() })
}
unsafe fn text<'a>(raw: *const c_char) -> Option<&'a str> {
(!raw.is_null())
.then(|| unsafe { CStr::from_ptr(raw) })
.and_then(|value| value.to_str().ok())
}
unsafe extern "C" fn query_trampoline(
_environment: *mut ffi::Environment,
logical_name: *const c_char,
raw_context: *mut c_void,
) -> bool {
catch_unwind(AssertUnwindSafe(|| {
let (Some(context), Some(logical_name)) =
(unsafe { (context(raw_context), text(logical_name)) })
else {
return false;
};
context
.router
.try_borrow_mut()
.map(|mut router| router.query(logical_name))
.unwrap_or(false)
}))
.unwrap_or(false)
}
unsafe extern "C" fn write_trampoline(
_environment: *mut ffi::Environment,
logical_name: *const c_char,
output: *const c_char,
raw_context: *mut c_void,
) {
let _ = catch_unwind(AssertUnwindSafe(|| {
let (Some(context), Some(logical_name), Some(output)) =
(unsafe { (context(raw_context), text(logical_name), text(output)) })
else {
return;
};
if let Ok(mut router) = context.router.try_borrow_mut() {
router.write(logical_name, output);
}
}));
}
unsafe extern "C" fn read_trampoline(
_environment: *mut ffi::Environment,
logical_name: *const c_char,
raw_context: *mut c_void,
) -> c_int {
catch_unwind(AssertUnwindSafe(|| {
let (Some(context), Some(logical_name)) =
(unsafe { (context(raw_context), text(logical_name)) })
else {
return -1;
};
context
.router
.try_borrow_mut()
.ok()
.and_then(|mut router| router.read(logical_name))
.map_or(-1, c_int::from)
}))
.unwrap_or(-1)
}
unsafe extern "C" fn unread_trampoline(
_environment: *mut ffi::Environment,
logical_name: *const c_char,
character: c_int,
raw_context: *mut c_void,
) -> c_int {
catch_unwind(AssertUnwindSafe(|| {
let (Some(context), Some(logical_name), Ok(byte)) = (
unsafe { context(raw_context) },
unsafe { text(logical_name) },
u8::try_from(character),
) else {
return -1;
};
if context
.router
.try_borrow_mut()
.map(|mut router| router.unread(logical_name, byte))
.unwrap_or(false)
{
character
} else {
-1
}
}))
.unwrap_or(-1)
}
unsafe extern "C" fn exit_trampoline(
_environment: *mut ffi::Environment,
exit_code: c_int,
raw_context: *mut c_void,
) {
let _ = catch_unwind(AssertUnwindSafe(|| {
let Some(context) = (unsafe { context(raw_context) }) else {
return;
};
if let Ok(mut router) = context.router.try_borrow_mut() {
router.exit(exit_code);
}
}));
}