Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: avoid unnecessary clone when building Merkle trees #872

Merged
merged 4 commits into from
Jul 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions crypto/src/merkle_tree/merkle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ where
B: IsMerkleTreeBackend,
{
pub fn build(unhashed_leaves: &[B::Data]) -> Self {
let mut hashed_leaves: Vec<B::Node> = B::hash_leaves(unhashed_leaves);
let hashed_leaves: Vec<B::Node> = B::hash_leaves(unhashed_leaves);

//The leaf must be a power of 2 set
hashed_leaves = complete_until_power_of_two(&mut hashed_leaves);
let hashed_leaves = complete_until_power_of_two(hashed_leaves);
let leaves_len = hashed_leaves.len();

//The length of leaves minus one inner node in the merkle tree
Expand Down
12 changes: 6 additions & 6 deletions crypto/src/merkle_tree/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@ pub fn parent_index(node_index: usize) -> usize {
}

// The list of values is completed repeating the last value to a power of two length
pub fn complete_until_power_of_two<T: Clone>(values: &mut Vec<T>) -> Vec<T> {
pub fn complete_until_power_of_two<T: Clone>(mut values: Vec<T>) -> Vec<T> {
while !is_power_of_two(values.len()) {
values.push(values[values.len() - 1].clone());
}
values.to_vec()
values
}

// ! NOTE !
Expand Down Expand Up @@ -101,8 +101,8 @@ mod tests {
#[test]
// expected |1|2|3|4|5|5|5|5|
fn complete_the_length_of_a_list_of_fields_elements_to_be_a_power_of_two() {
let mut values: Vec<FE> = (1..6).map(FE::new).collect();
let hashed_leaves = complete_until_power_of_two(&mut values);
let values: Vec<FE> = (1..6).map(FE::new).collect();
let hashed_leaves = complete_until_power_of_two(values);

let mut expected_leaves = (1..6).map(FE::new).collect::<Vec<FE>>();
expected_leaves.extend([FE::new(5); 3]);
Expand All @@ -115,8 +115,8 @@ mod tests {
#[test]
// expected |2|2|
fn complete_the_length_of_one_field_element_to_be_a_power_of_two() {
let mut values: Vec<FE> = vec![FE::new(2)];
let hashed_leaves = complete_until_power_of_two(&mut values);
let values: Vec<FE> = vec![FE::new(2)];
let hashed_leaves = complete_until_power_of_two(values);

let mut expected_leaves = vec![FE::new(2)];
expected_leaves.extend([FE::new(2)]);
Expand Down
Loading