[PATCH v4 6/7] rust: str: implement `from_bytes_with_nul_mut`

From: Alexandre Courbot
Date: Sun Jun 15 2025 - 23:36:11 EST


Given that `from_bytes_with_nul_unchecked` is paired with
`from_bytes_with_nul`, it looks asymmetric that
`from_bytes_with_nul_unchecked_mut` did not have its faillible safe
counterpart.

To avoid repetition, factorize the `CStr` validity check code into a
private function.

Signed-off-by: Alexandre Courbot <acourbot@xxxxxxxxxx>
---
rust/kernel/str.rs | 37 +++++++++++++++++++++++++++++++------
1 file changed, 31 insertions(+), 6 deletions(-)

diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs
index 28f2f359ab23e6a926e88913e3cc9f481aa86037..21d6f8801ea84686d4aa909fbb52578af96fe2d8 100644
--- a/rust/kernel/str.rs
+++ b/rust/kernel/str.rs
@@ -243,11 +243,13 @@ pub unsafe fn from_char_ptr<'a>(ptr: *const crate::ffi::c_char) -> &'a Self {
unsafe { Self::from_bytes_with_nul_unchecked(bytes) }
}

- /// Creates a [`CStr`] from a `[u8]`.
+ /// Returns `Ok` if `bytes` can safely be interpreted as a [`CStr`].
///
- /// The provided slice must be `NUL`-terminated, does not contain any
- /// interior `NUL` bytes.
- pub const fn from_bytes_with_nul(bytes: &[u8]) -> Result<&Self, CStrConvertError> {
+ /// `bytes` is a valid [`CStr`] if:
+ /// * It is not empty,
+ /// * It is zero-terminated,
+ /// * It does not contain any other zero byte.
+ const fn is_valid_cstr(bytes: &[u8]) -> Result<(), CStrConvertError> {
if bytes.is_empty() {
return Err(CStrConvertError::NotNulTerminated);
}
@@ -263,8 +265,31 @@ pub const fn from_bytes_with_nul(bytes: &[u8]) -> Result<&Self, CStrConvertError
}
i += 1;
}
- // SAFETY: We just checked that all properties hold.
- Ok(unsafe { Self::from_bytes_with_nul_unchecked(bytes) })
+
+ Ok(())
+ }
+
+ /// Creates a [`CStr`] from a `[u8]`.
+ ///
+ /// The provided slice must be `NUL`-terminated, does not contain any
+ /// interior `NUL` bytes.
+ pub const fn from_bytes_with_nul(bytes: &[u8]) -> Result<&Self, CStrConvertError> {
+ match Self::is_valid_cstr(bytes) {
+ // SAFETY: We just checked that all properties hold.
+ Ok(()) => Ok(unsafe { Self::from_bytes_with_nul_unchecked(bytes) }),
+ Err(e) => Err(e),
+ }
+ }
+
+ /// Creates a mutable [`CStr`] from a mutable `[u8]`.
+ ///
+ /// The provided slice must be `NUL`-terminated and not contain any interior `NUL` bytes.
+ pub const fn from_bytes_with_nul_mut(bytes: &mut [u8]) -> Result<&mut Self, CStrConvertError> {
+ match Self::is_valid_cstr(bytes) {
+ // SAFETY: We just checked that all properties hold.
+ Ok(()) => Ok(unsafe { Self::from_bytes_with_nul_unchecked_mut(bytes) }),
+ Err(e) => Err(e),
+ }
}

/// Creates a [`CStr`] from a `[u8]` without performing any additional

--
2.49.0