From a82062055af1ecdcb7f4d3371855aae843fc0ae3 Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Fri, 18 Apr 2025 11:18:25 -0400 Subject: [PATCH] Delegate `` to `ByteStr` This allows UTF-8 characters to be printed without escapes, rather than just ASCII. --- library/alloc/src/ffi/c_str.rs | 2 ++ library/core/src/ffi/c_str.rs | 4 +++- 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 8b448a18402c3..48849bf7536c0 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 595cc1fe025ec..f7a21072f5393 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 dc34240cd99d2..7d669cc1c3fff 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]