use crate::tree::Node;
use crate::{InsertError, MatchError, Params};
#[derive(Clone, Debug)]
pub struct Router<T> {
root: Node<T>,
}
impl<T> Default for Router<T> {
fn default() -> Self {
Self {
root: Node::default(),
}
}
}
impl<T> Router<T> {
pub fn new() -> Self {
Self::default()
}
pub fn insert(&mut self, route: impl Into<String>, value: T) -> Result<(), InsertError> {
self.root.insert(route.into(), value)
}
pub fn at<'path>(&self, path: &'path str) -> Result<Match<'_, 'path, &T>, MatchError> {
match self.root.at(path.as_bytes()) {
Ok((value, params)) => Ok(Match {
value: unsafe { &*value.get() },
params,
}),
Err(e) => Err(e),
}
}
pub fn at_mut<'path>(
&mut self,
path: &'path str,
) -> Result<Match<'_, 'path, &mut T>, MatchError> {
match self.root.at(path.as_bytes()) {
Ok((value, params)) => Ok(Match {
value: unsafe { &mut *value.get() },
params,
}),
Err(e) => Err(e),
}
}
pub fn remove(&mut self, path: impl Into<String>) -> Option<T> {
self.root.remove(path.into())
}
#[cfg(feature = "__test_helpers")]
pub fn check_priorities(&self) -> Result<u32, (u32, u32)> {
self.root.check_priorities()
}
}
#[derive(Debug)]
pub struct Match<'k, 'v, V> {
pub value: V,
pub params: Params<'k, 'v>,
}