use crate::escape::{UnescapedRef, UnescapedRoute};
use crate::tree::{denormalize_params, Node};
use std::fmt;
use std::ops::Deref;
#[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 {
match self {
Self::Conflict { with } => {
write!(
f,
"Insertion failed due to conflict with previously registered route: {with}"
)
}
Self::InvalidParamSegment => {
write!(f, "Only one parameter is allowed per path segment")
}
Self::InvalidParam => write!(f, "Parameters must be registered with a valid name"),
Self::InvalidCatchAll => write!(
f,
"Catch-all parameters are only allowed at the end of a route"
),
}
}
}
impl std::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.unescaped() == current.prefix.unescaped() {
denormalize_params(&mut route, ¤t.remapping);
return InsertError::Conflict {
with: String::from_utf8(route.into_unescaped()).unwrap(),
};
}
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: String::from_utf8(route.into_unescaped()).unwrap(),
}
}
}
#[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 std::error::Error for MergeError {}
impl Deref for MergeError {
type Target = Vec<InsertError>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum MatchError {
NotFound,
}
impl fmt::Display for MatchError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Matching route not found")
}
}
impl std::error::Error for MatchError {}