Pull the hashmap Serialize/Deserialize impl into a module

This commit is contained in:
Gwilym Inzani 2024-10-30 10:36:36 +00:00
parent b2d0e93f8c
commit 69219e3d73

View file

@ -7,9 +7,12 @@ use serde::{
use crate::{ClonableAllocator, HashMap}; use crate::{ClonableAllocator, HashMap};
impl<K: Serialize, V: Serialize, ALLOCATOR: ClonableAllocator> Serialize mod hashmap {
use super::*;
impl<K: Serialize, V: Serialize, ALLOCATOR: ClonableAllocator> Serialize
for HashMap<K, V, ALLOCATOR> for HashMap<K, V, ALLOCATOR>
{ {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where where
S: serde::Serializer, S: serde::Serializer,
@ -22,39 +25,39 @@ impl<K: Serialize, V: Serialize, ALLOCATOR: ClonableAllocator> Serialize
map.end() map.end()
} }
} }
impl<'de, K, V> Deserialize<'de> for HashMap<K, V> impl<'de, K, V> Deserialize<'de> for HashMap<K, V>
where where
K: Deserialize<'de> + Hash + Eq, K: Deserialize<'de> + Hash + Eq,
V: Deserialize<'de>, V: Deserialize<'de>,
{ {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where where
D: serde::Deserializer<'de>, D: serde::Deserializer<'de>,
{ {
deserializer.deserialize_map(HashMapVisitor::new()) deserializer.deserialize_map(HashMapVisitor::new())
} }
} }
#[derive(Default)] #[derive(Default)]
struct HashMapVisitor<K, V> { struct HashMapVisitor<K, V> {
_marker: PhantomData<fn() -> HashMap<K, V>>, _marker: PhantomData<fn() -> HashMap<K, V>>,
} }
impl<K, V> HashMapVisitor<K, V> { impl<K, V> HashMapVisitor<K, V> {
fn new() -> Self { fn new() -> Self {
Self { Self {
_marker: PhantomData, _marker: PhantomData,
} }
} }
} }
impl<'de, K, V> Visitor<'de> for HashMapVisitor<K, V> impl<'de, K, V> Visitor<'de> for HashMapVisitor<K, V>
where where
K: Deserialize<'de> + Hash + Eq, K: Deserialize<'de> + Hash + Eq,
V: Deserialize<'de>, V: Deserialize<'de>,
{ {
type Value = HashMap<K, V>; type Value = HashMap<K, V>;
fn expecting(&self, formatter: &mut alloc::fmt::Formatter) -> alloc::fmt::Result { fn expecting(&self, formatter: &mut alloc::fmt::Formatter) -> alloc::fmt::Result {
@ -73,4 +76,5 @@ where
Ok(map) Ok(map)
} }
}
} }