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
// Copyright 2018 Kyle Mayes
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! A library for zero-allocation parsing of binary formats.
//!
//! # Example
//!
//! ```
//! use tarrasque::{Endianness, ExtractError, Stream};
//! use tarrasque_macro::{extract};
//!
//! extract! {
//!     /// A 2D point.
//!     #[derive(Copy, Clone, Debug, PartialEq, Eq)]
//!     pub struct Point[4](endianness: Endianness) {
//!         /// The x-coordinate of this point.
//!         pub x: u16 = [endianness],
//!         /// The y-coordinate of this point.
//!         pub y: u16 = [endianness],
//!     }
//! }
//!
//! fn main() {
//!     let mut stream = Stream(&[1, 2, 3, 4, 5, 6, 7, 8]);
//!
//!     let point = stream.extract::<Point, _>(Endianness::Big);
//!     assert_eq!(point, Ok(Point { x: 258, y: 772 }));
//!
//!     let point = stream.extract::<Point, _>(Endianness::Little);
//!     assert_eq!(point, Ok(Point { x: 1541, y: 2055 }));
//!
//!     let point = stream.extract::<Point, _>(Endianness::Big);
//!     assert_eq!(point, Err(ExtractError::Insufficient(2)));
//! }
//! ```

#![deny(missing_copy_implementations, missing_debug_implementations, missing_docs)]

#![no_std]

mod array;
mod number;
mod view;

use core::ops::{Deref, DerefMut};
use core::str::{Utf8Error, from_utf8};

pub use crate::array::*;
pub use crate::number::*;
pub use crate::view::*;

/// An error encountered while extracting a value from a stream of bytes.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum ExtractError<'a> {
    /// An error code.
    Code(u32),
    /// The stream contained bytes that could not be converted into a valid UTF-8 string.
    Encoding(&'a [u8], Utf8Error),
    /// The stream did not contain enough bytes to extract the value.
    Insufficient(usize),
}

/// The result of extracting a value from a stream of bytes.
pub type ExtractResult<'a, T> = Result<T, ExtractError<'a>>;

/// A type that can be extracted from a stream of bytes.
pub trait Extract<'a, P> {
    /// Extracts a value of this type from the supplied stream of bytes.
    ///
    /// See [`Stream::extract`] for usage information.
    fn extract(stream: &mut Stream<'a>, _: P) -> ExtractResult<'a, Self> where Self: Sized;
}

impl<'a> Extract<'a, ()> for &'a [u8] {
    #[inline]
    fn extract(stream: &mut Stream<'a>, _: ()) -> ExtractResult<'a, Self> {
        stream.extract(stream.0.len())
    }
}

impl<'a> Extract<'a, ()> for &'a str {
    #[inline]
    fn extract(stream: &mut Stream<'a>, _: ()) -> ExtractResult<'a, Self> {
        stream.extract(stream.0.len())
    }
}

impl<'a> Extract<'a, usize> for &'a [u8] {
    #[inline]
    fn extract(stream: &mut Stream<'a>, length: usize) -> ExtractResult<'a, Self> {
        if stream.0.len() >= length {
            let value = &stream.0[..length];
            stream.0 = &stream.0[length..];
            Ok(value)
        } else {
            Err(ExtractError::Insufficient(length - stream.0.len()))
        }
    }
}

impl<'a> Extract<'a, usize> for &'a str {
    #[inline]
    fn extract(stream: &mut Stream<'a>, length: usize) -> ExtractResult<'a, Self> {
        let slice = stream.extract(length)?;
        match from_utf8(slice) {
            Ok(value) => Ok(value),
            Err(error) => Err(ExtractError::Encoding(slice, error)),
        }
    }
}

/// A type that spans a fixed number of bytes.
pub trait Span {
    /// The number of bytes spanned by values of this type.
    const SPAN: usize;
}

/// A stream of bytes from which values can be extracted.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Stream<'a>(pub &'a [u8]);

