Skip to content

Commit

Permalink
Rollup merge of #130608 - YohDeadfall:cstr-from-into-str, r=workingju…
Browse files Browse the repository at this point in the history
…bilee

Implemented `FromStr` for `CString` and `TryFrom<CString>` for `String`

The motivation of this change is making it possible to use `CString` in generic methods with `FromStr` and `TryInto<String>` trait bounds. The same traits are already implemented for `OsString` which is an FFI type too.
  • Loading branch information
matthiaskrgr authored Oct 15, 2024
2 parents 9322d18 + 3025513 commit 3a00d35
Showing 1 changed file with 25 additions and 1 deletion.
26 changes: 25 additions & 1 deletion library/alloc/src/ffi/c_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use core::borrow::Borrow;
use core::ffi::{CStr, c_char};
use core::num::NonZero;
use core::slice::memchr;
use core::str::{self, Utf8Error};
use core::str::{self, FromStr, Utf8Error};
use core::{fmt, mem, ops, ptr, slice};

use crate::borrow::{Cow, ToOwned};
Expand Down Expand Up @@ -817,6 +817,30 @@ impl From<Vec<NonZero<u8>>> for CString {
}
}

impl FromStr for CString {
type Err = NulError;

/// Converts a string `s` into a [`CString`].
///
/// This method is equivalent to [`CString::new`].
#[inline]
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::new(s)
}
}

impl TryFrom<CString> for String {
type Error = IntoStringError;

/// Converts a [`CString`] into a [`String`] if it contains valid UTF-8 data.
///
/// This method is equivalent to [`CString::into_string`].
#[inline]
fn try_from(value: CString) -> Result<Self, Self::Error> {
value.into_string()
}
}

#[cfg(not(test))]
#[stable(feature = "more_box_slice_clone", since = "1.29.0")]
impl Clone for Box<CStr> {
Expand Down

0 comments on commit 3a00d35

Please sign in to comment.