Skip to content

Commit 4f9972b

Browse files
committed
Delegate <CStr as Debug> to ByteStr
This allows UTF-8 characters to be printed without escapes, rather than just ASCII.
1 parent 8afd710 commit 4f9972b

File tree

3 files changed

+6
-2
lines changed

3 files changed

+6
-2
lines changed

library/alloc/src/ffi/c_str.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -714,6 +714,8 @@ impl ops::Deref for CString {
714714
}
715715
}
716716

717+
/// Delegates to the [`CStr`] implementation of [`fmt::Debug`],
718+
/// showing invalid UTF-8 as hex escapes.
717719
#[stable(feature = "rust1", since = "1.0.0")]
718720
impl fmt::Debug for CString {
719721
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {

library/core/src/ffi/c_str.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -162,10 +162,12 @@ impl fmt::Display for FromBytesUntilNulError {
162162
}
163163
}
164164

165+
/// Shows the underlying bytes as a normal string, with invalid UTF-8
166+
/// presented as hex escape sequences.
165167
#[stable(feature = "cstr_debug", since = "1.3.0")]
166168
impl fmt::Debug for CStr {
167169
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168-
write!(f, "\"{}\"", self.to_bytes().escape_ascii())
170+
fmt::Debug::fmt(crate::bstr::ByteStr::from_bytes(self.to_bytes()), f)
169171
}
170172
}
171173

library/coretests/tests/ffi/cstr.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ fn compares_as_u8s() {
1717
#[test]
1818
fn debug() {
1919
let s = c"abc\x01\x02\n\xE2\x80\xA6\xFF";
20-
assert_eq!(format!("{s:?}"), r#""abc\x01\x02\n\xe2\x80\xa6\xff""#);
20+
assert_eq!(format!("{s:?}"), "\"abc\\x01\\x02\\n…\\xff\"");
2121
}
2222

2323
#[test]

0 commit comments

Comments
 (0)