@@ -659,8 +659,8 @@ impl CStr {
659659 #[ must_use = "this does not display the `CStr`; \
660660 it returns an object that can be displayed"]
661661 #[ inline]
662- pub fn display ( & self ) -> impl fmt :: Display {
663- crate :: bstr :: ByteStr :: from_bytes ( self . to_bytes ( ) )
662+ pub fn display ( & self ) -> Display < ' _ > {
663+ Display { c_str : self }
664664 }
665665
666666 /// Returns the same string as a string slice `&CStr`.
@@ -858,3 +858,41 @@ impl Iterator for Bytes<'_> {
858858
859859#[ unstable( feature = "cstr_bytes" , issue = "112115" ) ]
860860impl FusedIterator for Bytes < ' _ > { }
861+
862+ /// Helper struct for safely printing a [`CStr`] with [`format!`] and `{}`.
863+ ///
864+ /// A [`CStr`] might contain non-Unicode data. This `struct` implements the
865+ /// [`Display`] trait in a way that mitigates that. It is created by the
866+ /// [`display`](CStr::display) method on [`CStr`]. This may perform lossy
867+ /// conversion, depending on the platform. If you would like an implementation
868+ /// which escapes the [`CStr`] please use [`Debug`] instead.
869+ ///
870+ /// # Examples
871+ ///
872+ /// ```
873+ /// #![feature(cstr_display)]
874+ ///
875+ /// let s = c"Hello, world!";
876+ /// println!("{}", s.display());
877+ /// ```
878+ ///
879+ /// [`Display`]: fmt::Display
880+ /// [`format!`]: ../../../std/macro.format.html
881+ #[ unstable( feature = "cstr_display" , issue = "139984" ) ]
882+ pub struct Display < ' a > {
883+ c_str : & ' a CStr ,
884+ }
885+
886+ #[ unstable( feature = "cstr_display" , issue = "139984" ) ]
887+ impl fmt:: Debug for Display < ' _ > {
888+ fn fmt ( & self , f : & mut fmt:: Formatter < ' _ > ) -> fmt:: Result {
889+ fmt:: Debug :: fmt ( & self . c_str , f)
890+ }
891+ }
892+
893+ #[ unstable( feature = "cstr_display" , issue = "139984" ) ]
894+ impl fmt:: Display for Display < ' _ > {
895+ fn fmt ( & self , f : & mut fmt:: Formatter < ' _ > ) -> fmt:: Result {
896+ fmt:: Display :: fmt ( crate :: bstr:: ByteStr :: from_bytes ( self . c_str . to_bytes ( ) ) , f)
897+ }
898+ }
0 commit comments