xitca_router/router.rs
1use super::{params::Params, tree::Node, InsertError, MatchError};
2
3/// A URL router.
4///
5/// See [the crate documentation](crate) for details.
6#[derive(Clone)]
7#[cfg_attr(test, derive(Debug))]
8pub struct Router<T> {
9 root: Node<T>,
10}
11
12impl<T> Default for Router<T> {
13 fn default() -> Self {
14 unimplemented!("please use Router::new");
15 }
16}
17
18impl<T> Router<T> {
19 /// Construct a new router.
20 pub const fn new() -> Self {
21 Self { root: Node::new() }
22 }
23
24 /// Insert a route.
25 ///
26 /// # Examples
27 ///
28 /// ```rust
29 /// # use xitca_router::Router;
30 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
31 /// let mut router = Router::new();
32 /// router.insert("/home", "Welcome!")?;
33 /// router.insert("/users/:id", "A User")?;
34 /// # Ok(())
35 /// # }
36 /// ```
37 pub fn insert(&mut self, route: impl Into<String>, value: T) -> Result<(), InsertError> {
38 self.root.insert(route, value)
39 }
40
41 /// Tries to find a value in the router matching the given path.
42 ///
43 /// # Examples
44 ///
45 /// ```rust
46 /// # use xitca_router::Router;
47 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
48 /// let mut router = Router::new();
49 /// router.insert("/home", "Welcome!")?;
50 ///
51 /// let matched = router.at("/home").unwrap();
52 /// assert_eq!(*matched.value, "Welcome!");
53 /// # Ok(())
54 /// # }
55 /// ```
56 #[inline]
57 pub fn at(&self, path: &str) -> Result<Match<&T>, MatchError> {
58 self.root.at(path).map(|(value, params)| Match { value, params })
59 }
60
61 #[cfg(feature = "__test_helpers")]
62 pub fn check_priorities(&self) -> Result<u32, (u32, u32)> {
63 self.root.check_priorities()
64 }
65}
66
67/// A successful match consisting of the registered value
68/// and URL parameters, returned by [`Router::at`](Router::at).
69#[derive(Debug)]
70pub struct Match<V> {
71 /// The value stored under the matched node.
72 pub value: V,
73 /// The route parameters. See [parameters](crate#parameters) for more details.
74 pub params: Params,
75}