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
use crate::types::*;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
use core::{default::Default, mem::MaybeUninit, slice};

/// This is the equivalent to the
/// [SeekFrom](https://doc.rust-lang.org/std/io/enum.SeekFrom.html) type from
/// the rust standard library, but reproduced here to avoid dependency on
/// `std::io`.
pub enum SeekFrom {
    Start(u64),
    End(i64),
    Current(i64),
}

/// The `Seek` trait provides a cursor which can be moved within a stream of
/// bytes. This is essentially a copy of
/// [std::io::Seek](https://doc.rust-lang.org/std/io/trait.Seek.html), but
/// avoiding its dependency on `std::io::Error`, and the associated code size
/// increase.
pub trait Seek {
    type Err;
    /// Seek to the new position. If successful, return the new position from
    /// the beginning of the stream.
    fn seek(&mut self, pos: SeekFrom) -> Result<u64, Self::Err>;
}

/// Reads `n` bytes from a given `source` without initializing the byte array
/// beforehand using MaybeUninit.
macro_rules! read_n_bytes {
    ($n:expr, $source:tt) => {{
        let mut bytes: MaybeUninit<[u8; $n]> = MaybeUninit::uninit();
        let write_bytes = unsafe { slice::from_raw_parts_mut(bytes.as_mut_ptr() as *mut u8, $n) };
        $source.read_exact(write_bytes)?;
        unsafe { bytes.assume_init() }
    }};
}

/// The `Read` trait provides a means of reading from byte streams.
pub trait Read {
    /// Read a number of bytes into the provided buffer. The returned value is
    /// `Ok(n)` if a read was successful, and `n` bytes were read (`n` could be
    /// 0).
    fn read(&mut self, buf: &mut [u8]) -> ParseResult<usize>;

    /// Read exactly the required number of bytes. If not enough bytes could be
    /// read the function returns `Err(_)`, and the contents of the given buffer
    /// is unspecified.
    fn read_exact(&mut self, buf: &mut [u8]) -> ParseResult<()> {
        let mut start = 0;
        while start < buf.len() {
            match self.read(&mut buf[start..]) {
                Ok(0) => break,
                Ok(n) => {
                    start += n;
                }
                Err(_e) => return Err(Default::default()),
            }
        }
        if start == buf.len() {
            Ok(())
        } else {
            Err(Default::default())
        }
    }

    /// Read a `u64` in little-endian format.
    fn read_u64(&mut self) -> ParseResult<u64> {
        let bytes = read_n_bytes!(8, self);
        Ok(u64::from_le_bytes(bytes))
    }

    /// Read a `u32` in little-endian format.
    fn read_u32(&mut self) -> ParseResult<u32> {
        let bytes = read_n_bytes!(4, self);
        Ok(u32::from_le_bytes(bytes))
    }

    /// Read a `u16` in little-endian format.
    fn read_u16(&mut self) -> ParseResult<u16> {
        let bytes = read_n_bytes!(2, self);
        Ok(u16::from_le_bytes(bytes))
    }

    /// Read a `u8`.
    fn read_u8(&mut self) -> ParseResult<u8> {
        let bytes = read_n_bytes!(1, self);
        Ok(u8::from_le_bytes(bytes))
    }

    /// Read a `i64` in little-endian format.
    fn read_i64(&mut self) -> ParseResult<i64> {
        let bytes = read_n_bytes!(8, self);
        Ok(i64::from_le_bytes(bytes))
    }

    /// Read a `i32` in little-endian format.
    fn read_i32(&mut self) -> ParseResult<i32> {
        let bytes = read_n_bytes!(4, self);
        Ok(i32::from_le_bytes(bytes))
    }

    /// Read a `i16` in little-endian format.
    fn read_i16(&mut self) -> ParseResult<i16> {
        let bytes = read_n_bytes!(2, self);
        Ok(i16::from_le_bytes(bytes))
    }

    /// Read a `i32` in little-endian format.
    fn read_i8(&mut self) -> ParseResult<i8> {
        let bytes = read_n_bytes!(1, self);
        Ok(i8::from_le_bytes(bytes))
    }
}

