Skip to content

impl Display for CStr{,ing} #139994

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
9 changes: 9 additions & 0 deletions library/alloc/src/ffi/c_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -716,6 +716,15 @@ impl fmt::Debug for CString {
}
}

/// Delegates to the [`CStr`] implementation of [`fmt::Display`],
/// showing invalid UTF-8 as the Unicode replacement character.
#[stable(feature = "cstr_display", since = "CURRENT_RUSTC_VERSION")]
impl fmt::Display for CString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self.as_c_str(), f)
}
}

#[stable(feature = "cstring_into", since = "1.7.0")]
impl From<CString> for Vec<u8> {
/// Converts a [`CString`] into a <code>[Vec]<[u8]></code>.
Expand Down
9 changes: 9 additions & 0 deletions library/core/src/ffi/c_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,15 @@ impl fmt::Debug for CStr {
}
}

/// Behaves as if `self` were first lossily converted to a `str`, with
/// invalid UTF-8 presented as the Unicode replacement character: �.
#[stable(feature = "cstr_display", since = "CURRENT_RUSTC_VERSION")]
impl fmt::Display for CStr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(crate::bstr::ByteStr::from_bytes(self.to_bytes()), f)
}
}

#[stable(feature = "cstr_default", since = "1.10.0")]
impl Default for &CStr {
#[inline]
Expand Down
6 changes: 6 additions & 0 deletions library/coretests/tests/ffi/cstr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,9 @@ 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""#);
}

#[test]
fn display() {
let s = c"\xf0\x28\x8c\xbc";
assert_eq!(format!("{s}"), "�(��");
}
Loading