nam_sparse_merkle_tree/
traits.rs

1use crate::{
2    error::Error,
3    tree::{BranchNode, LeafNode},
4    Hash as KeyHash, InternalKey, H256,
5};
6use core::hash::Hash;
7use core::ops::Deref;
8
9/// Trait for customize hash function
10pub trait Hasher {
11    fn write_bytes(&mut self, h: &[u8]);
12    fn finish(self) -> H256;
13    fn hash_op() -> ics23::HashOp {
14        ics23::HashOp::NoHash
15    }
16}
17
18/// This trait is map keys to / from the users key space into a finite
19/// key space used internally. This space is the set of all N-byte arrays
20/// where N < 2^32
21pub trait Key<const N: usize>:
22    Eq + PartialEq + Copy + Clone + Hash + Deref<Target = InternalKey<N>>
23{
24    /// The error type for failed mappings
25    type Error;
26    /// This should map from the internal key space
27    /// back into the user's key space
28    fn as_slice(&self) -> &[u8];
29    /// This should map from the internal key space
30    /// back into the user's key space
31    fn to_vec(&self) -> Vec<u8> {
32        self.as_slice().to_vec()
33    }
34    /// This should map from the user's key space into
35    /// the internal keyspace
36    fn try_from_bytes(bytes: &[u8]) -> Result<Self, Self::Error>;
37}
38
39impl Key<32> for KeyHash {
40    type Error = crate::error::Error;
41
42    fn as_slice(&self) -> &[u8] {
43        <Self as Deref>::deref(self).as_slice()
44    }
45
46    fn try_from_bytes(bytes: &[u8]) -> Result<Self, Self::Error> {
47        use std::convert::TryInto;
48        let bytes: [u8; 32] = bytes
49            .try_into()
50            .map_err(|_| crate::error::Error::KeyTooLarge)?;
51        Ok(bytes.into())
52    }
53}
54
55/// Trait for define value structures
56pub trait Value: PartialEq + Clone {
57    fn as_slice(&self) -> &[u8];
58    fn zero() -> Self;
59    fn is_zero(&self) -> bool {
60        self == &Self::zero()
61    }
62}
63
64impl Value for H256 {
65    fn as_slice(&self) -> &[u8] {
66        self.as_slice()
67    }
68    fn zero() -> Self {
69        H256::zero()
70    }
71}
72
73/// Trait for customize backend storage
74pub trait Store<K, V, const N: usize>: Default
75where
76    K: Key<N>,
77{
78    fn get_branch(&self, node: &H256) -> Result<Option<BranchNode<K, N>>, Error>;
79    fn get_leaf(&self, leaf_key: &H256) -> Result<Option<LeafNode<K, V, N>>, Error>;
80    fn insert_branch(&mut self, node: H256, branch: BranchNode<K, N>) -> Result<(), Error>;
81    fn insert_leaf(&mut self, leaf_key: H256, leaf: LeafNode<K, V, N>) -> Result<(), Error>;
82    fn remove_branch(&mut self, node: &H256) -> Result<(), Error>;
83    fn remove_leaf(&mut self, leaf_key: &H256) -> Result<(), Error>;
84    fn sorted_leaves<'a>(&'a self) -> impl Iterator<Item=(K, &'a V)> where V: 'a;
85    fn size(&self) -> usize;
86}
87