X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning%2Fsrc%2Futil%2Fser.rs;h=4e69a37d20e9fcc5e0d093804136ef9f90be1747;hb=2eb7db9ace08b57bfedbdac2b26961897b032e0b;hp=7bc09e7f8da00c4bc62c5a9944a1f0f8f3cf2e0d;hpb=77bdc32bbdd3cc532a74018b9e55d535372c4ce9;p=rust-lightning diff --git a/lightning/src/util/ser.rs b/lightning/src/util/ser.rs index 7bc09e7f8..4e69a37d2 100644 --- a/lightning/src/util/ser.rs +++ b/lightning/src/util/ser.rs @@ -249,28 +249,31 @@ impl Readable for OptionDeserWrapper { } } -const MAX_ALLOC_SIZE: u64 = 64*1024; - +/// Wrapper to write each element of a Vec with no length prefix pub(crate) struct VecWriteWrapper<'a, T: Writeable>(pub &'a Vec); impl<'a, T: Writeable> Writeable for VecWriteWrapper<'a, T> { #[inline] fn write(&self, writer: &mut W) -> Result<(), ::std::io::Error> { - (self.0.len() as u64).write(writer)?; for ref v in self.0.iter() { v.write(writer)?; } Ok(()) } } + +/// Wrapper to read elements from a given stream until it reaches the end of the stream. pub(crate) struct VecReadWrapper(pub Vec); impl Readable for VecReadWrapper { #[inline] - fn read(reader: &mut R) -> Result { - let count: u64 = Readable::read(reader)?; - let mut values = Vec::with_capacity(cmp::min(count, MAX_ALLOC_SIZE / (core::mem::size_of::() as u64)) as usize); - for _ in 0..count { - match Readable::read(reader) { + fn read(mut reader: &mut R) -> Result { + let mut values = Vec::new(); + loop { + let mut track_read = ReadTrackingReader::new(&mut reader); + match Readable::read(&mut track_read) { Ok(v) => { values.push(v); }, + // If we failed to read any bytes at all, we reached the end of our TLV + // stream and have simply exhausted all entries. + Err(ref e) if e == &DecodeError::ShortRead && !track_read.have_read => break, Err(e) => return Err(e), } } @@ -695,6 +698,18 @@ impl Readable for PaymentSecret { } } +impl Writeable for Box { + fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> { + T::write(&**self, w) + } +} + +impl Readable for Box { + fn read(r: &mut R) -> Result { + Ok(Box::new(Readable::read(r)?)) + } +} + impl Writeable for Option { fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> { match *self { @@ -821,3 +836,19 @@ impl Writeable for (A, B) { self.1.write(w) } } + +impl Readable for (A, B, C) { + fn read(r: &mut R) -> Result { + let a: A = Readable::read(r)?; + let b: B = Readable::read(r)?; + let c: C = Readable::read(r)?; + Ok((a, b, c)) + } +} +impl Writeable for (A, B, C) { + fn write(&self, w: &mut W) -> Result<(), ::std::io::Error> { + self.0.write(w)?; + self.1.write(w)?; + self.2.write(w) + } +}