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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
//! Defines a cursor over a slice of bytes.

#![no_std]

#[cfg(feature = "std")]
extern crate std;

use core::mem;
use core::result;

/////////////////////////////////////////////////////////////////////////
// Definitions
/////////////////////////////////////////////////////////////////////////

/// A result type to use in this crate.
pub type Result<T> = result::Result<T, Error>;

/// A generic error that can occur while reading bytes.
#[derive(Debug, PartialEq)]
#[cfg_attr(
    feature = "std",
    derive(thiserror::Error),
    error("wanted {size} bytes but {} bytes remain", self.len - self.pos),
)]
pub struct Error {
    size: usize,
    len: usize,
    pos: usize,
}

/// A cursor over a slice of bytes.
#[derive(Debug, Clone)]
pub struct Bytes<'a> {
    inner: &'a [u8],
    pos: usize,
}

/// Fallible conversion of bytes to a new type.
///
/// # Examples
///
/// ```
/// use frombytes::{Bytes, Error, FromBytes};
///
/// struct MyStruct {
///     a: u32,
///     b: i16,
/// }
///
/// impl FromBytes for MyStruct {
///     // we simply use the same error that primitives use
///     // but any error could be used
///     type Error = Error;
///
///     fn from_bytes(bytes: &mut Bytes) -> Result<Self, Self::Error> {
///         // uses type inference to know to read a `u32`
///         let a = bytes.read()?;
///         // uses type inference to know to read a `i16`
///         let b = bytes.read()?;
///         Ok(Self { a, b })
///     }
/// }
/// ```
pub trait FromBytes: Sized {
    /// The associated error which can be returned from parsing.
    ///
    /// All primitive types as well as radiotap fields implementing this trait
    /// set this error to [`Error`](struct.Error.html).
    type Error;

    /// Construct a type from bytes.
    ///
    /// This method is often used implicitly through
    /// [`Bytes`](struct.Bytes.html)'s [`read`](struct.Bytes.html#method.read)
    /// method.
    fn from_bytes(bytes: &mut Bytes) -> result::Result<Self, Self::Error>;
}

/////////////////////////////////////////////////////////////////////////
// Implementations
/////////////////////////////////////////////////////////////////////////

impl<'a> From<&'a [u8]> for Bytes<'a> {
    fn from(bytes: &'a [u8]) -> Self {
        Self::from_slice(bytes)
    }
}

impl<'a> Bytes<'a> {
    /// Returns a new cursor over a slice of bytes.
    pub const fn from_slice(bytes: &'a [u8]) -> Self {
        Self {
            inner: bytes,
            pos: 0,
        }
    }

    /// Consumes the `Bytes` and returns the underlying data.
    pub const fn into_inner(self) -> &'a [u8] {
        self.inner
    }

    /// Returns the current position of the `Bytes`.
    pub const fn position(&self) -> usize {
        self.pos
    }

    /// Returns the total length of the original underlying buffer.
    const fn len(&self) -> usize {
        self.inner.len()
    }

    fn checked_pos(&self, new_pos: usize) -> Result<usize> {
        let pos = self.pos;
        let len = self.len();
        if new_pos > self.len() {
            Err(Error {
                size: new_pos - pos,
                len,
                pos,
            })
        } else {
            Ok(new_pos)
        }
    }

    fn set_position(&mut self, new_pos: usize) -> Result<()> {
        self.pos = self.checked_pos(new_pos)?;
        Ok(())
    }

    /// Advances the position in the bytes.
    pub fn advance(&mut self, size: usize) -> Result<()> {
        self.set_position(self.pos + size)
    }

    /// Aligns the bytes to a particular word.
    ///
    /// # Panics
    ///
    /// If the align size is a not one of the following powers of two: 1, 2, 4,
    /// 8, or 16.
    pub fn align(&mut self, align: usize) -> Result<()> {
        assert!(matches!(align, 1 | 2 | 4 | 8 | 16));
        self.set_position((self.pos + align - 1) & !(align - 1))
    }

    fn read_slice(&mut self, size: usize) -> Result<&'a [u8]> {
        let start = self.pos;
        self.pos = self.checked_pos(start + size)?;
        Ok(&self.inner[start..self.pos])
    }

    /// Allows types implementing [`FromBytes`](trait.FromBytes.html) to be
    /// easily read from these bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// # use frombytes::*;
    /// let mut bytes = Bytes::from_slice(&[0x78, 0x56, 0x34, 0x12]);
    /// let value: u32 = bytes.read().unwrap();
    /// assert_eq!(value, 0x12345678);
    /// ```
    pub fn read<T: FromBytes>(&mut self) -> result::Result<T, <T as FromBytes>::Error> {
        T::from_bytes(self)
    }
}

