Skip to content

Commit 1eefda6

Browse files
committed
Add TryFrom impls for CString and CStr
Conversions: - Vec<u8> to CString - CString to String - &[u8] to &CStr
1 parent b9b82fd commit 1eefda6

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

src/libstd/ffi/c_str.rs

+28
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
use ascii;
1212
use borrow::{Cow, Borrow};
1313
use cmp::Ordering;
14+
use convert::TryFrom;
1415
use error::Error;
1516
use fmt::{self, Write};
1617
use io;
@@ -646,6 +647,24 @@ impl From<CString> for Vec<u8> {
646647
}
647648
}
648649

650+
#[unstable(feature = "try_from", issue = "33417")]
651+
impl TryFrom<Vec<u8>> for CString {
652+
type Error = NulError;
653+
654+
fn try_from(bytes: Vec<u8>) -> Result<CString, NulError> {
655+
CString::_new(bytes)
656+
}
657+
}
658+
659+
#[unstable(feature = "try_from", issue = "33417")]
660+
impl TryFrom<CString> for String {
661+
type Error = IntoStringError;
662+
663+
fn try_from(c_str: CString) -> Result<String, IntoStringError> {
664+
c_str.into_string()
665+
}
666+
}
667+
649668
#[stable(feature = "cstr_debug", since = "1.3.0")]
650669
impl fmt::Debug for CStr {
651670
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
@@ -657,6 +676,15 @@ impl fmt::Debug for CStr {
657676
}
658677
}
659678

679+
#[unstable(feature = "try_from", issue = "33417")]
680+
impl<'a> TryFrom<&'a [u8]> for &'a CStr {
681+
type Error = FromBytesWithNulError;
682+
683+
fn try_from(bytes: &[u8]) -> Result<&CStr, FromBytesWithNulError> {
684+
CStr::from_bytes_with_nul(bytes)
685+
}
686+
}
687+
660688
#[stable(feature = "cstr_default", since = "1.10.0")]
661689
impl<'a> Default for &'a CStr {
662690
fn default() -> &'a CStr {

0 commit comments

Comments
 (0)