use core::{error, fmt, ops::Deref};
use crate::{
String, Vec,
escape::{UnescapedRef, UnescapedRoute},
tree::{Node, denormalize_params},
};
#[non_exhaustive]
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum InsertError {
Conflict {
with: String,
},
InvalidParamSegment,
InvalidParam,
InvalidCatchAll,
}
impl fmt::Display for InsertError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let fmt = match self {
Self::Conflict { with } => {
return write!(
f,
"Insertion failed due to conflict with previously registered route: {with}"
);
}
Self::InvalidParamSegment => "Only one parameter is allowed per path segment",
Self::InvalidParam => "Parameters must be registered with a valid name",
Self::InvalidCatchAll => "Catch-all parameters are only allowed at the end of a route",
};
fmt::Display::fmt(fmt, f)
}
}
impl error::Error for InsertError {}
impl InsertError {
pub(crate) fn conflict<T>(route: &UnescapedRoute, prefix: UnescapedRef<'_>, current: &Node<T>) -> Self {
let mut route = route.clone();
if *prefix == *current.prefix {
denormalize_params(&mut route, ¤t.remapping);
return InsertError::Conflict {
with: route.into_unescaped(),
};
}
route.truncate(route.len() - prefix.len());
if !route.ends_with(¤t.prefix) {
route.append(¤t.prefix);
}
let mut child = current.children.first();
while let Some(node) = child {
route.append(&node.prefix);
child = node.children.first();
}
let mut last = current;
while let Some(node) = last.children.first() {
last = node;
}
denormalize_params(&mut route, &last.remapping);
InsertError::Conflict {
with: route.into_unescaped(),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MergeError(pub(crate) Vec<InsertError>);
impl MergeError {
pub fn into_errors(self) -> Vec<InsertError> {
self.0
}
}
impl fmt::Display for MergeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for error in self.0.iter() {
writeln!(f, "{error}")?;
}
Ok(())
}
}
impl error::Error for MergeError {}
impl Deref for MergeError {
type Target = [InsertError];
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct MatchError;
impl fmt::Display for MatchError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt("Matching route not found", f)
}
}
impl error::Error for MatchError {}