[][src]Struct dangerous::Reader

pub struct Reader<'i, E> { /* fields omitted */ }

A Reader is created from and consumes an Input.

You can only create a Reader from Input via Input::read_all(), Input::read_partial() or Input::read_infallible().

Errors

Functions on Reader are designed to provide a panic free interface and if applicable, clearly define the type of error that can can be thown.

To verify input and optionally return a type from that verification, verify(), try_verify(), expect(), try_expect() and try_expect_erased() is provided. These functions are the interface for creating errors based off what was expected.

try_expect_erased() is provided for reading a custom type that does not support a &mut Reader<'i, E> interface, for example a type implementing FromStr.

recover() and recover_if() are provided as an escape hatch when you wish to catch an error and try another branch.

context() and peek_context() are provided to add a Context to any error thrown inside their scope. This is useful for debugging.

Peeking

Peeking should be used to find the correct path to consume. Values read from peeking should not be used for the resulting type.

use dangerous::Invalid;

let input = dangerous::input(b"true");
let result: Result<_, Invalid> = input.read_all(|r| {
    // We use `peek_u8` here because we expect at least one byte.
    // If we wanted to handle the case when there is no more input left,
    // for example to provide a default, we would use `peek_u8_opt`.
    // The below allows us to handle a `RetryRequirement` if the
    // `Reader` is at the end of the input.
    r.try_expect("boolean", |r| match r.peek_u8()? {
        b't' => r.consume(b"true").map(|()| Some(true)),
        b'f' => r.consume(b"false").map(|()| Some(false)),
        _ => Ok(None),
    })
});
assert!(matches!(result, Ok(true)));

Implementations

impl<'i, E> Reader<'i, E>[src]

pub fn context<C, F, T>(&mut self, context: C, f: F) -> Result<T, E> where
    E: WithContext<'i>,
    C: Context,
    F: FnOnce(&mut Self) -> Result<T, E>, 
[src]

Mutably use the Reader with a given context.

Errors

Returns any error returned by the provided function with the specified context attached.

pub fn peek_context<C, F, T>(&self, context: C, f: F) -> Result<T, E> where
    E: WithContext<'i>,
    C: Context,
    F: FnOnce(&Self) -> Result<T, E>, 
[src]

Immutably use the Reader with a given context.

Errors

Returns any error returned by the provided function with the specified context attached.

#[must_use]pub fn at_end(&self) -> bool[src]

Returns true if the Reader has no more input to consume.

pub fn skip(&mut self, len: usize) -> Result<(), E> where
    E: From<ExpectedLength<'i>>, 
[src]

Skip len number of bytes.

Errors

Returns an error if the length requirement to skip could not be met.

pub fn skip_while<F>(&mut self, pred: F) -> usize where
    F: FnMut(u8) -> bool
[src]

Skip a length of input while a predicate check remains true.

Returns the total length of input skipped.

pub fn try_skip_while<F>(&mut self, pred: F) -> Result<usize, E> where
    E: WithContext<'i>,
    F: FnMut(u8) -> Result<bool, E>, 
[src]

Try skip a length of input while a predicate check remains successful and true.

Returns the total length of input skipped.

Errors

Returns any error the provided function does.

pub fn skip_str_while<F>(&mut self, pred: F) -> Result<usize, E> where
    E: WithContext<'i>,
    E: From<ExpectedValid<'i>>,
    E: From<ExpectedLength<'i>>,
    F: FnMut(char) -> bool
[src]

Skip a length of string input while a predicate check remains true.

Returns the total length of input skipped in bytes.

Errors

Returns ExpectedValid if the input could never be valid UTF-8 and ExpectedLength if a UTF-8 code point was cut short.

pub fn try_skip_str_while<F>(&mut self, pred: F) -> Result<usize, E> where
    E: WithContext<'i>,
    E: From<ExpectedValid<'i>>,
    E: From<ExpectedLength<'i>>,
    F: FnMut(char) -> Result<bool, E>, 
[src]

Try skip a length of string input while a predicate check remains successful and true.

