Linux kernel mirror (for testing)
git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel
os
linux
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.
8pub(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}