use crate::{
String, Vec,
error::{InsertError, MatchError, MergeError},
params::Params,
tree::Node,
};
#[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(&self, path: &str) -> Result<Match<&T>, MatchError> {
self.root.at(path).map(|(value, params)| Match { value, params })
}
pub fn remove(&mut self, path: impl Into<String>) -> Option<T> {
self.root.remove(path.into())
}
#[doc(hidden)]
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<V> {
pub value: V,
pub params: Params,
}