How to get a '&str' from a NUL-terminated byte slice if the NUL terminator isn't at the end of the slice?

后端 未结 3 1323
心在旅途
心在旅途 2021-01-19 01:02

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

3条回答
  •  抹茶落季
    2021-01-19 01:29

    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])
    }
    

提交回复
热议问题