Trait utils::parser::Parser

source ·
pub trait Parser: Sized {
    type Output<'i>;
    type Then<T: Parser>: Then<Self, T>;

Show 16 methods // Required method fn parse<'i>(&self, input: &'i [u8]) -> ParseResult<'i, Self::Output<'i>>; // Provided methods fn then<T: Parser>(self, next: T) -> Self::Then<T> { ... } fn or<T: for<'i> Parser<Output<'i> = Self::Output<'i>>>( self, alternative: T, ) -> Or<Self, T> { ... } fn map<O, F: for<'i> Fn(Self::Output<'i>) -> O>(self, f: F) -> Map<Self, F> { ... } fn map_res<O, F: for<'i> Fn(Self::Output<'i>) -> Result<O, &'static str>>( self, f: F, ) -> MapResult<Self, F> { ... } fn optional(self) -> Optional<Self> { ... } fn repeat_n<const N: usize, S: Parser>( self, separator: S, ) -> RepeatN<N, Self, S> where for<'i> Self::Output<'i>: Copy + Default { ... } fn repeat_arrayvec<const N: usize, S: Parser>( self, separator: S, min_elements: usize, ) -> RepeatArrayVec<N, Self, S> where for<'a> Self::Output<'a>: Copy + Default { ... } fn repeat<S: Parser>( self, separator: S, min_elements: usize, ) -> RepeatVec<Self, S> { ... } fn with_prefix<T: Parser>(self, prefix: T) -> WithPrefix<Self, T> { ... } fn with_suffix<T: Parser>(self, suffix: T) -> WithSuffix<Self, T> { ... } fn error_msg(self, message: &'static str) -> WithErrorMsg<Self> { ... } fn parse_complete<'i>( &self, input: &'i str, ) -> Result<Self::Output<'i>, InputError> { ... } fn parse_all<'i>( &self, input: &'i str, ) -> Result<Vec<Self::Output<'i>>, InputError> { ... } fn parse_lines<'i>( &self, input: &'i str, ) -> Result<Vec<Self::Output<'i>>, InputError> { ... } fn parse_iterator(self, input: &str) -> ParserIterator<'_, Self> { ... }
}
Expand description

Parser trait.

Implementations should avoid allocating where possible.

Required Associated Types§

source

type Output<'i>

Type of the value produced by parse when successful.

Generic over the input 'i lifetime.

source

type Then<T: Parser>: Then<Self, T>

Type of the chained parser returned by then.

This is used to allow multiple then calls to extend one tuple, instead of nesting tuples inside each other.

Required Methods§

source

fn parse<'i>(&self, input: &'i [u8]) -> ParseResult<'i, Self::Output<'i>>

Parse the given sequence of bytes.

Returns a tuple of the successfully parsed Output value and the remaining bytes, or a tuple containing a ParseError and the location of the error.

The returned slices must be subslices of the input slice, otherwise InputError::new (in parse_all) will panic.

§Examples
assert_eq!(parser::u32().parse(b"1234abc"), Ok((1234, &b"abc"[..])));
assert!(parser::u32().parse(b"abc1234").is_err());

Provided Methods§

source

fn then<T: Parser>(self, next: T) -> Self::Then<T>

Sequence another parser after this one.

§Examples
assert_eq!(
    parser::i32()
        .then(parser::i32())
        .parse(b"123-123"),
    Ok(((123, -123), &b""[..]))
);
source

fn or<T: for<'i> Parser<Output<'i> = Self::Output<'i>>>( self, alternative: T, ) -> Or<Self, T>

Attempt to parse using this parser, followed by provided parser.

If this parser succeeds, the alternative provider won’t be tried. If both error, the error from the parser which parsed further into the input is returned (preferring the first error if both errored at the same position).

See also parser::one_of.

§Examples
let parser = parser::u8()
    .map(|x| u32::from(x) * 1001001)
    .or(parser::u32());
