Skip to content

Commit ec5a4c8

Browse files
committed
Split out Vec<u8> and Vec<Signature> ser impls cause there's 2
Should resolve any performance issues with Vec<u8> serialization.
1 parent 114dee7 commit ec5a4c8

File tree

1 file changed

+25
-8
lines changed

1 file changed

+25
-8
lines changed

src/util/ser.rs

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ use std::result::Result;
22
use std::io::Read;
33
use std::collections::HashMap;
44
use std::hash::Hash;
5-
use std::mem;
65

76
use secp256k1::{Secp256k1, Signature};
87
use secp256k1::key::PublicKey;
@@ -163,43 +162,61 @@ impl<R, K, V> Readable<R> for HashMap<K, V>
163162
}
164163

165164
// Vectors
166-
impl<W: Writer, T: Writeable<W>> Writeable<W> for Vec<T> {
165+
impl<W: Writer> Writeable<W> for Vec<u8> {
166+
#[inline]
167+
fn write(&self, w: &mut W) -> Result<(), DecodeError> {
168+
(self.len() as u16).write(w)?;
169+
Ok(w.write_all(&self)?)
170+
}
171+
}
172+
173+
impl<R: Read> Readable<R> for Vec<u8> {
174+
#[inline]
175+
fn read(r: &mut R) -> Result<Self, DecodeError> {
176+
let len: u16 = Readable::read(r)?;
177+
let mut ret = Vec::with_capacity(len as usize);
178+
ret.resize(len as usize, 0);
179+
r.read_exact(&mut ret)?;
180+
Ok(ret)
181+
}
182+
}
183+
impl<W: Writer> Writeable<W> for Vec<Signature> {
167184
#[inline]
168185
fn write(&self, w: &mut W) -> Result<(), DecodeError> {
169186
let byte_size = (self.len() as usize)
170-
.checked_mul(mem::size_of::<T>())
187+
.checked_mul(33)
171188
.ok_or(DecodeError::BadLengthDescriptor)?;
172189
if byte_size > MAX_BUF_SIZE {
173190
return Err(DecodeError::BadLengthDescriptor);
174191
}
175192
(self.len() as u16).write(w)?;
176-
// performance with Vec<u8>
177193
for e in self.iter() {
178194
e.write(w)?;
179195
}
180196
Ok(())
181197
}
182198
}
183199

184-
impl<R: Read, T: Readable<R>> Readable<R> for Vec<T> {
200+
impl<R: Read> Readable<R> for Vec<Signature> {
185201
#[inline]
186202
fn read(r: &mut R) -> Result<Self, DecodeError> {
187203
let len: u16 = Readable::read(r)?;
188204
let byte_size = (len as usize)
189-
.checked_mul(mem::size_of::<T>())
205+
.checked_mul(33)
190206
.ok_or(DecodeError::BadLengthDescriptor)?;
191207
if byte_size > MAX_BUF_SIZE {
192208
return Err(DecodeError::BadLengthDescriptor);
193209
}
194210
let mut ret = Vec::with_capacity(len as usize);
195-
for _ in 0..len { ret.push(T::read(r)?); }
211+
for _ in 0..len { ret.push(Signature::read(r)?); }
196212
Ok(ret)
197213
}
198214
}
199215

200216
impl<W: Writer> Writeable<W> for Script {
201217
fn write(&self, w: &mut W) -> Result<(), DecodeError> {
202-
self.to_bytes().to_vec().write(w)
218+
(self.len() as u16).write(w)?;
219+
Ok(w.write_all(self.as_bytes())?)
203220
}
204221
}
205222

0 commit comments

Comments
 (0)