Savior

Custom (de-)serialization in Serde (Rust)

Feb 13th, 2020
749
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. extern crate serde;
  2. extern crate serde_derive;
  3. extern crate serde_json;
  4.  
  5. use std::collections::BTreeMap as Map;
  6.  
  7. use serde::{
  8.     de::{SeqAccess, Visitor},
  9.     // ser::SerializeSeq,
  10.     Deserialize,
  11.     Deserializer,
  12.     Serialize,
  13.     Serializer,
  14. };
  15.  
  16. // use std::time::Instant;
  17.  
  18. #[derive(Debug, Deserialize, Serialize)]
  19. struct Data<'a> {
  20.    title: &'a str,
  21.     #[serde(deserialize_with = "deserialize_vec_to_map")]
  22.     #[serde(serialize_with = "serialize_map_to_vec")]
  23.     values: Map<&'a str, bool>,
  24. }
  25.  
  26. struct SeqVisitor<T>(std::marker::PhantomData<T>);
  27.  
  28. impl<'de, T> Visitor<'de> for SeqVisitor<T>
  29. where
  30.    T: Deserialize<'de> + std::cmp::Ord,
  31. {
  32.     type Value = Map<T, bool>;
  33.  
  34.     fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
  35.         formatter.write_str("a sequence")
  36.     }
  37.  
  38.     fn visit_seq<V>(self, mut seq: V) -> Result<Map<T, bool>, V::Error>
  39.     where
  40.         V: SeqAccess<'de>,
  41.    {
  42.        let mut map: Map<T, bool> = Map::new();
  43.        while let Some(v) = seq.next_element()? {
  44.            map.insert(v, true);
  45.        }
  46.        Ok(map)
  47.    }
  48. }
  49.  
  50. fn deserialize_vec_to_map<'de, T, D>(deserializer: D) -> Result<Map<T, bool>, D::Error>
  51. where
  52.     T: Deserialize<'de> + std::cmp::Ord, // + Copy,
  53.    D: Deserializer<'de>,
  54. {
  55.     // Deserialize::deserialize(deserializer)
  56.     //     .map(|v: Vec<T>| v.iter().copied().map(|k| (k, true)).collect())
  57.     deserializer.deserialize_seq(SeqVisitor(std::marker::PhantomData))
  58. }
  59.  
  60. fn serialize_map_to_vec<T, S>(value: &Map<T, bool>, serializer: S) -> Result<S::Ok, S::Error>
  61. where
  62.     T: Serialize,
  63.     S: Serializer,
  64. {
  65.     // let mut seq = serializer.serialize_seq(Some(value.len()))?;
  66.     // for (k, _) in value.iter().filter(|(_, &v)| v) {
  67.     //     seq.serialize_element(k)?;
  68.     // }
  69.     // seq.end()
  70.     serializer.collect_seq(value.iter().filter(|(_, &v)| v).map(|(k, _)| k))
  71. }
  72.  
  73. fn main() -> Result<(), Box<dyn std::error::Error>> {
  74.     let src = r#"{"title":"Hello","values":["a", "b", "a"]}"#;
  75.     println!("Source: {}\n", src);
  76.  
  77.     // let t1 = Instant::now();
  78.     let serialized: Data = serde_json::from_str(src)?;
  79.     // let t2 = Instant::now();
  80.     println!("Serialized struct:\n{:#?}\n", serialized);
  81.     // println!("Serialized in {}ms", (t2 - t1).as_nanos() as f64 / 1_000_000.0);
  82.  
  83.     // let t1 = Instant::now();
  84.     let deserialized = serde_json::to_string(&serialized)?;
  85.     // let t2 = Instant::now();
  86.     println!("Deserialized: {}", deserialized);
  87.     // println!("Deserialized in {}ms", (t2 - t1).as_nanos() as f64 / 1_000_000.0);
  88.     Ok(())
  89. }
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×