//! An optional implementation of serialization/deserialization. extern crate serde; use std::fmt::{Formatter, Result as FmtResult}; use std::marker::PhantomData; use std::hash::{BuildHasher, Hash}; use super::LinkedHashMap; use self::serde::{Serialize, Serializer, Deserialize, Deserializer}; use self::serde::ser::SerializeMap; use self::serde::de::{Visitor, MapAccess, Error}; impl Serialize for LinkedHashMap where K: Serialize + Eq + Hash, V: Serialize, S: BuildHasher { #[inline] fn serialize(&self, serializer:T) -> Result where T: Serializer, { let mut map_serializer = try!(serializer.serialize_map(Some(self.len()))); for (k, v) in self { try!(map_serializer.serialize_key(k)); try!(map_serializer.serialize_value(v)); } map_serializer.end() } } #[derive(Debug)] /// `serde::de::Visitor` for a linked hash map. pub struct LinkedHashMapVisitor { marker: PhantomData>, } impl LinkedHashMapVisitor { /// Creates a new visitor for a linked hash map. pub fn new() -> Self { LinkedHashMapVisitor { marker: PhantomData, } } } impl Default for LinkedHashMapVisitor { fn default() -> Self { LinkedHashMapVisitor::new() } } impl<'de, K, V> Visitor<'de> for LinkedHashMapVisitor where K: Deserialize<'de> + Eq + Hash, V: Deserialize<'de>, { type Value = LinkedHashMap; fn expecting(&self, formatter: &mut Formatter) -> FmtResult { write!(formatter, "a map") } #[inline] fn visit_unit(self) -> Result where E: Error, { Ok(LinkedHashMap::new()) } #[inline] fn visit_map(self, mut map: M) -> Result where M: MapAccess<'de>, { let mut values = LinkedHashMap::with_capacity(map.size_hint().unwrap_or(0)); while let Some((key, value)) = map.next_entry()? { values.insert(key, value); } Ok(values) } } impl<'de, K, V> Deserialize<'de> for LinkedHashMap where K: Deserialize<'de> + Eq + Hash, V: Deserialize<'de>, { fn deserialize(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_map(LinkedHashMapVisitor::new()) } }