nam_sparse_merkle_tree/
default_store.rs

1use std::ops::Deref;
2use crate::{collections, error::Error, traits::Store, tree::{BranchNode, LeafNode}, Key, H256};
3#[cfg(feature = "borsh")]
4use borsh::{BorshDeserialize, BorshSerialize};
5use itertools::Itertools;
6
7#[derive(Debug, Clone)]
8#[cfg_attr(feature = "borsh", derive(BorshSerialize, BorshDeserialize))]
9pub struct DefaultStore<K, V, const N: usize>
10where
11    K: Key<N>,
12{
13    branches_map: Map<H256, BranchNode<K, N>>,
14    leaves_map: Map<H256, LeafNode<K, V, N>>,
15}
16
17impl<K, V, const N: usize> Default for DefaultStore<K, V, N>
18where
19    K: Key<N>,
20{
21    fn default() -> Self {
22        Self {
23            branches_map: Map::new(),
24            leaves_map: Map::new(),
25        }
26    }
27}
28
29impl<K, V, const N: usize> DefaultStore<K, V, N>
30where
31    K: Key<N>,
32{
33    pub fn branches_map(&self) -> &Map<H256, BranchNode<K, N>> {
34        &self.branches_map
35    }
36    pub fn leaves_map(&self) -> &Map<H256, LeafNode<K, V, N>> {
37        &self.leaves_map
38    }
39    pub fn clear(&mut self) {
40        self.branches_map.clear();
41        self.leaves_map.clear();
42    }
43}
44
45impl<K, V: Clone, const N: usize> Store<K, V, N> for DefaultStore<K, V, N>
46where
47    K: Key<N>,
48{
49    fn get_branch(&self, node: &H256) -> Result<Option<BranchNode<K, N>>, Error> {
50        Ok(self.branches_map.get(node).map(Clone::clone))
51    }
52    fn get_leaf(&self, leaf_hash: &H256) -> Result<Option<LeafNode<K, V, N>>, Error> {
53        Ok(self.leaves_map.get(leaf_hash).map(Clone::clone))
54    }
55    fn insert_branch(&mut self, node: H256, branch: BranchNode<K, N>) -> Result<(), Error> {
56        self.branches_map.insert(node, branch);
57        Ok(())
58    }
59    fn insert_leaf(&mut self, leaf_hash: H256, leaf: LeafNode<K, V, N>) -> Result<(), Error> {
60        self.leaves_map.insert(leaf_hash, leaf);
61        Ok(())
62    }
63    fn remove_branch(&mut self, node: &H256) -> Result<(), Error> {
64        self.branches_map.remove(node);
65        Ok(())
66    }
67    fn remove_leaf(&mut self, leaf_hash: &H256) -> Result<(), Error> {
68        self.leaves_map.remove(leaf_hash);
69        Ok(())
70    }
71
72    fn sorted_leaves<'a>(&'a self) -> impl Iterator<Item=(K, &'a V)> where V: 'a {
73        self.leaves_map
74            .iter()
75            .sorted_by_key(|(_, v)| <K as Deref>::deref(&v.key))
76            .map(|(_, v)| (v.key, &v.value))
77    }
78
79    fn size(&self) -> usize {
80        self.leaves_map.len()
81    }
82}
83
84cfg_if::cfg_if! {
85    if #[cfg(feature = "std")] {
86        pub type Map<K, V> = collections::HashMap<K, V>;
87        pub type Entry<'a, K, V> = collections::hash_map::Entry<'a, K, V>;
88    } else {
89        pub type Map<K, V> = collections::BTreeMap<K, V>;
90        pub type Entry<'a, K, V> = collections::btree_map::Entry<'a, K, V>;
91    }
92}