Skip to content

Commit 6154496

Browse files
committed
Optimize Witness Serialization
We allocated a new vector when serializing a `Witness`. That was inefficient and unnecessary. Use `serialize_seq` to feed the witness elements directly into the serializer. Optimize `Witness` serialization by removing the allocation.
1 parent 48cc8c1 commit 6154496

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

src/blockdata/witness.rs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,6 @@ use crate::prelude::*;
1111
use secp256k1::ecdsa;
1212
use crate::VarInt;
1313

14-
#[cfg(feature = "serde")]
15-
use serde;
16-
1714
/// The Witness is the data used to unlock bitcoins since the [segwit upgrade](https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki)
1815
///
1916
/// Can be logically seen as an array of byte-arrays `Vec<Vec<u8>>` and indeed you can convert from
@@ -282,8 +279,15 @@ impl serde::Serialize for Witness {
282279
where
283280
S: serde::Serializer,
284281
{
285-
let vec: Vec<_> = self.to_vec();
286-
serde::Serialize::serialize(&vec, serializer)
282+
use serde::ser::SerializeSeq;
283+
284+
let mut seq = serializer.serialize_seq(Some(self.witness_elements))?;
285+
286+
for elem in self.iter() {
287+
seq.serialize_element(&elem)?;
288+
}
289+
290+
seq.end()
287291
}
288292
}
289293
#[cfg(feature = "serde")]

0 commit comments

Comments
 (0)