impl<'a> Stream<'a> {
    /// Extracts bytes from this stream as a `T`.
    ///
    /// # Example
    ///
    /// ```
    /// # use tarrasque::{ExtractError, Stream};
    /// let mut stream = Stream(&[1, 2]);
    /// assert_eq!(stream.extract::<u8, _>(()), Ok(0x01));
    /// assert_eq!(stream.extract::<u8, _>(()), Ok(0x02));
    /// assert_eq!(stream.extract::<u8, _>(()), Err(ExtractError::Insufficient(1)));
    /// ```
    #[inline]
    pub fn extract<T, P>(&mut self, parameter: P) -> ExtractResult<'a, T> where T: Extract<'a, P> {
        T::extract(self, parameter)
    }

    /// Returns bytes from this stream as a `T` without extracting the bytes.
    ///
    /// # Example
    ///
    /// ```
    /// # use tarrasque::{ExtractError, Stream};
    /// let mut stream = Stream(&[1, 2, 3, 4]);
    /// assert_eq!(stream.peek::<u16, _>(()), Ok(0x0102));
    /// assert_eq!(stream.extract::<u16, _>(()), Ok(0x0102));
    /// assert_eq!(stream.peek::<u16, _>(()), Ok(0x0304));
    /// assert_eq!(stream.extract::<u16, _>(()), Ok(0x0304));
    /// assert_eq!(stream.peek::<u16, _>(()), Err(ExtractError::Insufficient(2)));
    /// assert_eq!(stream.extract::<u16, _>(()), Err(ExtractError::Insufficient(2)));
    /// ```
    #[inline]
    pub fn peek<T, P>(&mut self, parameter: P) -> ExtractResult<'a, T> where T: Extract<'a, P> {
        T::extract(&mut Stream(self.0), parameter)
    }

    /// Skips the supplied number of bytes in this stream.
    ///
    /// # Example
    ///
    /// ```
    /// # use tarrasque::{ExtractError, Stream};
    /// let mut stream = Stream(&[1, 2, 3, 4]);
    /// stream.skip(2);
    /// assert_eq!(stream.extract::<u16, _>(()), Ok(0x0304));
    /// assert_eq!(stream.extract::<u16, _>(()), Err(ExtractError::Insufficient(2)));
    /// ```
    #[inline]
    pub fn skip(&mut self, n: usize) {
        if self.0.len() > n {
            self.0 = &self.0[n..];
        } else {
            self.0 = &[];
        }
    }

    /// Skips bytes in this stream while the supplied condition is true for those bytes.
    ///
    /// # Example
    ///
    /// ```
    /// # use tarrasque::{ExtractError, Stream};
    /// let mut stream = Stream(&[1, 2, 3, 4]);
    /// stream.skip_while(|b| b < 3);
    /// assert_eq!(stream.extract::<u16, _>(()), Ok(0x0304));
    /// assert_eq!(stream.extract::<u16, _>(()), Err(ExtractError::Insufficient(2)));
    /// ```
    #[inline]
    pub fn skip_while<F: Fn(u8) -> bool>(&mut self, f: F) {
        while !self.0.is_empty() && f(self.0[0]) {
            self.0 = &self.0[1..];
        }
    }
}

/// A [`Stream`] wrapper that unwraps extracted values.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct UnwrapStream<'a>(pub Stream<'a>);

impl<'a> UnwrapStream<'a> {
    /// Extracts bytes from this stream as a `T` and unwraps the result.
    ///
    /// # Example
    ///
    /// ```
    /// # use tarrasque::{ExtractError, Stream, UnwrapStream};
    /// let mut stream = UnwrapStream(Stream(&[1, 2]));
    /// assert_eq!(stream.extract::<u8, _>(()), 0x01);
    /// assert_eq!(stream.extract::<u8, _>(()), 0x02);
    /// ```
    #[inline]
    pub fn extract<T, P>(&mut self, parameter: P) -> T where T: Extract<'a, P> {
        self.0.extract(parameter).unwrap()
    }
}

impl<'a> Deref for UnwrapStream<'a> {
    type Target = Stream<'a>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<'a> DerefMut for UnwrapStream<'a> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}