nmt_rs/simple_merkle/
db.rs1use crate::{
2 maybestd::{hash::Hash, vec::Vec},
3 NamespaceId, NamespaceMerkleHasher, NamespacedHash,
4};
5
6use super::tree::MerkleHash;
7
8#[cfg(not(feature = "std"))]
9trait HashType: Eq + Hash + crate::maybestd::cmp::Ord {}
10
11#[cfg(not(feature = "std"))]
12impl<H: Eq + Hash + Ord> HashType for H {}
13
14#[cfg(feature = "std")]
15trait HashType: Eq + Hash {}
16
17#[cfg(feature = "std")]
18impl<H: Eq + Hash> HashType for H {}
19
20#[derive(Default)]
22pub struct MemDb<H>(crate::maybestd::hash_or_btree_map::Map<H, Node<H>>);
23
24impl<H: HashType> PreimageReader<H> for MemDb<H> {
25 fn get(&self, image: &H) -> Option<&Node<H>> {
26 self.0.get(image)
27 }
28}
29impl<H: HashType> PreimageWriter<H> for MemDb<H> {
30 fn put(&mut self, image: H, preimage: Node<H>) {
31 self.0.insert(image, preimage);
32 }
33}
34
35impl<H: Default + HashType> PreimageDb<H> for MemDb<H> {}
36
37#[derive(Clone)]
39pub struct LeafWithHash<H: MerkleHash> {
40 data: Vec<u8>,
41 hash: H::Output,
42}
43
44impl<H: MerkleHash + Default> LeafWithHash<H> {
45 pub fn new(data: Vec<u8>) -> Self {
47 let hash = H::default().hash_leaf(&data);
48 Self { data, hash }
49 }
50}
51
52impl<H: MerkleHash> LeafWithHash<H> {
53 pub fn with_hasher(data: Vec<u8>, hasher: &H) -> Self {
55 let hash = hasher.hash_leaf(&data);
56 Self { data, hash }
57 }
58
59 pub fn data(&self) -> &[u8] {
61 &self.data
62 }
63
64 pub fn hash(&self) -> &H::Output {
66 &self.hash
67 }
68}
69
70impl<
71 M: NamespaceMerkleHasher<NS_ID_SIZE, Output = NamespacedHash<NS_ID_SIZE>>,
72 const NS_ID_SIZE: usize,
73 > LeafWithHash<M>
74{
75 pub fn new_with_namespace(
77 data: Vec<u8>,
78 namespace: NamespaceId<NS_ID_SIZE>,
79 ignore_max_ns: bool,
80 ) -> Self {
81 let hasher = M::with_ignore_max_ns(ignore_max_ns);
82 let hash = hasher.hash_leaf_with_namespace(&data, namespace);
83 Self { data, hash }
84 }
85}
86
87#[derive(PartialEq, Clone, Debug)]
89pub enum Node<H> {
90 Leaf(Vec<u8>),
92 Inner(H, H),
94}
95
96pub trait PreimageReader<H> {
98 fn get(&self, image: &H) -> Option<&Node<H>>;
100}
101
102pub trait PreimageWriter<H> {
104 fn put(&mut self, image: H, preimage: Node<H>);
106}
107
108pub trait PreimageDb<H>: PreimageReader<H> + PreimageWriter<H> + Default {}
110
111#[derive(Default)]
114pub struct NoopDb;
115
116impl<H: Eq + Hash> PreimageReader<H> for NoopDb {
117 fn get(&self, _image: &H) -> Option<&Node<H>> {
118 None
119 }
120}
121impl<H: Eq + Hash> PreimageWriter<H> for NoopDb {
122 fn put(&mut self, _image: H, _preimage: Node<H>) {}
123}
124
125impl<H: Default + Eq + Hash> PreimageDb<H> for NoopDb {}