Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implemented FromStr for CString and TryFrom<CString> for String #130608

Merged
merged 1 commit into from
Oct 15, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Implemented FromStr for CString and TryFrom<CString> for String
  • Loading branch information
YohDeadfall committed Oct 1, 2024
commit 302551388b1942bb4216bb5a15d9d55cee3643a8
26 changes: 25 additions & 1 deletion library/alloc/src/ffi/c_str.rs
Original file line number Diff line number Diff line change
@@ -7,7 +7,7 @@ use core::borrow::Borrow;
use core::ffi::{c_char, CStr};
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};
@@ -815,6 +815,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)
}
Comment on lines +824 to +827
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It might be good to explicitly document that this does not require a terminating NUL in the input, maybe something like

Suggested change
#[inline]
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::new(s)
}
/// Creates a new C-compatible string from a `&str`.
///
/// The trailing 0 byte will be appended by this function. If the provided data
/// contains any 0 bytes in it, `Err(NulError)` will be returned.
#[inline]
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::new(s)
}

or maybe just link to the docs for CString::new.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a short description with a link to the corresponding function, and also did the same for the backward conversion.

}

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> {
Loading