Skip to content

OsString Debug implementation prints escaped single quotes #114583

@tamird

Description

@tamird
fn main() {
    let string = "'";
    assert_eq!(
        format!("{:?}", string),
        format!("{:?}", std::ffi::OsString::from(string))
    );
}

produces

thread 'main' panicked at 'assertion failed: `(left == right)`
  left: `"\"'\""`,
 right: `"\"\\'\""`', src/main.rs:3:5

(playground)

#83046 reported the behavior of <str as Debug>::fmt escaping single quotes, and it was changed in #83079. Should we do the same for OsString?

I ran into this in #114132. It seems easy to fix for unix:

diff --git a/library/core/src/str/lossy.rs b/library/core/src/str/lossy.rs
index 59f873d1268..7e5ae364361 100644
--- a/library/core/src/str/lossy.rs
+++ b/library/core/src/str/lossy.rs
@@ -1,3 +1,4 @@
+use crate::char::EscapeDebugExtArgs;
 use crate::fmt;
 use crate::fmt::Formatter;
 use crate::fmt::Write;
@@ -85,7 +86,11 @@ fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
                 let valid = chunk.valid();
                 let mut from = 0;
                 for (i, c) in valid.char_indices() {
-                    let esc = c.escape_debug();
+                    let esc = c.escape_debug_ext(EscapeDebugExtArgs {
+                        escape_grapheme_extended: true,
+                        escape_single_quote: false,
+                        escape_double_quote: true,
+                    });
                     // If char needs escaping, flush backlog so far and write, else skip
                     if esc.len() != 1 {
                         f.write_str(&valid[from..i])?;

But on windows OsString is implemented using Wtf8, which is in std rather than core, which means it can't call char::escape_debug_ext:

for c in s.chars().flat_map(|c| c.escape_debug()) {

Metadata

Metadata

Assignees

Labels

A-fmtArea: `core::fmt`T-libsRelevant to the library team, which will review and decide on the PR/issue.relnotesMarks issues that should be documented in the release notes of the next release.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions