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