Skip to content

Commit 11115a5

Browse files
committed
Support Vec serialization that include element length prefix
We add new macro alternatives to impl_writeable_for_vec/impl_readable_for_vec that add a length prefix to each element in the `Vec`. This is intended to be used over the existing macros when attempting to serialize a `Vec` with elements of variable lengths.
1 parent cea39e7 commit 11115a5

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

lightning/src/util/ser.rs

+43
Original file line numberDiff line numberDiff line change
@@ -820,6 +820,49 @@ macro_rules! impl_for_vec {
820820
}
821821
}
822822

823+
// Alternatives to impl_writeable_for_vec/impl_readable_for_vec that add a length prefix to each
824+
// element in the Vec. Intended to be used when elements have variable lengths.
825+
macro_rules! impl_writeable_for_vec_with_element_length_prefix {
826+
($ty: ty $(, $name: ident)*) => {
827+
impl<$($name : Writeable),*> Writeable for Vec<$ty> {
828+
#[inline]
829+
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
830+
CollectionLength(self.len() as u64).write(w)?;
831+
for elem in self.iter() {
832+
CollectionLength(elem.serialized_length() as u64).write(w)?;
833+
elem.write(w)?;
834+
}
835+
Ok(())
836+
}
837+
}
838+
}
839+
}
840+
macro_rules! impl_readable_for_vec_with_element_length_prefix {
841+
($ty: ty $(, $name: ident)*) => {
842+
impl<$($name : Readable),*> Readable for Vec<$ty> {
843+
#[inline]
844+
fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
845+
let len: CollectionLength = Readable::read(r)?;
846+
let mut ret = Vec::with_capacity(cmp::min(len.0 as usize, MAX_BUF_SIZE / core::mem::size_of::<$ty>()));
847+
for _ in 0..len.0 {
848+
let elem_len: CollectionLength = Readable::read(r)?;
849+
let mut elem_reader = FixedLengthReader::new(r, elem_len.0);
850+
if let Some(val) = MaybeReadable::read(&mut elem_reader)? {
851+
ret.push(val);
852+
}
853+
}
854+
Ok(ret)
855+
}
856+
}
857+
}
858+
}
859+
macro_rules! impl_for_vec_with_element_length_prefix {
860+
($ty: ty $(, $name: ident)*) => {
861+
impl_writeable_for_vec_with_element_length_prefix!($ty $(, $name)*);
862+
impl_readable_for_vec_with_element_length_prefix!($ty $(, $name)*);
863+
}
864+
}
865+
823866
impl Writeable for Vec<u8> {
824867
#[inline]
825868
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {

0 commit comments

Comments
 (0)