assert_eq!(
    parser.parse(b"123"),
    Ok((123123123, &b""[..]))
);
assert_eq!(
    parser.parse(b"1000"),
    Ok((1000, &b""[..]))
);
source

fn map<O, F: for<'i> Fn(Self::Output<'i>) -> O>(self, f: F) -> Map<Self, F>

Map the output of this parser using the supplied function.

§Examples
assert_eq!(
    parser::u32()
        .map(|x| x * 2)
        .parse(b"123"),
    Ok((246, &b""[..]))
);
source

fn map_res<O, F: for<'i> Fn(Self::Output<'i>) -> Result<O, &'static str>>( self, f: F, ) -> MapResult<Self, F>

Map the output of this parser using the supplied fallible function.

Errors must be &'static str, which will be mapped to ParseError::Custom.

§Examples
let parser = parser::u8()
    .map_res(|x| x.checked_mul(2).ok_or("input too large"));
assert_eq!(
    parser.parse(b"123"),
    Ok((246, &b""[..]))
);
assert_eq!(
    parser.parse(b"200"),
    Err((ParseError::Custom("input too large"), &b"200"[..]))
);
source

fn optional(self) -> Optional<Self>

Wrap Output in Option, returning None on error.

§Examples
let parser = parser::u32()
    .optional();
assert_eq!(
    parser.parse(b"123"),
    Ok((Some(123), &b""[..]))
);
assert_eq!(
    parser.parse(b"abc"),
    Ok((None, &b"abc"[..]))
);
source

fn repeat_n<const N: usize, S: Parser>( self, separator: S, ) -> RepeatN<N, Self, S>
where for<'i> Self::Output<'i>: Copy + Default,

Repeat this parser N times, returning an array.

If the number of items is variable use repeat_arrayvec or repeat.

§Examples
assert_eq!(
    parser::u32()
        .repeat_n(",") // N = 3 is inferred
        .parse(b"12,34,56"),
    Ok(([12, 34, 56], &b""[..]))
);
source

fn repeat_arrayvec<const N: usize, S: Parser>( self, separator: S, min_elements: usize, ) -> RepeatArrayVec<N, Self, S>
where for<'a> Self::Output<'a>: Copy + Default,

Repeat this parser while it matches, returning a ArrayVec.

This parser can parse up to N items. If more items match, it will return an error.

See repeat if the upper bound is large or not known, and repeat_n if the number of items is consistent.

§Examples
let parser = parser::u32()
    .repeat(",", 3);
assert_eq!(parser.parse(b"12,34,56,78"), Ok((vec![12, 34, 56, 78], &b""[..])));
assert!(parser.parse(b"12,34").is_err());
source

fn repeat<S: Parser>( self, separator: S, min_elements: usize, ) -> RepeatVec<Self, S>

Repeat this parser while it matches, returning a Vec.

To avoid allocating, prefer repeat_n if the number of items is consistent and known in advance, or repeat_arrayvec if the number of items is variable but has a known upper bound.

§Examples
let parser = parser::u32()
    .repeat(",", 3);
assert_eq!(parser.parse(b"12,34,56,78"), Ok((vec![12, 34, 56, 78], &b""[..])));
assert!(parser.parse(b"12,34").is_err());
source

fn with_prefix<T: Parser>(self, prefix: T) -> WithPrefix<Self, T>

Parse a prefix (normally a string literal) before this parser.

The result of the prefix parser is discarded.

§Examples
assert_eq!(
    parser::u32()
        .with_prefix("abc")
        .parse(b"abc123"),
    Ok((123, &b""[..]))
);
source

fn with_suffix<T: Parser>(self, suffix: T) -> WithSuffix<Self, T>

Parse a suffix (normally a string literal) after this parser.

The result of the suffix parser is discarded.

§Examples
assert_eq!(
    parser::u32()
        .with_suffix("abc")
        .parse(b"123abc"),
    Ok((123, &b""[..]))
);
source