Returns the total length of input skipped in bytes.

Errors

Returns any error the provided function does, ExpectedValid if the the input could never be valid UTF-8 and ExpectedLength if a UTF-8 code point was cut short.

pub fn take(&mut self, len: usize) -> Result<Input<'i>, E> where
    E: From<ExpectedLength<'i>>, 
[src]

Read a length of input.

Errors

Returns an error if the length requirement to read could not be met.

pub fn take_remaining(&mut self) -> Input<'i>[src]

Read all of the remaining input.

pub fn take_remaining_str(&mut self) -> Result<Input<'i>, E> where
    E: WithContext<'i>,
    E: From<ExpectedValid<'i>>,
    E: From<ExpectedLength<'i>>, 
[src]

Read all of the remaining string input.

Errors

Returns ExpectedValid if the input could never be valid UTF-8 and ExpectedLength if a UTF-8 code point was cut short.

pub fn take_while<F>(&mut self, pred: F) -> Input<'i> where
    F: FnMut(u8) -> bool
[src]

Read a length of input while a predicate check remains true.

pub fn try_take_while<F>(&mut self, pred: F) -> Result<Input<'i>, E> where
    E: WithContext<'i>,
    F: FnMut(u8) -> Result<bool, E>, 
[src]

Try read a length of input while a predicate check remains successful and true.

Errors

Returns any error the provided function does.

pub fn take_str_while<F>(&mut self, pred: F) -> Result<Input<'i>, E> where
    E: WithContext<'i>,
    E: From<ExpectedValid<'i>>,
    E: From<ExpectedLength<'i>>,
    F: FnMut(char) -> bool
[src]

Read a length of string input while a predicate check remains true.

Errors

Returns ExpectedValid if the input could never be valid UTF-8 and ExpectedLength if a UTF-8 code point was cut short.

pub fn try_take_str_while<F>(&mut self, pred: F) -> Result<Input<'i>, E> where
    E: WithContext<'i>,
    E: From<ExpectedValid<'i>>,
    E: From<ExpectedLength<'i>>,
    F: FnMut(char) -> Result<bool, E>, 
[src]

Try read a length of string input while a predicate check remains true.

Errors

Returns any error the provided function does, ExpectedValid if the the input could never be valid UTF-8 and ExpectedLength if a UTF-8 code point was cut short.

pub fn take_consumed<F>(&mut self, consumer: F) -> Input<'i> where
    E: WithContext<'i>,
    F: FnOnce(&mut Self), 
[src]

Read a length of input that was successfully consumed from a sub-parse.

pub fn try_take_consumed<F>(&mut self, consumer: F) -> Result<Input<'i>, E> where
    E: WithContext<'i>,
    F: FnOnce(&mut Self) -> Result<(), E>, 
[src]

Try read a length of input that was successfully consumed from a sub-parse.

Example

use dangerous::Invalid;

let result: Result<_, Invalid> = dangerous::input(b"abc").read_all(|r| {
    r.try_take_consumed(|r| {
        r.skip(1)?;
        r.consume(b"bc")
    })
});

assert_eq!(result.unwrap(), b"abc"[..]);

Errors

Returns any error the provided function does.

pub fn peek<'p>(&'p self, len: usize) -> Result<Input<'p>, E> where
    E: From<ExpectedLength<'i>>, 
[src]

Peek a length of input.

The function lifetime is to prevent the peeked Input being used as a value in a parsed structure. Peeked values should only be used in choosing a correct parse path.

Errors

Returns an error if the length requirement to peek could not be met.

#[must_use = "peek result must be used"]pub fn peek_opt(&self, len: usize) -> Option<Input<'_>>[src]

Peek a length of input.

This is equivalent to peek but does not return an error. Don't use this function if you want an error if there isn't enough input.

#[must_use = "peek result must be used"]pub fn peek_eq(&self, bytes: &[u8]) -> bool[src]

Returns true if bytes is next in the Reader.

