Skip to content

Commit f7359d5

Browse files
committed
impl Display for CStr{,ing}
Delegate to `<ByteStr as Display>::fmt`. Link: rust-lang/libs-team#550 Link: #139984.
1 parent d6c1e45 commit f7359d5

File tree

3 files changed

+24
-0
lines changed

3 files changed

+24
-0
lines changed

library/alloc/src/ffi/c_str.rs

+9
Original file line numberDiff line numberDiff line change
@@ -716,6 +716,15 @@ impl fmt::Debug for CString {
716716
}
717717
}
718718

719+
/// Delegates to the [`CStr`] implementation of [`fmt::Display`],
720+
/// showing invalid UTF-8 as the Unicode replacement character.
721+
#[stable(feature = "cstr_display", since = "CURRENT_RUSTC_VERSION")]
722+
impl fmt::Display for CString {
723+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
724+
fmt::Display::fmt(self.as_c_str(), f)
725+
}
726+
}
727+
719728
#[stable(feature = "cstring_into", since = "1.7.0")]
720729
impl From<CString> for Vec<u8> {
721730
/// Converts a [`CString`] into a <code>[Vec]<[u8]></code>.

library/core/src/ffi/c_str.rs

+9
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,15 @@ impl fmt::Debug for CStr {
168168
}
169169
}
170170

171+
/// Behaves as if `self` were first lossily converted to a `str`, with
172+
/// invalid UTF-8 presented as the Unicode replacement character: �.
173+
#[stable(feature = "cstr_display", since = "CURRENT_RUSTC_VERSION")]
174+
impl fmt::Display for CStr {
175+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176+
fmt::Display::fmt(crate::bstr::ByteStr::from_bytes(self.to_bytes()), f)
177+
}
178+
}
179+
171180
#[stable(feature = "cstr_default", since = "1.10.0")]
172181
impl Default for &CStr {
173182
#[inline]

library/coretests/tests/ffi/cstr.rs

+6
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,9 @@ fn debug() {
1919
let s = c"abc\x01\x02\n\xE2\x80\xA6\xFF";
2020
assert_eq!(format!("{s:?}"), r#""abc\x01\x02\n\xe2\x80\xa6\xff""#);
2121
}
22+
23+
#[test]
24+
fn display() {
25+
let s = c"\xf0\x28\x8c\xbc";
26+
assert_eq!(format!("{s}"), "�(��");
27+
}

0 commit comments

Comments
 (0)