winnow::ascii

Function escaped_transform

Source
pub fn escaped_transform<Input, Error, Normal, Escape, Output>(
    normal: Normal,
    control_char: char,
    escape: Escape,
) -> impl Parser<Input, Output, Error>
where Input: StreamIsPartial + Stream + Compare<char>, Output: Accumulate<<Input as Stream>::Slice>, Normal: Parser<Input, <Input as Stream>::Slice, Error>, Escape: Parser<Input, <Input as Stream>::Slice, Error>, 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

§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) -> PResult<String, InputError<&'s str>> {
  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>) -> PResult<String, InputError<Partial<&'s str>>> {
  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"))));