impl Encodable for Annex to avoid allocation

This commit is contained in:
Riccardo Casatta 2021-07-16 15:05:15 +02:00
parent 1a7afed068
commit 2b3b22f559
No known key found for this signature in database
GPG Key ID: FD986A969E450397
2 changed files with 9 additions and 3 deletions

View File

@ -600,7 +600,7 @@ impl_vec!(u64);
#[cfg(feature = "std")] impl_vec!((u32, Address)); #[cfg(feature = "std")] impl_vec!((u32, Address));
#[cfg(feature = "std")] impl_vec!(AddrV2Message); #[cfg(feature = "std")] impl_vec!(AddrV2Message);
fn consensus_encode_with_size<S: io::Write>(data: &[u8], mut s: S) -> Result<usize, io::Error> { pub(crate) fn consensus_encode_with_size<S: io::Write>(data: &[u8], mut s: S) -> Result<usize, io::Error> {
let vi_len = VarInt(data.len() as u64).consensus_encode(&mut s)?; let vi_len = VarInt(data.len() as u64).consensus_encode(&mut s)?;
s.emit_slice(&data)?; s.emit_slice(&data)?;
Ok(vi_len + data.len()) Ok(vi_len + data.len())

View File

@ -20,7 +20,7 @@
//! //!
pub use blockdata::transaction::SigHashType as LegacySigHashType; pub use blockdata::transaction::SigHashType as LegacySigHashType;
use consensus::Encodable; use consensus::{encode, Encodable};
use core::fmt; use core::fmt;
use core::ops::{Deref, DerefMut}; use core::ops::{Deref, DerefMut};
use hashes::{sha256, sha256d, Hash}; use hashes::{sha256, sha256d, Hash};
@ -344,7 +344,7 @@ impl<R: Deref<Target = Transaction>> SigHashCache<R> {
// includes the mandatory 0x50 prefix. // includes the mandatory 0x50 prefix.
if let Some(annex) = annex { if let Some(annex) = annex {
let mut enc = sha256::Hash::engine(); let mut enc = sha256::Hash::engine();
annex.as_bytes().to_vec().consensus_encode(&mut enc)?; annex.consensus_encode(&mut enc)?;
let hash = sha256::Hash::from_engine(enc); let hash = sha256::Hash::from_engine(enc);
hash.consensus_encode(&mut writer)?; hash.consensus_encode(&mut writer)?;
} }
@ -626,6 +626,12 @@ impl<'a> Annex<'a> {
} }
} }
impl<'a> Encodable for Annex<'a> {
fn consensus_encode<W: io::Write>(&self, writer: W) -> Result<usize, io::Error> {
encode::consensus_encode_with_size(&self.0, writer)
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use consensus::deserialize; use consensus::deserialize;