1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
//! Traits which provides the serializations
//! into the byte sequences used by the Bitmessage network,
//! and traits which provides the deserializations
//! into the data types used by the Bitmessage protocol.

use std::{
    fmt,
    io::{self, Cursor, Read, Write},
    mem::size_of,
};

pub use crate::error::TooLongError;

/// Provides a method that writes this object as a Bitmessage entity to a writer.
pub trait WriteTo {
    /// Writes this object as a Bitmessage entity to a writer.
    fn write_to(&self, w: &mut dyn Write) -> io::Result<()>;
}

/// Provides a method that reads this object as a Bitmessage entity from a reader.
pub trait ReadFrom {
    /// Reads this object as a Bitmessage entity from a reader.
    fn read_from(r: &mut dyn Read) -> io::Result<Self>
    where
        Self: Sized;
}

impl WriteTo for u8 {
    fn write_to(&self, w: &mut dyn Write) -> io::Result<()> {
        let bytes = [*self];
        w.write_all(&bytes)
    }
}

impl ReadFrom for u8 {
    fn read_from(r: &mut dyn Read) -> io::Result<Self>
    where
        Self: Sized,
    {
        let mut buf = [0; 1];
        r.read_exact(&mut buf)?;
        Ok(buf[0])
    }
}

impl WriteTo for u16 {
    fn write_to(&self, w: &mut dyn Write) -> io::Result<()> {
        w.write_all(&self.to_be_bytes())
    }
}

impl ReadFrom for u16 {
    fn read_from(r: &mut dyn Read) -> io::Result<Self>
    where
        Self: Sized,
    {
        let mut buf = [0; 2];
        r.read_exact(&mut buf)?;
        Ok(Self::from_be_bytes(buf))
    }
}

impl WriteTo for u32 {
    fn write_to(&self, w: &mut dyn Write) -> io::Result<()> {
        w.write_all(&self.to_be_bytes())
    }
}

impl ReadFrom for u32 {
    fn read_from(r: &mut dyn Read) -> io::Result<Self>
    where
        Self: Sized,
    {
        let mut buf = [0; 4];
        r.read_exact(&mut buf)?;
        Ok(Self::from_be_bytes(buf))
    }
}

impl WriteTo for u64 {
    fn write_to(&self, w: &mut dyn Write) -> io::Result<()> {
        w.write_all(&self.to_be_bytes())
    }
}

impl ReadFrom for u64 {
    fn read_from(r: &mut dyn Read) -> io::Result<Self>
    where
        Self: Sized,
    {
        let mut buf = [0; 8];
        r.read_exact(&mut buf)?;
        Ok(Self::from_be_bytes(buf))
    }
}

impl WriteTo for [u8] {
    fn write_to(&self, w: &mut dyn Write) -> io::Result<()> {
        w.write_all(self)
    }
}

macro_rules! io_array {
    ($len:expr) => {
        impl ReadFrom for [u8; $len] {
            fn read_from(r: &mut dyn Read) -> io::Result<Self>
            where
                Self: Sized,
            {
                let mut buf = [0; $len];
                r.read_exact(&mut buf)?;
                Ok(buf)
            }
        }
    };
}

io_array!(4);
io_array!(6);
io_array!(10);
io_array!(12);
io_array!(16);
io_array!(18);
io_array!(32);

impl WriteTo for Vec<u8> {
    fn write_to(&self, w: &mut dyn Write) -> io::Result<()> {
        w.write_all(self)
    }
}

/// This error indicates
/// that some trailing bytes remained after reading had finished.
///
/// The length of the trailing bytes is retrievable
/// from the error object.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct TrailingBytesError(usize);

impl fmt::Display for TrailingBytesError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "found trailing {} bytes", self.0)
    }
}

impl std::error::Error for TrailingBytesError {}

impl TrailingBytesError {
    /// Constructs an error object from a length value.
    pub fn new(trailing_len: usize) -> Self {
        Self(trailing_len)
    }

    /// Returns the length of the trailing bytes.
    pub fn trailing_len(&self) -> usize {
        self.0
    }
}

/// Provides a method that reads this object as a Bitmessage entity from a reader
/// with a specified byte length.
pub trait SizedReadFrom {
    /// Reads this object as a Bitmessage entity from a reader
    /// with a specified byte length.
    fn sized_read_from(r: &mut dyn Read, len: usize) -> io::Result<Self>
    where
        Self: Sized;
}

impl SizedReadFrom for Vec<u8> {
    fn sized_read_from(r: &mut dyn Read, len: usize) -> io::Result<Self>
    where
        Self: Sized,
    {
        let mut r = r.take(len as u64);
        let mut bytes = Vec::with_capacity(len);
        r.read_to_end(&mut bytes)?;
        Ok(bytes)
    }
}

/// Provides a method that reads this object as a Bitmessage entity from a reader
/// with a limited item count.
pub trait LimitedReadFrom {
    /// Reads this object as a Bitmessage entity from a reader
    /// with a limited item count.
    fn limited_read_from(r: &mut dyn Read, max_len: usize) -> io::Result<Self>
    where
        Self: Sized;
}

/// Provides a method that reads this object as a Bitmessage entity
/// from a byte array with an exact length.
pub trait ReadFromExact {
    /// Reads this object as a Bitmessage entity
    /// from a byte array with an exact length.
    fn read_from_exact(bytes: impl AsRef<[u8]>) -> io::Result<Self>
    where
        Self: Sized;
}

impl<T> ReadFromExact for T
where
    T: ReadFrom,
{
    fn read_from_exact(bytes: impl AsRef<[u8]>) -> io::Result<Self>
    where
        Self: Sized,
    {
        let bytes = bytes.as_ref();
        let mut cur = Cursor::new(bytes);
        let v = Self::read_from(&mut cur)?;
        if cur.position() != bytes.len() as u64 {
            return Err(io::Error::new(
                io::ErrorKind::Other,
                TrailingBytesError(bytes.len() - cur.position() as usize),
            ));
        }
        Ok(v)
    }
}

/// Provides a method that reads this object as a Bitmessage entity
/// from a byte array with an exact length.
pub trait SizedReadFromExact {
    /// Reads this object as a Bitmessage entity
    /// from a byte array with an exact length.
    fn sized_read_from_exact(bytes: impl AsRef<[u8]>) -> io::Result<Self>
    where
        Self: Sized;
}

impl<T> SizedReadFromExact for T
where
    T: SizedReadFrom,
{
    fn sized_read_from_exact(bytes: impl AsRef<[u8]>) -> io::Result<Self>
    where
        Self: Sized,
    {
        let bytes = bytes.as_ref();
        let mut cur = Cursor::new(bytes);
        Self::sized_read_from(&mut cur, bytes.len())
    }
}

/// Provides a method that returns the object's byte length
/// when serialized as a Bitmessage entity.
pub trait LenBm {
    /// Returns the object's byte length
    /// when serialized as a Bitmessage entity.
    fn len_bm(&self) -> usize;
}

impl LenBm for u32 {
    fn len_bm(&self) -> usize {
        size_of::<u32>()
    }
}

impl LenBm for u64 {
    fn len_bm(&self) -> usize {
        size_of::<u64>()
    }
}