descape 1.2.0

Adds a single extension trait for &str to unescape any backslashes.
Documentation
descape-1.2.0 has been yanked.

GitHub Actions Workflow Status Coverage Documentation MSRV Repository Latest version License unsafe forbidden

descape

Provides utilities for easily parsing escape sequences in a string, using alloc::borrow::Cow to only borrow when needed.

This library supports many escape sequences:

  • All escapes mentioned in the documentation of core::ascii::Char
  • \\' -> '
  • \\" -> "
  • \\` -> `
  • \\\\ -> \\
  • \\xNN -> \xNN
  • \\o -> \o, for all octal digits o
  • \\oo -> \oo, for all octal digits o
  • \\ooo -> \ooo, for all octal digits o
  • \\uXXXX -> \u{XXXX}
  • \\u{HEX} -> \u{HEX}

Along with this, you can define your own custom escape handlers! See UnescapeExt::to_unescaped_with for more information on that.

This crate supports no-std.

Examples

Parsing an escaped string

let escaped = "Hello,\\nworld!".to_unescaped();
assert_eq!(
    escaped,
    Ok(Cow::Owned::<'_, str>("Hello,\nworld!".to_string()))
);

Not allocating for a string without escapes

let no_escapes = "No escapes here!".to_unescaped();
assert_eq!(
    no_escapes,
    Ok(Cow::Borrowed("No escapes here!"))
);

Erroring for invalid escapes

let invalid_escape = r"Uh oh! \xJJ".to_unescaped();
assert_eq!(
    invalid_escape,
    Err(7)
);

Custom escape handlers

fn raw(idx: usize, chr: char, _: &mut CharIndices) -> Result<Option<char>, ()> {
    Ok(Some(chr))
}

let escaped = r"\H\e\l\l\o \n \W\o\r\l\d";
let unescaped = escaped.to_unescaped_with(raw).expect("this is fine");
assert_eq!(unescaped, "Hello n World");