Skip to main content

object_rainbow_trie/
serde.rs

1use std::{
2    collections::BTreeMap,
3    task::{Context, Poll},
4};
5
6use ::serde::{Deserialize, Serialize, de::DeserializeOwned};
7use futures_util::{StreamExt, task::noop_waker_ref};
8
9use super::*;
10
11type Map<K, V> = BTreeMap<ByBytes<K>, V>;
12
13impl<K: ReflessObject + AsRef<[u8]>, V: 'static + Send + Sync + Clone> TrieMap<K, V>
14where
15    Option<V>: Traversible + InlineOutput,
16{
17    fn to_map(&self) -> object_rainbow::Result<Map<K, V>> {
18        let future = self
19            .range_stream(..)
20            .map_ok(|(k, v)| (ByBytes(k), v))
21            .try_collect();
22        let future = pin!(future);
23        match future.poll(&mut Context::from_waker(noop_waker_ref())) {
24            Poll::Ready(map) => map,
25            Poll::Pending => Err(object_rainbow::error_fetch!("not local")),
26        }
27    }
28
29    fn from_map(map: Map<K, V>) -> object_rainbow::Result<Self> {
30        let future =
31            Self::from_stream(futures_util::stream::iter(map).map(|(ByBytes(k), v)| Ok((k, v))));
32        let future = pin!(future);
33        match future.poll(&mut Context::from_waker(noop_waker_ref())) {
34            Poll::Ready(trie) => trie,
35            Poll::Pending => Err(object_rainbow::error_fetch!("not local")),
36        }
37    }
38}
39
40#[derive(Serialize, Deserialize)]
41struct ByBytes<K>(K);
42
43impl<K: AsRef<[u8]>> PartialEq for ByBytes<K> {
44    fn eq(&self, other: &Self) -> bool {
45        self.0.as_ref() == other.0.as_ref()
46    }
47}
48
49impl<K: AsRef<[u8]>> Eq for ByBytes<K> {}
50
51impl<K: AsRef<[u8]>> PartialOrd for ByBytes<K> {
52    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
53        Some(self.cmp(other))
54    }
55}
56
57impl<K: AsRef<[u8]>> Ord for ByBytes<K> {
58    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
59        self.0.as_ref().cmp(other.0.as_ref())
60    }
61}
62
63impl<K: ReflessObject + AsRef<[u8]> + Serialize, V: 'static + Send + Sync + Clone + Serialize>
64    Serialize for TrieMap<K, V>
65where
66    Option<V>: Traversible + InlineOutput,
67{
68    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
69    where
70        S: ::serde::Serializer,
71    {
72        self.to_map()
73            .map_err(<S::Error as ::serde::ser::Error>::custom)?
74            .serialize(serializer)
75    }
76}
77
78impl<
79    'de,
80    K: ReflessObject + AsRef<[u8]> + DeserializeOwned,
81    V: 'static + Send + Sync + Clone + DeserializeOwned,
82> Deserialize<'de> for TrieMap<K, V>
83where
84    Option<V>: Traversible + InlineOutput,
85{
86    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
87    where
88        D: ::serde::Deserializer<'de>,
89    {
90        Self::from_map(Map::deserialize(deserializer)?)
91            .map_err(<D::Error as ::serde::de::Error>::custom)
92    }
93}