Str Escape Default ASCII

Render control characters with str escape_default, rebuild the same text char by char, and compare it with escape_debug output.

RustData Integrity

Code

rustsnippet
20 lines
fn main() {
    let raw = "line one\nline two\t\"quoted\" é";

    // escape_default turns control bytes into printable ASCII escapes
    let escaped = raw.escape_default().to_string();
    println!("escaped: {escaped}");

    // each character can be escaped on its own
    let rebuilt: String = raw.chars().flat_map(char::escape_default).collect();
    println!("char by char: {rebuilt}");
    println!("same: {}", escaped == rebuilt);

    // escape_debug keeps printable Unicode instead of using code points
    let debug = raw.escape_debug().to_string();
    println!("debug: {debug}");
    println!("debug keeps accent: {}", debug.contains('é'));

    // a single escaped newline renders as a two-character sequence
    println!("newline escaped: {}", '\n'.escape_default().to_string());
}

How it works

All of the logic lives in the function main.

What to watch for

  • The whole dependency story is the language version itself.

Applying it

Entry signature: fn main()

Each run prints the 3 labeled blocks escaped:, char by char:, same: in source order.

Statements that matter

let rebuilt: String = raw.chars().flat_map(char::escape_default).collect();

Interactive Tools for This Topic

FAQ

What does Str Escape Default ASCII print when run?
Execute the whole file; each printed line is prefixed with a label like `escaped:`, `char by char:`, `same:`.