Skip to main content

osom_lib_hash_tables/serde_impl/
default.rs

1use core::{hash::Hash, marker::PhantomData};
2
3use osom_lib_alloc::traits::Allocator;
4use osom_lib_primitives::length::Length;
5use serde::{
6    Deserialize, Serialize,
7    de::{self, Visitor},
8    ser::SerializeMap,
9};
10
11use crate::{
12    defaults::DefaultHashTable,
13    traits::{ImmutableHashTable, MutableHashTable},
14};
15
16impl<TKey, TValue, TAllocator> Serialize for DefaultHashTable<TKey, TValue, TAllocator>
17where
18    TKey: Eq + Hash + Serialize,
19    TValue: Serialize,
20    TAllocator: Allocator,
21{
22    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
23    where
24        S: serde::Serializer,
25    {
26        let mut m = serializer.serialize_map(Some(self.length().as_usize()))?;
27        for kvp in self.iter() {
28            m.serialize_entry(&kvp.key, &kvp.value)?;
29        }
30        m.end()
31    }
32}
33
34struct DefaultHashTableVisitor<TKey, TValue, TAllocator> {
35    _phantom: PhantomData<(TKey, TValue, TAllocator)>,
36}
37
38impl<TKey, TValue, TAllocator> DefaultHashTableVisitor<TKey, TValue, TAllocator> {
39    #[inline(always)]
40    pub const fn new() -> Self {
41        Self { _phantom: PhantomData }
42    }
43}
44
45impl<'de, TKey, TValue, TAllocator> Visitor<'de> for DefaultHashTableVisitor<TKey, TValue, TAllocator>
46where
47    TKey: Eq + Hash + Deserialize<'de>,
48    TValue: Deserialize<'de>,
49    TAllocator: Allocator + Default,
50{
51    type Value = DefaultHashTable<TKey, TValue, TAllocator>;
52
53    fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
54        formatter.write_str("a (key, value) mapping")
55    }
56
57    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
58    where
59        A: serde::de::MapAccess<'de>,
60    {
61        let capacity = map.size_hint().unwrap_or(0);
62        let length = Length::try_from_usize(capacity).map_err(de::Error::custom)?;
63        let mut result =
64            DefaultHashTable::<TKey, TValue, TAllocator>::with_capacity(length).map_err(de::Error::custom)?;
65        while let Some((key, value)) = map.next_entry::<TKey, TValue>()? {
66            result.try_insert(key, value).map_err(de::Error::custom)?;
67        }
68        Ok(result)
69    }
70}
71
72impl<'de, TKey, TValue, TAllocator> Deserialize<'de> for DefaultHashTable<TKey, TValue, TAllocator>
73where
74    TKey: Eq + Hash + Deserialize<'de>,
75    TValue: Deserialize<'de>,
76    TAllocator: Allocator + Default,
77{
78    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
79    where
80        D: serde::Deserializer<'de>,
81    {
82        deserializer.deserialize_map(DefaultHashTableVisitor::new())
83    }
84}