From 79e05430600dca42571ba38703af2969bab48760 Mon Sep 17 00:00:00 2001 From: Jubilee Young Date: Tue, 26 Jul 2022 13:26:05 -0700 Subject: [PATCH 1/2] Use String::from_utf8_lossy in CStr demo --- library/core/src/ffi/c_str.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/core/src/ffi/c_str.rs b/library/core/src/ffi/c_str.rs index ee9baf811e29c..1deb41593d97b 100644 --- a/library/core/src/ffi/c_str.rs +++ b/library/core/src/ffi/c_str.rs @@ -66,7 +66,7 @@ use crate::str; /// /// fn my_string_safe() -> String { /// unsafe { -/// CStr::from_ptr(my_string()).to_string_lossy().into_owned() +/// String::from_utf8_lossy(CStr::from_ptr(my_string())) /// } /// } /// From d48a869b9db1196214e19d1330cb290fc8543683 Mon Sep 17 00:00:00 2001 From: Jubilee Young Date: Tue, 26 Jul 2022 14:10:26 -0700 Subject: [PATCH 2/2] Force the Cow into a String --- library/core/src/ffi/c_str.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/library/core/src/ffi/c_str.rs b/library/core/src/ffi/c_str.rs index 1deb41593d97b..59066a33c965e 100644 --- a/library/core/src/ffi/c_str.rs +++ b/library/core/src/ffi/c_str.rs @@ -65,9 +65,9 @@ use crate::str; /// extern "C" { fn my_string() -> *const c_char; } /// /// fn my_string_safe() -> String { -/// unsafe { -/// String::from_utf8_lossy(CStr::from_ptr(my_string())) -/// } +/// let cstr = unsafe { CStr::from_ptr(my_string()) }; +/// // Get copy-on-write Cow<'_, str>, then guarantee a freshly-owned String allocation +/// String::from_utf8_lossy(cstr.to_bytes()).to_string() /// } /// /// println!("string: {}", my_string_safe());