diff options
| author | Tamir Duberstein <tamird@gmail.com> | 2025-04-18 11:18:25 -0400 |
|---|---|---|
| committer | Tamir Duberstein <tamird@gmail.com> | 2025-06-12 12:53:14 -0400 |
| commit | a82062055af1ecdcb7f4d3371855aae843fc0ae3 (patch) | |
| tree | 2d97d6709ee8862732412220478aef2f6bf92801 | |
| parent | 6c8138de8f1c96b2f66adbbc0e37c73525444750 (diff) | |
| download | rust-a82062055af1ecdcb7f4d3371855aae843fc0ae3.tar.gz rust-a82062055af1ecdcb7f4d3371855aae843fc0ae3.zip | |
Delegate `<CStr as Debug>` to `ByteStr`
This allows UTF-8 characters to be printed without escapes, rather than just ASCII.
| -rw-r--r-- | library/alloc/src/ffi/c_str.rs | 2 | ||||
| -rw-r--r-- | library/core/src/ffi/c_str.rs | 4 | ||||
| -rw-r--r-- | library/coretests/tests/ffi/cstr.rs | 2 |
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] |
