rustmax::nom::multi

Function fold

Source
pub fn fold<I, E, F, G, H, J, R>(
    range: J,
    parser: F,
    init: H,
    fold: G,
) -> impl Parser<I, Output = R, Error = E>
where I: Clone + Input, F: Parser<I, Error = E>, G: FnMut(R, <F as Parser<I>>::Output) -> R, H: FnMut() -> R, E: ParseError<I>, J: NomRange<usize>,
Expand description

Applies a parser and accumulates the results using a given function and initial value. Fails if the amount of time the embedded parser is run is not within the specified range.

ยงArguments

  • range Constrains the number of iterations.
    • A range without an upper bound a.. allows the parser to run until it fails.
    • A single usize value is equivalent to value..=value.
    • An empty range is invalid.
  • parse The parser to apply.
  • init A function returning the initial value.
  • fold The function that combines a result of f with the current accumulator.
use nom::multi::fold;
use nom::bytes::complete::tag;

fn parser(s: &str) -> IResult<&str, Vec<&str>> {
  fold(
    0..=2,
    tag("abc"),
    Vec::new,
    |mut acc: Vec<_>, item| {
      acc.push(item);
      acc
    }
  ).parse(s)
}

assert_eq!(parser("abcabc"), Ok(("", vec!["abc", "abc"])));
assert_eq!(parser("abc123"), Ok(("123", vec!["abc"])));
assert_eq!(parser("123123"), Ok(("123123", vec![])));
assert_eq!(parser(""), Ok(("", vec![])));
assert_eq!(parser("abcabcabc"), Ok(("abc", vec!["abc", "abc"])));