Skip to content

Commit 6a3fb84

Browse files
evanlinjindanielabrozzoni
authored andcommitted
fix(chain): simplify Append::append impl for keychain::ChangeSet
We only need to loop though entries of `other`. The logic before was wasteful because we were also looping though all entries of `self` even if we do not need to modify the `self` entry.
1 parent 1d294b7 commit 6a3fb84

File tree

1 file changed

+17
-14
lines changed

1 file changed

+17
-14
lines changed

crates/chain/src/keychain/txout_index.rs

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -49,23 +49,26 @@ impl<K: Ord> Append for ChangeSet<K> {
4949
///
5050
/// For each `last_revealed` in the given [`ChangeSet`]:
5151
/// If the keychain already exists, increase the index when the other's index > self's index.
52-
fn append(&mut self, mut other: Self) {
53-
for (keychain, descriptor) in &mut self.keychains_added {
54-
if let Some(other_descriptor) = other.keychains_added.remove(keychain) {
55-
*descriptor = other_descriptor;
56-
}
57-
}
58-
59-
for (descriptor_id, index) in &mut self.last_revealed {
60-
if let Some(other_index) = other.last_revealed.remove(descriptor_id) {
61-
*index = other_index.max(*index);
62-
}
63-
}
64-
52+
fn append(&mut self, other: Self) {
6553
// We use `extend` instead of `BTreeMap::append` due to performance issues with `append`.
6654
// Refer to https://github.com/rust-lang/rust/issues/34666#issuecomment-675658420
6755
self.keychains_added.extend(other.keychains_added);
68-
self.last_revealed.extend(other.last_revealed);
56+
57+
// for `last_revealed`, entries of `other` will take precedence ONLY if it is greater than
58+
// what was originally in `self`.
59+
for (desc_id, index) in other.last_revealed {
60+
use crate::collections::btree_map::Entry;
61+
match self.last_revealed.entry(desc_id) {
62+
Entry::Vacant(entry) => {
63+
entry.insert(index);
64+
}
65+
Entry::Occupied(mut entry) => {
66+
if *entry.get() < index {
67+
entry.insert(index);
68+
}
69+
}
70+
}
71+
}
6972
}
7073

7174
/// Returns whether the changeset are empty.

0 commit comments

Comments
 (0)