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#[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 pub fn new(resource: T) -> Path<T> {
49 Path {
50 resource,
51 skip: 0,
52 segments: Vec::new(),
53 }
54 }
55
56 #[inline]
57 pub fn get_ref(&self) -> &T {
59 &self.resource
60 }
61
62 #[inline]
63 pub fn get_mut(&mut self) -> &mut T {
65 &mut self.resource
66 }
67
68 #[inline]
69 pub fn into_inner(self) -> T {
71 self.resource
72 }
73
74 #[inline]
75 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 pub fn set(&mut self, resource: T) {
89 self.skip = 0;
90 self.resource = resource;
91 self.segments.clear();
92 }
93
94 #[inline]
95 pub fn reset(&mut self) {
97 self.skip = 0;
98 self.segments.clear();
99 }
100
101 #[inline]
102 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 #[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 pub fn is_empty(&self) -> bool {
132 self.segments.is_empty()
133 }
134
135 #[inline]
136 pub fn len(&self) -> usize {
138 self.segments.len()
139 }
140
141 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 pub fn iter(&self) -> PathIter<'_, T> {
163 PathIter {
164 idx: 0,
165 params: self,
166 }
167 }
168
169 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#[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 #[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 #[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 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 #[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 #[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 #[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}