use crate::{
Augment, AugmentedRBTree,
alloc_proxy::proxy::{Allocator, Global},
};
use core::marker::PhantomData;
use serde::{
Deserialize, Deserializer, Serialize, Serializer,
de::{DeserializeSeed, SeqAccess},
ser::SerializeSeq,
};
#[derive(Debug)]
pub struct AugmentedRBTreeSeedInt<K, V, G, A: Allocator> {
pub allocator: A,
_marker: PhantomData<(K, V, G)>,
}
pub type AugmentedRBTreeSeed<K, V, G, A = Global> = AugmentedRBTreeSeedInt<K, V, G, A>;
impl<K, V, G, A: Allocator> AugmentedRBTreeSeedInt<K, V, G, A> {
pub fn new(allocator: A) -> Self {
Self {
allocator,
_marker: PhantomData,
}
}
}
impl<'de, K, V, G, A: Allocator> DeserializeSeed<'de> for AugmentedRBTreeSeedInt<K, V, G, A>
where
G: Augment<K, V>,
K: Deserialize<'de> + Ord,
V: Deserialize<'de>,
{
type Value = AugmentedRBTree<K, V, G, A>;
fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Value, D::Error> {
struct AllocatorVisitor<K, V, G, A> {
allocator: A,
_marker: core::marker::PhantomData<(K, V, G)>,
}
impl<'de, K, V, G, A: Allocator> serde::de::Visitor<'de> for AllocatorVisitor<K, V, G, A>
where
K: Deserialize<'de> + Ord,
V: Deserialize<'de>,
G: Augment<K, V>,
{
type Value = AugmentedRBTree<K, V, G, A>;
fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("a sequence of sorted (key, value) pairs")
}
fn visit_seq<SA: SeqAccess<'de>>(self, mut seq: SA) -> Result<Self::Value, SA::Error> {
let mut tree = AugmentedRBTree::<K, V, G, A>::new_in(self.allocator);
while let Some((k, v)) = seq.next_element::<(K, V)>()? {
tree.insert(k, v);
}
Ok(tree)
}
}
deserializer.deserialize_seq(AllocatorVisitor {
allocator: self.allocator,
_marker: core::marker::PhantomData,
})
}
}
impl<K, V, G, A: Allocator> Serialize for AugmentedRBTree<K, V, G, A>
where
G: Augment<K, V>,
K: Serialize + Ord,
V: Serialize,
{
fn serialize<Se: Serializer>(&self, serializer: Se) -> Result<Se::Ok, Se::Error> {
let mut seq = serializer.serialize_seq(Some(self.len()))?;
for (k, v, _) in self {
seq.serialize_element(&(k, v))?;
}
seq.end()
}
}