use core::fmt; use core::marker::PhantomData; use serde::de::{Deserialize, Deserializer, MapAccess, Visitor}; use serde::ser::{Serialize, SerializeMap, Serializer}; use super::{builder::Builder, Slab}; impl Serialize for Slab where T: Serialize, { fn serialize(&self, serializer: S) -> Result where S: Serializer, { let mut map_serializer = serializer.serialize_map(Some(self.len()))?; for (key, value) in self { map_serializer.serialize_key(&key)?; map_serializer.serialize_value(value)?; } map_serializer.end() } } struct SlabVisitor(PhantomData); impl<'de, T> Visitor<'de> for SlabVisitor where T: Deserialize<'de>, { type Value = Slab; fn expecting(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!(fmt, "a map") } fn visit_map(self, mut map: A) -> Result where A: MapAccess<'de>, { let mut builder = Builder::with_capacity(map.size_hint().unwrap_or(0)); while let Some((key, value)) = map.next_entry()? { builder.pair(key, value) } Ok(builder.build()) } } impl<'de, T> Deserialize<'de> for Slab where T: Deserialize<'de>, { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { deserializer.deserialize_map(SlabVisitor(PhantomData)) } }