Function winnow::ascii::escaped_transform

source ·
pub fn escaped_transform<I, Error, F, G, Output>(
    normal: F,
    control_char: char,
    transform: G,
) -> impl Parser<I, Output, Error>
where I: StreamIsPartial + Stream, <I as Stream>::Token: AsChar + Clone, Output: Accumulate<<I as Stream>::Slice>, F: Parser<I, <I as Stream>::Slice, Error>, G: Parser<I, <I as Stream>::Slice, Error>, Error: ParserError<I>,
Expand description

Matches a byte string with escaped characters.

  • The first argument matches the normal characters (it must not match the control character)
  • The second argument is the control character (like \ in most languages)
  • The third argument matches the escaped characters and transforms them

As an example, the chain abc\tdef could be abc def (it also consumes the control character)

§Example

use winnow::token::tag;
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::tag;
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"))));