Skip to content

Debug escaping is confusingly inconsistent #107035

Open

Description

@dfoxfranke

The behaviors of char::escape_debug, str::escape_debug, and <str as Debug>::fmt are confusingly inconsistent with each other, and the inconsistencies are poorly documented.

fn main() {
    let wat = "a\u{301}'";

    println!("{:?}", wat);
    println!("\"{}\"", wat.escape_debug());
    println!(
        "\"{}\"",
        wat.chars()
            .flat_map(|ch| ch.escape_debug())
            .collect::<String>()
    );
}
"a\u{301}'"
"á\'"
"a\u{301}\'"

It seems defensible that char::escape_debug escapes single-quotes while <str as Debug>::fmt doesn't, since char_escape_debug doesn't know whether it's being used to escape a character literal or a string literal. But if a difference is going to exist, it's less defensible that str::escape_debug should follow the behavior of char::escape_debug rather than the behavior of <str as Debug>::fmt.

str::escape_debug and <str as Debug>::fmt's differing behavior on grapheme extenders makes no sense at all. Furthermore, if the escaping of grapheme extenders is going to be position-dependent (a bad idea IMO), then the rule should be that they are unescaped only if they are preceded by an unescaped character. The current rule gives absurd results in cases like

fn main() {
    println!("{}", "\u{301}\u{301}".escape_debug());
}
\u{301}́

Activity

  1. dfoxfranke commented on Jan 18, 2023

    @dfoxfranke
    ContributorAuthor

    Btw, I don't mind if this gets addressed through behavior changes to one or more existing methods, but there is one particular use case that I need to remain feasible. Given an Iterator<Item=char>, I need to be able to replicate the behavior of <str as Debug>::fmt without having to collect the iterator into a String and without needing a Unicode character database in sync with std. Currently I can do this by special-casing single-quotes and passing everything else to char::escape_debug(). If char::escape_debug() and <str as Debug>::fmt start behaving differently with respect to grapheme extenders, then this gets painful, unless the (currently pub(crate)) char::is_grapheme_extended method is made public.

  2. clubby789 commented on Mar 27, 2023

    @clubby789
    Contributor

    @rustbot label +T-libs

  3. added
    T-libs
    on Mar 27, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-UnicodeT-libs

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions