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§
Required Methods§
sourcefn parse<'i>(&self, input: &'i [u8]) -> ParseResult<'i, Self::Output<'i>>
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§
sourcefn then<T: Parser>(self, next: T) -> Self::Then<T>
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""[..]))
);
sourcefn or<T: for<'i> Parser<Output<'i> = Self::Output<'i>>>(
self,
alternative: T,
) -> Or<Self, T>
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""[..]))
);
sourcefn map<O, F: for<'i> Fn(Self::Output<'i>) -> O>(self, f: F) -> Map<Self, F>
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""[..]))
);
sourcefn map_res<O, F: for<'i> Fn(Self::Output<'i>) -> Result<O, &'static str>>(
self,
f: F,
) -> MapResult<Self, F>
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"[..]))
);
sourcefn repeat_n<const N: usize, S: Parser>(
self,
separator: S,
) -> RepeatN<N, Self, S>
fn repeat_n<const N: usize, S: Parser>( self, separator: S, ) -> RepeatN<N, Self, S>
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""[..]))
);
sourcefn repeat_arrayvec<const N: usize, S: Parser>(
self,
separator: S,
min_elements: usize,
) -> RepeatArrayVec<N, Self, S>
fn repeat_arrayvec<const N: usize, S: Parser>( self, separator: S, min_elements: usize, ) -> RepeatArrayVec<N, Self, S>
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());
sourcefn repeat<S: Parser>(
self,
separator: S,
min_elements: usize,
) -> RepeatVec<Self, S>
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());
sourcefn with_prefix<T: Parser>(self, prefix: T) -> WithPrefix<Self, T>
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""[..]))
);
sourcefn with_suffix<T: Parser>(self, suffix: T) -> WithSuffix<Self, T>
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""[..]))
);
sourcefn error_msg(self, message: &'static str) -> WithErrorMsg<Self>
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"[..]))
);
sourcefn parse_complete<'i>(
&self,
input: &'i str,
) -> Result<Self::Output<'i>, InputError>
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());
sourcefn parse_all<'i>(
&self,
input: &'i str,
) -> Result<Vec<Self::Output<'i>>, InputError>
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),
]
);
sourcefn parse_lines<'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>
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),
]
);
sourcefn parse_iterator(self, input: &str) -> ParserIterator<'_, Self> ⓘ
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§
Implementations on Foreign Types§
source§impl Parser for &'static str
impl Parser for &'static str
Matches the string literal exactly.
Normally used with with_prefix
/with_suffix
.
source§impl Parser for u8
impl Parser for u8
Matches the byte exactly.
Normally used with with_prefix
/with_suffix
.