use crate::{DashMap, DashSet}; use core::fmt; use core::hash::Hash; use core::marker::PhantomData; use serde::de::{Deserialize, MapAccess, SeqAccess, Visitor}; use serde::ser::{Serialize, SerializeMap, SerializeSeq, Serializer}; use serde::Deserializer; pub struct DashMapVisitor { marker: PhantomData DashMap>, } impl DashMapVisitor where K: Eq + Hash, { fn new() -> Self { DashMapVisitor { marker: PhantomData, } } } impl<'de, K, V> Visitor<'de> for DashMapVisitor where K: Deserialize<'de> + Eq + Hash, V: Deserialize<'de>, { type Value = DashMap; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a DashMap") } fn visit_map(self, mut access: M) -> Result where M: MapAccess<'de>, { let map = DashMap::with_capacity(access.size_hint().unwrap_or(0)); while let Some((key, value)) = access.next_entry()? { map.insert(key, value); } Ok(map) } } impl<'de, K, V> Deserialize<'de> for DashMap where K: Deserialize<'de> + Eq + Hash, V: Deserialize<'de>, { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { deserializer.deserialize_map(DashMapVisitor::::new()) } } impl Serialize for DashMap where K: Serialize + Eq + Hash, V: Serialize, { fn serialize(&self, serializer: S) -> Result where S: Serializer, { let mut map = serializer.serialize_map(Some(self.len()))?; for ref_multi in self.iter() { map.serialize_entry(ref_multi.key(), ref_multi.value())?; } map.end() } } pub struct DashSetVisitor { marker: PhantomData DashSet>, } impl DashSetVisitor where K: Eq + Hash, { fn new() -> Self { DashSetVisitor { marker: PhantomData, } } } impl<'de, K> Visitor<'de> for DashSetVisitor where K: Deserialize<'de> + Eq + Hash, { type Value = DashSet; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a DashSet") } fn visit_seq(self, mut access: M) -> Result where M: SeqAccess<'de>, { let map = DashSet::with_capacity(access.size_hint().unwrap_or(0)); while let Some(key) = access.next_element()? { map.insert(key); } Ok(map) } } impl<'de, K> Deserialize<'de> for DashSet where K: Deserialize<'de> + Eq + Hash, { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { deserializer.deserialize_seq(DashSetVisitor::::new()) } } impl Serialize for DashSet where K: Serialize + Eq + Hash, { fn serialize(&self, serializer: S) -> Result where S: Serializer, { let mut seq = serializer.serialize_seq(Some(self.len()))?; for ref_multi in self.iter() { seq.serialize_element(ref_multi.key())?; } seq.end() } }