use crate::mw::Middleware;
use anyhow::Result;
use ubl_types::Dim;
use std::{collections::HashMap, sync::Arc};
pub type HandlerFn = dyn Fn(&[u8]) -> Result<Vec<u8>> + Send + Sync + 'static;
pub struct FnHandler<F>(pub F);
impl<F> FnHandler<F>
where
F: Fn(&[u8]) -> Result<Vec<u8>> + Send + Sync + 'static,
{
pub fn into_arc(self) -> Arc<HandlerFn> {
Arc::new(self.0)
}
}
#[derive(Default)]
pub struct Router {
pub(crate) map: HashMap<u16, Arc<HandlerFn>>,
pub(crate) mw_before: Vec<Box<dyn Middleware>>,
pub(crate) mw_after: Vec<Box<dyn Middleware>>,
}
impl Router {
pub fn add<F>(&mut self, dim: Dim, h: FnHandler<F>)
where
F: Fn(&[u8]) -> Result<Vec<u8>> + Send + Sync + 'static,
{
self.map.insert(dim.0, h.into_arc());
}
#[must_use]
pub fn get(&self, dim: Dim) -> Option<Arc<HandlerFn>> {
self.map.get(&dim.0).cloned()
}
pub fn use_before<M: Middleware + 'static>(&mut self, m: M) {
self.mw_before.push(Box::new(m));
}
pub fn use_after<M: Middleware + 'static>(&mut self, m: M) {
self.mw_after.push(Box::new(m));
}
}