rust-for-linux.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
From: Alexandre Courbot <acourbot@nvidia.com>
To: "Danilo Krummrich" <dakr@kernel.org>,
	"Miguel Ojeda" <ojeda@kernel.org>,
	"Alex Gaynor" <alex.gaynor@gmail.com>,
	"Boqun Feng" <boqun.feng@gmail.com>,
	"Gary Guo" <gary@garyguo.net>,
	"Björn Roy Baron" <bjorn3_gh@protonmail.com>,
	"Benno Lossin" <lossin@kernel.org>,
	"Andreas Hindborg" <a.hindborg@kernel.org>,
	"Alice Ryhl" <aliceryhl@google.com>,
	"Trevor Gross" <tmgross@umich.edu>
Cc: rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org,
	 Alexandre Courbot <acourbot@nvidia.com>
Subject: [PATCH v4 6/7] rust: str: implement `from_bytes_with_nul_mut`
Date: Mon, 16 Jun 2025 12:34:10 +0900	[thread overview]
Message-ID: <20250616-borrow_impls-v4-6-36f9beb3fe6a@nvidia.com> (raw)
In-Reply-To: <20250616-borrow_impls-v4-0-36f9beb3fe6a@nvidia.com>

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@nvidia.com>
---
 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


  parent reply	other threads:[~2025-06-16  3:35 UTC|newest]

Thread overview: 14+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2025-06-16  3:34 [PATCH v4 0/7] rust: a few common Borrow/BorrowMut implementations Alexandre Courbot
2025-06-16  3:34 ` [PATCH v4 1/7] rust: alloc: implement `Borrow` and `BorrowMut` for `Vec` Alexandre Courbot
2025-06-18 21:45   ` Danilo Krummrich
2025-06-16  3:34 ` [PATCH v4 2/7] rust: sync: implement `Borrow` and `BorrowMut` for `Arc` types Alexandre Courbot
2025-06-29 19:31   ` Miguel Ojeda
2025-06-16  3:34 ` [PATCH v4 3/7] rust: alloc: implement `Borrow` and `BorrowMut` for `KBox` Alexandre Courbot
2025-06-18 21:46   ` Danilo Krummrich
2025-06-16  3:34 ` [PATCH v4 4/7] rust: str: make `from_bytes_with_nul_unchecked_mut` const Alexandre Courbot
2025-06-18 21:08   ` Benno Lossin
2025-06-18 21:16   ` Benno Lossin
2025-06-19  2:32     ` Alexandre Courbot
2025-06-16  3:34 ` [PATCH v4 5/7] rust: str: use transmute in `from_bytes_with_nul_unchecked_mut` Alexandre Courbot
2025-06-16  3:34 ` Alexandre Courbot [this message]
2025-06-16  3:34 ` [PATCH v4 7/7] rust: str: implement `Borrow` and `BorrowMut` for `CString` Alexandre Courbot

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20250616-borrow_impls-v4-6-36f9beb3fe6a@nvidia.com \
    --to=acourbot@nvidia.com \
    --cc=a.hindborg@kernel.org \
    --cc=alex.gaynor@gmail.com \
    --cc=aliceryhl@google.com \
    --cc=bjorn3_gh@protonmail.com \
    --cc=boqun.feng@gmail.com \
    --cc=dakr@kernel.org \
    --cc=gary@garyguo.net \
    --cc=linux-kernel@vger.kernel.org \
    --cc=lossin@kernel.org \
    --cc=ojeda@kernel.org \
    --cc=rust-for-linux@vger.kernel.org \
    --cc=tmgross@umich.edu \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).