- 
                Notifications
    You must be signed in to change notification settings 
- Fork 13.9k
Description
The feature gate for the issue is #![feature(cstring_from_vec_with_nul)].
This adds the following method to CString:
pub unsafe fn from_vec_with_nul_unchecked(v: Vec<u8>) -> Self { /* ... */ }
pub fn from_vec_with_nul(v: Vec<u8>) -> Result<Self, FromVecWithNulError> { /* ... */ }FromVecWithNulError is a new error type, following the naming pattern of FromBytesWithNulError already existing for CStr::new.
This type, defined as:
#[derive(Clone, PartialEq, Eq, Debug)]
#[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
pub struct FromVecWithNulError {
    error_kind: FromBytesWithNulErrorKind,
    bytes: Vec<u8>,
}It is inspired from the FromUtf8Error type (having as_bytes and into_bytes method) that allows recuperating the input when conversion failed.
The fmt:Display implementation for the type uses the same text as the FromBytesWithNulError, without using the deprecated description method of the Error trait.
#[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")]
impl fmt::Display for FromVecWithNulError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.error_kind {
            FromBytesWithNulErrorKind::InteriorNul(pos) => {
                write!(f, "data provided contains an interior nul byte at pos {}", pos)
            }
            FromBytesWithNulErrorKind::NotNulTerminated => {
                write!(f, "data provided is not nul terminated")
            }
        }
    }
}Unresolved Questions
- Is this feature needed ? It was asked for issue Creating CString from nul-terminated data #73100 and CStr::from_bytes_with_nul(and itsuncheckedversion) seems to indicates that having an owned version would be logical.
- Names ? I just changed bytestovecin the names (CStr::from_bytes_with_nul->CString::from_vec_with_nulandCStr::from_bytes_with_nul_unchecked->CString::from_vec_with_nul_unchecked).
- Input type for the safe version: I used Vec<u8>but I seeCString::newusesInto<Vec<u8>>, should I use that too ?
Implementation history
PR #73139 implements this at the moment, in a unstable form, with documentation and doc tests.
PR #89292 by @CleanCut proposes to stabilize this 🥳
Edit: this being the first time I write a tracking issue, please do not hesitate to tell me if there is something to fix.