about summary refs log tree commit diff
diff options
context:
space:
mode:
authorMatthias Krüger <476013+matthiaskrgr@users.noreply.github.com>2025-06-13 05:16:55 +0200
committerGitHub <noreply@github.com>2025-06-13 05:16:55 +0200
commit8ae89893bec2c4c605fa404d8222b90da663ea0f (patch)
tree670f23fb364e100376dd10a9d3e328e433dc3b40
parentb12bb2530b12fedd93a2a54b806a4f8dc2e199c4 (diff)
parenta82062055af1ecdcb7f4d3371855aae843fc0ae3 (diff)
downloadrust-8ae89893bec2c4c605fa404d8222b90da663ea0f.tar.gz
rust-8ae89893bec2c4c605fa404d8222b90da663ea0f.zip
Rollup merge of #141491 - tamird:cstr-debug-bstr, r=joshtriplett
Delegate `<CStr as Debug>` to `ByteStr`

This allows UTF-8 characters to be printed without escapes, rather than
just ASCII.

r? `@joshtriplett`
-rw-r--r--library/alloc/src/ffi/c_str.rs2
-rw-r--r--library/core/src/ffi/c_str.rs4
-rw-r--r--library/coretests/tests/ffi/cstr.rs2
3 files changed, 6 insertions, 2 deletions
diff --git a/library/alloc/src/ffi/c_str.rs b/library/alloc/src/ffi/c_str.rs
index 8b448a18402..48849bf7536 100644
--- a/library/alloc/src/ffi/c_str.rs
+++ b/library/alloc/src/ffi/c_str.rs
@@ -714,6 +714,8 @@ impl ops::Deref for CString {
     }
 }
 
+/// Delegates to the [`CStr`] implementation of [`fmt::Debug`],
+/// showing invalid UTF-8 as hex escapes.
 #[stable(feature = "rust1", since = "1.0.0")]
 impl fmt::Debug for CString {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
diff --git a/library/core/src/ffi/c_str.rs b/library/core/src/ffi/c_str.rs
index 595cc1fe025..f7a21072f53 100644
--- a/library/core/src/ffi/c_str.rs
+++ b/library/core/src/ffi/c_str.rs
@@ -162,10 +162,12 @@ impl fmt::Display for FromBytesUntilNulError {
     }
 }
 
+/// Shows the underlying bytes as a normal string, with invalid UTF-8
+/// presented as hex escape sequences.
 #[stable(feature = "cstr_debug", since = "1.3.0")]
 impl fmt::Debug for CStr {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        write!(f, "\"{}\"", self.to_bytes().escape_ascii())
+        fmt::Debug::fmt(crate::bstr::ByteStr::from_bytes(self.to_bytes()), f)
     }
 }
 
diff --git a/library/coretests/tests/ffi/cstr.rs b/library/coretests/tests/ffi/cstr.rs
index dc34240cd99..7d669cc1c3f 100644
--- a/library/coretests/tests/ffi/cstr.rs
+++ b/library/coretests/tests/ffi/cstr.rs
@@ -17,7 +17,7 @@ fn compares_as_u8s() {
 #[test]
 fn debug() {
     let s = c"abc\x01\x02\n\xE2\x80\xA6\xFF";
-    assert_eq!(format!("{s:?}"), r#""abc\x01\x02\n\xe2\x80\xa6\xff""#);
+    assert_eq!(format!("{s:?}"), r#""abc\x01\x02\n…\xff""#);
 }
 
 #[test]