Skip to content

Commit b75a558

Browse files
committed
Convert Vec de/serialization impl to a macro and impl for tuples
...to make it easier to add new implementations and implement it for all tuples which implement `Readabe` + `Writeable`. Note that we don't want to just convert to a blanket implementation as we'd really like to keep our optimized `Vec<u8>` wrapper or we'll end up spinning way too much when writing vecs of bytes.
1 parent a03db3c commit b75a558

File tree

1 file changed

+31
-25
lines changed

1 file changed

+31
-25
lines changed

lightning/src/util/ser.rs

+31-25
Original file line numberDiff line numberDiff line change
@@ -662,6 +662,35 @@ where T: Readable + Eq + Hash
662662
}
663663

664664
// Vectors
665+
macro_rules! impl_for_vec {
666+
($ty: ty $(, $name: ident)*) => {
667+
impl<$($name : Writeable),*> Writeable for Vec<$ty> {
668+
#[inline]
669+
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
670+
(self.len() as u16).write(w)?;
671+
for elem in self.iter() {
672+
elem.write(w)?;
673+
}
674+
Ok(())
675+
}
676+
}
677+
678+
impl<$($name : Readable),*> Readable for Vec<$ty> {
679+
#[inline]
680+
fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
681+
let len: u16 = Readable::read(r)?;
682+
let mut ret = Vec::with_capacity(cmp::min(len as usize, MAX_BUF_SIZE / core::mem::size_of::<$ty>()));
683+
for _ in 0..len {
684+
if let Some(val) = MaybeReadable::read(r)? {
685+
ret.push(val);
686+
}
687+
}
688+
Ok(ret)
689+
}
690+
}
691+
}
692+
}
693+
665694
impl Writeable for Vec<u8> {
666695
#[inline]
667696
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
@@ -680,32 +709,9 @@ impl Readable for Vec<u8> {
680709
Ok(ret)
681710
}
682711
}
683-
impl Writeable for Vec<ecdsa::Signature> {
684-
#[inline]
685-
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
686-
(self.len() as u16).write(w)?;
687-
for e in self.iter() {
688-
e.write(w)?;
689-
}
690-
Ok(())
691-
}
692-
}
693712

694-
impl Readable for Vec<ecdsa::Signature> {
695-
#[inline]
696-
fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
697-
let len: u16 = Readable::read(r)?;
698-
let byte_size = (len as usize)
699-
.checked_mul(COMPACT_SIGNATURE_SIZE)
700-
.ok_or(DecodeError::BadLengthDescriptor)?;
701-
if byte_size > MAX_BUF_SIZE {
702-
return Err(DecodeError::BadLengthDescriptor);
703-
}
704-
let mut ret = Vec::with_capacity(len as usize);
705-
for _ in 0..len { ret.push(Readable::read(r)?); }
706-
Ok(ret)
707-
}
708-
}
713+
impl_for_vec!(ecdsa::Signature);
714+
impl_for_vec!((A, B), A, B);
709715

710716
impl Writeable for Script {
711717
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {

0 commit comments

Comments
 (0)