Move TransactionU16LenLimited to ser.rs
[rust-lightning] / lightning / src / util / ser.rs
index 707ca2b326d0d5720cae5abec48885e443b46a59..1570e5aeea44de753460b1bfcb8523c00b690dfc 100644 (file)
@@ -1349,6 +1349,45 @@ impl Readable for Duration {
        }
 }
 
+/// A wrapper for a `Transaction` which can only be constructed with [`TransactionU16LenLimited::new`]
+/// 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)]
+pub struct TransactionU16LenLimited(Transaction);
+
+impl TransactionU16LenLimited {
+       /// Constructs a new `TransactionU16LenLimited` from a `Transaction` only if it's consensus-
+       /// serialized length is <= u16::MAX.
+       pub fn new(transaction: Transaction) -> Result<Self, ()> {
+               if transaction.serialized_length() > (u16::MAX as usize) {
+                       Err(())
+               } else {
+                       Ok(Self(transaction))
+               }
+       }
+
+       /// Consumes this `TransactionU16LenLimited` and returns its contained `Transaction`.
+       pub fn into_transaction(self) -> Transaction {
+               self.0
+       }
+}
+
+impl Writeable for TransactionU16LenLimited {
+       fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
+               (self.0.serialized_length() as u16).write(w)?;
+               self.0.write(w)
+       }
+}
+
+impl Readable for TransactionU16LenLimited {
+       fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
+               let len = <u16 as Readable>::read(r)?;
+               let mut tx_reader = FixedLengthReader::new(r, len as u64);
+               Ok(Self(Readable::read(&mut tx_reader)?))
+       }
+}
+
 #[cfg(test)]
 mod tests {
        use core::convert::TryFrom;