[PATCH v4 7/7] rust: str: implement `Borrow` and `BorrowMut` for `CString`
From: Alexandre Courbot
Date: Sun Jun 15 2025 - 23:36:24 EST
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@xxxxxxxxxx>
Reviewed-by: Benno Lossin <lossin@xxxxxxxxxx>
Signed-off-by: Alexandre Courbot <acourbot@xxxxxxxxxx>
---
rust/kernel/str.rs | 45 +++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 45 insertions(+)
diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs
index 21d6f8801ea84686d4aa909fbb52578af96fe2d8..82924113bfecc41d9e16ba28d9dfb08d3a51d0bc 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};
@@ -936,6 +937,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 owned_cstring = Foo(CString::try_from_fmt(fmt!("{}", "abc"))?);
+///
+/// let str_data = b"abc\0";
+/// // Borrowed from `str_data`.
+/// let borrowed_cstr = 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 owned_cstring = Foo(CString::try_from_fmt(fmt!("{}", "abc"))?);
+///
+/// let mut str_data = [b'a', b'b', b'c', 0];
+/// // Borrowed from `str_data`.
+/// let borrowed_cstr = Foo(CStr::from_bytes_with_nul_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