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);
513 let v_opt = V::read(r)?;
514 if let Some(v) = v_opt {
515 if ret.insert(k, v).is_some() {
516 return Err(DecodeError::InvalidValue);
525 impl<T> Writeable for HashSet<T>
526 where T: Writeable + Eq + Hash
529 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
530 (self.len() as u16).write(w)?;
531 for item in self.iter() {
538 impl<T> Readable for HashSet<T>
539 where T: Readable + Eq + Hash
542 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
543 let len: u16 = Readable::read(r)?;
544 let mut ret = HashSet::with_capacity(len as usize);
546 if !ret.insert(T::read(r)?) {
547 return Err(DecodeError::InvalidValue)
555 impl Writeable for Vec<u8> {
557 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
558 (self.len() as u16).write(w)?;
563 impl Readable for Vec<u8> {
565 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
566 let len: u16 = Readable::read(r)?;
567 let mut ret = Vec::with_capacity(len as usize);
568 ret.resize(len as usize, 0);
569 r.read_exact(&mut ret)?;
573 impl Writeable for Vec<Signature> {
575 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
576 (self.len() as u16).write(w)?;
577 for e in self.iter() {
584 impl Readable for Vec<Signature> {
586 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
587 let len: u16 = Readable::read(r)?;
588 let byte_size = (len as usize)
589 .checked_mul(COMPACT_SIGNATURE_SIZE)
590 .ok_or(DecodeError::BadLengthDescriptor)?;
591 if byte_size > MAX_BUF_SIZE {
592 return Err(DecodeError::BadLengthDescriptor);
594 let mut ret = Vec::with_capacity(len as usize);
595 for _ in 0..len { ret.push(Readable::read(r)?); }
600 impl Writeable for Script {
601 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
602 (self.len() as u16).write(w)?;
603 w.write_all(self.as_bytes())
607 impl Readable for Script {
608 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
609 let len = <u16 as Readable>::read(r)? as usize;
610 let mut buf = vec![0; len];
611 r.read_exact(&mut buf)?;
612 Ok(Script::from(buf))
616 impl Writeable for PublicKey {
617 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
618 self.serialize().write(w)
621 fn serialized_length(&self) -> usize {
626 impl Readable for PublicKey {
627 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
628 let buf: [u8; PUBLIC_KEY_SIZE] = Readable::read(r)?;
629 match PublicKey::from_slice(&buf) {
631 Err(_) => return Err(DecodeError::InvalidValue),
636 impl Writeable for SecretKey {
637 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
638 let mut ser = [0; SECRET_KEY_SIZE];
639 ser.copy_from_slice(&self[..]);
643 fn serialized_length(&self) -> usize {
648 impl Readable for SecretKey {
649 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
650 let buf: [u8; SECRET_KEY_SIZE] = Readable::read(r)?;
651 match SecretKey::from_slice(&buf) {
653 Err(_) => return Err(DecodeError::InvalidValue),
658 impl Writeable for Sha256dHash {
659 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
660 w.write_all(&self[..])
664 impl Readable for Sha256dHash {
665 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
666 use bitcoin::hashes::Hash;
668 let buf: [u8; 32] = Readable::read(r)?;
669 Ok(Sha256dHash::from_slice(&buf[..]).unwrap())
673 impl Writeable for Signature {
674 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
675 self.serialize_compact().write(w)
678 fn serialized_length(&self) -> usize {
679 COMPACT_SIGNATURE_SIZE
683 impl Readable for Signature {
684 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
685 let buf: [u8; COMPACT_SIGNATURE_SIZE] = Readable::read(r)?;
686 match Signature::from_compact(&buf) {
688 Err(_) => return Err(DecodeError::InvalidValue),
693 impl Writeable for PaymentPreimage {
694 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
699 impl Readable for PaymentPreimage {
700 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
701 let buf: [u8; 32] = Readable::read(r)?;
702 Ok(PaymentPreimage(buf))
706 impl Writeable for PaymentHash {
707 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
712 impl Readable for PaymentHash {
713 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
714 let buf: [u8; 32] = Readable::read(r)?;
719 impl Writeable for PaymentSecret {
720 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
725 impl Readable for PaymentSecret {
726 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
727 let buf: [u8; 32] = Readable::read(r)?;
728 Ok(PaymentSecret(buf))
732 impl<T: Writeable> Writeable for Box<T> {
733 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
738 impl<T: Readable> Readable for Box<T> {
739 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
740 Ok(Box::new(Readable::read(r)?))
744 impl<T: Writeable> Writeable for Option<T> {
745 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
747 None => 0u8.write(w)?,
749 BigSize(data.serialized_length() as u64 + 1).write(w)?;
757 impl<T: Readable> Readable for Option<T>
759 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
760 let len: BigSize = Readable::read(r)?;
764 let mut reader = FixedLengthReader::new(r, len - 1);
765 Ok(Some(Readable::read(&mut reader)?))
771 impl Writeable for Txid {
772 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
773 w.write_all(&self[..])
777 impl Readable for Txid {
778 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
779 use bitcoin::hashes::Hash;
781 let buf: [u8; 32] = Readable::read(r)?;
782 Ok(Txid::from_slice(&buf[..]).unwrap())
786 impl Writeable for BlockHash {
787 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
788 w.write_all(&self[..])
792 impl Readable for BlockHash {
793 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
794 use bitcoin::hashes::Hash;
796 let buf: [u8; 32] = Readable::read(r)?;
797 Ok(BlockHash::from_slice(&buf[..]).unwrap())
801 impl Writeable for OutPoint {
802 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
809 impl Readable for OutPoint {
810 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
811 let txid = Readable::read(r)?;
812 let vout = Readable::read(r)?;
820 macro_rules! impl_consensus_ser {
821 ($bitcoin_type: ty) => {
822 impl Writeable for $bitcoin_type {
823 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
824 match self.consensus_encode(WriterWriteAdaptor(writer)) {
831 impl Readable for $bitcoin_type {
832 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
833 match consensus::encode::Decodable::consensus_decode(r) {
835 Err(consensus::encode::Error::Io(ref e)) if e.kind() == io::ErrorKind::UnexpectedEof => Err(DecodeError::ShortRead),
836 Err(consensus::encode::Error::Io(e)) => Err(DecodeError::Io(e.kind())),
837 Err(_) => Err(DecodeError::InvalidValue),
843 impl_consensus_ser!(Transaction);
844 impl_consensus_ser!(TxOut);
846 impl<T: Readable> Readable for Mutex<T> {
847 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
848 let t: T = Readable::read(r)?;
852 impl<T: Writeable> Writeable for Mutex<T> {
853 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
854 self.lock().unwrap().write(w)
858 impl<A: Readable, B: Readable> Readable for (A, B) {
859 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
860 let a: A = Readable::read(r)?;
861 let b: B = Readable::read(r)?;
865 impl<A: Writeable, B: Writeable> Writeable for (A, B) {
866 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
872 impl<A: Readable, B: Readable, C: Readable> Readable for (A, B, C) {
873 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
874 let a: A = Readable::read(r)?;
875 let b: B = Readable::read(r)?;
876 let c: C = Readable::read(r)?;
880 impl<A: Writeable, B: Writeable, C: Writeable> Writeable for (A, B, C) {
881 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
888 impl Writeable for () {
889 fn write<W: Writer>(&self, _: &mut W) -> Result<(), io::Error> {
893 impl Readable for () {
894 fn read<R: Read>(_r: &mut R) -> Result<Self, DecodeError> {
899 impl Writeable for String {
901 fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
902 (self.len() as u16).write(w)?;
903 w.write_all(self.as_bytes())
906 impl Readable for String {
908 fn read<R: Read>(r: &mut R) -> Result<Self, DecodeError> {
909 let v: Vec<u8> = Readable::read(r)?;
910 let ret = String::from_utf8(v).map_err(|_| DecodeError::InvalidValue)?;