Skip to content

Creating CString from nul-terminated data #73100

Closed
@r4v3n6101

Description

@r4v3n6101

It seems there's no idiomatic way to create CString from nul-terminated Vec<u8>. The only approriate way is to pop() last nul and then from_vec_unchecked will append a new one. Need the method just passes data as is (e.g. CString::from_vec_with_nul such as CStr::from_bytes_with_nul).
Possibly, code should be like:

pub unsafe fn from_vec_with_nul_unchecked(v: Vec<u8>) -> CString {
    CString { inner: v.into_boxed_slice() }
}

and safe version:

pub fn from_vec_with_nul(v: Vec<u8>) -> Result<CString, FromBytesWithNulError> {
    let nul_pos = memchr::memchr(0, bytes);
    match nul_pos {
        Some(nul_pos) if nul_pos + 1 == v.len() => Ok(unsafe { CString::from_vec_with_nul_unchecked(v) }),
        Some(nul_pos) => Err(FromBytesWithNulError::interior_nul(nul_pos)),
        None => Err(FromBytesWithNulError::not_nul_terminated()),
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-FFIArea: Foreign function interface (FFI)C-feature-requestCategory: A feature request, i.e: not implemented / a PR.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions