Skip to content

Commit 947be5f

Browse files
committed
add CStr::display
The implementation delegates to `<ByteStr as Display>::fmt`. Link: rust-lang/libs-team#550 Link: #139984.
1 parent 5af801b commit 947be5f

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

library/core/src/ffi/c_str.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -659,6 +659,30 @@ impl CStr {
659659
// instead of doing it afterwards.
660660
str::from_utf8(self.to_bytes())
661661
}
662+
663+
/// Returns an object that implements [`Display`] for safely printing a [`CStr`] that may
664+
/// contain non-Unicode data.
665+
///
666+
/// Behaves as if `self` were first lossily converted to a `str`, with invalid UTF-8 presented
667+
/// as the Unicode replacement character: �.
668+
///
669+
/// [`Display`]: fmt::Display
670+
///
671+
/// # Examples
672+
///
673+
/// ```
674+
/// #![feature(cstr_display)]
675+
///
676+
/// let cstr = c"Hello, world!";
677+
/// println!("{}", cstr.display());
678+
/// ```
679+
#[unstable(feature = "cstr_display", issue = "139984")]
680+
#[must_use = "this does not display the `CStr`; \
681+
it returns an object that can be displayed"]
682+
#[inline]
683+
pub fn display(&self) -> impl fmt::Display {
684+
crate::bstr::ByteStr::from_bytes(self.to_bytes())
685+
}
662686
}
663687

664688
// `.to_bytes()` representations are compared instead of the inner `[c_char]`s,

library/coretests/tests/ffi/cstr.rs

Lines changed: 6 additions & 0 deletions
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.display()), "�(��");
27+
}

library/coretests/tests/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
#![feature(core_io_borrowed_buf)]
2424
#![feature(core_private_bignum)]
2525
#![feature(core_private_diy_float)]
26+
#![feature(cstr_display)]
2627
#![feature(dec2flt)]
2728
#![feature(duration_constants)]
2829
#![feature(duration_constructors)]

0 commit comments

Comments
 (0)