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

Add methods to go from a nul-terminated Vec<u8> to a CString #73139

Merged
merged 7 commits into from
Jun 15, 2020
94 changes: 91 additions & 3 deletions src/libstd/ffi/c_str.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::ascii;
use crate::borrow::{Borrow, Cow};
use crate::cmp::Ordering;
use crate::convert::TryFrom;
use crate::error::Error;
use crate::fmt::{self, Write};
use crate::io;
Expand Down Expand Up @@ -234,15 +235,18 @@ pub struct NulError(usize, Vec<u8>);

/// An error indicating that a nul byte was not in the expected position.
///
/// The slice used to create a [`CStr`] must have one and only one nul
/// byte at the end of the slice.
/// The slice used to create a [`CStr`] or the vector used to create a
/// [`CString`] must have one and only one nul byte, positioned at the end.
///
/// This error is created by the
/// [`from_bytes_with_nul`][`CStr::from_bytes_with_nul`] method on
/// [`CStr`]. See its documentation for more.
/// [`CStr`] or the [`from_vec_with_nul`][`CString::from_vec_with_nul`] method
/// on [`CString`]. See their documentation for more.
///
/// [`CStr`]: struct.CStr.html
/// [`CStr::from_bytes_with_nul`]: struct.CStr.html#method.from_bytes_with_nul
/// [`CString`]: struct.CString.html
/// [`CString::from_vec_with_nul`]: struct.CString.html#method.from_vec_with_nul
///
/// # Examples
///
Expand Down Expand Up @@ -632,6 +636,77 @@ impl CString {
let this = mem::ManuallyDrop::new(self);
unsafe { ptr::read(&this.inner) }
}

/// Converts a `Vec` of `u8` to a `CString` without checking the invariants
/// on the given `Vec`.
///
/// # Safety
///
/// The given `Vec` **must** have one nul byte as its last element.
/// This means it cannot be empty nor have any other nul byte anywhere else.
///
/// # Example
///
/// ```
/// use std::ffi::CString;
/// assert_eq!(
/// unsafe { CString::from_vec_with_nul_unchecked(b"abc\0".to_vec()) },
/// unsafe { CString::from_vec_unchecked(b"abc".to_vec()) }
/// );
/// ```
#[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
pub unsafe fn from_vec_with_nul_unchecked(v: Vec<u8>) -> Self {
Self { inner: v.into_boxed_slice() }
}

/// Attempts to converts a `Vec` of `u8` to a `CString`.
///
/// Runtime checks are present to ensure there is only one nul byte in the
/// `Vec`, its last element.
///
/// # Errors
///
/// If a nul byte is present and not the last element or no nul bytes
/// is present, an error will be returned.
///
/// # Examples
///
/// A successful conversion will produce the same result as [`new`] when
/// called without the ending nul byte.
///
/// ```
/// use std::ffi::CString;
/// assert_eq!(
/// CString::from_vec_with_nul(b"abc\0".to_vec())
/// .expect("CString::from_vec_with_nul failed"),
/// CString::new(b"abc".to_vec())
/// );
/// ```
///
/// A incorrectly formatted vector will produce an error.
///
/// ```
/// use std::ffi::{CString, FromBytesWithNulError};
/// // Interior nul byte
/// let _: FromBytesWithNulError = CString::from_vec_with_nul(b"a\0bc".to_vec()).unwrap_err();
/// // No nul byte
/// let _: FromBytesWithNulError = CString::from_vec_with_nul(b"abc".to_vec()).unwrap_err();
/// ```
///
/// [`new`]: #method.new
#[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
pub fn from_vec_with_nul(v: Vec<u8>) -> Result<Self, FromBytesWithNulError> {
poliorcetics marked this conversation as resolved.
Show resolved Hide resolved
let nul_pos = memchr::memchr(0, &v);
match nul_pos {
Some(nul_pos) if nul_pos + 1 == v.len() => {
poliorcetics marked this conversation as resolved.
Show resolved Hide resolved
// SAFETY: We know there is only one nul byte, at the end
// of the vec.
Ok(unsafe { Self::from_vec_with_nul_unchecked(v) })
}
Some(nul_pos) => Err(FromBytesWithNulError::interior_nul(nul_pos)),
None => Err(FromBytesWithNulError::not_nul_terminated()),
}
}
}

// Turns this `CString` into an empty string to prevent
Expand Down Expand Up @@ -779,6 +854,19 @@ impl From<Vec<NonZeroU8>> for CString {
}
}

#[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
impl TryFrom<Vec<u8>> for CString {
poliorcetics marked this conversation as resolved.
Show resolved Hide resolved
type Error = FromBytesWithNulError;

/// See the document about [`from_vec_with_nul`] for more
/// informations about the behaviour of this method.
///
/// [`from_vec_with_nul`]: CString::from_vec_with_nul
fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
Self::from_vec_with_nul(value)
}
}

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