Function escaped

Source
pub fn escaped<Input, Error, Normal, NormalOutput, Escape, EscapeOutput, Output>(
    normal: Normal,
    control_char: char,
    escape: Escape,
) -> impl Parser<Input, Output, Error>
where Input: StreamIsPartial + Stream + Compare<char>, Normal: Parser<Input, NormalOutput, Error>, Escape: Parser<Input, EscapeOutput, Error>, Output: Accumulate<NormalOutput> + Accumulate<EscapeOutput>, Error: ParserError<Input>,
Expand description

Parse escaped characters, unescaping them

Arguments:

  • normal: unescapeable characters
    • Must not include control
  • control_char: e.g. \ for strings in most languages
  • escape: parse and transform the escaped character

Parsing ends when:

  • alt(normal, control._char) Backtracks
  • normal doesn’t advance the input stream
  • (complete) input stream is exhausted

Warning: If the normal parser passed to escaped_transform accepts empty inputs (like alpha0 or digit0), escaped_transform will return an error, to prevent going into an infinite loop.

§Example

use winnow::token::literal;
use winnow::ascii::escaped_transform;
use winnow::ascii::alpha1;
use winnow::combinator::alt;

fn parser<'s>(input: &mut &'s str) -> ModalResult<String> {
  escaped_transform(
    alpha1,
    '\\',
    alt((
      "\\".value("\\"),
      "\"".value("\""),
      "n".value("\n"),
    ))
  ).parse_next(input)
}

assert_eq!(parser.parse_peek("ab\\\"cd"), Ok(("", String::from("ab\"cd"))));
assert_eq!(parser.parse_peek("ab\\ncd"), Ok(("", String::from("ab\ncd"))));
use winnow::token::literal;
use winnow::ascii::escaped_transform;
use winnow::ascii::alpha1;
use winnow::combinator::alt;

fn parser<'s>(input: &mut Partial<&'s str>) -> ModalResult<String> {
  escaped_transform(
    alpha1,
    '\\',
    alt((
      "\\".value("\\"),
      "\"".value("\""),
      "n".value("\n"),
    ))
  ).parse_next(input)
}

assert_eq!(parser.parse_peek(Partial::new("ab\\\"cd\"")), Ok((Partial::new("\""), String::from("ab\"cd"))));