File tree Expand file tree Collapse file tree 3 files changed +31
-0
lines changed Expand file tree Collapse file tree 3 files changed +31
-0
lines changed Original file line number Diff line number Diff line change @@ -632,6 +632,30 @@ impl CStr {
632632 // instead of doing it afterwards.
633633 str:: from_utf8 ( self . to_bytes ( ) )
634634 }
635+
636+ /// Returns an object that implements [`Display`] for safely printing a [`CStr`] that may
637+ /// contain non-Unicode data.
638+ ///
639+ /// Behaves as if `self` were first lossily converted to a `str`, with invalid UTF-8 presented
640+ /// as the Unicode replacement character: �.
641+ ///
642+ /// [`Display`]: fmt::Display
643+ ///
644+ /// # Examples
645+ ///
646+ /// ```
647+ /// #![feature(cstr_display)]
648+ ///
649+ /// let cstr = c"Hello, world!";
650+ /// println!("{}", cstr.display());
651+ /// ```
652+ #[ unstable( feature = "cstr_display" , issue = "139984" ) ]
653+ #[ must_use = "this does not display the `CStr`; \
654+ it returns an object that can be displayed"]
655+ #[ inline]
656+ pub fn display ( & self ) -> impl fmt:: Display {
657+ crate :: bstr:: ByteStr :: from_bytes ( self . to_bytes ( ) )
658+ }
635659}
636660
637661// `.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+ }
Original file line number Diff line number Diff line change 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) ]
You can’t perform that action at this time.
0 commit comments