Is there a function like char::escape_default for u8 bytes?

Viewed 294

The Rust standard library has a char::escape_default function which will print the literal character if it's printable, or a sensible escape sequence (\n, \u{XXXX}, etc.) if not.

Is there an equivalent for bytes? Specifically, I would like it to return the literal byte if it's printable, or return a byte escape sequence (\xNN) if not.

1 Answers

The standard library has a std::ascii::escape_default function that satisfies this use case:

fn main() {
    let x = String::from_utf8(
        "The compiler said “you have an error!”."
            .bytes()
            .flat_map(|b| std::ascii::escape_default(b))
            .collect::<Vec<u8>>(),
    )
    .unwrap();
    println!("{}", x);
}
Related