X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning%2Fsrc%2Futil%2Fser.rs;h=9682c09d95c9aa4e096c6213513b980f9a5ed98b;hb=fb670c8faae8c1e990496b869e62dfbde10a64f8;hp=af4de88a1a7dda59145b1ea25fa7b7e434519f76;hpb=f97d5203227d9f0985c8cb3c7acc1f21971aaae7;p=rust-lightning diff --git a/lightning/src/util/ser.rs b/lightning/src/util/ser.rs index af4de88a..9682c09d 100644 --- a/lightning/src/util/ser.rs +++ b/lightning/src/util/ser.rs @@ -17,7 +17,7 @@ use crate::prelude::*; use crate::io::{self, Read, Seek, Write}; use crate::io_extras::{copy, sink}; use core::hash::Hash; -use crate::sync::Mutex; +use crate::sync::{Mutex, RwLock}; use core::cmp; use core::convert::TryFrom; use core::ops::Deref; @@ -199,8 +199,14 @@ pub trait Writeable { /// Writes `self` out to a `Vec`. fn encode(&self) -> Vec { - let mut msg = VecWriter(Vec::new()); + let len = self.serialized_length(); + let mut msg = VecWriter(Vec::with_capacity(len)); self.write(&mut msg).unwrap(); + // Note that objects with interior mutability may change size between when we called + // serialized_length and when we called write. That's okay, but shouldn't happen during + // testing as most of our tests are not threaded. + #[cfg(test)] + debug_assert_eq!(len, msg.0.len()); msg.0 } @@ -211,6 +217,7 @@ pub trait Writeable { 0u16.write(&mut msg).unwrap(); self.write(&mut msg).unwrap(); let len = msg.0.len(); + debug_assert_eq!(len - 2, self.serialized_length()); msg.0[..2].copy_from_slice(&(len as u16 - 2).to_be_bytes()); msg.0 } @@ -1195,6 +1202,18 @@ impl Writeable for Mutex { } } +impl Readable for RwLock { + fn read(r: &mut R) -> Result { + let t: T = Readable::read(r)?; + Ok(RwLock::new(t)) + } +} +impl Writeable for RwLock { + fn write(&self, w: &mut W) -> Result<(), io::Error> { + self.read().unwrap().write(w) + } +} + impl Readable for (A, B) { fn read(r: &mut R) -> Result { let a: A = Readable::read(r)?; @@ -1277,7 +1296,7 @@ impl Readable for String { /// This serialization is used by [`BOLT 7`] hostnames. /// /// [`BOLT 7`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct Hostname(String); impl Hostname { /// Returns the length of the hostname. @@ -1285,6 +1304,13 @@ impl Hostname { (&self.0).len() as u8 } } + +impl core::fmt::Display for Hostname { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "{}", self.0)?; + Ok(()) + } +} impl Deref for Hostname { type Target = String; @@ -1363,7 +1389,7 @@ impl Readable for Duration { /// if the `Transaction`'s consensus-serialized length is <= u16::MAX. /// /// Use [`TransactionU16LenLimited::into_transaction`] to convert into the contained `Transaction`. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct TransactionU16LenLimited(Transaction); impl TransactionU16LenLimited {