Skip to main content

ntex_router/
path.rs

1use std::ops::Index;
2
3use serde::de;
4
5use crate::de::PathDeserializer;
6use crate::{Resource, ResourcePath};
7
8#[derive(Debug, Clone)]
9pub(super) enum PathItem {
10    Static(&'static str),
11    Segment(String),
12    IdxSegment(u32, u32),
13}
14
15/// Resource path match information
16///
17/// Wraps a path source and stores the values of dynamic segments matched by
18/// a [`Router`](crate::Router).
19#[derive(Debug)]
20pub struct Path<T> {
21    resource: T,
22    pub(super) skip: u32,
23    pub(super) segments: Vec<(&'static str, PathItem)>,
24}
25
26impl<T: Default> Default for Path<T> {
27    fn default() -> Self {
28        Path {
29            resource: T::default(),
30            skip: 0,
31            segments: Vec::new(),
32        }
33    }
34}
35
36impl<T: Clone> Clone for Path<T> {
37    fn clone(&self) -> Self {
38        Path {
39            resource: self.resource.clone(),
40            skip: self.skip,
41            segments: self.segments.clone(),
42        }
43    }
44}
45
46impl<T: ResourcePath> Path<T> {
47    /// Creates a new path state for the path source.
48    pub fn new(resource: T) -> Path<T> {
49        Path {
50            resource,
51            skip: 0,
52            segments: Vec::new(),
53        }
54    }
55
56    #[inline]
57    /// Get reference to inner path instance
58    pub fn get_ref(&self) -> &T {
59        &self.resource
60    }
61
62    #[inline]
63    /// Get mutable reference to inner path instance
64    pub fn get_mut(&mut self) -> &mut T {
65        &mut self.resource
66    }
67
68    #[inline]
69    /// Consume the path state and return the inner path instance
70    pub fn into_inner(self) -> T {
71        self.resource
72    }
73
74    #[inline]
75    /// Path that is not matched yet, e.g. the rest of the path after a prefix
76    /// resource matched.
77    ///
78    /// Unlike [`get_ref().path()`](ResourcePath::path), which is the full path,
79    /// it excludes the skipped part of the path.
80    pub fn path(&self) -> &str {
81        let skip = self.skip as usize;
82        let path = self.resource.path();
83        if skip <= path.len() { &path[skip..] } else { "" }
84    }
85
86    #[inline]
87    /// Set new path source and reset state
88    pub fn set(&mut self, resource: T) {
89        self.skip = 0;
90        self.resource = resource;
91        self.segments.clear();
92    }
93
94    #[inline]
95    /// Reset skipped length and matched segments
96    pub fn reset(&mut self) {
97        self.skip = 0;
98        self.segments.clear();
99    }
100
101    #[inline]
102    /// Skip first `n` bytes in path, matching starts after them
103    ///
104    /// The skipped length is limited to the path length.
105    ///
106    /// # Panics
107    ///
108    /// Panics if the skipped length ends inside a multi-byte character.
109    pub fn skip(&mut self, n: u32) {
110        let path = self.resource.path();
111        let len = u32::try_from(path.len()).unwrap_or(u32::MAX);
112        let skip = self.skip.saturating_add(n).min(len);
113        assert!(
114            path.is_char_boundary(skip as usize),
115            "skipped length {skip} is not a char boundary of path {path:?}"
116        );
117        self.skip = skip;
118    }
119
120    // pub(crate) fn add(&mut self, name: &'static str, value: String) {
121    //     self.segments.push((name, PathItem::Segment(value)))
122    // }
123
124    #[doc(hidden)]
125    pub fn add_static(&mut self, name: &'static str, value: &'static str) {
126        self.segments.push((name, PathItem::Static(value)));
127    }
128
129    #[inline]
130    /// Check if there are any matched segments
131    pub fn is_empty(&self) -> bool {
132        self.segments.is_empty()
133    }
134
135    #[inline]
136    /// Number of matched segments
137    pub fn len(&self) -> usize {
138        self.segments.len()
139    }
140
141    /// Get matched segment by name without type conversion
142    ///
143    /// If no segment is named `tail`, the `tail` key returns the unprocessed
144    /// part of the path, see [`path()`](Self::path).
145    pub fn get(&self, key: &str) -> Option<&str> {
146        for item in &self.segments {
147            if key == item.0 {
148                return match item.1 {
149                    PathItem::Static(s) => Some(s),
150                    PathItem::Segment(ref s) => Some(s),
151                    PathItem::IdxSegment(s, e) => {
152                        Some(&self.resource.path()[(s as usize)..(e as usize)])
153                    }
154                };
155            }
156        }
157        if key == "tail" { Some(self.path()) } else { None }
158    }
159
160    /// Iterator over matched segments as `(name, value)` pairs, in pattern
161    /// order
162    pub fn iter(&self) -> PathIter<'_, T> {
163        PathIter {
164            idx: 0,
165            params: self,
166        }
167    }
168
169    /// Try to deserialize matched segments to a specified type `U`
170    ///
171    /// See [`PathDeserializer`].
172    pub fn load<'de, U: serde::Deserialize<'de>>(&'de self) -> Result<U, de::value::Error> {
173        de::Deserialize::deserialize(PathDeserializer::new(self))
174    }
175}
176
177/// Iterator over matched segments, see [`Path::iter()`]
178#[derive(Debug)]
179pub struct PathIter<'a, T> {
180    idx: usize,
181    params: &'a Path<T>,
182}
183
184impl<'a, T: ResourcePath> Iterator for PathIter<'a, T> {
185    type Item = (&'a str, &'a str);
186
187    #[inline]
188    fn next(&mut self) -> Option<(&'a str, &'a str)> {
189        if self.idx < self.params.len() {
190            let idx = self.idx;
191            let res = match self.params.segments[idx].1 {
192                PathItem::Static(s) => s,
193                PathItem::Segment(ref s) => s.as_str(),
194                PathItem::IdxSegment(s, e) => {
195                    &self.params.resource.path()[(s as usize)..(e as usize)]
196                }
197            };
198            self.idx += 1;
199            return Some((self.params.segments[idx].0, res));
200        }
201        None
202    }
203}
204
205impl<'a, T: ResourcePath> IntoIterator for &'a Path<T> {
206    type Item = (&'a str, &'a str);
207    type IntoIter = PathIter<'a, T>;
208
209    fn into_iter(self) -> PathIter<'a, T> {
210        self.iter()
211    }
212}
213
214impl<'a, T: ResourcePath> Index<&'a str> for Path<T> {
215    type Output = str;
216
217    fn index(&self, name: &'a str) -> &str {
218        self.get(name)
219            .expect("Value for parameter is not available")
220    }
221}
222
223impl<T: ResourcePath> Index<usize> for Path<T> {
224    type Output = str;
225
226    fn index(&self, idx: usize) -> &str {
227        let Some((_, item)) = self.segments.get(idx) else {
228            panic!(
229                "Segment index {idx} is out of range, path has {} segments",
230                self.segments.len()
231            )
232        };
233        match *item {
234            PathItem::Static(s) => s,
235            PathItem::Segment(ref s) => s,
236            PathItem::IdxSegment(s, e) => &self.resource.path()[(s as usize)..(e as usize)],
237        }
238    }
239}
240
241impl<T: ResourcePath> Resource<T> for Path<T> {
242    fn path(&self) -> &str {
243        self.path()
244    }
245
246    fn resource_path(&mut self) -> &mut Path<T> {
247        self
248    }
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254
255    /// STATEMENT: Path mutation, cloning, skipping, resetting, and indexed captures preserve
256    /// the underlying source.
257    ///
258    /// HOW:
259    /// - Mutate a default `Path<String>` to `test` and verify both the source and its clone.
260    /// - Skip two bytes and check the remaining path and fallback `tail` are `st`, an unknown
261    ///   key is absent, and the source remains `test`.
262    /// - Reset the path, then add an indexed `k1` segment and verify it extracts `te`.
263    #[test]
264    fn test_path() {
265        let mut p: Path<String> = Path::default();
266        assert_eq!(p.get_ref(), &String::new());
267        p.get_mut().push_str("test");
268        assert_eq!(p.get_ref().as_str(), "test");
269        let p2 = p.clone();
270        assert_eq!(p2.get_ref().as_str(), "test");
271
272        p.skip(2);
273        assert_eq!(p.get("tail").unwrap(), "st");
274        assert_eq!(p.get("unknown"), None);
275        assert_eq!(p.path(), "st");
276        assert_eq!(p.get_ref().path(), "test");
277
278        p.reset();
279        assert_eq!(p.path(), "test");
280
281        p.segments.push(("k1", PathItem::IdxSegment(0, 2)));
282        assert_eq!(p.get("k1").unwrap(), "te");
283    }
284
285    /// STATEMENT: Paths expose static and owned captures, bound skipping, and clear captures
286    /// when their source is replaced.
287    ///
288    /// HOW:
289    /// - Skip the prefix of `/first/path`, add static and owned captures, and verify the
290    ///   remaining path, length, named and numeric access, and iteration order.
291    /// - Skip beyond the source length and confirm the remaining path is empty.
292    /// - Set the source to `/second` and verify captures are cleared and both path accessors
293    ///   return the replacement.
294    #[test]
295    fn test_path_set_and_items() {
296        let mut p = Path::new("/first/path");
297        p.skip(7);
298        p.add_static("st", "static");
299        p.segments
300            .push(("seg", PathItem::Segment("owned".to_string())));
301        assert_eq!(p.path(), "path");
302        assert_eq!(p.len(), 2);
303        assert_eq!(p.get("st"), Some("static"));
304        assert_eq!(p.get("seg"), Some("owned"));
305        assert_eq!(&p[0], "static");
306        assert_eq!(&p[1], "owned");
307        assert_eq!(
308            p.iter().collect::<Vec<_>>(),
309            vec![("st", "static"), ("seg", "owned")]
310        );
311
312        // skip is limited to the path length
313        p.skip(100);
314        assert_eq!(p.path(), "");
315
316        p.set("/second");
317        assert!(p.is_empty());
318        assert_eq!(p.path(), "/second");
319        assert_eq!(*p.get_ref(), "/second");
320    }
321
322    /// STATEMENT: Indexing a missing named parameter panics with the expected unavailable-value
323    /// message.
324    ///
325    /// HOW:
326    /// - Create a `Path` for `/` without captures and index it with `missing`.
327    /// - Use `should_panic` to verify the panic contains `Value for parameter is not
328    ///   available`.
329    #[test]
330    #[should_panic(expected = "Value for parameter is not available")]
331    fn test_path_index_missing() {
332        let p = Path::new("/");
333        let _ = &p["missing"];
334    }
335
336    /// STATEMENT: Numeric parameter indexing panics with the expected bounds message when the
337    /// index is too large.
338    ///
339    /// HOW:
340    /// - Add one static capture to `/test` and verify index `0` returns `static`.
341    /// - Access index `1` and use `should_panic` to verify the message reports index `1` and
342    ///   one segment.
343    #[test]
344    #[should_panic(expected = "Segment index 1 is out of range, path has 1 segments")]
345    fn index_out_of_range() {
346        let mut p = Path::new("/test");
347        p.add_static("st", "static");
348        assert_eq!(&p[0], "static");
349        let _ = &p[1];
350    }
351
352    /// STATEMENT: `skip` accepts lengths at char boundaries and panics inside a multi-byte
353    /// character instead of failing later in `path()`.
354    ///
355    /// HOW:
356    /// - Skip the three bytes of `/é` in `/é/x` and confirm the remaining path is `/x`.
357    /// - Skip two bytes of `/é` and confirm the panic names the length and the path.
358    #[test]
359    fn test_skip_char_boundary() {
360        let mut p = Path::new("/é/x");
361        p.skip(3);
362        assert_eq!(p.path(), "/x");
363
364        let msg = std::panic::catch_unwind(|| Path::new("/é").skip(2))
365            .unwrap_err()
366            .downcast::<String>()
367            .unwrap();
368        assert_eq!(
369            *msg,
370            r#"skipped length 2 is not a char boundary of path "/é""#
371        );
372    }
373}