1use std::any::type_name;
4use std::fmt;
5use std::ops::{Deref, DerefMut};
6
7use http::StatusCode;
8use http::request::Parts;
9use serde::de::{
10 self, DeserializeOwned, DeserializeSeed, Error as _, MapAccess, SeqAccess, Visitor,
11};
12use serde::forward_to_deserialize_any;
13
14use super::rejection::PathRejection;
15use super::{FromRequestParts, OptionalFromRequestParts};
16use crate::routing::PathParams;
17
18#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
46pub struct Path<T>(pub T);
47
48impl<T> Deref for Path<T> {
49 type Target = T;
50
51 fn deref(&self) -> &T {
52 &self.0
53 }
54}
55
56impl<T> DerefMut for Path<T> {
57 fn deref_mut(&mut self) -> &mut T {
58 &mut self.0
59 }
60}
61
62impl<T: DeserializeOwned + Send> FromRequestParts for Path<T> {
63 type Rejection = PathRejection;
64
65 async fn from_request_parts(parts: &mut Parts) -> Result<Self, Self::Rejection> {
66 Self::from_params(params_of(parts))
67 }
68}
69
70impl<T: DeserializeOwned + Send> Path<T> {
71 pub fn from_params(params: &PathParams) -> Result<Self, PathRejection> {
73 let pairs: Vec<(&str, &str)> = params.iter().collect();
74 T::deserialize(PathDeserializer { params: &pairs })
75 .map(Path)
76 .map_err(|error| PathRejection(error.kind))
77 }
78}
79
80impl<T: DeserializeOwned + Send> OptionalFromRequestParts for Path<T> {
82 type Rejection = PathRejection;
83
84 async fn from_request_parts(parts: &mut Parts) -> Result<Option<Self>, Self::Rejection> {
85 match Self::from_params(params_of(parts)) {
86 Ok(path) => Ok(Some(path)),
87 Err(PathRejection(PathErrorKind::WrongNumberOfParameters { got: 0, .. })) => Ok(None),
88 Err(error) => Err(error),
89 }
90 }
91}
92
93fn params_of(parts: &Parts) -> &PathParams {
95 static EMPTY: std::sync::OnceLock<PathParams> = std::sync::OnceLock::new();
96 parts
97 .extensions
98 .get::<PathParams>()
99 .unwrap_or_else(|| EMPTY.get_or_init(PathParams::empty))
100}
101
102#[derive(Clone, Debug, PartialEq, Eq)]
104#[non_exhaustive]
105pub enum PathErrorKind {
106 WrongNumberOfParameters {
108 got: usize,
110 expected: usize,
112 },
113 ParseErrorAtKey {
115 key: String,
117 value: String,
119 expected_type: &'static str,
121 },
122 ParseErrorAtIndex {
124 index: usize,
126 value: String,
128 expected_type: &'static str,
130 },
131 ParseError {
133 value: String,
135 expected_type: &'static str,
137 },
138 UnsupportedType {
140 name: &'static str,
142 },
143 DeserializeError {
145 key: String,
147 value: String,
149 message: String,
151 },
152 Message(String),
154}
155
156impl PathErrorKind {
157 pub fn status(&self) -> StatusCode {
160 match self {
161 PathErrorKind::WrongNumberOfParameters { .. }
162 | PathErrorKind::UnsupportedType { .. } => StatusCode::INTERNAL_SERVER_ERROR,
163 _ => StatusCode::BAD_REQUEST,
164 }
165 }
166}
167
168impl fmt::Display for PathErrorKind {
169 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
170 match self {
171 PathErrorKind::Message(message) => f.write_str(message),
172 PathErrorKind::WrongNumberOfParameters { got, expected } => {
173 write!(
174 f,
175 "Wrong number of path arguments for `Path`. Expected {expected} but got {got}"
176 )?;
177 if *expected == 1 {
178 f.write_str(". Note that multiple parameters must be extracted with a tuple `Path<(_, _)>` or a struct `Path<YourParams>`")?;
179 }
180 Ok(())
181 }
182 PathErrorKind::UnsupportedType { name } => write!(f, "Unsupported type `{name}`"),
183 PathErrorKind::ParseErrorAtKey {
184 key,
185 value,
186 expected_type,
187 } => write!(
188 f,
189 "Cannot parse `{key}` with value `{value}` to a `{expected_type}`"
190 ),
191 PathErrorKind::ParseError {
192 value,
193 expected_type,
194 } => write!(f, "Cannot parse `{value}` to a `{expected_type}`"),
195 PathErrorKind::ParseErrorAtIndex {
196 index,
197 value,
198 expected_type,
199 } => write!(
200 f,
201 "Cannot parse value at index {index} with value `{value}` to a `{expected_type}`"
202 ),
203 PathErrorKind::DeserializeError {
204 key,
205 value,
206 message,
207 } => write!(f, "Cannot parse `{key}` with value `{value}`: {message}"),
208 }
209 }
210}
211
212#[derive(Debug)]
214struct PathError {
215 kind: PathErrorKind,
216}
217
218impl PathError {
219 fn new(kind: PathErrorKind) -> Self {
220 Self { kind }
221 }
222
223 fn wrong_number(got: usize, expected: usize) -> Self {
224 Self::new(PathErrorKind::WrongNumberOfParameters { got, expected })
225 }
226
227 fn unsupported<T>() -> Self {
228 Self::new(PathErrorKind::UnsupportedType {
229 name: type_name::<T>(),
230 })
231 }
232}
233
234impl fmt::Display for PathError {
235 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
236 self.kind.fmt(f)
237 }
238}
239
240impl std::error::Error for PathError {}
241
242impl de::Error for PathError {
243 fn custom<T: fmt::Display>(message: T) -> Self {
244 Self::new(PathErrorKind::Message(message.to_string()))
245 }
246}
247
248#[derive(Clone, Copy, Debug)]
251enum At<'de> {
252 Key(&'de str),
253 Index { index: usize, key: &'de str },
254}
255
256impl<'de> At<'de> {
257 fn key(self) -> &'de str {
258 match self {
259 At::Key(key) | At::Index { key, .. } => key,
260 }
261 }
262}
263
264struct PathDeserializer<'a, 'de> {
266 params: &'a [(&'de str, &'de str)],
267}
268
269impl<'de> PathDeserializer<'_, 'de> {
270 fn single(&self) -> Result<(&'de str, &'de str), PathError> {
272 match self.params {
273 [single] => Ok(*single),
274 params => Err(PathError::wrong_number(params.len(), 1)),
275 }
276 }
277}
278
279macro_rules! single_value {
281 ($($method:ident => $visit:ident, $ty:ty, $name:literal;)*) => {
282 $(
283 fn $method<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, PathError> {
284 let (_, value) = self.single()?;
285 let parsed = value.parse::<$ty>().map_err(|_| {
286 PathError::new(PathErrorKind::ParseError {
287 value: value.to_owned(),
288 expected_type: $name,
289 })
290 })?;
291 visitor.$visit(parsed)
292 }
293 )*
294 };
295}
296
297impl<'de> de::Deserializer<'de> for PathDeserializer<'_, 'de> {
298 type Error = PathError;
299
300 single_value! {
301 deserialize_bool => visit_bool, bool, "bool";
302 deserialize_i8 => visit_i8, i8, "i8";
303 deserialize_i16 => visit_i16, i16, "i16";
304 deserialize_i32 => visit_i32, i32, "i32";
305 deserialize_i64 => visit_i64, i64, "i64";
306 deserialize_i128 => visit_i128, i128, "i128";
307 deserialize_u8 => visit_u8, u8, "u8";
308 deserialize_u16 => visit_u16, u16, "u16";
309 deserialize_u32 => visit_u32, u32, "u32";
310 deserialize_u64 => visit_u64, u64, "u64";
311 deserialize_u128 => visit_u128, u128, "u128";
312 deserialize_f32 => visit_f32, f32, "f32";
313 deserialize_f64 => visit_f64, f64, "f64";
314 deserialize_string => visit_string, String, "String";
315 deserialize_byte_buf => visit_string, String, "String";
316 deserialize_char => visit_char, char, "char";
317 }
318
319 fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, PathError> {
320 self.deserialize_str(visitor)
321 }
322
323 fn deserialize_str<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, PathError> {
324 let (key, value) = self.single()?;
325 visitor
326 .visit_borrowed_str(value)
327 .map_err(|error| keyed(error, At::Key(key), value))
328 }
329
330 fn deserialize_bytes<V: Visitor<'de>>(self, _visitor: V) -> Result<V::Value, PathError> {
331 Err(PathError::unsupported::<V::Value>())
332 }
333
334 fn deserialize_option<V: Visitor<'de>>(self, _visitor: V) -> Result<V::Value, PathError> {
335 Err(PathError::unsupported::<V::Value>())
336 }
337
338 fn deserialize_identifier<V: Visitor<'de>>(self, _visitor: V) -> Result<V::Value, PathError> {
339 Err(PathError::unsupported::<V::Value>())
340 }
341
342 fn deserialize_ignored_any<V: Visitor<'de>>(self, _visitor: V) -> Result<V::Value, PathError> {
343 Err(PathError::unsupported::<V::Value>())
344 }
345
346 fn deserialize_unit<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, PathError> {
347 visitor.visit_unit()
348 }
349
350 fn deserialize_unit_struct<V: Visitor<'de>>(
351 self,
352 _name: &'static str,
353 visitor: V,
354 ) -> Result<V::Value, PathError> {
355 visitor.visit_unit()
356 }
357
358 fn deserialize_newtype_struct<V: Visitor<'de>>(
359 self,
360 _name: &'static str,
361 visitor: V,
362 ) -> Result<V::Value, PathError> {
363 visitor.visit_newtype_struct(self)
364 }
365
366 fn deserialize_seq<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, PathError> {
367 visitor.visit_seq(Sequence {
368 params: self.params,
369 index: 0,
370 })
371 }
372
373 fn deserialize_tuple<V: Visitor<'de>>(
374 self,
375 len: usize,
376 visitor: V,
377 ) -> Result<V::Value, PathError> {
378 if self.params.len() != len {
379 return Err(PathError::wrong_number(self.params.len(), len));
380 }
381 self.deserialize_seq(visitor)
382 }
383
384 fn deserialize_tuple_struct<V: Visitor<'de>>(
385 self,
386 _name: &'static str,
387 len: usize,
388 visitor: V,
389 ) -> Result<V::Value, PathError> {
390 self.deserialize_tuple(len, visitor)
391 }
392
393 fn deserialize_map<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, PathError> {
394 visitor.visit_map(Map {
395 params: self.params,
396 value: None,
397 })
398 }
399
400 fn deserialize_struct<V: Visitor<'de>>(
401 self,
402 _name: &'static str,
403 _fields: &'static [&'static str],
404 visitor: V,
405 ) -> Result<V::Value, PathError> {
406 self.deserialize_map(visitor)
407 }
408
409 fn deserialize_enum<V: Visitor<'de>>(
410 self,
411 _name: &'static str,
412 _variants: &'static [&'static str],
413 visitor: V,
414 ) -> Result<V::Value, PathError> {
415 let (_, value) = self.single()?;
416 visitor.visit_enum(Variant { name: value })
417 }
418}
419
420fn keyed(error: PathError, at: At<'_>, value: &str) -> PathError {
423 match error.kind {
424 PathErrorKind::Message(message) => PathError::new(PathErrorKind::DeserializeError {
425 key: at.key().to_owned(),
426 value: value.to_owned(),
427 message,
428 }),
429 kind => PathError::new(kind),
430 }
431}
432
433struct Map<'a, 'de> {
435 params: &'a [(&'de str, &'de str)],
436 value: Option<(&'de str, &'de str)>,
437}
438
439impl<'de> MapAccess<'de> for Map<'_, 'de> {
440 type Error = PathError;
441
442 fn next_key_seed<K: DeserializeSeed<'de>>(
443 &mut self,
444 seed: K,
445 ) -> Result<Option<K::Value>, PathError> {
446 let Some((first, rest)) = self.params.split_first() else {
447 return Ok(None);
448 };
449 self.params = rest;
450 self.value = Some(*first);
451 seed.deserialize(Key(first.0)).map(Some)
452 }
453
454 fn next_value_seed<V: DeserializeSeed<'de>>(&mut self, seed: V) -> Result<V::Value, PathError> {
455 let (key, value) = self
456 .value
457 .take()
458 .ok_or_else(|| PathError::custom("value is missing"))?;
459 seed.deserialize(Value {
460 at: Some(At::Key(key)),
461 value,
462 })
463 }
464}
465
466struct Sequence<'a, 'de> {
468 params: &'a [(&'de str, &'de str)],
469 index: usize,
470}
471
472impl<'de> SeqAccess<'de> for Sequence<'_, 'de> {
473 type Error = PathError;
474
475 fn next_element_seed<T: DeserializeSeed<'de>>(
476 &mut self,
477 seed: T,
478 ) -> Result<Option<T::Value>, PathError> {
479 let Some(((key, value), rest)) = self.params.split_first() else {
480 return Ok(None);
481 };
482 self.params = rest;
483 let index = self.index;
484 self.index += 1;
485 seed.deserialize(Value {
486 at: Some(At::Index { index, key }),
487 value,
488 })
489 .map(Some)
490 }
491}
492
493struct Key<'de>(&'de str);
495
496impl<'de> de::Deserializer<'de> for Key<'de> {
497 type Error = PathError;
498
499 fn deserialize_identifier<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, PathError> {
500 visitor.visit_borrowed_str(self.0)
501 }
502
503 fn deserialize_str<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, PathError> {
504 visitor.visit_borrowed_str(self.0)
505 }
506
507 fn deserialize_string<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, PathError> {
508 visitor.visit_borrowed_str(self.0)
509 }
510
511 fn deserialize_any<V: Visitor<'de>>(self, _visitor: V) -> Result<V::Value, PathError> {
512 Err(PathError::custom("Unexpected key type"))
513 }
514
515 forward_to_deserialize_any! {
516 bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char bytes
517 byte_buf option unit unit_struct seq tuple
518 tuple_struct map newtype_struct struct enum ignored_any
519 }
520}
521
522struct Value<'de> {
524 at: Option<At<'de>>,
525 value: &'de str,
526}
527
528macro_rules! parse_value {
530 ($($method:ident => $visit:ident, $ty:ty, $name:literal;)*) => {
531 $(
532 fn $method<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, PathError> {
533 let parsed = self.value.parse::<$ty>().map_err(|_| self.parse_error($name))?;
534 visitor.$visit(parsed)
535 }
536 )*
537 };
538}
539
540impl Value<'_> {
541 fn parse_error(&self, expected_type: &'static str) -> PathError {
542 let value = self.value.to_owned();
543 PathError::new(match self.at {
544 Some(At::Key(key)) => PathErrorKind::ParseErrorAtKey {
545 key: key.to_owned(),
546 value,
547 expected_type,
548 },
549 Some(At::Index { index, .. }) => PathErrorKind::ParseErrorAtIndex {
550 index,
551 value,
552 expected_type,
553 },
554 None => PathErrorKind::ParseError {
555 value,
556 expected_type,
557 },
558 })
559 }
560}
561
562impl<'de> de::Deserializer<'de> for Value<'de> {
563 type Error = PathError;
564
565 parse_value! {
566 deserialize_bool => visit_bool, bool, "bool";
567 deserialize_i8 => visit_i8, i8, "i8";
568 deserialize_i16 => visit_i16, i16, "i16";
569 deserialize_i32 => visit_i32, i32, "i32";
570 deserialize_i64 => visit_i64, i64, "i64";
571 deserialize_i128 => visit_i128, i128, "i128";
572 deserialize_u8 => visit_u8, u8, "u8";
573 deserialize_u16 => visit_u16, u16, "u16";
574 deserialize_u32 => visit_u32, u32, "u32";
575 deserialize_u64 => visit_u64, u64, "u64";
576 deserialize_u128 => visit_u128, u128, "u128";
577 deserialize_f32 => visit_f32, f32, "f32";
578 deserialize_f64 => visit_f64, f64, "f64";
579 deserialize_string => visit_string, String, "String";
580 deserialize_byte_buf => visit_string, String, "String";
581 deserialize_char => visit_char, char, "char";
582 }
583
584 fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, PathError> {
585 self.deserialize_str(visitor)
586 }
587
588 fn deserialize_str<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, PathError> {
589 let (at, value) = (self.at, self.value);
590 visitor.visit_borrowed_str(value).map_err(|error| match at {
591 Some(at) => keyed(error, at, value),
592 None => error,
593 })
594 }
595
596 fn deserialize_bytes<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, PathError> {
597 visitor.visit_borrowed_bytes(self.value.as_bytes())
598 }
599
600 fn deserialize_option<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, PathError> {
601 visitor.visit_some(self)
602 }
603
604 fn deserialize_unit<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, PathError> {
605 visitor.visit_unit()
606 }
607
608 fn deserialize_unit_struct<V: Visitor<'de>>(
609 self,
610 _name: &'static str,
611 visitor: V,
612 ) -> Result<V::Value, PathError> {
613 visitor.visit_unit()
614 }
615
616 fn deserialize_newtype_struct<V: Visitor<'de>>(
617 self,
618 _name: &'static str,
619 visitor: V,
620 ) -> Result<V::Value, PathError> {
621 visitor.visit_newtype_struct(self)
622 }
623
624 fn deserialize_tuple<V: Visitor<'de>>(
627 self,
628 len: usize,
629 visitor: V,
630 ) -> Result<V::Value, PathError> {
631 match (len, self.at) {
632 (2, Some(At::Index { key, .. })) => visitor.visit_seq(Pair {
633 key: Some(key),
634 value: Some(self.value),
635 }),
636 (2, Some(At::Key(_))) => Err(PathError::custom("array types are not supported")),
637 _ => Err(PathError::unsupported::<V::Value>()),
638 }
639 }
640
641 fn deserialize_seq<V: Visitor<'de>>(self, _visitor: V) -> Result<V::Value, PathError> {
642 Err(PathError::unsupported::<V::Value>())
643 }
644
645 fn deserialize_tuple_struct<V: Visitor<'de>>(
646 self,
647 _name: &'static str,
648 _len: usize,
649 _visitor: V,
650 ) -> Result<V::Value, PathError> {
651 Err(PathError::unsupported::<V::Value>())
652 }
653
654 fn deserialize_map<V: Visitor<'de>>(self, _visitor: V) -> Result<V::Value, PathError> {
655 Err(PathError::unsupported::<V::Value>())
656 }
657
658 fn deserialize_struct<V: Visitor<'de>>(
659 self,
660 _name: &'static str,
661 _fields: &'static [&'static str],
662 _visitor: V,
663 ) -> Result<V::Value, PathError> {
664 Err(PathError::unsupported::<V::Value>())
665 }
666
667 fn deserialize_identifier<V: Visitor<'de>>(self, _visitor: V) -> Result<V::Value, PathError> {
668 Err(PathError::unsupported::<V::Value>())
669 }
670
671 fn deserialize_enum<V: Visitor<'de>>(
672 self,
673 _name: &'static str,
674 _variants: &'static [&'static str],
675 visitor: V,
676 ) -> Result<V::Value, PathError> {
677 visitor.visit_enum(Variant { name: self.value })
678 }
679
680 fn deserialize_ignored_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, PathError> {
681 visitor.visit_unit()
682 }
683}
684
685struct Pair<'de> {
687 key: Option<&'de str>,
688 value: Option<&'de str>,
689}
690
691impl<'de> SeqAccess<'de> for Pair<'de> {
692 type Error = PathError;
693
694 fn next_element_seed<T: DeserializeSeed<'de>>(
695 &mut self,
696 seed: T,
697 ) -> Result<Option<T::Value>, PathError> {
698 if let Some(key) = self.key.take() {
699 return seed.deserialize(Key(key)).map(Some);
700 }
701 self.value
702 .take()
703 .map(|value| seed.deserialize(Value { at: None, value }))
704 .transpose()
705 }
706}
707
708struct Variant<'de> {
710 name: &'de str,
711}
712
713impl<'de> de::EnumAccess<'de> for Variant<'de> {
714 type Error = PathError;
715 type Variant = UnitOnly;
716
717 fn variant_seed<V: DeserializeSeed<'de>>(
718 self,
719 seed: V,
720 ) -> Result<(V::Value, UnitOnly), PathError> {
721 Ok((seed.deserialize(Key(self.name))?, UnitOnly))
722 }
723}
724
725struct UnitOnly;
726
727impl<'de> de::VariantAccess<'de> for UnitOnly {
728 type Error = PathError;
729
730 fn unit_variant(self) -> Result<(), PathError> {
731 Ok(())
732 }
733
734 fn newtype_variant_seed<T: DeserializeSeed<'de>>(
735 self,
736 _seed: T,
737 ) -> Result<T::Value, PathError> {
738 Err(PathError::new(PathErrorKind::UnsupportedType {
739 name: "newtype enum variant",
740 }))
741 }
742
743 fn tuple_variant<V: Visitor<'de>>(
744 self,
745 _len: usize,
746 _visitor: V,
747 ) -> Result<V::Value, PathError> {
748 Err(PathError::new(PathErrorKind::UnsupportedType {
749 name: "tuple enum variant",
750 }))
751 }
752
753 fn struct_variant<V: Visitor<'de>>(
754 self,
755 _fields: &'static [&'static str],
756 _visitor: V,
757 ) -> Result<V::Value, PathError> {
758 Err(PathError::new(PathErrorKind::UnsupportedType {
759 name: "struct enum variant",
760 }))
761 }
762}
763
764#[cfg(test)]
765mod tests {
766 use std::collections::HashMap;
767 use std::sync::Arc;
768
769 use serde::Deserialize;
770
771 use super::*;
772
773 fn params(pairs: &[(&str, &str)]) -> PathParams {
774 let names: Arc<[Box<str>]> = pairs.iter().map(|(name, _)| (*name).into()).collect();
775 let values: Vec<&str> = pairs.iter().map(|(_, value)| *value).collect();
776 PathParams::decode(names, &values, false).expect("valid")
777 }
778
779 fn path<T: DeserializeOwned + Send>(pairs: &[(&str, &str)]) -> Result<T, PathErrorKind> {
780 Path::<T>::from_params(¶ms(pairs))
781 .map(|Path(value)| value)
782 .map_err(|rejection| rejection.0)
783 }
784
785 #[derive(Debug, Deserialize, PartialEq)]
786 struct Ids {
787 user: u32,
788 team: String,
789 }
790
791 #[derive(Debug, Deserialize, PartialEq)]
792 #[serde(rename_all = "snake_case")]
793 enum Tab {
794 Notes,
795 Files,
796 }
797
798 #[test]
799 fn one_value_reads_into_any_text_type() {
800 assert_eq!(path::<u32>(&[("id", "42")]), Ok(42));
801 assert_eq!(
802 path::<String>(&[("id", "caf%C3%A9")]),
803 Ok("café".to_owned())
804 );
805 assert_eq!(path::<Tab>(&[("tab", "notes")]), Ok(Tab::Notes));
806 assert_eq!(
807 path::<uuid::Uuid>(&[("id", "67e55044-10b1-426f-9247-bb680e5fe0c8")])
808 .map(|id| id.to_string()),
809 Ok("67e55044-10b1-426f-9247-bb680e5fe0c8".to_owned())
810 );
811 }
812
813 #[test]
814 fn several_values_read_into_tuples_structs_and_maps() {
815 let pairs = [("user", "7"), ("team", "core")];
816 assert_eq!(path::<(u32, String)>(&pairs), Ok((7, "core".to_owned())));
817 assert_eq!(
818 path::<Ids>(&pairs),
819 Ok(Ids {
820 user: 7,
821 team: "core".to_owned()
822 })
823 );
824 let map = path::<HashMap<String, String>>(&pairs).unwrap();
825 assert_eq!(map["team"], "core");
826 assert_eq!(
827 path::<Vec<(String, String)>>(&pairs).unwrap(),
828 [
829 ("user".to_owned(), "7".to_owned()),
830 ("team".to_owned(), "core".to_owned())
831 ]
832 );
833 assert_eq!(path::<()>(&[]), Ok(()));
834 }
835
836 #[test]
837 fn rejections_read_as_before() {
838 let render = |kind: PathErrorKind| (kind.status().as_u16(), kind.to_string());
839 assert_eq!(
840 render(path::<u32>(&[("id", "x")]).unwrap_err()),
841 (400, "Cannot parse `x` to a `u32`".to_owned())
842 );
843 assert_eq!(
844 render(path::<Ids>(&[("user", "x"), ("team", "a")]).unwrap_err()),
845 (
846 400,
847 "Cannot parse `user` with value `x` to a `u32`".to_owned()
848 )
849 );
850 assert_eq!(
851 render(path::<(String, u8)>(&[("a", "x"), ("b", "300")]).unwrap_err()),
852 (
853 400,
854 "Cannot parse value at index 1 with value `300` to a `u8`".to_owned()
855 )
856 );
857 let uuid = path::<uuid::Uuid>(&[("id", "not-a-uuid")]).unwrap_err();
858 assert_eq!(uuid.status(), StatusCode::BAD_REQUEST);
859 assert!(
860 uuid.to_string()
861 .starts_with("Cannot parse `id` with value `not-a-uuid`: UUID parsing failed"),
862 "{uuid}"
863 );
864 assert_eq!(
865 render(path::<u32>(&[("a", "1"), ("b", "2")]).unwrap_err()),
866 (500, "Wrong number of path arguments for `Path`. Expected 1 but got 2. Note that multiple parameters must be extracted with a tuple `Path<(_, _)>` or a struct `Path<YourParams>`".to_owned())
867 );
868 assert_eq!(
869 render(path::<(u32, u32, u32)>(&[("a", "1"), ("b", "2")]).unwrap_err()),
870 (
871 500,
872 "Wrong number of path arguments for `Path`. Expected 3 but got 2".to_owned()
873 )
874 );
875 assert_eq!(
876 path::<Tab>(&[("tab", "other")]).unwrap_err().to_string(),
877 "unknown variant `other`, expected `notes` or `files`"
878 );
879 let nested = path::<HashMap<String, Vec<u8>>>(&[("a", "1")]).unwrap_err();
880 assert_eq!(nested.status(), StatusCode::INTERNAL_SERVER_ERROR);
881 }
882}