Implemented FromStr for CString and TryFrom for String · qinheping/verify-rust-std@bf40ab2 (original) (raw)

Original file line number Diff line number Diff line change
@@ -7,7 +7,7 @@ use core::borrow::Borrow;
7 7 use core::ffi::{c_char, CStr};
8 8 use core::num::NonZero;
9 9 use core::slice::memchr;
10 -use core::str::{self, Utf8Error};
10 +use core::str::{self, FromStr, Utf8Error};
11 11 use core::{fmt, mem, ops, ptr, slice};
12 12
13 13 use crate::borrow::{Cow, ToOwned};
@@ -815,6 +815,30 @@ impl From<Vec<NonZero>> for CString {
815 815 }
816 816 }
817 817
818 +impl FromStr for CString {
819 +type Err = NulError;
820 +
821 +/// Converts a string `s` into a [`CString`].
822 + ///
823 + /// This method is equivalent to [`CString::new`].
824 + #[inline]
825 +fn from_str(s: &str) -> Result<Self, Self::Err> {
826 +Self::new(s)
827 +}
828 +}
829 +
830 +impl TryFrom<CString> for String {
831 +type Error = IntoStringError;
832 +
833 +/// Converts a [`CString`] into a [`String`] if it contains valid UTF-8 data.
834 + ///
835 + /// This method is equivalent to [`CString::into_string`].
836 + #[inline]
837 +fn try_from(value: CString) -> Result<Self, Self::Error> {
838 + value.into_string()
839 +}
840 +}
841 +
818 842 #[cfg(not(test))]
819 843 #[stable(feature = "more_box_slice_clone", since = "1.29.0")]
820 844 impl Clone for Box<CStr> {