use crate::error::MergeError;
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)
}
#[inline]
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),
}
}
#[inline]
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()
}
pub fn merge(&mut self, other: Self) -> Result<(), MergeError> {
let mut errors = Vec::new();
other.root.for_each(|path, value| {
if let Err(err) = self.insert(path, value) {
errors.push(err);
}
});
if errors.is_empty() {
Ok(())
} else {
Err(MergeError(errors))
}
}
}
#[derive(Debug)]
pub struct Match<'k, 'v, V> {
pub value: V,
pub params: Params<'k, 'v>,
}