Skip to content

Commit 82ba871

Browse files
committed
Add doc example for CStr::to_string_lossy.
1 parent 5d71e8c commit 82ba871

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

src/libstd/ffi/c_str.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -893,6 +893,31 @@ impl CStr {
893893
///
894894
/// [`Cow`]: ../borrow/enum.Cow.html
895895
/// [`str`]: ../primitive.str.html
896+
///
897+
/// # Examples
898+
///
899+
/// Calling `to_string_lossy` on a `CStr` containing valid UTF-8:
900+
///
901+
/// ```
902+
/// use std::borrow::Cow;
903+
/// use std::ffi::CStr;
904+
///
905+
/// let c_str = CStr::from_bytes_with_nul(b"Hello World\0").unwrap();
906+
/// assert_eq!(c_str.to_string_lossy(), Cow::Borrowed("Hello World"));
907+
/// ```
908+
///
909+
/// Calling `to_string_lossy` on a `CStr` containing invalid UTF-8:
910+
///
911+
/// ```
912+
/// use std::borrow::Cow;
913+
/// use std::ffi::CStr;
914+
///
915+
/// let c_str = CStr::from_bytes_with_nul(b"Hello \xF0\x90\x80World\0").unwrap();
916+
/// assert_eq!(
917+
/// c_str.to_string_lossy(),
918+
/// Cow::Owned(String::from("Hello �World")) as Cow<str>
919+
/// );
920+
/// ```
896921
#[stable(feature = "cstr_to_str", since = "1.4.0")]
897922
pub fn to_string_lossy(&self) -> Cow<str> {
898923
String::from_utf8_lossy(self.to_bytes())

0 commit comments

Comments
 (0)