fn error_msg(self, message: &'static str) -> WithErrorMsg<Self>

Replace this parser’s error message with the provided string.

§Examples
let parser = parser::u8()
    .error_msg("expected power level");
assert_eq!(
    parser.parse(b"123"),
    Ok((123, &b""[..]))
);
assert_eq!(
    parser.parse(b"abc"),
    Err((ParseError::Custom("expected power level"), &b"abc"[..]))
);
source

fn parse_complete<'i>( &self, input: &'i str, ) -> Result<Self::Output<'i>, InputError>

Apply this parser once, checking the provided input is fully consumed.

§Examples
assert_eq!(parser::u32().parse_complete("1234").unwrap(), 1234);
assert!(parser::u32().parse_complete("1234abc").is_err());
source

fn parse_all<'i>( &self, input: &'i str, ) -> Result<Vec<Self::Output<'i>>, InputError>

Apply this parser repeatedly until the provided input is fully consumed.

Equivalent to parser.repeat(parser::noop(), 0).parse_complete(input).

§Examples
assert_eq!(
    parser::u32()
        .then(parser::u32().with_prefix("x"))
        .with_suffix(",".or(parser::eof()))
        .parse_all("1x2,3x4,1234x5678")
        .unwrap(),
    vec![
        (1, 2),
        (3, 4),
        (1234, 5678),
    ]
);
source

fn parse_lines<'i>( &self, input: &'i str, ) -> Result<Vec<Self::Output<'i>>, InputError>

Similar to parse_all but expects a newline after each item.

Equivalent to parser.with_suffix(parser::eol()).parse_all(input).

§Examples
assert_eq!(
    parser::u32()
        .then(parser::u32().with_prefix("x"))
        .parse_lines("1x2\n3x4\n1234x5678")
        .unwrap(),
    vec![
        (1, 2),
        (3, 4),
        (1234, 5678),
    ]
);
source

fn parse_iterator(self, input: &str) -> ParserIterator<'_, Self>

Create an iterator which applies this parser repeatedly until the provided input is fully consumed.

The returned iterator will lazily parse the provided input string, producing a sequence of Result values. Once the end of input is reached, or an error is returned, the parser will always return None.

§Examples
let iterator = parser::u32()
    .with_suffix(parser::eol())
    .parse_iterator("12\n34\n56\n78");
for item in iterator {
    println!("{}", item?);
}
let mut iterator = parser::u32()
    .with_suffix(parser::eol())
    .parse_iterator("12\n34\nnot a integer");
assert_eq!(iterator.next().unwrap().unwrap(), 12);
assert_eq!(iterator.next().unwrap().unwrap(), 34);
assert!(iterator.next().unwrap().is_err());
assert!(iterator.next().is_none());
let filtered = parser::u32()
    .with_suffix(parser::eol())
    .parse_iterator("11\n22\n33\n44\n55")
    .filter(|r| r.is_err() || r.as_ref().is_ok_and(|v| v % 2 == 0))
    .collect::<Result<Vec<u32>, InputError>>()?;
assert_eq!(filtered, vec![22, 44]);

Object Safety§

This trait is not object safe.

Implementations on Foreign Types§

source§

impl Parser for &'static str

Matches the string literal exactly.

Normally used with with_prefix/with_suffix.

source§

type Output<'i> = ()

source§

type Then<T: Parser> = Then2<&'static str, T>

source§

fn parse<'i>(&self, input: &'i [u8]) -> ParseResult<'i, Self::Output<'i>>

source§

impl Parser for u8

Matches the byte exactly.

Normally used with with_prefix/with_suffix.

source§

type Output<'i> = ()

source§

type Then<T: Parser> = Then2<u8, T>

source§

fn parse<'i>(&self, input: &'i [u8]) -> ParseResult<'i, Self::Output<'i>>

Implementors§

source§

impl<O, F: Fn(&[u8]) -> ParseResult<'_, O>> Parser for F

Allow custom functions and closures to be used as parsers.

source§

type Output<'i> = O

source§

type Then<T: Parser> = Then2<F, T>