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 301 302 303 304 305 306 307 308 309 310 311 312 313 314
// 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, 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() {
//! // A stream of bytes.
//! let mut stream = Stream(&[1, 2, 3, 4, 5, 6, 7, 8]);
//!
//! // Extract a point containing two big-endian `u16`s from the stream.
//! let point = stream.extract::<Point, _>(Endianness::Big);
//! assert_eq!(point, Ok(Point { x: 258, y: 772 }));
//!
//! // Extract a point containing two little-endian `u16`s from the stream.
//! let point = stream.extract::<Point, _>(Endianness::Little);
//! assert_eq!(point, Ok(Point { x: 1541, y: 2055 }));
//!
//! // Attempt to extract a point from the empty stream.
//! 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, RangeBounds};
use core::str::{Utf8Error, from_utf8};
pub use tarrasque_macro::{extract};
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<'s> {
/// An error code.
Code(u32),
/// The stream contained bytes that could not be converted into a valid
/// UTF-8 string.
Encoding(&'s [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<'s, T> = Result<T, ExtractError<'s>>;
/// A type that can be extracted from a stream of bytes.
pub trait Extract<'s, P> {
/// Extracts a value of this type from the supplied stream of bytes.
///
/// See [`Stream::extract`] for usage information.
fn extract(
stream: &mut Stream<'s>, _: P
) -> ExtractResult<'s, Self> where Self: Sized;
}
impl<'s> Extract<'s, ()> for &'s [u8] {
#[inline]
fn extract(stream: &mut Stream<'s>, _: ()) -> ExtractResult<'s, Self> {
stream.extract(stream.len())
}
}
impl<'s> Extract<'s, ()> for &'s str {
#[inline]
fn extract(stream: &mut Stream<'s>, _: ()) -> ExtractResult<'s, Self> {
stream.extract(stream.len())
}
}
impl<'s> Extract<'s, usize> for &'s [u8] {
#[inline]
fn extract(
stream: &mut Stream<'s>, length: usize
) -> ExtractResult<'s, Self> {
if stream.len() >= length {
let value = &stream[..length];
stream.skip(length);
Ok(value)
} else {
Err(ExtractError::Insufficient(length - stream.len()))
}
}
}
impl<'s> Extract<'s, usize> for &'s str {
#[inline]
fn extract(
stream: &mut Stream<'s>, length: usize
) -> ExtractResult<'s, 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<'s>(pub &'s [u8]);
impl<'s> Stream<'s> {
/// Extracts bytes from this stream as a `T`.
///
/// # Example
///
/// ```
/// # use tarrasque::{Stream};
/// # use tarrasque::ExtractError::*;
/// 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(Insufficient(1)));
/// ```
#[inline]
pub fn extract<T, P>(
&mut self, parameter: P
) -> ExtractResult<'s, T> where T: Extract<'s, P> {
T::extract(self, parameter)
}
/// Returns bytes from this stream as a `T` without extracting the bytes.
///
/// # Example
///
/// ```
/// # use tarrasque::{Stream};
/// # use tarrasque::ExtractError::*;
/// 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(Insufficient(2)));
/// assert_eq!(stream.extract::<u16, _>(()), Err(Insufficient(2)));
/// ```
#[inline]
pub fn peek<T, P>(
&mut self, parameter: P
) -> ExtractResult<'s, T> where T: Extract<'s, P> {
T::extract(&mut Stream(self.0), parameter)
}
/// Skips the supplied number of bytes in this stream.
///
/// # Example
///
/// ```
/// # use tarrasque::{Stream};
/// # use tarrasque::ExtractError::*;
/// let mut stream = Stream(&[1, 2, 3, 4]);
/// stream.skip(2);
/// assert_eq!(stream.extract::<u16, _>(()), Ok(0x0304));
/// assert_eq!(stream.extract::<u16, _>(()), Err(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::{Stream};
/// # use tarrasque::ExtractError::*;
/// 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(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..];
}
}
/// Returns the substream in this stream corresponding to the supplied range.
///
/// # Example
///
/// ```
/// # use tarrasque::{Stream};
/// # use tarrasque::ExtractError::*;
/// let stream = Stream(&[1, 2, 3, 4]);
/// assert_eq!(stream.substream(1..3), Ok(Stream(&[2, 3])));
/// assert_eq!(stream.substream(4..), Err(Insufficient(5)));
/// assert_eq!(stream.substream(..5), Err(Insufficient(5)));
/// assert_eq!(stream.substream(..=4), Err(Insufficient(5)));
/// ```
#[inline]
pub fn substream(
&self, bounds: impl RangeBounds<usize>
) -> ExtractResult<'s, Stream<'s>> {
use core::ops::Bound::*;
if let Included(start) = bounds.start_bound() {
if *start >= self.0.len() {
return Err(ExtractError::Insufficient(*start + 1));
}
}
match bounds.end_bound() {
Included(end) if *end >= self.0.len() =>
return Err(ExtractError::Insufficient(*end + 1)),
Excluded(end) if *end > self.0.len() =>
return Err(ExtractError::Insufficient(*end)),
_ => { },
}
match (bounds.start_bound(), bounds.end_bound()) {
(Included(start), Included(end)) => Ok(Stream(&self.0[*start..=*end])),
(Included(start), Excluded(end)) => Ok(Stream(&self.0[*start..*end])),
(Included(start), Unbounded) => Ok(Stream(&self.0[*start..])),
(Unbounded, Included(end)) => Ok(Stream(&self.0[..=*end])),
(Unbounded, Excluded(end)) => Ok(Stream(&self.0[..*end])),
(Unbounded, Unbounded) => Ok(*self),
_ => unreachable!(),
}
}
}
impl<'s> Deref for Stream<'s> {
type Target = &'s [u8];
fn deref(&self) -> &Self::Target {
&self.0
}
}
/// A [`Stream`] wrapper that unwraps extracted values.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct UnwrapStream<'s>(pub Stream<'s>);
impl<'s> UnwrapStream<'s> {
/// Extracts bytes from this stream as a `T` and unwraps the result.
///
/// # Example
///
/// ```
/// # use tarrasque::{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<'s, P> {
self.0.extract(parameter).unwrap()
}
}
impl<'s> Deref for UnwrapStream<'s> {
type Target = Stream<'s>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<'s> DerefMut for UnwrapStream<'s> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}