File tree Expand file tree Collapse file tree 2 files changed +28
-0
lines changed Expand file tree Collapse file tree 2 files changed +28
-0
lines changed Original file line number Diff line number Diff line change @@ -659,6 +659,28 @@ 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+ /// let cstr = c"Hello, world!";
675+ /// println!("{}", cstr.display());
676+ /// ```
677+ #[ unstable( feature = "cstr_display" , issue = "139984" ) ]
678+ #[ must_use = "this does not display the `CStr`; \
679+ it returns an object that can be displayed"]
680+ #[ inline]
681+ pub fn display ( & self ) -> impl fmt:: Display {
682+ crate :: bstr:: ByteStr :: from_bytes ( self . to_bytes ( ) )
683+ }
662684}
663685
664686// `.to_bytes()` representations are compared instead of the inner `[c_char]`s,
Original file line number Diff line number Diff 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+ }
You can’t perform that action at this time.
0 commit comments