* [PATCH] rust: Improve CStr UTF-8 conversion methods
@ 2025-08-22 20:57 Sami Daniel
2025-08-22 21:32 ` Miguel Ojeda
2025-08-22 21:34 ` Miguel Ojeda
0 siblings, 2 replies; 3+ messages in thread
From: Sami Daniel @ 2025-08-22 20:57 UTC (permalink / raw)
To: ojeda; +Cc: alex.gaynor, rust-for-linux, linux-kernel, Sami Daniel
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
^ permalink raw reply related [flat|nested] 3+ messages in thread
* Re: [PATCH] rust: Improve CStr UTF-8 conversion methods
2025-08-22 20:57 [PATCH] rust: Improve CStr UTF-8 conversion methods Sami Daniel
@ 2025-08-22 21:32 ` Miguel Ojeda
2025-08-22 21:34 ` Miguel Ojeda
1 sibling, 0 replies; 3+ messages in thread
From: Miguel Ojeda @ 2025-08-22 21:32 UTC (permalink / raw)
To: samidanielpersonal; +Cc: ojeda, alex.gaynor, rust-for-linux, linux-kernel
On Fri, Aug 22, 2025 at 10:57 PM Sami Daniel
<samidanielpersonal@gmail.com> wrote:
>
> + pub fn as_str(&self) -> Result<&str, core::str::Utf8Error> {
Should we use the `as_` prefix?
The standard library calls this `to_str`, likely because it isn't free
and it doesn't decrease abstraction.
Cheers,
Miguel
^ permalink raw reply [flat|nested] 3+ messages in thread
* Re: [PATCH] rust: Improve CStr UTF-8 conversion methods
2025-08-22 20:57 [PATCH] rust: Improve CStr UTF-8 conversion methods Sami Daniel
2025-08-22 21:32 ` Miguel Ojeda
@ 2025-08-22 21:34 ` Miguel Ojeda
1 sibling, 0 replies; 3+ messages in thread
From: Miguel Ojeda @ 2025-08-22 21:34 UTC (permalink / raw)
To: samidanielpersonal, Tamir Duberstein
Cc: ojeda, alex.gaynor, rust-for-linux, linux-kernel
On Fri, Aug 22, 2025 at 10:57 PM Sami Daniel
<samidanielpersonal@gmail.com> wrote:
>
> 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
Is there a use case in mind?
Please also note that we are trying to move to the `core` `CStr`, so
is this needed if that succeeds?
Cc'ing Tamir.
Thanks for the patch!
Cheers,
Miguel
^ permalink raw reply [flat|nested] 3+ messages in thread
end of thread, other threads:[~2025-08-22 21:35 UTC | newest]
Thread overview: 3+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2025-08-22 20:57 [PATCH] rust: Improve CStr UTF-8 conversion methods Sami Daniel
2025-08-22 21:32 ` Miguel Ojeda
2025-08-22 21:34 ` Miguel Ojeda
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox