xref: /linux/drivers/gpu/nova-core/util.rs (revision 6dfafbd0299a60bfb5d5e277fdf100037c7ded07)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 /// Converts a null-terminated byte slice to a string, or `None` if the array does not
4 /// contains any null byte or contains invalid characters.
5 ///
6 /// Contrary to [`kernel::str::CStr::from_bytes_with_nul`], the null byte can be anywhere in the
7 /// slice, and not only in the last position.
8 pub(crate) fn str_from_null_terminated(bytes: &[u8]) -> Option<&str> {
9     use kernel::str::CStr;
10 
11     bytes
12         .iter()
13         .position(|&b| b == 0)
14         .and_then(|null_pos| CStr::from_bytes_with_nul(&bytes[..=null_pos]).ok())
15         .and_then(|cstr| cstr.to_str().ok())
16 }
17