pub fn peek_u8(&self) -> Result<u8, E> where
    E: From<ExpectedLength<'i>>, 
[src]

Peek the next byte in the input without mutating the Reader.

Errors

Returns an error if the Reader has no more input.

#[must_use = "peek result must be used"]pub fn peek_u8_opt(&self) -> Option<u8>[src]

Peek the next byte in the input without mutating the Reader.

This is equivalent to peek_u8 but does not return an error. Don't use this function if you want an error if there isn't enough input.

#[must_use = "peek result must be used"]pub fn peek_u8_eq(&self, byte: u8) -> bool[src]

Returns true if byte is next in the Reader.

pub fn consume(&mut self, bytes: &'i [u8]) -> Result<(), E> where
    E: From<ExpectedValue<'i>>, 
[src]

Consume expected bytes.

Doesn't effect the internal state of the Reader if the bytes couldn't be consumed.

Errors

Returns an error if the bytes could not be consumed.

pub fn consume_opt(&mut self, bytes: &[u8]) -> bool[src]

Consume optional bytes.

Returns true if the bytes were consumed, false if not.

Doesn't effect the internal state of the Reader if the bytes couldn't be consumed.

pub fn consume_u8(&mut self, byte: u8) -> Result<(), E> where
    E: From<ExpectedValue<'i>>, 
[src]

Consume an expected byte.

Doesn't effect the internal state of the Reader if the byte couldn't be consumed.

Errors

Returns an error if the byte could not be consumed.

pub fn consume_u8_opt(&mut self, byte: u8) -> bool[src]

Consume an optional byte.

Returns true if the byte was consumed, false if not.

Doesn't effect the internal state of the Reader if the byte couldn't be consumed.

pub fn verify<F>(
    &mut self,
    expected: &'static str,
    verifier: F
) -> Result<(), E> where
    F: FnOnce(&mut Self) -> bool,
    E: WithContext<'i>,
    E: From<ExpectedValid<'i>>, 
[src]

Read and verify a value without returning it.

Errors

Returns an error if the verifier function returned false.

pub fn try_verify<F>(
    &mut self,
    expected: &'static str,
    verifier: F
) -> Result<(), E> where
    F: FnOnce(&mut Self) -> Result<bool, E>,
    E: WithContext<'i>,
    E: From<ExpectedValid<'i>>, 
[src]

Try read and verify a value without returning it.

Errors

Returns an error if the verifier function returned false or an error.

pub fn expect<F, T>(&mut self, expected: &'static str, f: F) -> Result<T, E> where
    F: FnOnce(&mut Self) -> Option<T>,
    E: WithContext<'i>,
    E: From<ExpectedValid<'i>>, 
[src]

Expect a value to be read and returned as Some(T).

Errors

Returns an error if the returned value was None.

pub fn try_expect<F, T>(&mut self, expected: &'static str, f: F) -> Result<T, E> where
    E: WithContext<'i>,
    E: From<ExpectedValid<'i>>,
    F: FnOnce(&mut Self) -> Result<Option<T>, E>, 
[src]

Expect a value to be read successfully and returned as Some(O).

Errors

Returns an error if the returned value was None or if the provided function does.

pub fn try_expect_erased<F, T, R>(
    &mut self,
    expected: &'static str,
    f: F
) -> Result<T, E> where
    E: WithContext<'i>,
    E: From<ExpectedValid<'i>>,
    F: FnOnce(&mut Self) -> Result<T, R>,
    R: ToRetryRequirement
[src]

Expect a value with any error's details erased except for an optional RetryRequirement.

This function is useful for reading custom/unsupported types easily without having to create custom errors.

Example

use std::net::Ipv4Addr;

use dangerous::{Error, Expected, Invalid, Reader};

// Our custom reader function
fn read_ipv4_addr<'i, E>(r: &mut Reader<'i, E>) -> Result<Ipv4Addr, E>
where
  E: Error<'i>,
{
    r.try_expect_erased("ipv4 addr", |i| {
        i.take_remaining()
            .to_dangerous_str()
            .and_then(|s| s.parse().map_err(|_| Invalid::fatal()))
    })
}

let input = dangerous::input(b"192.168.1.x");
let error: Expected = input.read_all(read_ipv4_addr).unwrap_err();

// Prefer string input formatting
println!("{:#}", error);

Errors

Returns an error if provided function does.

pub fn recover<F, T>(&mut self, f: F) -> Option<T> where
    F: FnOnce(&mut Self) -> Result<T, E>, 
[src]

Recovers from an error returning Some(O) if successful, or None if an error occurred.

If an error is recovered from the Reader's internal state is reset.

pub fn recover_if<F, T, R>(&mut self, f: F, pred: R) -> Result<Option<T>, E> where
    E: WithContext<'i>,
    F: FnOnce(&mut Self) -> Result<T, E>,
    R: FnOnce(&E) -> bool
[src]

Recovers from an error based on a predicate.

If an error is recovered from the Reader's internal state is reset.

If an error occurs and the predicate returns true the error is recovered, Ok(None) is returned.

Errors

If an error occurs and the predicate returns false the error is not recovered, Err(E) is returned.

pub fn error<F, T, S>(&mut self, f: F) -> T where
    F: FnOnce(&mut Reader<'i, S>) -> T, 
[src]

Read with a different error type.

Keep in mind using different errors types can increase your binary size, use sparingly.

Example

use dangerous::{Error, Expected, Fatal, Reader};

fn branch_a<'i, E>(r: &mut Reader<'i, E>) -> Result<u8, E>
where
    E: Error<'i>
{
    r.consume(b"hello").map(|()| 1)
}

fn branch_b<'i, E>(r: &mut Reader<'i, E>) -> Result<u8, E>
where
    E: Error<'i>
{
    r.consume(b"world").map(|()| 2)
}

let input = dangerous::input(b"world");
let result: Result<_, Expected> = input.read_all(|r| {
    r.expect("valid branch", |r| {
        r.error(|r: &mut Reader<Fatal>| {
            r.recover(branch_a).or_else(|| r.recover(branch_b))
        })
    })
});

assert_eq!(result.unwrap(), 2);

pub fn read_u8(&mut self) -> Result<u8, E> where
    E: From<ExpectedLength<'i>>, 
[src]

Read a byte.

Errors

Returns an error if there is no more input.

pub fn read_i8_le(&mut self) -> Result<i8, E> where
    E: From<ExpectedLength<'i>>, 
[src]

Read a little-endian encoded i8.

Errors

Returns an error if there is not sufficient input left to read.

pub fn read_i8_be(&mut self) -> Result<i8, E> where
    E: From<ExpectedLength<'i>>, 
[src]

Read a big-endian encoded i8.

Errors

Returns an error if there is not sufficient input left to read.

pub fn read_u16_le(&mut self) -> Result<u16, E> where
    E: From<ExpectedLength<'i>>, 
[src]

Read a little-endian encoded u16.

Errors

Returns an error if there is not sufficient input left to read.

pub fn read_u16_be(&mut self) -> Result<u16, E> where
    E: From<ExpectedLength<'i>>, 
[src]

Read a big-endian encoded u16.

Errors

Returns an error if there is not sufficient input left to read.

pub fn read_i16_le(&mut self) -> Result<i16, E> where
    E: From<ExpectedLength<'i>>, 
[src]

Read a little-endian encoded i16.

Errors

Returns an error if there is not sufficient input left to read.

pub fn read_i16_be(&mut self) -> Result<i16, E> where
    E: From<ExpectedLength<'i>>, 
[src]

Read a big-endian encoded i16.

Errors

Returns an error if there is not sufficient input left to read.

pub fn read_u32_le(&mut self) -> Result<u32, E> where
    E: From<ExpectedLength<'i>>, 
[src]

Read a little-endian encoded u32.

Errors

Returns an error if there is not sufficient input left to read.

pub fn read_u32_be(&mut self) -> Result<u32, E> where
    E: From<ExpectedLength<'i>>, 
[src]

Read a big-endian encoded u32.

Errors

Returns an error if there is not sufficient input left to read.

pub fn read_i32_le(&mut self) -> Result<i32, E> where
    E: From<ExpectedLength<'i>>, 
[src]

Read a little-endian encoded i32.

Errors

Returns an error if there is not sufficient input left to read.

pub fn read_i32_be(&mut self) -> Result<i32, E> where
    E: From<ExpectedLength<'i>>, 
[src]

Read a big-endian encoded i32.

Errors

Returns an error if there is not sufficient input left to read.

pub fn read_u64_le(&mut self) -> Result<u64, E> where
    E: From<ExpectedLength<'i>>, 
[src]

Read a little-endian encoded u64.

Errors

Returns an error if there is not sufficient input left to read.

pub fn read_u64_be(&mut self) -> Result<u64, E> where
    E: From<ExpectedLength<'i>>, 
[src]

Read a big-endian encoded u64.

Errors

Returns an error if there is not sufficient input left to read.

pub fn read_i64_le(&mut self) -> Result<i64, E> where
    E: From<ExpectedLength<'i>>, 
[src]

Read a little-endian encoded i64.

Errors

Returns an error if there is not sufficient input left to read.

pub fn read_i64_be(&mut self) -> Result<i64, E> where
    E: From<ExpectedLength<'i>>, 
[src]

Read a big-endian encoded i64.

Errors

Returns an error if there is not sufficient input left to read.

pub fn read_u128_le(&mut self) -> Result<u128, E> where
    E: From<ExpectedLength<'i>>, 
[src]

Read a little-endian encoded u128.

Errors

Returns an error if there is not sufficient input left to read.

pub fn read_u128_be(&mut self) -> Result<u128, E> where
    E: From<ExpectedLength<'i>>, 
[src]

Read a big-endian encoded u128.

Errors

Returns an error if there is not sufficient input left to read.

pub fn read_i128_le(&mut self) -> Result<i128, E> where
    E: From<ExpectedLength<'i>>, 
[src]

Read a little-endian encoded i128.

Errors

Returns an error if there is not sufficient input left to read.

pub fn read_i128_be(&mut self) -> Result<i128, E> where
    E: From<ExpectedLength<'i>>, 
[src]

Read a big-endian encoded i128.

Errors

Returns an error if there is not sufficient input left to read.

pub fn read_f32_le(&mut self) -> Result<f32, E> where
    E: From<ExpectedLength<'i>>, 
[src]

Read a little-endian encoded f32.

Errors

Returns an error if there is not sufficient input left to read.

pub fn read_f32_be(&mut self) -> Result<f32, E> where
    E: From<ExpectedLength<'i>>, 
[src]

Read a big-endian encoded f32.

Errors

Returns an error if there is not sufficient input left to read.

pub fn read_f64_le(&mut self) -> Result<f64, E> where
    E: From<ExpectedLength<'i>>, 
[src]

Read a little-endian encoded f64.

Errors

Returns an error if there is not sufficient input left to read.

pub fn read_f64_be(&mut self) -> Result<f64, E> where
    E: From<ExpectedLength<'i>>, 
[src]

Read a big-endian encoded f64.

Errors

Returns an error if there is not sufficient input left to read.

Trait Implementations

impl<'i, E> Debug for Reader<'i, E>[src]

impl<'i, E> NoInteriorMut for Reader<'i, E>[src]

Auto Trait Implementations

impl<'i, E> RefUnwindSafe for Reader<'i, E> where
    E: RefUnwindSafe
[src]

impl<'i, E> Send for Reader<'i, E> where
    E: Send
[src]

impl<'i, E> Sync for Reader<'i, E> where
    E: Sync
[src]

impl<'i, E> Unpin for Reader<'i, E> where
    E: Unpin
[src]

impl<'i, E> UnwindSafe for Reader<'i, E> where
    E: UnwindSafe
[src]

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> From<T> for T[src]

impl<T> Guarded for T where
    T: NoInteriorMut
[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.