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
This example finds the first NUL byte using a simple for loop, then uses Rust's standard library to return the slice as a &str (referencing the original data - zero copy).
There may well be a better way to find the first NUL byte using closures:
pub unsafe fn str_from_u8_nul_utf8_unchecked(utf8_src: &[u8]) -> &str {
// does Rust have a built-in 'memchr' equivalent?
let mut nul_range_end = 1_usize;
for b in utf8_src {
if *b == 0 {
break;
}
nul_range_end += 1;
}
return ::std::str::from_utf8_unchecked(&utf8_src[0..nul_range_end]);
}
While utf8_src.iter().position(|&c| c == b'\0').unwrap_or(utf8_src.len()); returns the first NUL byte (or the total length), Rust 1.15 does not optimize it into something like memchr, so a for loop might not be such a bad option for now.