1use crate::mw::Middleware;
3use anyhow::Result;
4use ubl_types::Dim;
5use std::{collections::HashMap, sync::Arc};
6
7pub type HandlerFn = dyn Fn(&[u8]) -> Result<Vec<u8>> + Send + Sync + 'static;
9pub struct FnHandler<F>(pub F);
11impl<F> FnHandler<F>
12where
13 F: Fn(&[u8]) -> Result<Vec<u8>> + Send + Sync + 'static,
14{
15 pub fn into_arc(self) -> Arc<HandlerFn> {
17 Arc::new(self.0)
18 }
19}
20
21#[derive(Default)]
23pub struct Router {
24 pub(crate) map: HashMap<u16, Arc<HandlerFn>>,
25 pub(crate) mw_before: Vec<Box<dyn Middleware>>,
26 pub(crate) mw_after: Vec<Box<dyn Middleware>>,
27}
28impl Router {
29 pub fn add<F>(&mut self, dim: Dim, h: FnHandler<F>)
31 where
32 F: Fn(&[u8]) -> Result<Vec<u8>> + Send + Sync + 'static,
33 {
34 self.map.insert(dim.0, h.into_arc());
35 }
36 #[must_use]
38 pub fn get(&self, dim: Dim) -> Option<Arc<HandlerFn>> {
39 self.map.get(&dim.0).cloned()
40 }
41 pub fn use_before<M: Middleware + 'static>(&mut self, m: M) {
43 self.mw_before.push(Box::new(m));
44 }
45 pub fn use_after<M: Middleware + 'static>(&mut self, m: M) {
47 self.mw_after.push(Box::new(m));
48 }
49}