primitives: avoid extra reallocation when decoding witness
What changed, and why it matters
This is a small performance optimization in how Bitcoin witness data is decoded. It changes when memory is reserved during decoding to avoid one extra memory reallocation for large witness elements. There is no security bug being fixed and no indication this change is security-relevant.
No security action required. Treat as a normal performance improvement.
Security signals we found
No strong security signals were identified.
Evidence from the diff
The patch moves a reserve_exact call from the end() method into the per-element decoding loop, triggering it only when the final element’s last chunk is being copied. This reduces allocations from three to two for single witness elements larger than ~128 bytes. It is purely an optimization of memory allocation behavior and does not alter parsing logic, bounds checking, or output semantics.
Changed components
primitives/src/witness.rsWitnessDecoderInspect captured patch +5 / −0
diff --git a/primitives/src/witness.rs b/primitives/src/witness.rs
index 07ce98ec..660ee908 100644
--- a/primitives/src/witness.rs
+++ b/primitives/src/witness.rs
@@ -395,6 +395,11 @@ impl encoding::Decoder for WitnessDecoder {
// Else we are reading the element's length.
if let Some(bytes_to_read) = self.element_bytes_remaining {
let can_copy = bytes.len().min(bytes_to_read);
+ // To avoid reallocating the index space in `end()` we reserve it here, the moment
+ // the final element's data is copied.
+ if can_copy == bytes_to_read && self.element_idx + 1 == witness_elements {
+ self.content.reserve_exact(can_copy + witness_elements * 4);
+ }
self.content.extend_from_slice(&bytes[..can_copy]);
*bytes = &bytes[can_copy..];
let remaining = bytes_to_read - can_copy;
Why this scored 20/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.