]> git.lizzy.rs Git - rust.git/blobdiff - src/libstd/ffi/c_str.rs
Auto merge of #29140 - sorear:dst-document-on-sized, r=alexcrichton
[rust.git] / src / libstd / ffi / c_str.rs
index 23daa87401a45641b712ee916dde9d945d881b2e..89427f7851b389cbbb54599eac953a82e21e6623 100644 (file)
@@ -23,7 +23,7 @@
 use option::Option::{self, Some, None};
 use result::Result::{self, Ok, Err};
 use slice;
-use str;
+use str::{self, Utf8Error};
 use string::String;
 use vec::Vec;
 
@@ -119,7 +119,7 @@ pub struct CString {
 /// Converting a foreign C string into a Rust `String`
 ///
 /// ```no_run
-/// # #![feature(libc,cstr_to_str)]
+/// # #![feature(libc)]
 /// extern crate libc;
 /// use std::ffi::CStr;
 ///
@@ -151,6 +151,15 @@ pub struct CStr {
 #[stable(feature = "rust1", since = "1.0.0")]
 pub struct NulError(usize, Vec<u8>);
 
+/// An error returned from `CString::into_string` to indicate that a UTF-8 error
+/// was encountered during the conversion.
+#[derive(Clone, PartialEq, Debug)]
+#[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
+pub struct IntoStringError {
+    inner: CString,
+    error: Utf8Error,
+}
+
 impl CString {
     /// Creates a new C-compatible string from a container of bytes.
     ///
@@ -181,7 +190,10 @@ impl CString {
     /// the position of the nul byte.
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> {
-        let bytes = t.into();
+        Self::_new(t.into())
+    }
+
+    fn _new(bytes: Vec<u8>) -> Result<CString, NulError> {
         match bytes.iter().position(|x| *x == 0) {
             Some(i) => Err(NulError(i, bytes)),
             None => Ok(unsafe { CString::from_vec_unchecked(bytes) }),
@@ -203,13 +215,13 @@ pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString {
     /// Retakes ownership of a CString that was transferred to C.
     ///
     /// The only appropriate argument is a pointer obtained by calling
-    /// `into_ptr`. The length of the string will be recalculated
+    /// `into_raw`. The length of the string will be recalculated
     /// using the pointer.
-    #[unstable(feature = "cstr_memory", reason = "recently added",
+    #[unstable(feature = "cstr_memory2", reason = "recently added",
                issue = "27769")]
     #[deprecated(since = "1.4.0", reason = "renamed to from_raw")]
     pub unsafe fn from_ptr(ptr: *const libc::c_char) -> CString {
-        CString::from_raw(ptr)
+        CString::from_raw(ptr as *mut _)
     }
 
     /// Retakes ownership of a CString that was transferred to C.
@@ -217,9 +229,8 @@ pub unsafe fn from_ptr(ptr: *const libc::c_char) -> CString {
     /// The only appropriate argument is a pointer obtained by calling
     /// `into_raw`. The length of the string will be recalculated
     /// using the pointer.
-    #[unstable(feature = "cstr_memory", reason = "recently added",
-               issue = "27769")]
-    pub unsafe fn from_raw(ptr: *const libc::c_char) -> CString {
+    #[stable(feature = "cstr_memory", since = "1.4.0")]
+    pub unsafe fn from_raw(ptr: *mut libc::c_char) -> CString {
         let len = libc::strlen(ptr) + 1; // Including the NUL byte
         let slice = slice::from_raw_parts(ptr, len as usize);
         CString { inner: mem::transmute(slice) }
@@ -233,28 +244,56 @@ pub unsafe fn from_raw(ptr: *const libc::c_char) -> CString {
     /// this string.
     ///
     /// Failure to call `from_raw` will lead to a memory leak.
-    #[unstable(feature = "cstr_memory", reason = "recently added",
+    #[unstable(feature = "cstr_memory2", reason = "recently added",
                issue = "27769")]
     #[deprecated(since = "1.4.0", reason = "renamed to into_raw")]
     pub fn into_ptr(self) -> *const libc::c_char {
-        self.into_raw()
+        self.into_raw() as *const _
     }
 
     /// Transfers ownership of the string to a C caller.
     ///
     /// The pointer must be returned to Rust and reconstituted using
-    /// `from_ptr` to be properly deallocated. Specifically, one
+    /// `from_raw` to be properly deallocated. Specifically, one
     /// should *not* use the standard C `free` function to deallocate
     /// this string.
     ///
-    /// Failure to call `from_ptr` will lead to a memory leak.
-    #[unstable(feature = "cstr_memory", reason = "recently added",
-               issue = "27769")]
-    pub fn into_raw(self) -> *const libc::c_char {
-        // It is important that the bytes be sized to fit - we need
-        // the capacity to be determinable from the string length, and
-        // shrinking to fit is the only way to be sure.
-        Box::into_raw(self.inner) as *const libc::c_char
+    /// Failure to call `from_raw` will lead to a memory leak.
+    #[stable(feature = "cstr_memory", since = "1.4.0")]
+    pub fn into_raw(self) -> *mut libc::c_char {
+        Box::into_raw(self.inner) as *mut libc::c_char
+    }
+
+    /// Converts the `CString` into a `String` if it contains valid Unicode data.
+    ///
+    /// On failure, ownership of the original `CString` is returned.
+    #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
+    pub fn into_string(self) -> Result<String, IntoStringError> {
+        String::from_utf8(self.into_bytes())
+            .map_err(|e| IntoStringError {
+                error: e.utf8_error(),
+                inner: unsafe { CString::from_vec_unchecked(e.into_bytes()) },
+            })
+    }
+
+    /// Returns the underlying byte buffer.
+    ///
+    /// The returned buffer does **not** contain the trailing nul separator and
+    /// it is guaranteed to not have any interior nul bytes.
+    #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
+    pub fn into_bytes(self) -> Vec<u8> {
+        // FIXME: Once this method becomes stable, add an `impl Into<Vec<u8>> for CString`
+        let mut vec = self.inner.into_vec();
+        let _nul = vec.pop();
+        debug_assert_eq!(_nul, Some(0u8));
+        vec
+    }
+
+    /// Equivalent to the `into_bytes` function except that the returned vector
+    /// includes the trailing nul byte.
+    #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
+    pub fn into_bytes_with_nul(self) -> Vec<u8> {
+        self.inner.into_vec()
     }
 
     /// Returns the contents of this `CString` as a slice of bytes.
@@ -338,6 +377,35 @@ fn from(_: NulError) -> io::Error {
     }
 }
 
+impl IntoStringError {
+    /// Consumes this error, returning original `CString` which generated the
+    /// error.
+    #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
+    pub fn into_cstring(self) -> CString {
+        self.inner
+    }
+
+    /// Access the underlying UTF-8 error that was the cause of this error.
+    #[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
+    pub fn utf8_error(&self) -> Utf8Error {
+        self.error
+    }
+}
+
+#[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
+impl Error for IntoStringError {
+    fn description(&self) -> &str {
+        Error::description(&self.error)
+    }
+}
+
+#[unstable(feature = "cstring_into", reason = "recently added", issue = "29157")]
+impl fmt::Display for IntoStringError {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        fmt::Display::fmt(&self.error, f)
+    }
+}
+
 impl CStr {
     /// Casts a raw C string to a safe C string wrapper.
     ///
@@ -432,8 +500,7 @@ pub fn to_bytes_with_nul(&self) -> &[u8] {
     /// > after a 0-cost cast, but it is planned to alter its definition in the
     /// > future to perform the length calculation in addition to the UTF-8
     /// > check whenever this method is called.
-    #[unstable(feature = "cstr_to_str", reason = "recently added",
-               issue = "27764")]
+    #[stable(feature = "cstr_to_str", since = "1.4.0")]
     pub fn to_str(&self) -> Result<&str, str::Utf8Error> {
         // NB: When CStr is changed to perform the length check in .to_bytes()
         // instead of in from_ptr(), it may be worth considering if this should
@@ -453,8 +520,7 @@ pub fn to_str(&self) -> Result<&str, str::Utf8Error> {
     /// > after a 0-cost cast, but it is planned to alter its definition in the
     /// > future to perform the length calculation in addition to the UTF-8
     /// > check whenever this method is called.
-    #[unstable(feature = "cstr_to_str", reason = "recently added",
-               issue = "27764")]
+    #[stable(feature = "cstr_to_str", since = "1.4.0")]
     pub fn to_string_lossy(&self) -> Cow<str> {
         String::from_utf8_lossy(self.to_bytes())
     }