]> git.bitcoin.ninja Git - rust-lightning/commitdiff
Simplify serialization a bit by removing the useless newtypes
authorMatt Corallo <git@bluematt.me>
Fri, 14 Sep 2018 21:50:48 +0000 (17:50 -0400)
committerMatt Corallo <git@bluematt.me>
Sun, 16 Sep 2018 18:33:50 +0000 (14:33 -0400)
fuzz/fuzz_targets/channel_target.rs
fuzz/fuzz_targets/msg_targets/utils.rs
fuzz/fuzz_targets/router_target.rs
src/ln/msgs.rs
src/ln/peer_handler.rs
src/util/ser.rs
src/util/ser_macros.rs

index 5cf0783c58bc7201155ac8234e0dd51b4f43a14e..e7cc6f76c999e42d6bdfc861a6a0244f500b1885 100644 (file)
@@ -15,7 +15,7 @@ use lightning::chain::chaininterface::{FeeEstimator, ConfirmationTarget};
 use lightning::chain::transaction::OutPoint;
 use lightning::util::reset_rng_state;
 use lightning::util::logger::Logger;
-use lightning::util::ser::{Readable, Reader};
+use lightning::util::ser::Readable;
 
 mod utils;
 
@@ -121,7 +121,7 @@ pub fn do_test(data: &[u8]) {
 
        macro_rules! decode_msg {
                ($MsgType: path, $len: expr) => {{
-                       let mut reader = Reader::new(::std::io::Cursor::new(get_slice!($len)));
+                       let mut reader = ::std::io::Cursor::new(get_slice!($len));
                        match <($MsgType)>::read(&mut reader) {
                                Ok(msg) => msg,
                                Err(e) => match e {
index c1bcd8f361887003d4e2823d2e5445fc4ce16496..52ea530cf9fed976438e30f5ad1beff30ac94af7 100644 (file)
@@ -4,16 +4,16 @@
 macro_rules! test_msg {
        ($MsgType: path, $data: ident) => {
                {
-                       use lightning::util::ser::{Writer, Reader, Writeable, Readable};
-                       let mut r = Reader::new(::std::io::Cursor::new($data));
+                       use lightning::util::ser::{Writeable, Readable};
+                       let mut r = ::std::io::Cursor::new($data);
                        if let Ok(msg) = <$MsgType as Readable<::std::io::Cursor<&[u8]>>>::read(&mut r) {
-                               let p = r.get_ref().position() as usize;
-                               let mut w = Writer::new(::std::io::Cursor::new(vec![]));
+                               let p = r.position() as usize;
+                               let mut w = ::std::io::Cursor::new(vec![]);
                                msg.write(&mut w).unwrap();
 
-                               let buf = w.into_inner().into_inner();
+                               let buf = w.into_inner();
                                assert_eq!(buf.len(), p);
-                               assert_eq!(&r.into_inner().into_inner()[..p], &buf[..p]);
+                               assert_eq!(&r.into_inner()[..p], &buf[..p]);
                        }
                }
        }
@@ -23,10 +23,10 @@ macro_rules! test_msg {
 macro_rules! test_msg_simple {
        ($MsgType: path, $data: ident) => {
                {
-                       use lightning::util::ser::{Writer, Reader, Writeable, Readable};
-                       let mut r = Reader::new(::std::io::Cursor::new($data));
+                       use lightning::util::ser::{Writeable, Readable};
+                       let mut r = ::std::io::Cursor::new($data);
                        if let Ok(msg) = <$MsgType as Readable<::std::io::Cursor<&[u8]>>>::read(&mut r) {
-                               msg.write(&mut Writer::new(::std::io::Cursor::new(vec![]))).unwrap();
+                               msg.write(&mut ::std::io::Cursor::new(vec![])).unwrap();
                        }
                }
        }
@@ -36,14 +36,14 @@ macro_rules! test_msg_simple {
 macro_rules! test_msg_exact {
        ($MsgType: path, $data: ident) => {
                {
-                       use lightning::util::ser::{Writer, Reader, Writeable, Readable};
-                       let mut r = Reader::new(::std::io::Cursor::new($data));
+                       use lightning::util::ser::{Writeable, Readable};
+                       let mut r = ::std::io::Cursor::new($data);
                        if let Ok(msg) = <$MsgType as Readable<::std::io::Cursor<&[u8]>>>::read(&mut r) {
-                               let mut w = Writer::new(::std::io::Cursor::new(vec![]));
+                               let mut w = ::std::io::Cursor::new(vec![]);
                                msg.write(&mut w).unwrap();
 
-                               let buf = w.into_inner().into_inner();
-                               assert_eq!(&r.into_inner().into_inner()[..], &buf[..]);
+                               let buf = w.into_inner();
+                               assert_eq!(&r.into_inner()[..], &buf[..]);
                        }
                }
        }
@@ -53,17 +53,17 @@ macro_rules! test_msg_exact {
 macro_rules! test_msg_hole {
        ($MsgType: path, $data: ident, $hole: expr, $hole_len: expr) => {
                {
-                       use lightning::util::ser::{Writer, Reader, Writeable, Readable};
-                       let mut r = Reader::new(::std::io::Cursor::new($data));
+                       use lightning::util::ser::{Writeable, Readable};
+                       let mut r = ::std::io::Cursor::new($data);
                        if let Ok(msg) = <$MsgType as Readable<::std::io::Cursor<&[u8]>>>::read(&mut r) {
-                               let mut w = Writer::new(::std::io::Cursor::new(vec![]));
+                               let mut w = ::std::io::Cursor::new(vec![]);
                                msg.write(&mut w).unwrap();
-                               let p = w.get_ref().position() as usize;
+                               let p = w.position() as usize;
 
-                               let buf = w.into_inner().into_inner();
+                               let buf = w.into_inner();
                                assert_eq!(buf.len(),p);
-                               assert_eq!(&r.get_ref().get_ref()[..$hole], &buf[..$hole]);
-                               assert_eq!(&r.get_ref().get_ref()[$hole+$hole_len..p], &buf[$hole+$hole_len..]);
+                               assert_eq!(&r.get_ref()[..$hole], &buf[..$hole]);
+                               assert_eq!(&r.get_ref()[$hole+$hole_len..p], &buf[$hole+$hole_len..]);
                        }
                }
        }
index fc3e9e9ba9ace20c1de0db547b14fb88360e369b..4ccd32746e39a2b87a247a9581808ade4eb74459 100644 (file)
@@ -12,7 +12,7 @@ use lightning::ln::msgs::{RoutingMessageHandler};
 use lightning::ln::router::{Router, RouteHint};
 use lightning::util::reset_rng_state;
 use lightning::util::logger::Logger;
-use lightning::util::ser::{Reader, Readable};
+use lightning::util::ser::Readable;
 
 use secp256k1::key::PublicKey;
 use secp256k1::Secp256k1;
@@ -121,7 +121,7 @@ pub fn do_test(data: &[u8]) {
 
        macro_rules! decode_msg {
                ($MsgType: path, $len: expr) => {{
-                       let mut reader = Reader::new(::std::io::Cursor::new(get_slice!($len)));
+                       let mut reader = ::std::io::Cursor::new(get_slice!($len));
                        match <($MsgType)>::read(&mut reader) {
                                Ok(msg) => msg,
                                Err(e) => match e {
index b4432c7084d9ebf8340b547ec2ca515700650ca0..a96f34f51a2c489c6c3d8cad094d7544494394d8 100644 (file)
@@ -7,10 +7,11 @@ use bitcoin::blockdata::script::Script;
 
 use std::error::Error;
 use std::{cmp, fmt};
+use std::io::Read;
 use std::result::Result;
 
 use util::{byte_utils, internal_traits, events};
-use util::ser::{Readable, Reader, Writeable, Writer};
+use util::ser::{Readable, Writeable, Writer};
 
 pub trait MsgEncodable {
        fn encode(&self) -> Vec<u8>;
@@ -1728,8 +1729,8 @@ impl_writeable!(AnnouncementSignatures, {
        bitcoin_signature
 });
 
-impl<W: ::std::io::Write> Writeable<W> for ChannelReestablish {
-       fn write(&self, w: &mut Writer<W>) -> Result<(), DecodeError> {
+impl<W: Writer> Writeable<W> for ChannelReestablish {
+       fn write(&self, w: &mut W) -> Result<(), DecodeError> {
                self.channel_id.write(w)?;
                self.next_local_commitment_number.write(w)?;
                self.next_remote_commitment_number.write(w)?;
@@ -1741,8 +1742,8 @@ impl<W: ::std::io::Write> Writeable<W> for ChannelReestablish {
        }
 }
 
-impl<R: ::std::io::Read> Readable<R> for ChannelReestablish{
-       fn read(r: &mut Reader<R>) -> Result<Self, DecodeError> {
+impl<R: Read> Readable<R> for ChannelReestablish{
+       fn read(r: &mut R) -> Result<Self, DecodeError> {
                Ok(Self {
                        channel_id: Readable::read(r)?,
                        next_local_commitment_number: Readable::read(r)?,
@@ -1871,8 +1872,8 @@ impl_writeable!(OnionErrorPacket, {
        data
 });
 
-impl<W: ::std::io::Write> Writeable<W> for OnionPacket {
-       fn write(&self, w: &mut Writer<W>) -> Result<(), DecodeError> {
+impl<W: Writer> Writeable<W> for OnionPacket {
+       fn write(&self, w: &mut W) -> Result<(), DecodeError> {
                self.version.write(w)?;
                match self.public_key {
                        Ok(pubkey) => pubkey.write(w)?,
@@ -1884,8 +1885,8 @@ impl<W: ::std::io::Write> Writeable<W> for OnionPacket {
        }
 }
 
-impl<R: ::std::io::Read> Readable<R> for OnionPacket {
-       fn read(r: &mut Reader<R>) -> Result<Self, DecodeError> {
+impl<R: Read> Readable<R> for OnionPacket {
+       fn read(r: &mut R) -> Result<Self, DecodeError> {
                Ok(OnionPacket {
                        version: Readable::read(r)?,
                        public_key: {
@@ -1908,8 +1909,8 @@ impl_writeable!(UpdateAddHTLC, {
        onion_routing_packet
 });
 
-impl<W: ::std::io::Write> Writeable<W> for OnionRealm0HopData {
-       fn write(&self, w: &mut Writer<W>) -> Result<(), DecodeError> {
+impl<W: Writer> Writeable<W> for OnionRealm0HopData {
+       fn write(&self, w: &mut W) -> Result<(), DecodeError> {
                self.short_channel_id.write(w)?;
                self.amt_to_forward.write(w)?;
                self.outgoing_cltv_value.write(w)?;
@@ -1918,8 +1919,8 @@ impl<W: ::std::io::Write> Writeable<W> for OnionRealm0HopData {
        }
 }
 
-impl<R: ::std::io::Read> Readable<R> for OnionRealm0HopData {
-       fn read(r: &mut Reader<R>) -> Result<Self, DecodeError> {
+impl<R: Read> Readable<R> for OnionRealm0HopData {
+       fn read(r: &mut R) -> Result<Self, DecodeError> {
                Ok(OnionRealm0HopData {
                        short_channel_id: Readable::read(r)?,
                        amt_to_forward: Readable::read(r)?,
@@ -1932,8 +1933,8 @@ impl<R: ::std::io::Read> Readable<R> for OnionRealm0HopData {
        }
 }
 
-impl<W: ::std::io::Write> Writeable<W> for OnionHopData {
-       fn write(&self, w: &mut Writer<W>) -> Result<(), DecodeError> {
+impl<W: Writer> Writeable<W> for OnionHopData {
+       fn write(&self, w: &mut W) -> Result<(), DecodeError> {
                self.realm.write(w)?;
                self.data.write(w)?;
                self.hmac.write(w)?;
@@ -1941,8 +1942,8 @@ impl<W: ::std::io::Write> Writeable<W> for OnionHopData {
        }
 }
 
-impl<R: ::std::io::Read> Readable<R> for OnionHopData {
-       fn read(r: &mut Reader<R>) -> Result<Self, DecodeError> {
+impl<R: Read> Readable<R> for OnionHopData {
+       fn read(r: &mut R) -> Result<Self, DecodeError> {
                Ok(OnionHopData {
                        realm: {
                                let r: u8 = Readable::read(r)?;
@@ -1957,16 +1958,16 @@ impl<R: ::std::io::Read> Readable<R> for OnionHopData {
        }
 }
 
-impl<W: ::std::io::Write> Writeable<W> for Ping {
-       fn write(&self, w: &mut Writer<W>) -> Result<(), DecodeError> {
+impl<W: Writer> Writeable<W> for Ping {
+       fn write(&self, w: &mut W) -> Result<(), DecodeError> {
                self.ponglen.write(w)?;
                vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
                Ok(())
        }
 }
 
-impl<R: ::std::io::Read> Readable<R> for Ping {
-       fn read(r: &mut Reader<R>) -> Result<Self, DecodeError> {
+impl<R: Read> Readable<R> for Ping {
+       fn read(r: &mut R) -> Result<Self, DecodeError> {
                Ok(Ping {
                        ponglen: Readable::read(r)?,
                        byteslen: {
@@ -1978,15 +1979,15 @@ impl<R: ::std::io::Read> Readable<R> for Ping {
        }
 }
 
-impl<W: ::std::io::Write> Writeable<W> for Pong {
-       fn write(&self, w: &mut Writer<W>) -> Result<(), DecodeError> {
+impl<W: Writer> Writeable<W> for Pong {
+       fn write(&self, w: &mut W) -> Result<(), DecodeError> {
                vec![0u8; self.byteslen as usize].write(w)?; // size-unchecked write
                Ok(())
        }
 }
 
-impl<R: ::std::io::Read> Readable<R> for Pong {
-       fn read(r: &mut Reader<R>) -> Result<Self, DecodeError> {
+impl<R: Read> Readable<R> for Pong {
+       fn read(r: &mut R) -> Result<Self, DecodeError> {
                Ok(Pong {
                        byteslen: {
                                let byteslen = Readable::read(r)?;
@@ -1997,8 +1998,8 @@ impl<R: ::std::io::Read> Readable<R> for Pong {
        }
 }
 
-impl<W: ::std::io::Write> Writeable<W> for UnsignedChannelAnnouncement {
-       fn write(&self, w: &mut Writer<W>) -> Result<(), DecodeError> {
+impl<W: Writer> Writeable<W> for UnsignedChannelAnnouncement {
+       fn write(&self, w: &mut W) -> Result<(), DecodeError> {
                self.features.write(w)?;
                self.chain_hash.write(w)?;
                self.short_channel_id.write(w)?;
@@ -2011,8 +2012,8 @@ impl<W: ::std::io::Write> Writeable<W> for UnsignedChannelAnnouncement {
        }
 }
 
-impl<R: ::std::io::Read> Readable<R> for UnsignedChannelAnnouncement {
-       fn read(r: &mut Reader<R>) -> Result<Self, DecodeError> {
+impl<R: Read> Readable<R> for UnsignedChannelAnnouncement {
+       fn read(r: &mut R) -> Result<Self, DecodeError> {
                Ok(Self {
                        features: {
                                let f: GlobalFeatures = Readable::read(r)?;
@@ -2044,8 +2045,8 @@ impl_writeable!(ChannelAnnouncement,{
        contents
 });
 
-impl<W: ::std::io::Write> Writeable<W> for UnsignedChannelUpdate {
-       fn write(&self, w: &mut Writer<W>) -> Result<(), DecodeError> {
+impl<W: Writer> Writeable<W> for UnsignedChannelUpdate {
+       fn write(&self, w: &mut W) -> Result<(), DecodeError> {
                self.chain_hash.write(w)?;
                self.short_channel_id.write(w)?;
                self.timestamp.write(w)?;
@@ -2059,8 +2060,8 @@ impl<W: ::std::io::Write> Writeable<W> for UnsignedChannelUpdate {
        }
 }
 
-impl<R: ::std::io::Read> Readable<R> for UnsignedChannelUpdate {
-       fn read(r: &mut Reader<R>) -> Result<Self, DecodeError> {
+impl<R: Read> Readable<R> for UnsignedChannelUpdate {
+       fn read(r: &mut R) -> Result<Self, DecodeError> {
                Ok(Self {
                        chain_hash: Readable::read(r)?,
                        short_channel_id: Readable::read(r)?,
@@ -2084,16 +2085,16 @@ impl_writeable!(ChannelUpdate, {
        contents
 });
 
-impl<W: ::std::io::Write> Writeable<W> for ErrorMessage {
-       fn write(&self, w: &mut Writer<W>) -> Result<(), DecodeError> {
+impl<W: Writer> Writeable<W> for ErrorMessage {
+       fn write(&self, w: &mut W) -> Result<(), DecodeError> {
                self.channel_id.write(w)?;
                self.data.as_bytes().to_vec().write(w)?; // write with size prefix
                Ok(())
        }
 }
 
-impl<R: ::std::io::Read> Readable<R> for ErrorMessage {
-       fn read(r: &mut Reader<R>) -> Result<Self, DecodeError> {
+impl<R: Read> Readable<R> for ErrorMessage {
+       fn read(r: &mut R) -> Result<Self, DecodeError> {
                Ok(Self {
                        channel_id: Readable::read(r)?,
                        data: {
@@ -2110,8 +2111,8 @@ impl<R: ::std::io::Read> Readable<R> for ErrorMessage {
        }
 }
 
-impl<W: ::std::io::Write> Writeable<W> for UnsignedNodeAnnouncement {
-       fn write(&self, w: &mut Writer<W>) -> Result<(), DecodeError> {
+impl<W: Writer> Writeable<W> for UnsignedNodeAnnouncement {
+       fn write(&self, w: &mut W) -> Result<(), DecodeError> {
                self.features.write(w)?;
                self.timestamp.write(w)?;
                self.node_id.write(w)?;
@@ -2156,8 +2157,8 @@ impl<W: ::std::io::Write> Writeable<W> for UnsignedNodeAnnouncement {
        }
 }
 
-impl<R: ::std::io::Read> Readable<R> for UnsignedNodeAnnouncement {
-       fn read(r: &mut Reader<R>) -> Result<Self, DecodeError> {
+impl<R: Read> Readable<R> for UnsignedNodeAnnouncement {
+       fn read(r: &mut R) -> Result<Self, DecodeError> {
                let features: GlobalFeatures = Readable::read(r)?;
                if features.requires_unknown_bits() {
                        return Err(DecodeError::UnknownRequiredFeature);
index 81ae8ca3863363e17aeca9ac6fb3bfc61a78bb04..52abecb4bc5f3128827e8cc3a259898c675be56e 100644 (file)
@@ -1,7 +1,7 @@
 use secp256k1::key::{SecretKey,PublicKey};
 
 use ln::msgs;
-use util::ser::{Writer, Reader, Writeable, Readable};
+use util::ser::{Writeable, Readable};
 use ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
 use util::byte_utils;
 use util::events::{EventsProvider,Event};
@@ -114,10 +114,10 @@ pub struct PeerManager<Descriptor: SocketDescriptor> {
 
 macro_rules! encode_msg {
        ($msg: expr, $msg_code: expr) => {{
-               let mut w = Writer::new(::std::io::Cursor::new(vec![]));
+               let mut w = ::std::io::Cursor::new(vec![]);
                0u16.write(&mut w).unwrap();
                $msg.write(&mut w).unwrap();
-               let mut msg = w.into_inner().into_inner();
+               let mut msg = w.into_inner();
                let len = msg.len();
                msg[..2].copy_from_slice(&byte_utils::be16_to_array(len as u16 - 2));
                msg
@@ -437,7 +437,7 @@ impl<Descriptor: SocketDescriptor> PeerManager<Descriptor> {
                                                                                        // Need an init message as first message
                                                                                        return Err(PeerHandleError{ no_connection_possible: false });
                                                                                }
-                                                                               let mut reader = Reader::new(::std::io::Cursor::new(&msg_data[2..]));
+                                                                               let mut reader = ::std::io::Cursor::new(&msg_data[2..]);
                                                                                match msg_type {
                                                                                        // Connection control:
                                                                                        16 => {
index cd5e6a0db2cdb1959e9fcd9b69b930c3b30f9edd..7f795fe46a23defb08494c03f1eef71396bfd670 100644 (file)
@@ -1,5 +1,5 @@
 use std::result::Result;
-use std::io::{Read, Write};
+use std::io::Read;
 use std::collections::HashMap;
 use std::hash::Hash;
 use std::mem;
@@ -15,147 +15,106 @@ use util::byte_utils::{be64_to_array, be32_to_array, be16_to_array, slice_to_be1
 
 const MAX_BUF_SIZE: usize = 64 * 1024;
 
-/// A struct that holds an std::io::Write-impl'ing object and implements various
-/// rust-lightning-specific write functions.
-pub struct Writer<W: Write> { writer: W }
-/// A struct that holds an std::io::Read-impl'ing object and implements various
-/// rust-lightning-specific read functions.
-pub struct Reader<R: Read> { reader: R }
+/// A trait that is similar to std::io::Write.
+/// An impl is provided for any type that also impls std::io::Write.
+pub trait Writer {
+       /// Writes the given buf out. See std::io::Write::write_all for more
+       fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error>;
+}
+
+impl<W: ::std::io::Write> Writer for W {
+       fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
+               <Self as ::std::io::Write>::write_all(self, buf)
+       }
+}
 
 /// A trait that various rust-lightning types implement allowing them to be written out to a Writer
-pub trait Writeable<W: Write> {
+pub trait Writeable<W: Writer> {
        /// Writes self out to the given Writer
-       fn write(&self, writer: &mut Writer<W>) -> Result<(), DecodeError>;
+       fn write(&self, writer: &mut W) -> Result<(), DecodeError>;
 }
 
-/// A trait that various rust-lightning types implement allowing them to be read in from a Reader
+/// A trait that various rust-lightning types implement allowing them to be read in from a Read
 pub trait Readable<R>
        where Self: Sized,
              R: Read
 {
-       /// Reads a Self in from the given Reader
-       fn read(reader: &mut Reader<R>) -> Result<Self, DecodeError>;
+       /// Reads a Self in from the given Read
+       fn read(reader: &mut R) -> Result<Self, DecodeError>;
 }
 
-impl<W: Write> Writer<W> {
-       /// Creates a new Writer from an std::io::Write-impl'ing object
-       pub fn new(writer: W) -> Writer<W> {
-               return Writer { writer }
-       }
-       /// Consumes this object and returns the original writer
-       pub fn into_inner(self) -> W { self.writer }
-       /// Gets a reference to the original writer
-       pub fn get_ref(&self) -> &W { &self.writer }
-       fn write_u64(&mut self, v: u64) -> Result<(), DecodeError> {
-               Ok(self.writer.write_all(&be64_to_array(v))?)
-       }
-       fn write_u32(&mut self, v: u32) -> Result<(), DecodeError> {
-               Ok(self.writer.write_all(&be32_to_array(v))?)
-       }
-       fn write_u16(&mut self, v: u16) -> Result<(), DecodeError> {
-               Ok(self.writer.write_all(&be16_to_array(v))?)
-       }
-       fn write_u8(&mut self, v: u8) -> Result<(), DecodeError> {
-               Ok(self.writer.write_all(&[v])?)
-       }
-       fn write_bool(&mut self, v: bool) -> Result<(), DecodeError> {
-               Ok(self.writer.write_all(&[if v {1} else {0}])?)
-       }
-       pub(crate) fn write_all(&mut self, v: &[u8]) -> Result<(), DecodeError> {
-               Ok(self.writer.write_all(v)?)
+macro_rules! impl_writeable_primitive {
+       ($val_type:ty, $meth_write:ident, $len: expr, $meth_read:ident) => {
+               impl<W: Writer> Writeable<W> for $val_type {
+                       #[inline]
+                       fn write(&self, writer: &mut W) -> Result<(), DecodeError> {
+                               Ok(writer.write_all(&$meth_write(*self))?)
+                       }
+               }
+               impl<R: Read> Readable<R> for $val_type {
+                       #[inline]
+                       fn read(reader: &mut R) -> Result<$val_type, DecodeError> {
+                               let mut buf = [0; $len];
+                               reader.read_exact(&mut buf)?;
+                               Ok($meth_read(&buf))
+                       }
+               }
        }
 }
 
-impl<R: Read> Reader<R> {
-       /// Creates a new Reader from an std::io::Read-impl'ing object
-       pub fn new(reader: R) -> Reader<R> {
-               return Reader { reader }
-       }
-       /// Consumes this object and returns the original reader
-       pub fn into_inner(self) -> R { self.reader }
-       /// Gets a reference to the original reader
-       pub fn get_ref(&self) -> &R { &self.reader }
+impl_writeable_primitive!(u64, be64_to_array, 8, slice_to_be64);
+impl_writeable_primitive!(u32, be32_to_array, 4, slice_to_be32);
+impl_writeable_primitive!(u16, be16_to_array, 2, slice_to_be16);
 
-       fn read_u64(&mut self) -> Result<u64, DecodeError> {
-               let mut buf = [0; 8];
-               self.reader.read_exact(&mut buf)?;
-               Ok(slice_to_be64(&buf))
-       }
-
-       fn read_u32(&mut self) -> Result<u32, DecodeError> {
-               let mut buf = [0; 4];
-               self.reader.read_exact(&mut buf)?;
-               Ok(slice_to_be32(&buf))
-       }
-
-       fn read_u16(&mut self) -> Result<u16, DecodeError> {
-               let mut buf = [0; 2];
-               self.reader.read_exact(&mut buf)?;
-               Ok(slice_to_be16(&buf))
+impl<W: Writer> Writeable<W> for u8 {
+       #[inline]
+       fn write(&self, writer: &mut W) -> Result<(), DecodeError> {
+               Ok(writer.write_all(&[*self])?)
        }
-
-       fn read_u8(&mut self) -> Result<u8, DecodeError> {
+}
+impl<R: Read> Readable<R> for u8 {
+       #[inline]
+       fn read(reader: &mut R) -> Result<u8, DecodeError> {
                let mut buf = [0; 1];
-               self.reader.read_exact(&mut buf)?;
+               reader.read_exact(&mut buf)?;
                Ok(buf[0])
        }
-       fn read_bool(&mut self) -> Result<bool, DecodeError> {
+}
+
+impl<W: Writer> Writeable<W> for bool {
+       #[inline]
+       fn write(&self, writer: &mut W) -> Result<(), DecodeError> {
+               Ok(writer.write_all(&[if *self {1} else {0}])?)
+       }
+}
+impl<R: Read> Readable<R> for bool {
+       #[inline]
+       fn read(reader: &mut R) -> Result<bool, DecodeError> {
                let mut buf = [0; 1];
-               self.reader.read_exact(&mut buf)?;
+               reader.read_exact(&mut buf)?;
                if buf[0] != 0 && buf[0] != 1 {
                        return Err(DecodeError::InvalidValue);
                }
                Ok(buf[0] == 1)
        }
-       pub(crate) fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), DecodeError> {
-               Ok(self.reader.read_exact(buf)?)
-       }
-       pub(crate) fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize, DecodeError> {
-               Ok(self.reader.read_to_end(buf)?)
-       }
 }
 
-macro_rules! impl_writeable_primitive {
-       ($val_type:ty, $meth_write:ident, $meth_read:ident) => {
-               impl<W:Write> Writeable<W> for $val_type {
-                       #[inline]
-                       fn write(&self, writer: &mut Writer<W>) -> Result<(), DecodeError> {
-                               writer.$meth_write(*self)
-                       }
-               }
-               impl<R:Read> Readable<R> for $val_type {
-                       #[inline]
-                       fn read(reader: &mut Reader<R>) -> Result<$val_type, DecodeError> {
-                               reader.$meth_read()
-                       }
-               }
-       }
-}
-
-impl_writeable_primitive!(u64, write_u64, read_u64);
-impl_writeable_primitive!(u32, write_u32, read_u32);
-impl_writeable_primitive!(u16, write_u16, read_u16);
-impl_writeable_primitive!(u8, write_u8, read_u8);
-impl_writeable_primitive!(bool, write_bool, read_bool);
-
 // u8 arrays
 macro_rules! impl_array {
        ( $size:expr ) => (
-               impl<W> Writeable<W> for [u8; $size]
-                       where W: Write
+               impl<W: Writer> Writeable<W> for [u8; $size]
                {
                        #[inline]
-                       fn write(&self, w: &mut Writer<W>) -> Result<(), DecodeError> {
+                       fn write(&self, w: &mut W) -> Result<(), DecodeError> {
                                w.write_all(self)?;
                                Ok(())
                        }
                }
 
-               impl<R> Readable<R> for [u8; $size]
-                       where R: Read
+               impl<R: Read> Readable<R> for [u8; $size]
                {
                        #[inline]
-                       fn read(r: &mut Reader<R>) -> Result<Self, DecodeError> {
+                       fn read(r: &mut R) -> Result<Self, DecodeError> {
                                let mut buf = [0u8; $size];
                                r.read_exact(&mut buf)?;
                                Ok(buf)
@@ -172,12 +131,12 @@ impl_array!(1300); // for OnionPacket.hop_data
 
 // HashMap
 impl<W, K, V> Writeable<W> for HashMap<K, V>
-       where W: Write,
+       where W: Writer,
              K: Writeable<W> + Eq + Hash,
              V: Writeable<W>
 {
        #[inline]
-       fn write(&self, w: &mut Writer<W>) -> Result<(), DecodeError> {
+       fn write(&self, w: &mut W) -> Result<(), DecodeError> {
        (self.len() as u16).write(w)?;
                for (key, value) in self.iter() {
                        key.write(w)?;
@@ -193,7 +152,7 @@ impl<R, K, V> Readable<R> for HashMap<K, V>
              V: Readable<R>
 {
        #[inline]
-       fn read(r: &mut Reader<R>) -> Result<Self, DecodeError> {
+       fn read(r: &mut R) -> Result<Self, DecodeError> {
                let len: u16 = Readable::read(r)?;
                let mut ret = HashMap::with_capacity(len as usize);
                for _ in 0..len {
@@ -204,9 +163,9 @@ impl<R, K, V> Readable<R> for HashMap<K, V>
 }
 
 // Vectors
-impl<W: Write, T: Writeable<W>> Writeable<W> for Vec<T> {
+impl<W: Writer, T: Writeable<W>> Writeable<W> for Vec<T> {
        #[inline]
-       fn write(&self, w: &mut Writer<W>) -> Result<(), DecodeError> {
+       fn write(&self, w: &mut W) -> Result<(), DecodeError> {
                let byte_size = (self.len() as usize)
                                .checked_mul(mem::size_of::<T>())
                                .ok_or(DecodeError::BadLengthDescriptor)?;
@@ -224,7 +183,7 @@ impl<W: Write, T: Writeable<W>> Writeable<W> for Vec<T> {
 
 impl<R: Read, T: Readable<R>> Readable<R> for Vec<T> {
        #[inline]
-       fn read(r: &mut Reader<R>) -> Result<Self, DecodeError> {
+       fn read(r: &mut R) -> Result<Self, DecodeError> {
                let len: u16 = Readable::read(r)?;
                let byte_size = (len as usize)
                                .checked_mul(mem::size_of::<T>())
@@ -238,14 +197,14 @@ impl<R: Read, T: Readable<R>> Readable<R> for Vec<T> {
        }
 }
 
-impl<W: Write> Writeable<W> for Script {
-       fn write(&self, w: &mut Writer<W>) -> Result<(), DecodeError> {
+impl<W: Writer> Writeable<W> for Script {
+       fn write(&self, w: &mut W) -> Result<(), DecodeError> {
                self.to_bytes().to_vec().write(w)
        }
 }
 
 impl<R: Read> Readable<R> for Script {
-       fn read(r: &mut Reader<R>) -> Result<Self, DecodeError> {
+       fn read(r: &mut R) -> Result<Self, DecodeError> {
                let len = <u16 as Readable<R>>::read(r)? as usize;
                let mut buf = vec![0; len];
                r.read_exact(&mut buf)?;
@@ -253,8 +212,8 @@ impl<R: Read> Readable<R> for Script {
        }
 }
 
-impl<W: Write> Writeable<W> for Option<Script> {
-       fn write(&self, w: &mut Writer<W>) -> Result<(), DecodeError> {
+impl<W: Writer> Writeable<W> for Option<Script> {
+       fn write(&self, w: &mut W) -> Result<(), DecodeError> {
                if let &Some(ref script) = self {
                        script.write(w)?;
                }
@@ -263,7 +222,7 @@ impl<W: Write> Writeable<W> for Option<Script> {
 }
 
 impl<R: Read> Readable<R> for Option<Script> {
-       fn read(r: &mut Reader<R>) -> Result<Self, DecodeError> {
+       fn read(r: &mut R) -> Result<Self, DecodeError> {
                match <u16 as Readable<R>>::read(r) {
                        Ok(len) => {
                                let mut buf = vec![0; len as usize];
@@ -276,14 +235,14 @@ impl<R: Read> Readable<R> for Option<Script> {
        }
 }
 
-impl<W: Write> Writeable<W> for PublicKey {
-       fn write(&self, w: &mut Writer<W>) -> Result<(), DecodeError> {
+impl<W: Writer> Writeable<W> for PublicKey {
+       fn write(&self, w: &mut W) -> Result<(), DecodeError> {
                self.serialize().write(w)
        }
 }
 
 impl<R: Read> Readable<R> for PublicKey {
-       fn read(r: &mut Reader<R>) -> Result<Self, DecodeError> {
+       fn read(r: &mut R) -> Result<Self, DecodeError> {
                let buf: [u8; 33] = Readable::read(r)?;
                match PublicKey::from_slice(&Secp256k1::without_caps(), &buf) {
                        Ok(key) => Ok(key),
@@ -292,27 +251,27 @@ impl<R: Read> Readable<R> for PublicKey {
        }
 }
 
-impl<W: Write> Writeable<W> for Sha256dHash {
-       fn write(&self, w: &mut Writer<W>) -> Result<(), DecodeError> {
+impl<W: Writer> Writeable<W> for Sha256dHash {
+       fn write(&self, w: &mut W) -> Result<(), DecodeError> {
                self.as_bytes().write(w)
        }
 }
 
 impl<R: Read> Readable<R> for Sha256dHash {
-       fn read(r: &mut Reader<R>) -> Result<Self, DecodeError> {
+       fn read(r: &mut R) -> Result<Self, DecodeError> {
                let buf: [u8; 32] = Readable::read(r)?;
                Ok(From::from(&buf[..]))
        }
 }
 
-impl<W: Write> Writeable<W> for Signature {
-       fn write(&self, w: &mut Writer<W>) -> Result<(), DecodeError> {
+impl<W: Writer> Writeable<W> for Signature {
+       fn write(&self, w: &mut W) -> Result<(), DecodeError> {
                self.serialize_compact(&Secp256k1::without_caps()).write(w)
        }
 }
 
 impl<R: Read> Readable<R> for Signature {
-       fn read(r: &mut Reader<R>) -> Result<Self, DecodeError> {
+       fn read(r: &mut R) -> Result<Self, DecodeError> {
                let buf: [u8; 64] = Readable::read(r)?;
                match Signature::from_compact(&Secp256k1::without_caps(), &buf) {
                        Ok(sig) => Ok(sig),
index 619d8e2f782595f0c1b76927fffc7dcb76ca9e23..2e1386a9c304e34f80beedd4b23a82ffac2c49da 100644 (file)
@@ -1,14 +1,14 @@
 macro_rules! impl_writeable {
        ($st:ident, {$($field:ident),*}) => {
-               impl<W: ::std::io::Write> Writeable<W> for $st {
-                       fn write(&self, w: &mut Writer<W>) -> Result<(), DecodeError> {
+               impl<W: Writer> Writeable<W> for $st {
+                       fn write(&self, w: &mut W) -> Result<(), DecodeError> {
                                $( self.$field.write(w)?; )*
                                Ok(())
                        }
                }
 
-               impl<R: ::std::io::Read> Readable<R> for $st {
-                       fn read(r: &mut Reader<R>) -> Result<Self, DecodeError> {
+               impl<R: Read> Readable<R> for $st {
+                       fn read(r: &mut R) -> Result<Self, DecodeError> {
                                Ok(Self {
                                        $($field: Readable::read(r)?),*
                                })