Skip to content

Commit bf40ab2

Browse files
committed
Implemented FromStr for CString and TryFrom<CString> for String
1 parent 03ff0df commit bf40ab2

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

alloc/src/ffi/c_str.rs

+25-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use core::borrow::Borrow;
77
use core::ffi::{c_char, CStr};
88
use core::num::NonZero;
99
use core::slice::memchr;
10-
use core::str::{self, Utf8Error};
10+
use core::str::{self, FromStr, Utf8Error};
1111
use core::{fmt, mem, ops, ptr, slice};
1212

1313
use crate::borrow::{Cow, ToOwned};
@@ -815,6 +815,30 @@ impl From<Vec<NonZero<u8>>> for CString {
815815
}
816816
}
817817

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+
818842
#[cfg(not(test))]
819843
#[stable(feature = "more_box_slice_clone", since = "1.29.0")]
820844
impl Clone for Box<CStr> {

0 commit comments

Comments
 (0)