xitca_router/
error.rs

1use core::{fmt, str::Utf8Error};
2
3use super::tree::{denormalize_params, Node};
4
5/// Represents errors that can occur when inserting a new route.
6#[non_exhaustive]
7#[derive(Clone, Debug, Eq, PartialEq)]
8pub enum InsertError {
9    /// Attempted to insert a path that conflicts with an existing route.
10    Conflict {
11        /// The existing route that the insertion is conflicting with.
12        with: String,
13    },
14    /// Route path is not in utf-8 format.
15    Parse(Utf8Error),
16    /// Only one parameter per route segment is allowed.
17    TooManyParams,
18    /// Parameters must be registered with a name.
19    UnnamedParam,
20    /// Catch-all parameters are only allowed at the end of a path.
21    InvalidCatchAll,
22}
23
24impl fmt::Display for InsertError {
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        match self {
27            Self::Conflict { with } => {
28                write!(
29                    f,
30                    "insertion failed due to conflict with previously registered route: {with}",
31                )
32            }
33            Self::Parse(ref e) => fmt::Display::fmt(e, f),
34            Self::TooManyParams => f.write_str("only one parameter is allowed per path segment"),
35            Self::UnnamedParam => f.write_str("parameters must be registered with a name"),
36            Self::InvalidCatchAll => f.write_str("catch-all parameters are only allowed at the end of a route"),
37        }
38    }
39}
40
41impl std::error::Error for InsertError {}
42
43impl From<Utf8Error> for InsertError {
44    fn from(e: Utf8Error) -> Self {
45        Self::Parse(e)
46    }
47}
48
49impl InsertError {
50    pub(crate) fn conflict<T>(route: &[u8], prefix: &[u8], current: &Node<T>) -> Self {
51        let mut route = route[..route.len() - prefix.len()].to_owned();
52
53        if !route.ends_with(current.prefix.as_bytes()) {
54            route.extend_from_slice(current.prefix.as_bytes());
55        }
56
57        let mut last = current;
58        while let Some(node) = last.children.first() {
59            last = node;
60        }
61
62        let mut current = current.children.first();
63        while let Some(node) = current {
64            route.extend_from_slice(node.prefix.as_bytes());
65            current = node.children.first();
66        }
67
68        denormalize_params(&mut route, &last.param_remapping);
69
70        InsertError::Conflict {
71            with: String::from_utf8(route).unwrap(),
72        }
73    }
74}
75
76/// error type indicate Router can not find a matching route.
77#[derive(Debug, PartialEq, Eq, Clone, Copy)]
78pub struct MatchError;
79
80impl fmt::Display for MatchError {
81    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82        f.write_str("router error: route not found")
83    }
84}
85
86impl std::error::Error for MatchError {}