From: Sami Daniel <samidanielpersonal@gmail.com>
To: ojeda@kernel.org
Cc: alex.gaynor@gmail.com, rust-for-linux@vger.kernel.org,
linux-kernel@vger.kernel.org,
Sami Daniel <samidanielpersonal@gmail.com>
Subject: [PATCH] rust: Improve CStr UTF-8 conversion methods
Date: Fri, 22 Aug 2025 17:57:13 -0300 [thread overview]
Message-ID: <20250822205715.83437-1-samidanielpersonal@gmail.com> (raw)
Add safe conversion from CStr to &str with UTF-8 validation.
- Returns Result<&str, Utf8Error> for safe conversion
- Complements existing str methods on str.rs
Signed-off-by: Sami Daniel <samidanielpersonal@gmail.com>
---
rust/kernel/str.rs | 72 ++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 72 insertions(+)
diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs
index 6c892550c0ba..ef94a0b2acf7 100644
--- a/rust/kernel/str.rs
+++ b/rust/kernel/str.rs
@@ -384,6 +384,34 @@ pub unsafe fn as_str_unchecked(&self) -> &str {
unsafe { core::str::from_utf8_unchecked(self.as_bytes()) }
}
+ /// Convert this [`CStr`] into a [`&str`], checking for valid UTF-8.
+ ///
+ /// This function validates that the [`CStr`] contains valid UTF-8 data
+ /// and returns the corresponding [`&str`] slice. If the contents are not
+ /// valid UTF-8, it returns an error.
+ ///
+ /// This is the safe alternative to [`as_str_unchecked`].
+ ///
+ /// [`as_str_unchecked`]: #method.as_str_unchecked
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// # use kernel::c_str;
+ /// # use kernel::str::CStr;
+ /// let valid_utf8 = c_str!("ツ");
+ /// assert_eq!(valid_utf8.as_str().unwrap(), "ツ");
+ ///
+ /// // This would fail for invalid UTF-8
+ /// let bytes = b"\xc3\x28\0";
+ /// let invalid_cstr = CStr::from_bytes_with_nul(bytes).unwrap();
+ /// assert!(invalid_cstr.as_str().is_err());
+ /// ```
+ #[inline]
+ pub fn as_str(&self) -> Result<&str, core::str::Utf8Error> {
+ core::str::from_utf8(self.as_bytes())
+ }
+
/// Convert this [`CStr`] into a [`CString`] by allocating memory and
/// copying over the string data.
pub fn to_cstring(&self) -> Result<CString, AllocError> {
@@ -654,6 +682,50 @@ fn test_cstr_as_str_unchecked() -> Result {
Ok(())
}
+ #[test]
+ fn test_cstr_as_str_valid_utf8() -> Result {
+ let valid_bytes = b"\xf0\x9f\xa6\x80\0";
+ let cstr = CStr::from_bytes_with_nul(valid_bytes)?;
+ let result = cstr.as_str();
+ assert!(result.is_ok());
+ assert_eq!(result.unwrap(), "🦀");
+
+ let ascii_bytes = b"hello, world!\0";
+ let ascii_cstr = CStr::from_bytes_with_nul(ascii_bytes)?;
+ let ascii_result = ascii_cstr.as_str();
+ assert!(ascii_result.is_ok());
+ assert_eq!(ascii_result.unwrap(), "hello, world!");
+
+ let empty_bytes = b"\0";
+ let empty_cstr = CStr::from_bytes_with_nul(empty_bytes)?;
+ let empty_result = empty_cstr.as_str();
+ assert!(empty_result.is_ok());
+ assert_eq!(empty_result.unwrap(), "");
+
+ Ok(())
+ }
+
+ #[test]
+ fn test_cstr_as_str_invalid_utf8() -> Result {
+ let bad_bytes = b"\xc3\x28\0";
+ let bad_cstr = CStr::from_bytes_with_nul(bad_bytes)?;
+ let result = bad_cstr.as_str();
+ assert!(result.is_err());
+
+ let bad_bytes2 = b"\xf0\x28\x8c\x28\0";
+ let bad_cstr2 = CStr::from_bytes_with_nul(bad_bytes2)?;
+ let result2 = bad_cstr2.as_str();
+ assert!(result2.is_err());
+
+ // Test with incomplete UTF-8 sequence
+ let incomplete_bytes = b"\xf0\x9f\0";
+ let incomplete_cstr = CStr::from_bytes_with_nul(incomplete_bytes)?;
+ let incomplete_result = incomplete_cstr.as_str();
+ assert!(incomplete_result.is_err());
+
+ Ok(())
+ }
+
#[test]
fn test_cstr_display() -> Result {
let hello_world = CStr::from_bytes_with_nul(b"hello, world!\0")?;
--
2.50.1
next reply other threads:[~2025-08-22 20:57 UTC|newest]
Thread overview: 3+ messages / expand[flat|nested] mbox.gz Atom feed top
2025-08-22 20:57 Sami Daniel [this message]
2025-08-22 21:32 ` [PATCH] rust: Improve CStr UTF-8 conversion methods Miguel Ojeda
2025-08-22 21:34 ` Miguel Ojeda
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=20250822205715.83437-1-samidanielpersonal@gmail.com \
--to=samidanielpersonal@gmail.com \
--cc=alex.gaynor@gmail.com \
--cc=linux-kernel@vger.kernel.org \
--cc=ojeda@kernel.org \
--cc=rust-for-linux@vger.kernel.org \
/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