From ee9533a9057c0dc0cf78a37ecb767f6981e8f734 Mon Sep 17 00:00:00 2001 From: Matt Corallo Date: Sat, 15 Sep 2018 22:06:13 -0400 Subject: [PATCH] Split out Vec and Vec ser impls cause there's 2 Should resolve any performance issues with Vec serialization. --- src/util/ser.rs | 33 +++++++++++++++++++++++++-------- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/src/util/ser.rs b/src/util/ser.rs index 7f795fe46..6c4082090 100644 --- a/src/util/ser.rs +++ b/src/util/ser.rs @@ -2,7 +2,6 @@ use std::result::Result; use std::io::Read; use std::collections::HashMap; use std::hash::Hash; -use std::mem; use secp256k1::{Secp256k1, Signature}; use secp256k1::key::PublicKey; @@ -163,17 +162,34 @@ impl Readable for HashMap } // Vectors -impl> Writeable for Vec { +impl Writeable for Vec { + #[inline] + fn write(&self, w: &mut W) -> Result<(), DecodeError> { + (self.len() as u16).write(w)?; + Ok(w.write_all(&self)?) + } +} + +impl Readable for Vec { + #[inline] + fn read(r: &mut R) -> Result { + let len: u16 = Readable::read(r)?; + let mut ret = Vec::with_capacity(len as usize); + ret.resize(len as usize, 0); + r.read_exact(&mut ret)?; + Ok(ret) + } +} +impl Writeable for Vec { #[inline] fn write(&self, w: &mut W) -> Result<(), DecodeError> { let byte_size = (self.len() as usize) - .checked_mul(mem::size_of::()) + .checked_mul(33) .ok_or(DecodeError::BadLengthDescriptor)?; if byte_size > MAX_BUF_SIZE { return Err(DecodeError::BadLengthDescriptor); } (self.len() as u16).write(w)?; - // performance with Vec for e in self.iter() { e.write(w)?; } @@ -181,25 +197,26 @@ impl> Writeable for Vec { } } -impl> Readable for Vec { +impl Readable for Vec { #[inline] fn read(r: &mut R) -> Result { let len: u16 = Readable::read(r)?; let byte_size = (len as usize) - .checked_mul(mem::size_of::()) + .checked_mul(33) .ok_or(DecodeError::BadLengthDescriptor)?; if byte_size > MAX_BUF_SIZE { return Err(DecodeError::BadLengthDescriptor); } let mut ret = Vec::with_capacity(len as usize); - for _ in 0..len { ret.push(T::read(r)?); } + for _ in 0..len { ret.push(Signature::read(r)?); } Ok(ret) } } impl Writeable for Script { fn write(&self, w: &mut W) -> Result<(), DecodeError> { - self.to_bytes().to_vec().write(w) + (self.len() as u16).write(w)?; + Ok(w.write_all(self.as_bytes())?) } } -- 2.39.5