/// The `Write` trait provides functionality for writing to byte streams.
pub trait Write {
    type Err: Default;
    /// Try to write the given buffer into the output stream. If writes are
    /// successful returns the number of bytes written.
    fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Err>;

    /// Attempt to write the entirety of the buffer to the output by repeatedly
    /// calling `write` until either no more output can written, or writing
    /// fails.
    fn write_all(&mut self, buf: &[u8]) -> Result<(), Self::Err> {
        let mut start = 0;
        while start < buf.len() {
            match self.write(&buf[start..]) {
                Ok(n) if n > 0 => start += n,
                _ => return Err(Default::default()),
            }
        }
        Ok(())
    }

    /// Write a single byte to the output.
    fn write_u8(&mut self, x: u8) -> Result<(), Self::Err> { self.write_all(&x.to_le_bytes()) }

    /// Write a `u16` in little endian.
    fn write_u16(&mut self, x: u16) -> Result<(), Self::Err> { self.write_all(&x.to_le_bytes()) }

    /// Write a `u32` in little endian.
    fn write_u32(&mut self, x: u32) -> Result<(), Self::Err> { self.write_all(&x.to_le_bytes()) }

    /// Write a `u64` in little endian.
    fn write_u64(&mut self, x: u64) -> Result<(), Self::Err> { self.write_all(&x.to_le_bytes()) }

    /// Write a `i8` to the output.
    fn write_i8(&mut self, x: i8) -> Result<(), Self::Err> { self.write_all(&x.to_le_bytes()) }

    /// Write a `i16` in little endian.
    fn write_i16(&mut self, x: i16) -> Result<(), Self::Err> { self.write_all(&x.to_le_bytes()) }

    /// Write a `i32` in little endian.
    fn write_i32(&mut self, x: i32) -> Result<(), Self::Err> { self.write_all(&x.to_le_bytes()) }

    /// Write a `i64` in little endian.
    fn write_i64(&mut self, x: i64) -> Result<(), Self::Err> { self.write_all(&x.to_le_bytes()) }
}

impl Write for Vec<u8> {
    type Err = ();

    fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Err> {
        let _ = self.extend_from_slice(buf);
        Ok(buf.len())
    }
}

/// The `Serial` trait provides a means of writing structures into byte-sinks
/// (`Write`).
///
/// Can be derived using `#[derive(Serial)]` for most cases.
pub trait Serial {
    /// Attempt to write the structure into the provided writer, failing if
    /// only part of the structure could be written.
    ///
    /// NB: We use Result instead of Option for better composability with other
    /// constructs.
    fn serial<W: Write>(&self, _out: &mut W) -> Result<(), W::Err>;
}

/// The `Deserial` trait provides a means of reading structures from byte-sinks
/// (`Read`).
///
/// Can be derived using `#[derive(Deserial)]` for most cases.
pub trait Deserial: Sized {
    /// Attempt to read a structure from a given source, failing if an error
    /// occurs during deserialization or reading.
    fn deserial<R: Read>(_source: &mut R) -> ParseResult<Self>;
}

/// The `Serialize` trait provides a means of writing structures into byte-sinks
/// (`Write`) or reading structures from byte sources (`Read`).
///
/// Can be derived using `#[derive(Serialized)]` for most cases.
pub trait Serialize: Serial + Deserial {}

/// Generic instance deriving Serialize for any type that implements both Serial
/// and Deserial.
impl<A: Deserial + Serial> Serialize for A {}

/// A more convenient wrapper around `Deserial` that makes it easier to write
/// deserialization code. It has a blanked implementation for any read and
/// serialize pair. The key idea is that the type to deserialize is inferred
/// from the context, enabling one to write, for example,
///
/// ```ignore
///   let x = source.get()?;
///   let y = source.get()?;
///   ...
/// ```
/// where `source` is any type that implements `Read`.
pub trait Get<T> {
    fn get(&mut self) -> ParseResult<T>;
}

impl<R: Read, T: Deserial> Get<T> for R {
    #[inline(always)]
    fn get(&mut self) -> ParseResult<T> { T::deserial(self) }
}