From bb3eadc0756062e82a6feb73d4bae5bd1cb18917 Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Mon, 16 Jun 2025 11:07:20 +0200 Subject: Use bytes instead of string for data values --- src/merkle/node.rs | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) (limited to 'src/merkle/node.rs') 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, } 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(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::::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 -- cgit v1.2.3-71-g8e6c