`&CStr` from `&[c_char]`, safely

I am wondering if it would make sense and if it would be sound to have the following API:

impl CStr {
    pub fn from_c_char_with_nul(data: &[std::os::raw::c_char]) -> Result<&CStr, FromCCharWithNulError>;
}

The reason behind this is that AFAIK there is not a zero cost, safe way to convert &[c_char] into &[u8]. CStr::from_ptr (which is unsafe) casts a *const c_char into *const u8 in order to recreate a slice. CStr::to_bytes_with_nul performs the same operation as well, therefore I think the conversion should be fine.

Am I missing a completely safe way of doing the same thing without any cost? Do you think that it is a valuable API that we should have?

1 Like

Sure. Converting from c_char to u8 is sound, so combining that with from_bytes_with_nul would not be an issue.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.