1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! A very simple serialization framework which is used to serialize/deserialize messages as well
11 //! as ChannelsManagers and ChannelMonitors.
14 use io::{self, Read, Write};
15 use io_extras::{copy, sink};
20 use bitcoin::secp256k1::Signature;
21 use bitcoin::secp256k1::key::{PublicKey, SecretKey};
22 use bitcoin::secp256k1::constants::{PUBLIC_KEY_SIZE, SECRET_KEY_SIZE, COMPACT_SIGNATURE_SIZE};
23 use bitcoin::blockdata::script::Script;
24 use bitcoin::blockdata::transaction::{OutPoint, Transaction, TxOut};
25 use bitcoin::consensus;
26 use bitcoin::consensus::Encodable;
27 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
28 use bitcoin::hash_types::{Txid, BlockHash};
29 use core::marker::Sized;
30 use ln::msgs::DecodeError;
31 use ln::{PaymentPreimage, PaymentHash, PaymentSecret};
33 use util::byte_utils::{be48_to_array, slice_to_be48};
35 /// serialization buffer size
36 pub const MAX_BUF_SIZE: usize = 64 * 1024;
38 /// A simplified version of std::io::Write that exists largely for backwards compatibility.
39 /// An impl is provided for any type that also impls std::io::Write.
41 /// (C-not exported) as we only export serialization to/from byte arrays instead
43 /// Writes the given buf out. See std::io::Write::write_all for more
44 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error>;
47 impl<W: Write> Writer for W {
49 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
50 <Self as io::Write>::write_all(self, buf)
54 pub(crate) struct WriterWriteAdaptor<'a, W: Writer + 'a>(pub &'a mut W);
55 impl<'a, W: Writer + 'a> Write for WriterWriteAdaptor<'a, W> {
57 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
61 fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
62 self.0.write_all(buf)?;
66 fn flush(&mut self) -> Result<(), io::Error> {
71 pub(crate) struct VecWriter(pub Vec<u8>);
72 impl Writer for VecWriter {
74 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
75 self.0.extend_from_slice(buf);
80 /// Writer that only tracks the amount of data written - useful if you need to calculate the length
81 /// of some data when serialized but don't yet need the full data.
82 pub(crate) struct LengthCalculatingWriter(pub usize);
83 impl Writer for LengthCalculatingWriter {
85 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
91 /// Essentially std::io::Take but a bit simpler and with a method to walk the underlying stream
92 /// forward to ensure we always consume exactly the fixed length specified.
93 pub(crate) struct FixedLengthReader<R: Read> {
98 impl<R: Read> FixedLengthReader<R> {
99 pub fn new(read: R, total_bytes: u64) -> Self {
100 Self { read, bytes_read: 0, total_bytes }
104 pub fn bytes_remain(&mut self) -> bool {
105 self.bytes_read != self.total_bytes
109 pub fn eat_remaining(&mut self) -> Result<(), DecodeError> {
110 copy(self, &mut sink()).unwrap();
111 if self.bytes_read != self.total_bytes {
112 Err(DecodeError::ShortRead)
118 impl<R: Read> Read for FixedLengthReader<R> {
120 fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
121 if self.total_bytes == self.bytes_read {
124 let read_len = cmp::min(dest.len() as u64, self.total_bytes - self.bytes_read);
125 match self.read.read(&mut dest[0..(read_len as usize)]) {
127 self.bytes_read += v as u64;
136 /// A Read which tracks whether any bytes have been read at all. This allows us to distinguish
137 /// between "EOF reached before we started" and "EOF reached mid-read".
138 pub(crate) struct ReadTrackingReader<R: Read> {
142 impl<R: Read> ReadTrackingReader<R> {
143 pub fn new(read: R) -> Self {
144 Self { read, have_read: false }
147 impl<R: Read> Read for ReadTrackingReader<R> {
149 fn read(&mut self, dest: &mut [u8]) -> Result<usize, io::Error> {
150 match self.read.read(dest) {
153 self.have_read = true;
161 /// A trait that various rust-lightning types implement allowing them to be written out to a Writer
163 /// (C-not exported) as we only export serialization to/from byte arrays instead
164 pub trait Writeable {
165 /// Writes self out to the given Writer
166 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error>;
168 /// Writes self out to a Vec<u8>
169 fn encode(&self) -> Vec<u8> {
170 let mut msg = VecWriter(Vec::new());
171 self.write(&mut msg).unwrap();
175 /// Writes self out to a Vec<u8>
176 fn encode_with_len(&self) -> Vec<u8> {
177 let mut msg = VecWriter(Vec::new());
178 0u16.write(&mut msg).unwrap();
179 self.write(&mut msg).unwrap();
180 let len = msg.0.len();
181 msg.0[..2].copy_from_slice(&(len as u16 - 2).to_be_bytes());
185 /// Gets the length of this object after it has been serialized. This can be overridden to
186 /// optimize cases where we prepend an object with its length.
187 // Note that LLVM optimizes this away in most cases! Check that it isn't before you override!
189 fn serialized_length(&self) -> usize {
190 let mut len_calc = LengthCalculatingWriter(0);
191 self.write(&mut len_calc).expect("No in-memory data may fail to serialize");
196 impl<'a, T: Writeable> Writeable for &'a T {
197 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { (*self).write(writer) }
200 /// A trait that various rust-lightning types implement allowing them to be read in from a Read
202 /// (C-not exported) as we only export serialization to/from byte arrays instead
206 /// Reads a Self in from the given Read
207 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError>;
210 /// A trait that various higher-level rust-lightning types implement allowing them to be read in
211 /// from a Read given some additional set of arguments which is required to deserialize.
213 /// (C-not exported) as we only export serialization to/from byte arrays instead
214 pub trait ReadableArgs<P>
217 /// Reads a Self in from the given Read
218 fn read<R: Read>(reader: &mut R, params: P) -> Result<Self, DecodeError>;
221 /// A trait that various rust-lightning types implement allowing them to (maybe) be read in from a Read
223 /// (C-not exported) as we only export serialization to/from byte arrays instead
224 pub trait MaybeReadable
227 /// Reads a Self in from the given Read
228 fn read<R: Read>(reader: &mut R) -> Result<Option<Self>, DecodeError>;
231 impl<T: Readable> MaybeReadable for T {
233 fn read<R: Read>(reader: &mut R) -> Result<Option<T>, DecodeError> {
234 Ok(Some(Readable::read(reader)?))
238 pub(crate) struct OptionDeserWrapper<T: Readable>(pub Option<T>);
239 impl<T: Readable> Readable for OptionDeserWrapper<T> {
241 fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
242 Ok(Self(Some(Readable::read(reader)?)))
246 /// Wrapper to write each element of a Vec with no length prefix
247 pub(crate) struct VecWriteWrapper<'a, T: Writeable>(pub &'a Vec<T>);
248 impl<'a, T: Writeable> Writeable for VecWriteWrapper<'a, T> {
250 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
251 for ref v in self.0.iter() {
258 /// Wrapper to read elements from a given stream until it reaches the end of the stream.
259 pub(crate) struct VecReadWrapper<T>(pub Vec<T>);
260 impl<T: MaybeReadable> Readable for VecReadWrapper<T> {
262 fn read<R: Read>(mut reader: &mut R) -> Result<Self, DecodeError> {
263 let mut values = Vec::new();
265 let mut track_read = ReadTrackingReader::new(&mut reader);
266 match MaybeReadable::read(&mut track_read) {
267 Ok(Some(v)) => { values.push(v); },
269 // If we failed to read any bytes at all, we reached the end of our TLV
270 // stream and have simply exhausted all entries.
271 Err(ref e) if e == &DecodeError::ShortRead && !track_read.have_read => break,
272 Err(e) => return Err(e),
279 pub(crate) struct U48(pub u64);
280 impl Writeable for U48 {
282 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
283 writer.write_all(&be48_to_array(self.0))
286 impl Readable for U48 {
288 fn read<R: Read>(reader: &mut R) -> Result<U48, DecodeError> {
289 let mut buf = [0; 6];
290 reader.read_exact(&mut buf)?;
291 Ok(U48(slice_to_be48(&buf)))
295 /// Lightning TLV uses a custom variable-length integer called BigSize. It is similar to Bitcoin's
296 /// variable-length integers except that it is serialized in big-endian instead of little-endian.
298 /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be
299 /// encoded in several different ways, which we must check for at deserialization-time. Thus, if
300 /// you're looking for an example of a variable-length integer to use for your own project, move
301 /// along, this is a rather poor design.
302 pub(crate) struct BigSize(pub u64);
303 impl Writeable for BigSize {
305 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
308 (self.0 as u8).write(writer)
311 0xFDu8.write(writer)?;
312 (self.0 as u16).write(writer)
314 0x10000...0xFFFFFFFF => {
315 0xFEu8.write(writer)?;
316 (self.0 as u32).write(writer)
319 0xFFu8.write(writer)?;
320 (self.0 as u64).write(writer)
325 impl Readable for BigSize {
327 fn read<R: Read>(reader: &mut R) -> Result<BigSize, DecodeError> {
328 let n: u8 = Readable::read(reader)?;
331 let x: u64 = Readable::read(reader)?;
333 Err(DecodeError::InvalidValue)
339 let x: u32 = Readable::read(reader)?;
341 Err(DecodeError::InvalidValue)
343 Ok(BigSize(x as u64))
347 let x: u16 = Readable::read(reader)?;
349 Err(DecodeError::InvalidValue)
351 Ok(BigSize(x as u64))
354 n => Ok(BigSize(n as u64))
359 /// In TLV we occasionally send fields which only consist of, or potentially end with, a
360 /// variable-length integer which is simply truncated by skipping high zero bytes. This type
361 /// encapsulates such integers implementing Readable/Writeable for them.
362 #[cfg_attr(test, derive(PartialEq, Debug))]
363 pub(crate) struct HighZeroBytesDroppedVarInt<T>(pub T);
365 macro_rules! impl_writeable_primitive {
366 ($val_type:ty, $len: expr) => {
367 impl Writeable for $val_type {
369 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
370 writer.write_all(&self.to_be_bytes())
373 impl Writeable for HighZeroBytesDroppedVarInt<$val_type> {
375 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
376 // Skip any full leading 0 bytes when writing (in BE):
377 writer.write_all(&self.0.to_be_bytes()[(self.0.leading_zeros()/8) as usize..$len])
380 impl Readable for $val_type {
382 fn read<R: Read>(reader: &mut R) -> Result<$val_type, DecodeError> {
383 let mut buf = [0; $len];
384 reader.read_exact(&mut buf)?;
385 Ok(<$val_type>::from_be_bytes(buf))
388 impl Readable for HighZeroBytesDroppedVarInt<$val_type> {
390 fn read<R: Read>(reader: &mut R) -> Result<HighZeroBytesDroppedVarInt<$val_type>, DecodeError> {
391 // We need to accept short reads (read_len == 0) as "EOF" and handle them as simply
392 // the high bytes being dropped. To do so, we start reading into the middle of buf
393 // and then convert the appropriate number of bytes with extra high bytes out of
395 let mut buf = [0; $len*2];
396 let mut read_len = reader.read(&mut buf[$len..])?;
397 let mut total_read_len = read_len;
398 while read_len != 0 && total_read_len != $len {
399 read_len = reader.read(&mut buf[($len + total_read_len)..])?;
400 total_read_len += read_len;
402 if total_read_len == 0 || buf[$len] != 0 {
403 let first_byte = $len - ($len - total_read_len);
404 let mut bytes = [0; $len];
405 bytes.copy_from_slice(&buf[first_byte..first_byte + $len]);
406 Ok(HighZeroBytesDroppedVarInt(<$val_type>::from_be_bytes(bytes)))
408 // If the encoding had extra zero bytes, return a failure even though we know
409 // what they meant (as the TLV test vectors require this)
410 Err(DecodeError::InvalidValue)
417 impl_writeable_primitive!(u64, 8);
418 impl_writeable_primitive!(u32, 4);
419 impl_writeable_primitive!(u16, 2);
421 impl Writeable for u8 {
423 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
424 writer.write_all(&[*self])
427 impl Readable for u8 {
429 fn read<R: Read>(reader: &mut R) -> Result<u8, DecodeError> {
430 let mut buf = [0; 1];
431 reader.read_exact(&mut buf)?;
436 impl Writeable for bool {
438 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
439 writer.write_all(&[if *self {1} else {0}])
442 impl Readable for bool {
444 fn read<R: Read>(reader: &mut R) -> Result<bool, DecodeError> {
445 let mut buf = [0; 1];
446 reader.read_exact(&mut buf)?;
447 if buf[0] != 0 && buf[0] != 1 {
448 return Err(DecodeError::InvalidValue);
455 macro_rules! impl_array {
457 impl Writeable for [u8; $size]
460 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
465 impl Readable for [u8; $size]
468 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
469 let mut buf = [0u8; $size];
470 r.read_exact(&mut buf)?;
477 //TODO: performance issue with [u8; size] with impl_array!()
478 impl_array!(3); // for rgb
479 impl_array!(4); // for IPv4
480 impl_array!(10); // for OnionV2
481 impl_array!(16); // for IPv6
482 impl_array!(32); // for channel id & hmac
483 impl_array!(PUBLIC_KEY_SIZE); // for PublicKey
484 impl_array!(COMPACT_SIGNATURE_SIZE); // for Signature
485 impl_array!(1300); // for OnionPacket.hop_data
488 impl<K, V> Writeable for HashMap<K, V>
489 where K: Writeable + Eq + Hash,
493 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
494 (self.len() as u16).write(w)?;
495 for (key, value) in self.iter() {
503 impl<K, V> Readable for HashMap<K, V>
504 where K: Readable + Eq + Hash,
508 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
509 let len: u16 = Readable::read(r)?;
510 let mut ret = HashMap::with_capacity(len as usize);
512 ret.insert(K::read(r)?, V::read(r)?);
519 impl<T> Writeable for HashSet<T>
520 where T: Writeable + Eq + Hash
523 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
524 (self.len() as u16).write(w)?;
525 for item in self.iter() {
532 impl<T> Readable for HashSet<T>
533 where T: Readable + Eq + Hash
536 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
537 let len: u16 = Readable::read(r)?;
538 let mut ret = HashSet::with_capacity(len as usize);
540 if !ret.insert(T::read(r)?) {
541 return Err(DecodeError::InvalidValue)
549 impl Writeable for Vec<u8> {
551 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
552 (self.len() as u16).write(w)?;
557 impl Readable for Vec<u8> {
559 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
560 let len: u16 = Readable::read(r)?;
561 let mut ret = Vec::with_capacity(len as usize);
562 ret.resize(len as usize, 0);
563 r.read_exact(&mut ret)?;
567 impl Writeable for Vec<Signature> {
569 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
570 (self.len() as u16).write(w)?;
571 for e in self.iter() {
578 impl Readable for Vec<Signature> {
580 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
581 let len: u16 = Readable::read(r)?;
582 let byte_size = (len as usize)
583 .checked_mul(COMPACT_SIGNATURE_SIZE)
584 .ok_or(DecodeError::BadLengthDescriptor)?;
585 if byte_size > MAX_BUF_SIZE {
586 return Err(DecodeError::BadLengthDescriptor);
588 let mut ret = Vec::with_capacity(len as usize);
589 for _ in 0..len { ret.push(Readable::read(r)?); }
594 impl Writeable for Script {
595 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
596 (self.len() as u16).write(w)?;
597 w.write_all(self.as_bytes())
601 impl Readable for Script {
602 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
603 let len = <u16 as Readable>::read(r)? as usize;
604 let mut buf = vec![0; len];
605 r.read_exact(&mut buf)?;
606 Ok(Script::from(buf))
610 impl Writeable for PublicKey {
611 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
612 self.serialize().write(w)
615 fn serialized_length(&self) -> usize {
620 impl Readable for PublicKey {
621 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
622 let buf: [u8; PUBLIC_KEY_SIZE] = Readable::read(r)?;
623 match PublicKey::from_slice(&buf) {
625 Err(_) => return Err(DecodeError::InvalidValue),
630 impl Writeable for SecretKey {
631 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
632 let mut ser = [0; SECRET_KEY_SIZE];
633 ser.copy_from_slice(&self[..]);
637 fn serialized_length(&self) -> usize {
642 impl Readable for SecretKey {
643 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
644 let buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
645 match SecretKey::from_slice(&buf) {
647 Err(_) => return Err(DecodeError::InvalidValue),
652 impl Writeable for Sha256dHash {
653 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
654 w.write_all(&self[..])
658 impl Readable for Sha256dHash {
659 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
660 use bitcoin::hashes::Hash;
662 let buf: [u8; 32] = Readable::read(r)?;
663 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
667 impl Writeable for Signature {
668 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
669 self.serialize_compact().write(w)
672 fn serialized_length(&self) -> usize {
673 COMPACT_SIGNATURE_SIZE
677 impl Readable for Signature {
678 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
679 let buf: [u8; COMPACT_SIGNATURE_SIZE] = Readable::read(r)?;
680 match Signature::from_compact(&buf) {
682 Err(_) => return Err(DecodeError::InvalidValue),
687 impl Writeable for PaymentPreimage {
688 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
693 impl Readable for PaymentPreimage {
694 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
695 let buf: [u8; 32] = Readable::read(r)?;
696 Ok(PaymentPreimage(buf))
700 impl Writeable for PaymentHash {
701 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
706 impl Readable for PaymentHash {
707 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
708 let buf: [u8; 32] = Readable::read(r)?;
713 impl Writeable for PaymentSecret {
714 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
719 impl Readable for PaymentSecret {
720 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
721 let buf: [u8; 32] = Readable::read(r)?;
722 Ok(PaymentSecret(buf))
726 impl<T: Writeable> Writeable for Box<T> {
727 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
732 impl<T: Readable> Readable for Box<T> {
733 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
734 Ok(Box::new(Readable::read(r)?))
738 impl<T: Writeable> Writeable for Option<T> {
739 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
741 None => 0u8.write(w)?,
743 BigSize(data.serialized_length() as u64 + 1).write(w)?;
751 impl<T: Readable> Readable for Option<T>
753 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
754 let len: BigSize = Readable::read(r)?;
758 let mut reader = FixedLengthReader::new(r, len - 1);
759 Ok(Some(Readable::read(&mut reader)?))
765 impl Writeable for Txid {
766 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
767 w.write_all(&self[..])
771 impl Readable for Txid {
772 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
773 use bitcoin::hashes::Hash;
775 let buf: [u8; 32] = Readable::read(r)?;
776 Ok(Txid::from_slice(&buf[..]).unwrap())
780 impl Writeable for BlockHash {
781 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
782 w.write_all(&self[..])
786 impl Readable for BlockHash {
787 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
788 use bitcoin::hashes::Hash;
790 let buf: [u8; 32] = Readable::read(r)?;
791 Ok(BlockHash::from_slice(&buf[..]).unwrap())
795 impl Writeable for OutPoint {
796 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
803 impl Readable for OutPoint {
804 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
805 let txid = Readable::read(r)?;
806 let vout = Readable::read(r)?;
814 macro_rules! impl_consensus_ser {
815 ($bitcoin_type: ty) => {
816 impl Writeable for $bitcoin_type {
817 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
818 match self.consensus_encode(WriterWriteAdaptor(writer)) {
825 impl Readable for $bitcoin_type {
826 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
827 match consensus::encode::Decodable::consensus_decode(r) {
829 Err(consensus::encode::Error::Io(ref e)) if e.kind() == io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
830 Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e.kind())),
831 Err(_) => Err(DecodeError::InvalidValue),
837 impl_consensus_ser!(Transaction);
838 impl_consensus_ser!(TxOut);
840 impl<T: Readable> Readable for Mutex<T> {
841 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
842 let t: T = Readable::read(r)?;
846 impl<T: Writeable> Writeable for Mutex<T> {
847 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
848 self.lock().unwrap().write(w)
852 impl<A: Readable, B: Readable> Readable for (A, B) {
853 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
854 let a: A = Readable::read(r)?;
855 let b: B = Readable::read(r)?;
859 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
860 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
866 impl<A: Readable, B: Readable, C: Readable> Readable for (A, B, C) {
867 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
868 let a: A = Readable::read(r)?;
869 let b: B = Readable::read(r)?;
870 let c: C = Readable::read(r)?;
874 impl<A: Writeable, B: Writeable, C: Writeable> Writeable for (A, B, C) {
875 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
882 impl Readable for () {
883 fn read<R: Read>(_r: &mut R) -> Result<Self, DecodeError> {