While CStr
is typically used for FFI, I am reading from a &[u8]
which is NUL-terminated and is ensured to be valid UTF-8 so no checks are neede
I would use iterator adaptors to find the index of the first zero byte:
pub unsafe fn str_from_u8_nul_utf8_unchecked(utf8_src: &[u8]) -> &str {
let nul_range_end = utf8_src.iter()
.position(|&c| c == b'\0')
.unwrap_or(utf8_src.len()); // default to length if no `\0` present
::std::str::from_utf8_unchecked(&utf8_src[0..nul_range_end])
}
This has the major advantage of requiring one to catch all cases (like no 0 in the array).
If you want the version that checks for well-formed UTF-8:
pub fn str_from_u8_nul_utf8(utf8_src: &[u8]) -> Result<&str, std::str::Utf8Error> {
let nul_range_end = utf8_src.iter()
.position(|&c| c == b'\0')
.unwrap_or(utf8_src.len()); // default to length if no `\0` present
::std::str::from_utf8(&utf8_src[0..nul_range_end])
}