[PATCH v3 4/4] rust: str: implement `Borrow` and `BorrowMut` for `CString`

Alexandre Courbot posted 4 patches 3 months, 3 weeks ago
There is a newer version of this series
[PATCH v3 4/4] rust: str: implement `Borrow` and `BorrowMut` for `CString`
Posted by Alexandre Courbot 3 months, 3 weeks ago
Implement `Borrow<CStr>` and `BorrowMut<CStr>` for `CString`. This
allows `CString` to be used in generic APIs asking for types
implementing those traits. `&CStr` and `&mut CStr` also implement those
traits allowing users to use either owned or borrowed values.

Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Benno Lossin <lossin@kernel.org>
Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
---
 rust/kernel/str.rs | 45 +++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 45 insertions(+)

diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs
index a927db8e079c3597860880947a03959e1d6d712e..1cf787d4ace36a84d0ece7a7017ef0c67499bf89 100644
--- a/rust/kernel/str.rs
+++ b/rust/kernel/str.rs
@@ -3,6 +3,7 @@
 //! String representations.
 
 use crate::alloc::{flags::*, AllocError, KVec};
+use core::borrow::{Borrow, BorrowMut};
 use core::fmt::{self, Write};
 use core::ops::{self, Deref, DerefMut, Index};
 
@@ -911,6 +912,50 @@ fn deref_mut(&mut self) -> &mut Self::Target {
     }
 }
 
+/// # Examples
+///
+/// ```
+/// # use core::borrow::Borrow;
+/// # use kernel::str::{CStr, CString};
+/// # use kernel::fmt;
+/// struct Foo<B: Borrow<CStr>>(B);
+///
+/// // Owned instance using `CString`.
+/// let foo_owned = Foo(CString::try_from_fmt(fmt!("{}", "abc"))?);
+///
+/// let str_data = b"abc\0";
+/// // Borrowed from `str_data`.
+/// let foo_borrowed = Foo(CStr::from_bytes_with_nul(str_data)?);
+/// # Ok::<(), Error>(())
+/// ```
+impl Borrow<CStr> for CString {
+    fn borrow(&self) -> &CStr {
+        self.deref()
+    }
+}
+
+/// # Examples
+///
+/// ```
+/// # use core::borrow::BorrowMut;
+/// # use kernel::str::{CStr, CString};
+/// # use kernel::fmt;
+/// struct Foo<B: BorrowMut<CStr>>(B);
+///
+/// // Owned instance using `CString`.
+/// let foo_owned = Foo(CString::try_from_fmt(fmt!("{}", "abc"))?);
+///
+/// let mut str_data = [b'a', b'b', b'c', 0];
+/// // Borrowed from `str_data`.
+/// let foo_borrowed = Foo(unsafe { CStr::from_bytes_with_nul_unchecked_mut(&mut str_data) });
+/// # Ok::<(), Error>(())
+/// ```
+impl BorrowMut<CStr> for CString {
+    fn borrow_mut(&mut self) -> &mut CStr {
+        self.deref_mut()
+    }
+}
+
 impl<'a> TryFrom<&'a CStr> for CString {
     type Error = AllocError;
 

-- 
2.49.0
Re: [PATCH v3 4/4] rust: str: implement `Borrow` and `BorrowMut` for `CString`
Posted by Miguel Ojeda 3 months, 3 weeks ago
On Sun, Jun 15, 2025 at 2:37 PM Alexandre Courbot <acourbot@nvidia.com> wrote:
>
> +/// // Borrowed from `str_data`.
> +/// let foo_borrowed = Foo(unsafe { CStr::from_bytes_with_nul_unchecked_mut(&mut str_data) });

We will need a `// SAFETY:` comment -- Clippy should complain.

Or to add a safe `from_bytes_with_nul_mut`, I guess.

Cheers,
Miguel
Re: [PATCH v3 4/4] rust: str: implement `Borrow` and `BorrowMut` for `CString`
Posted by Alexandre Courbot 3 months, 3 weeks ago
On Sun Jun 15, 2025 at 10:15 PM JST, Miguel Ojeda wrote:
> On Sun, Jun 15, 2025 at 2:37 PM Alexandre Courbot <acourbot@nvidia.com> wrote:
>>
>> +/// // Borrowed from `str_data`.
>> +/// let foo_borrowed = Foo(unsafe { CStr::from_bytes_with_nul_unchecked_mut(&mut str_data) });
>
> We will need a `// SAFETY:` comment -- Clippy should complain.

I thought I could get away with it since it is in a test, and clippy
does not seem to complain about it, but...

>
> Or to add a safe `from_bytes_with_nul_mut`, I guess.

... as penance (and for symmetry with `from_bytes_with_nul`), let me
implement that so we don't need a safety block at all. :)
Re: [PATCH v3 4/4] rust: str: implement `Borrow` and `BorrowMut` for `CString`
Posted by Miguel Ojeda 3 months, 3 weeks ago
On Sun, Jun 15, 2025 at 3:48 PM Alexandre Courbot <acourbot@nvidia.com> wrote:
>
> I thought I could get away with it since it is in a test, and clippy
> does not seem to complain about it, but...

Hmm... It should:

error: unsafe block missing a safety comment
    --> rust/doctests_kernel_generated.rs:7973:24
     |
7973 | let foo_borrowed = Foo(unsafe {
CStr::from_bytes_with_nul_unchecked_mut(&mut str_data) });
     |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Do you have the doctests enabled? i.e. CONFIG_RUST_KERNEL_DOCTESTS=y

> ... as penance (and for symmetry with `from_bytes_with_nul`), let me
> implement that so we don't need a safety block at all. :)

:)

Cheers,
Miguel
Re: [PATCH v3 4/4] rust: str: implement `Borrow` and `BorrowMut` for `CString`
Posted by Alexandre Courbot 3 months, 3 weeks ago
On Sun Jun 15, 2025 at 10:57 PM JST, Miguel Ojeda wrote:
> On Sun, Jun 15, 2025 at 3:48 PM Alexandre Courbot <acourbot@nvidia.com> wrote:
>>
>> I thought I could get away with it since it is in a test, and clippy
>> does not seem to complain about it, but...
>
> Hmm... It should:
>
> error: unsafe block missing a safety comment
>     --> rust/doctests_kernel_generated.rs:7973:24
>      |
> 7973 | let foo_borrowed = Foo(unsafe {
> CStr::from_bytes_with_nul_unchecked_mut(&mut str_data) });
>      |
> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>
> Do you have the doctests enabled? i.e. CONFIG_RUST_KERNEL_DOCTESTS=y

... and that's what I was missing. ^_^; Thanks!