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.
This commit is contained in:
DanGould 2022-06-28 22:32:39 +08:00
parent b645b6b4b5
commit 9bf959180b
No known key found for this signature in database
GPG Key ID: B07290B28996AFE0
1 changed files with 9 additions and 5 deletions

View File

@ -11,9 +11,6 @@ use crate::prelude::*;
use secp256k1::ecdsa; use secp256k1::ecdsa;
use crate::VarInt; use crate::VarInt;
#[cfg(feature = "serde")]
use serde;
/// The Witness is the data used to unlock bitcoins since the [segwit upgrade](https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki) /// The Witness is the data used to unlock bitcoins since the [segwit upgrade](https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki)
/// ///
/// Can be logically seen as an array of byte-arrays `Vec<Vec<u8>>` and indeed you can convert from /// 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 {
where where
S: serde::Serializer, S: serde::Serializer,
{ {
let vec: Vec<_> = self.to_vec(); use serde::ser::SerializeSeq;
serde::Serialize::serialize(&vec, serializer)
let mut seq = serializer.serialize_seq(Some(self.witness_elements))?;
for elem in self.iter() {
seq.serialize_element(&elem)?;
}
seq.end()
} }
} }
#[cfg(feature = "serde")] #[cfg(feature = "serde")]