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()),
}
}
It seems there's no idiomatic way to create
CStringfrom nul-terminatedVec<u8>. The only approriate way is topop()last nul and thenfrom_vec_uncheckedwill append a new one. Need the method just passes data as is (e.g.CString::from_vec_with_nulsuch asCStr::from_bytes_with_nul).Possibly, code should be like:
and safe version: