Skip to content

Delegate <CStr as Debug> to ByteStr #141491

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 13, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions library/alloc/src/ffi/c_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
4 changes: 3 additions & 1 deletion library/core/src/ffi/c_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

Expand Down
2 changes: 1 addition & 1 deletion library/coretests/tests/ffi/cstr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
Loading