Trait EscapeHandler

Source
pub trait EscapeHandler {
    // Required method
    fn escape(
        &mut self,
        idx: usize,
        chr: char,
        iter: &mut CharIndices<'_>,
    ) -> Result<Option<char>, ()>;
}
Expand description

A trait distinguishing an object as a handler for custom escape sequences.

For convenience, this trait is automatically implemented for all implementors of FnMut with the correct signature.

Required Methods§

Source

fn escape( &mut self, idx: usize, chr: char, iter: &mut CharIndices<'_>, ) -> Result<Option<char>, ()>

Definition of a custom escape handler.

Custom escape handlers are called before parsing any escape sequences, and are given 3 arguments:

  • idx: The index of the current character (e.g. Hello\nthere gets 5)
  • chr: The current character in the string (e.g. \\n gets 'n')
  • iter: A mutable reference to the underlying character iterator - use this to get the rest of the string via CharIndices::as_str, or get the next characters

Handlers return a Result<Option<char>, ()>. Returning Ok(Some(char)) replaces the sequence with the given character, returning Ok(None) removes the sequence entirely, and returning Err errors the unescaping at the index of the escape sequence.

§Examples
§Permitting any escape, handing it back raw
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");
§Removing escape sequences entirely
fn raw(idx: usize, chr: char, _: &mut CharIndices) -> Result<Option<char>, ()> {
    Ok(None)
}
let escaped = r"What if I want a \nnewline?";
let unescaped = escaped.to_unescaped_with(raw).expect("this should work");
assert_eq!(unescaped, "What if I want a newline?");
§Not allowing escape sequences unsupported by Rust
fn rust_only(idx: usize, chr: char, iter: &mut CharIndices) -> Result<Option<char>, ()> {
    match chr {
        'a' | 'b' | 'v' | 'f' | 'e' | '`' => Err(()),
        _ => descape::DefaultHandler.escape(idx, chr, iter)
    }
}
r"This is \nfine".to_unescaped_with(rust_only).expect(r"\n is valid");
r"This is not \fine".to_unescaped_with(rust_only).expect_err(r"\f is invalid");
§An informal note

Ideally, this trait would return Result<Option<char>, Option<Box<dyn Error>>>, but Error has only been in core since Rust version 1.82.0. Using it would bump the MSRV by a tremendous amount, and as such it has been left out.

Implementors§

Source§

impl EscapeHandler for DefaultHandler

Source§

impl<F> EscapeHandler for F
where F: for<'iter, 'source> FnMut(usize, char, &'iter mut CharIndices<'source>) -> Result<Option<char>, ()>,