macro_rules! impl_primitive {
    ($Type:ty) => {
        impl FromBytes for $Type {
            type Error = Error;

            fn from_bytes(bytes: &mut Bytes) -> Result<Self> {
                const COUNT: usize = mem::size_of::<$Type>();
                let mut buf = [0; COUNT];
                buf.copy_from_slice(bytes.read_slice(COUNT)?);
                Ok(Self::from_le_bytes(buf))
            }
        }
    };
}

impl_primitive!(u8);
impl_primitive!(u16);
impl_primitive!(u32);
impl_primitive!(u64);
impl_primitive!(u128);

impl_primitive!(i8);
impl_primitive!(i16);
impl_primitive!(i32);
impl_primitive!(i64);
impl_primitive!(i128);

macro_rules! impl_array {
    ($SIZE:expr) => {
        impl<T, E> FromBytes for [T; $SIZE]
        where
            T: FromBytes<Error = E> + Default,
        {
            type Error = E;

            fn from_bytes(bytes: &mut Bytes) -> result::Result<Self, E> {
                let mut buf = Self::default();
                for i in 0..$SIZE {
                    buf[i] = bytes.read()?;
                }
                Ok(buf)
            }
        }
    };
}

impl_array!(1);
impl_array!(2);
impl_array!(3);
impl_array!(4);

/////////////////////////////////////////////////////////////////////////
// Unit tests
/////////////////////////////////////////////////////////////////////////

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn bytes_align() {
        fn check_align(align: usize, expected_pos: usize) {
            let mut bytes = Bytes {
                inner: &[0; 25],
                pos: 13,
            };
            bytes.align(align).unwrap();
            assert_eq!(bytes.pos, expected_pos);
        }

        check_align(1, 13);
        check_align(2, 14);
        check_align(4, 16);
        check_align(8, 16);
        check_align(16, 16);
    }

    #[test]
    fn bytes_read_primitive_x8() {
        let mut bytes = Bytes::from_slice(&[1, !2 + 1]);
        assert_eq!(bytes.read::<u8>().unwrap(), 1);
        assert_eq!(bytes.read::<i8>().unwrap(), -2);
    }

    #[test]
    fn bytes_read_primitive_x16() {
        let mut bytes = Bytes::from_slice(&[0xfb, 0xfa, 0xff, 0xff]);
        assert_eq!(bytes.read::<u16>().unwrap(), 0xfafb);
        assert_eq!(bytes.read::<i16>().unwrap(), -0x0001);
    }

    #[test]
    fn bytes_read_array_primitives() {
        let mut bytes = Bytes::from_slice(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
        assert_eq!(
            bytes.read::<[u32; 3]>().unwrap(),
            [0x04030201, 0x08070605, 0x0C0B0A09]
        );
    }

    #[test]
    fn bytes_read_array_newtype() {
        #[derive(Debug, Default, PartialEq)]
        struct NewType(i16);

        impl FromBytes for NewType {
            type Error = Error;

            fn from_bytes(bytes: &mut Bytes) -> Result<Self> {
                bytes.read().map(Self)
            }
        }

        let mut bytes = Bytes::from_slice(&[1, 2, 3, 4, 5, 6]);
        assert_eq!(
            bytes.read::<[NewType; 3]>().unwrap(),
            [NewType(0x0201), NewType(0x0403), NewType(0x0605)]
        );
    }

    #[test]
    #[cfg(feature = "std")]
    fn error_display() {
        let mut bytes = Bytes::from_slice(&[]);
        let err = bytes.read::<u8>().unwrap_err();
        assert_eq!(
            std::string::ToString::to_string(&err),
            "wanted 1 bytes but 0 bytes remain"
        );
    }
}