use std::sync::{Arc, Mutex};
use tracing::{instrument, Span};
use crate::{new_error, Result};
pub trait OutBHandlerCaller: Sync + Send {
fn call(&mut self, port: u16, payload: u64) -> Result<()>;
}
pub type OutBHandlerWrapper = Arc<Mutex<dyn OutBHandlerCaller>>;
pub(crate) type OutBHandlerFunction = Box<dyn FnMut(u16, u64) -> Result<()> + Send>;
pub(crate) struct OutBHandler(Arc<Mutex<OutBHandlerFunction>>);
impl From<OutBHandlerFunction> for OutBHandler {
#[instrument(skip_all, parent = Span::current(), level= "Trace")]
fn from(func: OutBHandlerFunction) -> Self {
Self(Arc::new(Mutex::new(func)))
}
}
impl OutBHandlerCaller for OutBHandler {
#[instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace")]
fn call(&mut self, port: u16, payload: u64) -> Result<()> {
let mut func = self
.0
.try_lock()
.map_err(|e| new_error!("Error locking at {}:{}: {}", file!(), line!(), e))?;
func(port, payload)
}
}
pub trait MemAccessHandlerCaller: Send {
fn call(&mut self) -> Result<()>;
}
pub type MemAccessHandlerWrapper = Arc<Mutex<dyn MemAccessHandlerCaller>>;
pub(crate) type MemAccessHandlerFunction = Box<dyn FnMut() -> Result<()> + Send>;
pub(crate) struct MemAccessHandler(Arc<Mutex<MemAccessHandlerFunction>>);
impl From<MemAccessHandlerFunction> for MemAccessHandler {
#[instrument(skip_all, parent = Span::current(), level= "Trace")]
fn from(func: MemAccessHandlerFunction) -> Self {
Self(Arc::new(Mutex::new(func)))
}
}
impl MemAccessHandlerCaller for MemAccessHandler {
#[instrument(err(Debug), skip_all, parent = Span::current(), level= "Trace")]
fn call(&mut self) -> Result<()> {
let mut func = self
.0
.try_lock()
.map_err(|e| new_error!("Error locking at {}:{}: {}", file!(), line!(), e))?;
func()
}
}