nam_sparse_merkle_tree/
merge.rs

1use crate::h256::H256;
2use crate::traits::{Hasher, Value};
3use crate::Key;
4
5/// Merge two hashes
6/// this function is optimized for ZERO_HASH
7/// if one of lhs or rhs is ZERO_HASH, this function just returns the another one
8pub fn merge<H: Hasher + Default>(lhs: &H256, rhs: &H256) -> H256 {
9    if lhs.is_zero() {
10        return *rhs;
11    } else if rhs.is_zero() {
12        return *lhs;
13    }
14    let mut hasher = H::default();
15    hasher.write_bytes(lhs.as_slice());
16    hasher.write_bytes(rhs.as_slice());
17    hasher.finish()
18}
19
20/// hash_leaf = hash(prefix | key | value)
21/// zero value indicates a key is to be deleted, this function returns zero for zero value
22pub fn hash_leaf<H: Hasher + Default, K, V, const N: usize>(key: &K, value: &V) -> H256
23where
24    K: Key<N>,
25    V: Value,
26{
27    if value.is_zero() {
28        return H256::zero();
29    }
30    let mut hasher = H::default();
31    hasher.write_bytes(H256::zero().as_slice());
32    hasher.write_bytes(key.as_slice());
33    hasher.write_bytes(value.as_slice());
34    hasher.finish()
35}