Skip to main content

ntex_router/
de.rs

1use serde::de::{self, Deserializer, Error as DeError, Visitor};
2use serde::forward_to_deserialize_any;
3
4use crate::{ResourcePath, path::Path, path::PathIter};
5
6macro_rules! unsupported_type {
7    ($trait_fn:ident, $name:expr) => {
8        fn $trait_fn<V>(self, _: V) -> Result<V::Value, Self::Error>
9        where
10            V: Visitor<'de>,
11        {
12            Err(de::value::Error::custom(concat!(
13                "unsupported type: ",
14                $name
15            )))
16        }
17    };
18}
19
20macro_rules! parse_single_value {
21    ($trait_fn:ident, $visit_fn:ident, $tp:tt) => {
22        fn $trait_fn<V>(self, visitor: V) -> Result<V::Value, Self::Error>
23        where
24            V: Visitor<'de>,
25        {
26            if self.path.len() != 1 {
27                Err(de::value::Error::custom(
28                    format!("wrong number of parameters: {} expected 1", self.path.len()).as_str(),
29                ))
30            } else {
31                let v = self.path[0].parse().map_err(|_| {
32                    de::value::Error::custom(format!(
33                        "can not parse {:?} to a {}",
34                        &self.path[0], $tp
35                    ))
36                })?;
37                visitor.$visit_fn(v)
38            }
39        }
40    };
41}
42
43#[derive(Debug)]
44/// Serde deserializer for the dynamic segments of a matched [`Path`].
45///
46/// A struct or map is deserialized from segments by name, a tuple or
47/// sequence from segments in pattern order, a single value from the only
48/// segment. See [`Path::load()`].
49pub struct PathDeserializer<'de, T: ResourcePath> {
50    path: &'de Path<T>,
51}
52
53impl<'de, T: ResourcePath + 'de> PathDeserializer<'de, T> {
54    /// Creates a deserializer for the path.
55    pub fn new(path: &'de Path<T>) -> Self {
56        PathDeserializer { path }
57    }
58}
59
60impl<'de, T: ResourcePath + 'de> Deserializer<'de> for PathDeserializer<'de, T> {
61    type Error = de::value::Error;
62
63    fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
64    where
65        V: Visitor<'de>,
66    {
67        visitor.visit_map(ParamsDeserializer {
68            params: self.path.iter(),
69            current: None,
70        })
71    }
72
73    fn deserialize_struct<V>(
74        self,
75        _: &'static str,
76        _: &'static [&'static str],
77        visitor: V,
78    ) -> Result<V::Value, Self::Error>
79    where
80        V: Visitor<'de>,
81    {
82        self.deserialize_map(visitor)
83    }
84
85    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
86    where
87        V: Visitor<'de>,
88    {
89        visitor.visit_unit()
90    }
91
92    fn deserialize_unit_struct<V>(
93        self,
94        _: &'static str,
95        visitor: V,
96    ) -> Result<V::Value, Self::Error>
97    where
98        V: Visitor<'de>,
99    {
100        self.deserialize_unit(visitor)
101    }
102
103    fn deserialize_newtype_struct<V>(
104        self,
105        _: &'static str,
106        visitor: V,
107    ) -> Result<V::Value, Self::Error>
108    where
109        V: Visitor<'de>,
110    {
111        visitor.visit_newtype_struct(self)
112    }
113
114    fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
115    where
116        V: Visitor<'de>,
117    {
118        if self.path.len() < len {
119            Err(de::value::Error::custom(
120                format!(
121                    "wrong number of parameters: {} expected {}",
122                    self.path.len(),
123                    len
124                )
125                .as_str(),
126            ))
127        } else {
128            visitor.visit_seq(ParamsSeq {
129                params: self.path.iter(),
130            })
131        }
132    }
133
134    fn deserialize_tuple_struct<V>(
135        self,
136        _: &'static str,
137        len: usize,
138        visitor: V,
139    ) -> Result<V::Value, Self::Error>
140    where
141        V: Visitor<'de>,
142    {
143        if self.path.len() < len {
144            Err(de::value::Error::custom(
145                format!(
146                    "wrong number of parameters: {} expected {}",
147                    self.path.len(),
148                    len
149                )
150                .as_str(),
151            ))
152        } else {
153            visitor.visit_seq(ParamsSeq {
154                params: self.path.iter(),
155            })
156        }
157    }
158
159    fn deserialize_enum<V>(
160        self,
161        _: &'static str,
162        _: &'static [&'static str],
163        visitor: V,
164    ) -> Result<V::Value, Self::Error>
165    where
166        V: Visitor<'de>,
167    {
168        if self.path.is_empty() {
169            Err(de::value::Error::custom("expected at least one parameter"))
170        } else {
171            visitor.visit_enum(ValueEnum {
172                value: &self.path[0],
173            })
174        }
175    }
176
177    fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
178    where
179        V: Visitor<'de>,
180    {
181        if self.path.is_empty() {
182            Err(de::value::Error::custom(
183                format!("wrong number of parameters: {} expected 1", self.path.len()).as_str(),
184            ))
185        } else {
186            visitor.visit_borrowed_str(&self.path[0])
187        }
188    }
189
190    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
191    where
192        V: Visitor<'de>,
193    {
194        visitor.visit_seq(ParamsSeq {
195            params: self.path.iter(),
196        })
197    }
198
199    unsupported_type!(deserialize_any, "'any'");
200    unsupported_type!(deserialize_bytes, "bytes");
201    unsupported_type!(deserialize_option, "Option<T>");
202    unsupported_type!(deserialize_identifier, "identifier");
203    unsupported_type!(deserialize_ignored_any, "ignored_any");
204
205    parse_single_value!(deserialize_bool, visit_bool, "bool");
206    parse_single_value!(deserialize_i8, visit_i8, "i8");
207    parse_single_value!(deserialize_i16, visit_i16, "i16");
208    parse_single_value!(deserialize_i32, visit_i32, "i32");
209    parse_single_value!(deserialize_i64, visit_i64, "i64");
210    parse_single_value!(deserialize_u8, visit_u8, "u8");
211    parse_single_value!(deserialize_u16, visit_u16, "u16");
212    parse_single_value!(deserialize_u32, visit_u32, "u32");
213    parse_single_value!(deserialize_u64, visit_u64, "u64");
214    parse_single_value!(deserialize_f32, visit_f32, "f32");
215    parse_single_value!(deserialize_f64, visit_f64, "f64");
216    parse_single_value!(deserialize_string, visit_string, "String");
217    parse_single_value!(deserialize_byte_buf, visit_string, "String");
218    parse_single_value!(deserialize_char, visit_char, "char");
219}
220
221struct ParamsDeserializer<'de, T: ResourcePath> {
222    params: PathIter<'de, T>,
223    current: Option<(&'de str, &'de str)>,
224}
225
226impl<'de, T: ResourcePath> de::MapAccess<'de> for ParamsDeserializer<'de, T> {
227    type Error = de::value::Error;
228
229    fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
230    where
231        K: de::DeserializeSeed<'de>,
232    {
233        self.current = self.params.next().map(|ref item| (item.0, item.1));
234        match self.current {
235            Some((key, _)) => Ok(Some(seed.deserialize(Key { key })?)),
236            None => Ok(None),
237        }
238    }
239
240    fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
241    where
242        V: de::DeserializeSeed<'de>,
243    {
244        if let Some((_, value)) = self.current.take() {
245            seed.deserialize(Value { value })
246        } else {
247            Err(de::value::Error::custom("unexpected item"))
248        }
249    }
250}
251
252struct Key<'de> {
253    key: &'de str,
254}
255
256impl<'de> Deserializer<'de> for Key<'de> {
257    type Error = de::value::Error;
258
259    fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>
260    where
261        V: Visitor<'de>,
262    {
263        visitor.visit_str(self.key)
264    }
265
266    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
267    where
268        V: Visitor<'de>,
269    {
270        visitor.visit_borrowed_str(self.key)
271    }
272
273    forward_to_deserialize_any! {
274        bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
275            byte_buf option unit unit_struct newtype_struct seq tuple
276            tuple_struct map struct enum ignored_any
277    }
278}
279
280macro_rules! parse_value {
281    ($trait_fn:ident, $visit_fn:ident, $tp:tt) => {
282        fn $trait_fn<V>(self, visitor: V) -> Result<V::Value, Self::Error>
283        where
284            V: Visitor<'de>,
285        {
286            let v = self.value.parse().map_err(|_| {
287                de::value::Error::custom(format!("can not parse {:?} to a {}", self.value, $tp))
288            })?;
289            visitor.$visit_fn(v)
290        }
291    };
292}
293
294struct Value<'de> {
295    value: &'de str,
296}
297
298impl<'de> Deserializer<'de> for Value<'de> {
299    type Error = de::value::Error;
300
301    parse_value!(deserialize_bool, visit_bool, "bool");
302    parse_value!(deserialize_i8, visit_i8, "i8");
303    parse_value!(deserialize_i16, visit_i16, "i16");
304    parse_value!(deserialize_i32, visit_i32, "i32");
305    parse_value!(deserialize_i64, visit_i64, "i64");
306    parse_value!(deserialize_u8, visit_u8, "u8");
307    parse_value!(deserialize_u16, visit_u16, "u16");
308    parse_value!(deserialize_u32, visit_u32, "u32");
309    parse_value!(deserialize_u64, visit_u64, "u64");
310    parse_value!(deserialize_f32, visit_f32, "f32");
311    parse_value!(deserialize_f64, visit_f64, "f64");
312    parse_value!(deserialize_string, visit_string, "String");
313    parse_value!(deserialize_byte_buf, visit_string, "String");
314    parse_value!(deserialize_char, visit_char, "char");
315
316    fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
317    where
318        V: Visitor<'de>,
319    {
320        visitor.visit_unit()
321    }
322
323    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
324    where
325        V: Visitor<'de>,
326    {
327        visitor.visit_unit()
328    }
329
330    fn deserialize_unit_struct<V>(
331        self,
332        _: &'static str,
333        visitor: V,
334    ) -> Result<V::Value, Self::Error>
335    where
336        V: Visitor<'de>,
337    {
338        visitor.visit_unit()
339    }
340
341    fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
342    where
343        V: Visitor<'de>,
344    {
345        visitor.visit_borrowed_bytes(self.value.as_bytes())
346    }
347
348    fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
349    where
350        V: Visitor<'de>,
351    {
352        visitor.visit_borrowed_str(self.value)
353    }
354
355    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
356    where
357        V: Visitor<'de>,
358    {
359        visitor.visit_some(self)
360    }
361
362    fn deserialize_enum<V>(
363        self,
364        _: &'static str,
365        _: &'static [&'static str],
366        visitor: V,
367    ) -> Result<V::Value, Self::Error>
368    where
369        V: Visitor<'de>,
370    {
371        visitor.visit_enum(ValueEnum { value: self.value })
372    }
373
374    fn deserialize_newtype_struct<V>(
375        self,
376        _: &'static str,
377        visitor: V,
378    ) -> Result<V::Value, Self::Error>
379    where
380        V: Visitor<'de>,
381    {
382        visitor.visit_newtype_struct(self)
383    }
384
385    fn deserialize_tuple<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error>
386    where
387        V: Visitor<'de>,
388    {
389        Err(de::value::Error::custom("unsupported type: tuple"))
390    }
391
392    fn deserialize_struct<V>(
393        self,
394        _: &'static str,
395        _: &'static [&'static str],
396        _: V,
397    ) -> Result<V::Value, Self::Error>
398    where
399        V: Visitor<'de>,
400    {
401        Err(de::value::Error::custom("unsupported type: struct"))
402    }
403
404    fn deserialize_tuple_struct<V>(
405        self,
406        _: &'static str,
407        _: usize,
408        _: V,
409    ) -> Result<V::Value, Self::Error>
410    where
411        V: Visitor<'de>,
412    {
413        Err(de::value::Error::custom("unsupported type: tuple struct"))
414    }
415
416    unsupported_type!(deserialize_any, "any");
417    unsupported_type!(deserialize_seq, "seq");
418    unsupported_type!(deserialize_map, "map");
419    unsupported_type!(deserialize_identifier, "identifier");
420}
421
422struct ParamsSeq<'de, T: ResourcePath> {
423    params: PathIter<'de, T>,
424}
425
426impl<'de, T: ResourcePath> de::SeqAccess<'de> for ParamsSeq<'de, T> {
427    type Error = de::value::Error;
428
429    fn next_element_seed<U>(&mut self, seed: U) -> Result<Option<U::Value>, Self::Error>
430    where
431        U: de::DeserializeSeed<'de>,
432    {
433        match self.params.next() {
434            Some(item) => Ok(Some(seed.deserialize(Value { value: item.1 })?)),
435            None => Ok(None),
436        }
437    }
438}
439
440struct ValueEnum<'de> {
441    value: &'de str,
442}
443
444impl<'de> de::EnumAccess<'de> for ValueEnum<'de> {
445    type Error = de::value::Error;
446    type Variant = UnitVariant;
447
448    fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
449    where
450        V: de::DeserializeSeed<'de>,
451    {
452        Ok((seed.deserialize(Key { key: self.value })?, UnitVariant))
453    }
454}
455
456struct UnitVariant;
457
458impl<'de> de::VariantAccess<'de> for UnitVariant {
459    type Error = de::value::Error;
460
461    fn unit_variant(self) -> Result<(), Self::Error> {
462        Ok(())
463    }
464
465    fn newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value, Self::Error>
466    where
467        T: de::DeserializeSeed<'de>,
468    {
469        Err(de::value::Error::custom("not supported"))
470    }
471
472    fn tuple_variant<V>(self, _len: usize, _visitor: V) -> Result<V::Value, Self::Error>
473    where
474        V: Visitor<'de>,
475    {
476        Err(de::value::Error::custom("not supported"))
477    }
478
479    fn struct_variant<V>(self, _: &'static [&'static str], _: V) -> Result<V::Value, Self::Error>
480    where
481        V: Visitor<'de>,
482    {
483        Err(de::value::Error::custom("not supported"))
484    }
485}
486
487#[cfg(test)]
488#[allow(clippy::items_after_statements)]
489mod tests {
490    use serde_derive::Deserialize;
491
492    use super::*;
493    use crate::path::PathItem;
494
495    #[derive(Deserialize)]
496    struct MyStruct {
497        key: String,
498        value: String,
499    }
500
501    #[derive(Debug, Deserialize)]
502    struct Test1(String, u32);
503
504    #[derive(Debug, Deserialize)]
505    struct Test2 {
506        key: String,
507        value: u32,
508    }
509
510    #[derive(Debug, Deserialize, PartialEq)]
511    #[serde(rename_all = "lowercase")]
512    enum TestEnum {
513        Val1,
514        Val2,
515    }
516
517    #[derive(Debug, Deserialize)]
518    struct Test3 {
519        val: TestEnum,
520    }
521
522    /// STATEMENT: Named path parameters deserialize into supported structs, tuples, sequences,
523    /// and scalar values.
524    ///
525    /// HOW:
526    /// - Populate `key` and `value` captures with `name` and `user1`; verify unit, `MyStruct`,
527    ///   tuple, and borrowed-string extraction, including `Path::load`.
528    /// - Replace `value` with `32` and verify numeric fields in `Test1`, its newtype wrapper,
529    ///   `Test2`, and a tuple.
530    /// - Confirm a tuple containing `Test2` is rejected, while unit and optional tuple elements
531    ///   and a string vector deserialize with the expected values.
532    /// - Verify a unit newtype, unit, and a tuple ending in unit also deserialize successfully.
533    #[test]
534    #[allow(clippy::let_unit_value, clippy::unit_cmp)]
535    fn test_request_extract() {
536        let mut path = Path::new("/name/user1/");
537        path.segments = vec![
538            ("key", PathItem::Static("name")),
539            ("value", PathItem::Static("user1")),
540        ];
541
542        let s: () = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
543        assert_eq!(s, ());
544
545        let s: MyStruct = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
546        assert_eq!(s.key, "name");
547        assert_eq!(s.value, "user1");
548
549        let s: MyStruct = path.load().unwrap();
550        assert_eq!(s.key, "name");
551        assert_eq!(s.value, "user1");
552
553        let s: (String, String) =
554            de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
555        assert_eq!(s.0, "name");
556        assert_eq!(s.1, "user1");
557
558        let s: &str = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
559        assert_eq!(s, "name");
560
561        let mut path = Path::new("/name/user1/");
562        path.segments = vec![
563            ("key", PathItem::Static("name")),
564            ("value", PathItem::Static("32")),
565        ];
566
567        let s: Test1 = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
568        assert_eq!(s.0, "name");
569        assert_eq!(s.1, 32);
570
571        #[derive(Deserialize)]
572        struct T(Test1);
573
574        let s: T = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
575        assert_eq!((s.0).0, "name");
576        assert_eq!((s.0).1, 32);
577
578        let s: Test2 = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
579        assert_eq!(s.key, "name");
580        assert_eq!(s.value, 32);
581
582        let s: Result<(Test2,), _> = de::Deserialize::deserialize(PathDeserializer::new(&path));
583        assert!(s.is_err());
584
585        let s: (String, u8) = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
586        assert_eq!(s.0, "name");
587        assert_eq!(s.1, 32);
588
589        let s: (&str, ()) = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
590        assert_eq!(s.0, "name");
591        assert_eq!(s.1, ());
592
593        let s: (&str, Option<u8>) =
594            de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
595        assert_eq!(s.0, "name");
596        assert_eq!(s.1, Some(32));
597
598        let res: Vec<String> = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
599        assert_eq!(res[0], "name".to_owned());
600        assert_eq!(res[1], "32".to_owned());
601
602        #[derive(Debug, Deserialize)]
603        struct S2(());
604        let s: Result<S2, de::value::Error> =
605            de::Deserialize::deserialize(PathDeserializer::new(&path));
606        assert!(s.is_ok());
607
608        let s: Result<(), de::value::Error> =
609            de::Deserialize::deserialize(PathDeserializer::new(&path));
610        assert!(s.is_ok());
611
612        let s: Result<(String, ()), de::value::Error> =
613            de::Deserialize::deserialize(PathDeserializer::new(&path));
614        assert!(s.is_ok());
615    }
616
617    /// STATEMENT: Single-value extraction accepts exactly one parameter and rejects
618    /// incompatible parameter counts.
619    ///
620    /// HOW:
621    /// - Set one capture to `32` and verify extraction as `i8`, a one-element tuple, and a
622    ///   newtype yields `32`.
623    /// - Confirm a two-element tuple fails with one capture.
624    /// - Add a second capture and confirm scalar `i8` extraction fails.
625    #[test]
626    fn test_extract_path_single() {
627        let mut path = Path::new("/name/user1/");
628        path.segments = vec![("value", PathItem::Static("32"))];
629        let i: i8 = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
630        assert_eq!(i, 32);
631
632        let i: (i8,) = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
633        assert_eq!(i, (32,));
634
635        let i: Result<(i8, i8), _> = de::Deserialize::deserialize(PathDeserializer::new(&path));
636        assert!(i.is_err());
637
638        #[derive(Deserialize)]
639        struct Test(i8);
640        let i: Test = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
641        assert_eq!(i.0, 32);
642
643        path.segments.push(("value2", PathItem::Static("32")));
644        let i: Result<i8, _> = de::Deserialize::deserialize(PathDeserializer::new(&path));
645        assert!(i.is_err());
646    }
647
648    /// STATEMENT: Lowercase parameter values deserialize into unit enum variants as scalars and
649    /// tuple elements.
650    ///
651    /// HOW:
652    /// - Set one capture to `val1` and verify scalar extraction returns `TestEnum::Val1`.
653    /// - Set two captures to `val1` and `val2` and verify a tuple contains `TestEnum::Val1` and
654    ///   `TestEnum::Val2` in order.
655    #[test]
656    fn test_extract_enum() {
657        let mut path = Path::new("/val1/");
658        path.segments = vec![("val", PathItem::Static("val1"))];
659        let i: TestEnum = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
660        assert_eq!(i, TestEnum::Val1);
661
662        let mut path = Path::new("/val1/");
663        path.segments = vec![
664            ("val1", PathItem::Static("val1")),
665            ("val2", PathItem::Static("val2")),
666        ];
667        let i: (TestEnum, TestEnum) =
668            de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
669        assert_eq!(i, (TestEnum::Val1, TestEnum::Val2));
670    }
671
672    /// STATEMENT: Enum-valued struct fields accept known variants and report unknown variants
673    /// as errors.
674    ///
675    /// HOW:
676    /// - Populate the `val` capture with `val1`, deserialize `Test3`, and verify its field is
677    ///   `TestEnum::Val1`.
678    /// - Change the capture to `val3` and confirm deserialization fails with an `unknown
679    ///   variant` diagnostic.
680    #[test]
681    fn test_extract_enum_value() {
682        let mut path = Path::new("/val1/");
683        path.segments = vec![("val", PathItem::Static("val1"))];
684        let i: Test3 = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
685        assert_eq!(i.val, TestEnum::Val1);
686
687        let mut path = Path::new("/val3/");
688        path.segments = vec![("val", PathItem::Static("val3"))];
689        let i: Result<Test3, de::value::Error> =
690            de::Deserialize::deserialize(PathDeserializer::new(&path));
691        assert!(i.is_err());
692        assert!(format!("{i:?}").contains("unknown variant"));
693    }
694
695    /// STATEMENT: Invalid parameter counts, values, and missing fields produce descriptive
696    /// extraction errors.
697    ///
698    /// HOW:
699    /// - Set a single `value` capture to `name`; verify `Test1` and a two-string tuple fail
700    ///   with wrong-count diagnostics, while `Test2` and `u32` report parse failures.
701    /// - Extract a struct requiring `_inner` and confirm the error reports the missing field.
702    /// - Use a path without captures and verify borrowed-string extraction reports zero
703    ///   parameters instead of one, while enum extraction reports that at least one parameter
704    ///   is required.
705    #[test]
706    fn test_extract_errors() {
707        let mut path = Path::new("/name/");
708        path.segments = vec![("value", PathItem::Static("name"))];
709
710        let s: Result<Test1, de::value::Error> =
711            de::Deserialize::deserialize(PathDeserializer::new(&path));
712        assert!(s.is_err());
713        assert!(format!("{s:?}").contains("wrong number of parameters"));
714
715        let s: Result<Test2, de::value::Error> =
716            de::Deserialize::deserialize(PathDeserializer::new(&path));
717        assert!(s.is_err());
718        assert!(format!("{s:?}").contains("can not parse"));
719
720        let s: Result<(String, String), de::value::Error> =
721            de::Deserialize::deserialize(PathDeserializer::new(&path));
722        assert!(s.is_err());
723        assert!(format!("{s:?}").contains("wrong number of parameters"));
724
725        let s: Result<u32, de::value::Error> =
726            de::Deserialize::deserialize(PathDeserializer::new(&path));
727        assert!(s.is_err());
728        assert!(format!("{s:?}").contains("can not parse"));
729
730        #[derive(Debug, Deserialize)]
731        struct S {
732            _inner: (String,),
733        }
734        let s: Result<S, de::value::Error> =
735            de::Deserialize::deserialize(PathDeserializer::new(&path));
736        assert!(s.is_err());
737        assert!(format!("{s:?}").contains("missing field `_inner`"));
738
739        let path = Path::new("");
740        let s: Result<&str, de::value::Error> =
741            de::Deserialize::deserialize(PathDeserializer::new(&path));
742        assert!(s.is_err());
743        assert!(format!("{s:?}").contains("wrong number of parameters: 0 expected 1"));
744
745        let s: Result<TestEnum, de::value::Error> =
746            de::Deserialize::deserialize(PathDeserializer::new(&path));
747        assert!(s.is_err());
748        assert!(format!("{s:?}").contains("expected at least one parameter"));
749    }
750
751    /// STATEMENT: Struct and map extraction support typed values, ignore unused fields, and
752    /// report invalid keys or values.
753    ///
754    /// HOW:
755    /// - Populate captures for booleans, signed and unsigned integers, floats, a character,
756    ///   unit, newtype, option, and bytes, plus an ignored field.
757    /// - Load `Values` and compare every field with the expected typed value, including
758    ///   `Some(8)` and raw bytes.
759    /// - Load a string map and verify all fifteen entries and the character value; load a
760    ///   borrowed-key numeric map and verify its parsed value.
761    /// - Confirm numeric map keys produce an invalid-type diagnostic and an invalid `i32` field
762    ///   reports the attempted value and target type.
763    #[test]
764    fn test_extract_value_types() {
765        use std::collections::HashMap;
766
767        #[derive(Debug, Deserialize, PartialEq)]
768        struct Unit;
769
770        #[derive(Debug, Deserialize, PartialEq)]
771        struct NewType(u16);
772
773        #[derive(Debug, Deserialize, PartialEq)]
774        struct Values {
775            b: bool,
776            i1: i16,
777            i2: i32,
778            i3: i64,
779            u1: u8,
780            u2: u16,
781            u3: u64,
782            f1: f32,
783            f2: f64,
784            c: char,
785            unit: Unit,
786            nt: NewType,
787            opt: Option<u32>,
788            #[serde(with = "serde_bytes_str")]
789            bytes: Vec<u8>,
790        }
791
792        mod serde_bytes_str {
793            pub(super) fn deserialize<'de, D: serde::Deserializer<'de>>(
794                d: D,
795            ) -> Result<Vec<u8>, D::Error> {
796                struct V;
797                impl serde::de::Visitor<'_> for V {
798                    type Value = Vec<u8>;
799                    fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
800                        f.write_str("bytes")
801                    }
802                    fn visit_bytes<E>(self, v: &[u8]) -> Result<Vec<u8>, E> {
803                        Ok(v.to_vec())
804                    }
805                }
806                d.deserialize_bytes(V)
807            }
808        }
809
810        let mut path = Path::new("/");
811        path.segments = vec![
812            ("b", PathItem::Static("true")),
813            ("i1", PathItem::Static("-1")),
814            ("i2", PathItem::Static("-2")),
815            ("i3", PathItem::Static("-3")),
816            ("u1", PathItem::Static("1")),
817            ("u2", PathItem::Static("2")),
818            ("u3", PathItem::Static("3")),
819            ("f1", PathItem::Static("1.5")),
820            ("f2", PathItem::Static("2.5")),
821            ("c", PathItem::Static("x")),
822            ("unit", PathItem::Static("")),
823            ("nt", PathItem::Static("7")),
824            ("opt", PathItem::Static("8")),
825            ("bytes", PathItem::Static("raw")),
826            ("ignored", PathItem::Static("i")),
827        ];
828        let v: Values = path.load().unwrap();
829        assert_eq!(
830            v,
831            Values {
832                b: true,
833                i1: -1,
834                i2: -2,
835                i3: -3,
836                u1: 1,
837                u2: 2,
838                u3: 3,
839                f1: 1.5,
840                f2: 2.5,
841                c: 'x',
842                unit: Unit,
843                nt: NewType(7),
844                opt: Some(8),
845                bytes: b"raw".to_vec(),
846            }
847        );
848
849        let m: HashMap<String, String> = path.load().unwrap();
850        assert_eq!(m.len(), 15);
851        assert_eq!(m["c"], "x");
852        let mut p = Path::new("/");
853        p.segments = vec![("a", PathItem::Static("1"))];
854        let m: HashMap<&str, u8> = p.load().unwrap();
855        assert_eq!(m["a"], 1);
856
857        let res: Result<HashMap<u32, String>, _> = path.load();
858        assert!(format!("{res:?}").contains("invalid type"), "{res:?}");
859
860        #[derive(Debug, Deserialize)]
861        struct I32 {
862            _v: i32,
863        }
864        let mut path = Path::new("/");
865        path.segments = vec![("_v", PathItem::Static("x"))];
866        let res: Result<I32, _> = path.load();
867        assert!(
868            format!("{res:?}").contains("can not parse \\\"x\\\" to a i32"),
869            "{res:?}"
870        );
871    }
872
873    /// STATEMENT: Reading a map value without first reading its key is an error, and a
874    /// value can be read only once per key.
875    ///
876    /// HOW:
877    /// - Create a `ParamsDeserializer` over a path with the single capture `k` = `v`.
878    /// - Read a value before any key and confirm the `unexpected item` error.
879    /// - Read the key `k` and its value `v`, then confirm a second value read fails the
880    ///   same way.
881    #[test]
882    fn test_params_value_without_key() {
883        use serde::de::MapAccess;
884
885        let mut path = Path::new("/");
886        path.segments = vec![("k", PathItem::Static("v"))];
887        let mut params = ParamsDeserializer {
888            params: path.iter(),
889            current: None,
890        };
891
892        let err = params.next_value::<String>().unwrap_err();
893        assert_eq!(err.to_string(), "unexpected item");
894        assert_eq!(params.next_key::<String>().unwrap().as_deref(), Some("k"));
895        assert_eq!(params.next_value::<String>().unwrap(), "v");
896        let err = params.next_value::<String>().unwrap_err();
897        assert_eq!(err.to_string(), "unexpected item");
898    }
899
900    /// STATEMENT: Single captures deserialize into supported primitive types and report
901    /// unsupported scalar or nested types precisely.
902    ///
903    /// HOW:
904    /// - Load `false` as `bool` and `1` as signed and unsigned integers, floats within epsilon,
905    ///   `char`, `String`, and a unit struct.
906    /// - Verify exact unsupported-type errors for scalar `Option`, `IgnoredAny`, and custom
907    ///   requests for any, identifier, or bytes deserialization.
908    /// - Attempt vectors of sequences, maps, tuples, structs, tuple structs, and custom any or
909    ///   identifier values; verify each exact unsupported-type diagnostic.
910    #[test]
911    fn test_extract_single_value_types() {
912        #[derive(Debug, Deserialize, PartialEq)]
913        struct Unit;
914
915        let mut path = Path::new("/");
916        path.segments = vec![("v", PathItem::Static("1"))];
917
918        let mut bool_path = Path::new("/");
919        bool_path.segments = vec![("v", PathItem::Static("false"))];
920        assert!(!bool_path.load::<bool>().unwrap());
921        assert_eq!(path.load::<i16>().unwrap(), 1);
922        assert_eq!(path.load::<i32>().unwrap(), 1);
923        assert_eq!(path.load::<i64>().unwrap(), 1);
924        assert_eq!(path.load::<u8>().unwrap(), 1);
925        assert_eq!(path.load::<u16>().unwrap(), 1);
926        assert_eq!(path.load::<u64>().unwrap(), 1);
927        assert!((path.load::<f32>().unwrap() - 1.0).abs() < f32::EPSILON);
928        assert!((path.load::<f64>().unwrap() - 1.0).abs() < f64::EPSILON);
929        assert_eq!(path.load::<char>().unwrap(), '1');
930        assert_eq!(path.load::<String>().unwrap(), "1");
931        assert_eq!(path.load::<Unit>().unwrap(), Unit);
932
933        let err = |res: Result<(), de::value::Error>| res.unwrap_err().to_string();
934        assert_eq!(
935            err(path.load::<Option<u8>>().map(drop)),
936            "unsupported type: Option<T>"
937        );
938        assert_eq!(
939            err(path.load::<serde::de::IgnoredAny>().map(drop)),
940            "unsupported type: ignored_any"
941        );
942        assert_eq!(
943            err(path.load::<Vec<Vec<u8>>>().map(drop)),
944            "unsupported type: seq"
945        );
946        assert_eq!(
947            err(path
948                .load::<Vec<std::collections::HashMap<String, String>>>()
949                .map(drop)),
950            "unsupported type: map"
951        );
952        assert_eq!(
953            err(path.load::<Vec<(u8, u8)>>().map(drop)),
954            "unsupported type: tuple"
955        );
956
957        #[derive(Debug, Deserialize)]
958        struct S {
959            _a: u8,
960        }
961        #[derive(Debug, Deserialize)]
962        struct TS(#[allow(dead_code)] u8, #[allow(dead_code)] u8);
963        assert_eq!(
964            err(path.load::<Vec<S>>().map(drop)),
965            "unsupported type: struct"
966        );
967        assert_eq!(
968            err(path.load::<Vec<TS>>().map(drop)),
969            "unsupported type: tuple struct"
970        );
971        assert_eq!(
972            err(path.load::<Vec<serde_value::Any>>().map(drop)),
973            "unsupported type: any"
974        );
975        assert_eq!(
976            err(path.load::<Vec<serde_value::Ident>>().map(drop)),
977            "unsupported type: identifier"
978        );
979        assert_eq!(
980            err(path.load::<serde_value::Any>().map(drop)),
981            "unsupported type: 'any'"
982        );
983        assert_eq!(
984            err(path.load::<serde_value::Ident>().map(drop)),
985            "unsupported type: identifier"
986        );
987        assert_eq!(
988            err(path.load::<serde_value::Bytes>().map(drop)),
989            "unsupported type: bytes"
990        );
991    }
992
993    /// Types that request specific deserializer methods
994    mod serde_value {
995        use serde::de::{Deserialize, Deserializer, IgnoredAny, Visitor};
996        use std::fmt;
997
998        struct V;
999        impl Visitor<'_> for V {
1000            type Value = ();
1001            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1002                f.write_str("anything")
1003            }
1004        }
1005
1006        #[derive(Debug)]
1007        pub(super) struct Any;
1008        impl<'de> Deserialize<'de> for Any {
1009            fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
1010                d.deserialize_any(IgnoredAny).map(|_| Any)
1011            }
1012        }
1013
1014        #[derive(Debug)]
1015        pub(super) struct Ident;
1016        impl<'de> Deserialize<'de> for Ident {
1017            fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
1018                d.deserialize_identifier(V).map(|()| Ident)
1019            }
1020        }
1021
1022        #[derive(Debug)]
1023        pub(super) struct Bytes;
1024        impl<'de> Deserialize<'de> for Bytes {
1025            fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
1026                d.deserialize_bytes(V).map(|()| Bytes)
1027            }
1028        }
1029    }
1030
1031    /// STATEMENT: Enum extraction supports unit variants but rejects variants that require
1032    /// associated data.
1033    ///
1034    /// HOW:
1035    /// - Define lowercase unit, newtype, tuple, and struct variants and populate a capture with
1036    ///   each variant name.
1037    /// - Verify scalar extraction succeeds only for the unit variant and each other variant
1038    ///   reports `not supported`.
1039    /// - Repeat extraction as a one-element enum tuple and verify the same success and failure
1040    ///   results.
1041    #[test]
1042    fn test_extract_enum_variants() {
1043        #[derive(Debug, Deserialize)]
1044        #[serde(rename_all = "lowercase")]
1045        #[allow(dead_code)]
1046        enum E {
1047            Unit,
1048            New(u8),
1049            Tuple(u8, u8),
1050            Struct { a: u8 },
1051        }
1052
1053        let mut path = Path::new("/");
1054        for (name, ok) in [
1055            ("unit", true),
1056            ("new", false),
1057            ("tuple", false),
1058            ("struct", false),
1059        ] {
1060            path.segments = vec![("v", PathItem::Static(name))];
1061            let res: Result<E, _> = path.load();
1062            assert_eq!(res.is_ok(), ok, "{name}");
1063            if !ok {
1064                assert!(format!("{res:?}").contains("not supported"), "{name}");
1065            }
1066            // enum as a value of a sequence element
1067            let res: Result<(E,), _> = path.load();
1068            assert_eq!(res.is_ok(), ok, "{name}");
1069        }
1070    }
1071}