Advertisement
Guest User

Untitled

a guest
Oct 14th, 2019
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.23 KB | None | 0 0
  1. use std::fmt;
  2. use serde::de::{self, Deserializer, Visitor, SeqAccess, MapAccess};
  3. use serde::Deserialize;
  4.  
  5. fn main() {}
  6.  
  7. struct Duration {
  8. secs: u64,
  9. nanos: u32,
  10. }
  11.  
  12. impl<'de> de::Deserialize<'de> for Duration {
  13. fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  14. where
  15. D: Deserializer<'de>,
  16. {
  17. // Comment out these lines and uncomment the manual impl of Deserialize
  18. // to make it work
  19. #[derive(Deserialize)]
  20. #[serde(field_identifier, rename_all = "lowercase")]
  21. enum Field { Secs, Nanos }
  22.  
  23. // enum Field { Secs, Nanos };
  24. //
  25. // impl<'de> Deserialize<'de> for Field {
  26. // fn deserialize<D>(deserializer: D) -> Result<Field, D::Error>
  27. // where
  28. // D: Deserializer<'de>,
  29. // {
  30. // struct FieldVisitor;
  31. //
  32. // impl<'de> Visitor<'de> for FieldVisitor {
  33. // type Value = Field;
  34. //
  35. // fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  36. // formatter.write_str("`secs` or `nanos`")
  37. // }
  38. //
  39. // fn visit_str<E>(self, value: &str) -> Result<Field, E>
  40. // where
  41. // E: de::Error,
  42. // {
  43. // match value {
  44. // "secs" => Ok(Field::Secs),
  45. // "nanos" => Ok(Field::Nanos),
  46. // _ => Err(de::Error::unknown_field(value, FIELDS)),
  47. // }
  48. // }
  49. // }
  50. //
  51. // deserializer.deserialize_identifier(FieldVisitor)
  52. // }
  53. // }
  54.  
  55. struct DurationVisitor;
  56.  
  57. impl<'de> Visitor<'de> for DurationVisitor {
  58. type Value = Duration;
  59.  
  60. fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  61. formatter.write_str("struct Duration")
  62. }
  63.  
  64. fn visit_map<V>(self, mut map: V) -> Result<Duration, V::Error>
  65. where
  66. V: MapAccess<'de>,
  67. {
  68. let mut secs = None;
  69. let mut nanos = None;
  70. while let Some(key) = map.next_key()? {
  71. match key {
  72. Field::Secs => {
  73. if secs.is_some() {
  74. return Err(de::Error::duplicate_field("secs"));
  75. }
  76. secs = Some(map.next_value()?);
  77. }
  78. Field::Nanos => {
  79. if nanos.is_some() {
  80. return Err(de::Error::duplicate_field("nanos"));
  81. }
  82. nanos = Some(map.next_value()?);
  83. }
  84. }
  85. }
  86. let secs = secs.ok_or_else(|| de::Error::missing_field("secs"))?;
  87. let nanos = nanos.ok_or_else(|| de::Error::missing_field("nanos"))?;
  88. Ok(Duration { secs, nanos })
  89. }
  90. }
  91.  
  92. const FIELDS: &'static [&'static str] = &["secs", "nanos"];
  93. deserializer.deserialize_struct("Duration", FIELDS, DurationVisitor)
  94. }
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement