use matchit::Router as MatchitRouter;
use reinhardt_http::PathParams;
#[derive(Debug, thiserror::Error)]
pub enum RadixRouterError {
#[error("Invalid pattern: {0}")]
InvalidPattern(String),
#[error("Route insertion failed: {0}")]
InsertionFailed(String),
}
pub struct RadixRouter {
router: MatchitRouter<String>,
}
impl RadixRouter {
pub fn new() -> Self {
Self {
router: MatchitRouter::new(),
}
}
pub fn add_route(&mut self, pattern: &str, handler_id: String) -> Result<(), RadixRouterError> {
self.router
.insert(pattern, handler_id)
.map_err(|e| RadixRouterError::InsertionFailed(e.to_string()))
}
pub fn match_path(&self, path: &str) -> Option<(String, PathParams)> {
match self.router.at(path) {
Ok(matched) => {
let handler_id = matched.value.clone();
let params: PathParams = matched
.params
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
Some((handler_id, params))
}
Err(_) => None,
}
}
}
impl Default for RadixRouter {
fn default() -> Self {
Self::new()
}
}