summaryrefslogtreecommitdiffstats
path: root/src/merkle/node.rs
diff options
context:
space:
mode:
authorSanto Cariotti <santo@dcariotti.me>2025-06-16 09:07:20 +0000
committerSanto Cariotti <santo@dcariotti.me>2025-06-16 09:07:20 +0000
commitbb3eadc0756062e82a6feb73d4bae5bd1cb18917 (patch)
treef1e89b1552e3a9e20f7b55a70d83262625362d37 /src/merkle/node.rs
parentc470ba5f7b1a85bfd1cd96e5ec14d2f42a25ec55 (diff)
Use bytes instead of string for data values
Diffstat (limited to 'src/merkle/node.rs')
-rw-r--r--src/merkle/node.rs19
1 files changed, 15 insertions, 4 deletions
diff --git a/src/merkle/node.rs b/src/merkle/node.rs
index 0e5e904..021b1c3 100644
--- a/src/merkle/node.rs
+++ b/src/merkle/node.rs
@@ -36,6 +36,8 @@ pub struct Node {
hash: String,
/// Type of the node: leaf or internal.
kind: NodeType,
+ /// Data in bytes.
+ data: Vec<u8>,
}
impl Node {
@@ -45,10 +47,11 @@ impl Node {
///
/// * `hasher` - A reference to a hashing strategy.
/// * `data` - The data to be hashed and stored as a leaf.
- pub fn new_leaf<T: ToString>(hasher: &dyn Hasher, data: T) -> Self {
- let hash = hasher.hash(&data.to_string());
+ pub fn new_leaf(hasher: &dyn Hasher, data: &[u8]) -> Self {
+ let hash = hasher.hash(&data);
Self {
hash,
+ data: data.to_vec(),
kind: NodeType::Leaf,
}
}
@@ -65,10 +68,13 @@ impl Node {
///
/// The internal node hash is computed as the hash of the concatenated children's hashes.
pub fn new_internal(hasher: &dyn Hasher, left: Node, right: Node) -> Self {
- let combined = format!("{}{}", left.hash, right.hash);
- let hash = hasher.hash(&combined);
+ let mut buffer = Vec::<u8>::new();
+ buffer.extend_from_slice(left.hash().as_bytes());
+ buffer.extend_from_slice(right.hash().as_bytes());
+ let hash = hasher.hash(&buffer);
Self {
hash,
+ data: buffer,
kind: NodeType::Internal(Box::new(left), Box::new(right)),
}
}
@@ -78,6 +84,11 @@ impl Node {
&self.hash
}
+ /// Returns the data value in bytes format.
+ pub fn data(&self) -> &[u8] {
+ &self.data
+ }
+
/// Returns a reference to the node's type (leaf or internal).
pub fn kind(&self) -> &NodeType {
&self.kind