Skip to main content

ntex_router/
lib.rs

1#![forbid(unsafe_code)]
2#![deny(clippy::pedantic)]
3#![allow(
4    clippy::must_use_candidate,
5    clippy::missing_panics_doc,
6    clippy::missing_errors_doc,
7    clippy::cast_possible_wrap,
8    clippy::cast_sign_loss,
9    clippy::cast_possible_truncation,
10    clippy::too_many_lines
11)]
12
13//! Resource path matching library.
14//!
15//! A [`Router`] maps request paths to values. Resources are registered with
16//! a [`RouterBuilder`] from path patterns, see [`ResourceDef`]. Matching a
17//! [`Path`] returns the value of the first registered resource that matches,
18//! and stores the values of the pattern's dynamic segments in the `Path`.
19//!
20//! # Pattern syntax
21//!
22//! Patterns are split into segments by `/`.
23//!
24//! * `/users/list` — static segments match literally. A trailing `/` is
25//!   significant, `/users/` does not match `/users`.
26//! * `/users/{id}` — a dynamic segment matches one or more characters up to
27//!   the next `/` and stores them as `id`.
28//! * `/files/{name}.{ext}` — a segment can combine static text and several
29//!   dynamic parts.
30//! * `/users/{id:[0-9]+}` — a dynamic segment with a custom regular
31//!   expression.
32//! * `/static/{tail}*` — a tail segment matches the rest of the path,
33//!   including `/`, and may be empty: `/static/` matches with an empty
34//!   `tail`. Custom regular expressions are not supported for tails.
35//! * `/static/*` — a static tail matches the rest of the path without storing
36//!   it. Unlike `{tail}*` it needs at least one character, `/static/` does
37//!   not match.
38//!
39//! Each parameter name may be used once per pattern, including the names of
40//! named groups inside custom regular expressions. Such a group is stored
41//! only if it participates in the match: `{a:(?P<x>q)?z}` matches `z` with
42//! `a` and without `x`.
43//!
44//! [`ResourceDef::prefix()`] creates a resource that matches paths starting
45//! with the pattern, at a segment boundary. After a match, [`Path::path()`]
46//! returns the rest of the path.
47//!
48//! # Example
49//!
50//! ```
51//! use ntex_router::{Path, Router};
52//!
53//! let mut builder = Router::<&str>::builder();
54//! builder.path("/users/{id}", "user");
55//! builder.path("/files/{tail}*", "files");
56//! let router = builder.build();
57//!
58//! let mut path = Path::new("/users/42");
59//! let (value, _) = router.recognize(&mut path).unwrap();
60//! assert_eq!(*value, "user");
61//! assert_eq!(path.get("id"), Some("42"));
62//!
63//! let mut path = Path::new("/files/css/site.css");
64//! let (value, _) = router.recognize(&mut path).unwrap();
65//! assert_eq!(*value, "files");
66//! assert_eq!(&path["tail"], "css/site.css");
67//!
68//! assert!(router.recognize(&mut Path::new("/unknown")).is_none());
69//! ```
70#![warn(missing_docs)]
71mod de;
72mod path;
73mod resource;
74mod router;
75mod tree;
76
77pub use self::de::PathDeserializer;
78pub use self::path::{Path, PathIter};
79pub use self::resource::{BuildPathError, ResourceDef};
80pub use self::router::{ResourceId, Router, RouterBuilder, RouterEntry};
81
82/// A value that can be matched by a [`Router`].
83///
84/// [`Path`] implements it, a request type can implement it to be matched
85/// directly.
86pub trait Resource<T: ResourcePath> {
87    /// Path to match.
88    fn path(&self) -> &str;
89
90    /// Path state that stores match results.
91    fn resource_path(&mut self) -> &mut Path<T>;
92}
93
94/// A path source, e.g. a string or an `urly::Url`.
95pub trait ResourcePath {
96    /// Full path.
97    fn path(&self) -> &str;
98
99    /// Decodes a path segment before it is matched.
100    ///
101    /// The path is split into segments on `/` before decoding, so a decoded
102    /// segment may contain `/`. The default implementation returns the
103    /// segment unchanged.
104    fn unquote(s: &str) -> std::borrow::Cow<'_, str> {
105        s.into()
106    }
107
108    /// Returns `false` if `unquote` returns every segment of `path` unchanged,
109    /// so the router can skip decoding them.
110    ///
111    /// The default implementation returns `true`.
112    fn needs_unquote(path: &str) -> bool {
113        let _ = path;
114        true
115    }
116}
117
118impl ResourcePath for String {
119    fn path(&self) -> &str {
120        self.as_str()
121    }
122
123    fn needs_unquote(_: &str) -> bool {
124        false
125    }
126}
127
128impl ResourcePath for &str {
129    fn path(&self) -> &str {
130        self
131    }
132
133    fn needs_unquote(_: &str) -> bool {
134        false
135    }
136}
137
138impl ResourcePath for ntex_bytes::ByteString {
139    fn path(&self) -> &str {
140        self
141    }
142
143    fn needs_unquote(_: &str) -> bool {
144        false
145    }
146}
147
148impl<T: ResourcePath> ResourcePath for &T {
149    fn path(&self) -> &str {
150        (*self).path()
151    }
152
153    fn unquote(s: &str) -> std::borrow::Cow<'_, str> {
154        T::unquote(s)
155    }
156
157    fn needs_unquote(path: &str) -> bool {
158        T::needs_unquote(path)
159    }
160}
161
162/// Helper trait for type that could be converted to path patterns.
163///
164/// Implemented for strings, and for vectors and arrays of strings for
165/// resources with several patterns.
166pub trait IntoPattern {
167    /// Path patterns.
168    fn patterns(&self) -> Vec<String>;
169}
170
171impl IntoPattern for String {
172    fn patterns(&self) -> Vec<String> {
173        vec![self.clone()]
174    }
175}
176
177impl IntoPattern for &String {
178    fn patterns(&self) -> Vec<String> {
179        vec![self.as_str().to_string()]
180    }
181}
182
183impl IntoPattern for &str {
184    fn patterns(&self) -> Vec<String> {
185        vec![(*self).to_string()]
186    }
187}
188
189impl<T: AsRef<str>> IntoPattern for Vec<T> {
190    fn patterns(&self) -> Vec<String> {
191        self.iter().map(|v| v.as_ref().to_string()).collect()
192    }
193}
194
195impl<T: AsRef<str>, const N: usize> IntoPattern for [T; N] {
196    fn patterns(&self) -> Vec<String> {
197        self.iter().map(|v| v.as_ref().to_string()).collect()
198    }
199}
200
201mod url_support {
202    use super::ResourcePath;
203    use urly::Url;
204
205    /// Path segments are percent-decoded, escapes that would not decode to
206    /// valid utf-8 are kept percent-encoded.
207    ///
208    /// Segments are decoded after the path is split on `/`, so parameter
209    /// values can contain any character, including `/` and `%`. For example
210    /// `/files/..%2F..%2Fetc` matches `/files/{name}` with `name` set to
211    /// `../../etc`. Such values must be validated before they are used, e.g.
212    /// as a file system path.
213    impl ResourcePath for Url {
214        fn path(&self) -> &str {
215            self.path().as_str()
216        }
217
218        fn unquote(s: &str) -> std::borrow::Cow<'_, str> {
219            urly::quoting::unquote(s, urly::quoting::Component::Path)
220        }
221
222        fn needs_unquote(path: &str) -> bool {
223            // path segments are decoded only at `%`
224            path.bytes().any(|b| b == b'%')
225        }
226    }
227}