Skip to contentSkip to conversation

rust: a few common Borrow/BorrowMut implementations

PATCH Applied Alexandre Courbot 4 participants 14 messages Jun 16, 2025 – Jun 29, 2025

Subsystems (3)
lore
Share & tools
lore

Alexandre Courbot

author reviewer
#0 lore raw

v4 cover rust: a few common Borrow/BorrowMut implementations

The Borrow trait has multiple uses, one of them being to store either an owned value or a reference to it inside a generic container. This series adds these implementations for Box, Arc, Vec, and CString. I came across the need for this while experimenting with the scatterlist abstraction series [1].

In order to avoid an unsightly unsafe block in the doctest, this also implements from_bytes_with_nul_mut. from_bytes_with_nul and from_bytes_with_nul_unchecked_mut already exist, so it looked strange to not have it anyway.

While doing this, I noticed that from_bytes_with_nul_unchecked_mut was not const and not using transmute, which I attributed to the absence of the const_mut_refs feature at the time the code was written. I've tentatively fixed that, but my assumption for doing this might be wrong so a double-check from someone more familiar with the timeline of this code would be appreciated.

[1] https://lore.kernel.org/rust-for-linux/[email protected]/

---
Changes in v4:
- Implement from_bytes_with_nul_mut to avoid unsafe block in doctest.
- Make from_bytes_with_nul_unchecked_mut const and use transmute.
- Use more explicit names for variables in doctests.
- Link to v3: https://lore.kernel.org/r/[email protected]

Changes in v3:
- Remove undeeded first line of doccomments.
- Link to v2: https://lore.kernel.org/r/[email protected]

Changes in v2:
- Rebase on top of v6.16-rc1.
- Improve commit messages. (thanks Benno!)
- Add examples on each impl block.
- Link to v1: https://lore.kernel.org/r/[email protected]

---
Alexandre Courbot (7):
rust: alloc: implement Borrow and BorrowMut for Vec
rust: sync: implement Borrow and BorrowMut for Arc types
rust: alloc: implement Borrow and BorrowMut for KBox
rust: str: make from_bytes_with_nul_unchecked_mut const
rust: str: use transmute in from_bytes_with_nul_unchecked_mut
rust: str: implement from_bytes_with_nul_mut
rust: str: implement Borrow and BorrowMut for CString

 rust/kernel/alloc/kbox.rs | 57 +++++++++++++++++++++++++++++++
 rust/kernel/alloc/kvec.rs | 53 +++++++++++++++++++++++++++++
 rust/kernel/str.rs        | 86 ++++++++++++++++++++++++++++++++++++++++++-----
 rust/kernel/sync/arc.rs   | 78 +++++++++++++++++++++++++++++++++++++++++-
 4 files changed, 265 insertions(+), 9 deletions(-)

---
base-commit: 19272b37aa4f83ca52bdf9c16d5d81bdd1354494
change-id: 20250531-borrow_impls-8dfef3fcee93

Best regards,

Signature · 1 line
Alexandre Courbot <[email protected]>
author reviewer
#1 lore raw

PATCH v4 1/7 rust: alloc: implement `Borrow` and `BorrowMut` for `Vec`

Implement Borrow<[T]> and BorrowMut<[T]> for Vec<T>. This allows Vec<T> to be used in generic APIs asking for types implementing those traits. [T; N] and &mut [T] also implement those traits allowing users to use either owned, borrowed and heap-owned values.

The implementation leverages as_slice and as_mut_slice.

---
 rust/kernel/alloc/kvec.rs | 53 +++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 53 insertions(+)
rust/kernel/alloc/kvec.rs +53 -0
index 1a0dd852a468ccda6ea1b521bc1e7dbc8d7fc79c..b121cb39de85575f4487208ad5deee3c3ac06111 100644
@@ -8,6 +8,7 @@
     AllocError, Allocator, Box, Flags,
 };
 use core::{
+    borrow::{Borrow, BorrowMut},
     fmt,
     marker::PhantomData,
     mem::{ManuallyDrop, MaybeUninit},
@@ -890,6 +891,58 @@ fn deref_mut(&mut self) -> &mut [T] {
     }
 }
 
+/// # Examples
+///
+/// ```
+/// # use core::borrow::Borrow;
+/// struct Foo<B: Borrow<[u32]>>(B);
+///
+/// // Owned array.
+/// let owned_array = Foo([1, 2, 3]);
+///
+/// // Owned vector.
+/// let owned_vec = Foo(KVec::from_elem(0, 3, GFP_KERNEL)?);
+///
+/// let arr = [1, 2, 3];
+/// // Borrowed slice from `arr`.
+/// let borrowed_slice = Foo(&arr[..]);
+/// # Ok::<(), Error>(())
+/// ```
+impl<T, A> Borrow<[T]> for Vec<T, A>
+where
+    A: Allocator,
+{
+    fn borrow(&self) -> &[T] {
+        self.as_slice()
+    }
+}
+
+/// # Examples
+///
+/// ```
+/// # use core::borrow::BorrowMut;
+/// struct Foo<B: BorrowMut<[u32]>>(B);
+///
+/// // Owned array.
+/// let owned_array = Foo([1, 2, 3]);
+///
+/// // Owned vector.
+/// let owned_vec = Foo(KVec::from_elem(0, 3, GFP_KERNEL)?);
+///
+/// let mut arr = [1, 2, 3];
+/// // Borrowed slice from `arr`.
+/// let borrowed_slice = Foo(&mut arr[..]);
+/// # Ok::<(), Error>(())
+/// ```
+impl<T, A> BorrowMut<[T]> for Vec<T, A>
+where
+    A: Allocator,
+{
+    fn borrow_mut(&mut self) -> &mut [T] {
+        self.as_mut_slice()
+    }
+}
+
 impl<T: Eq, A> Eq for Vec<T, A> where A: Allocator {}
 
 impl<T, I: SliceIndex<[T]>, A> Index<I> for Vec<T, A>
Signature · 1 line
2.49.0
maintainer Applied
#2 lore raw

Re: [PATCH v4 1/7] rust: alloc: implement `Borrow` and `BorrowMut` for `Vec`

Quoted 10 lines · Alexandre Courbot

Implement Borrow<[T]> and BorrowMut<[T]> for Vec<T>. This allows Vec<T> to be used in generic APIs asking for types implementing those traits. [T; N] and &mut [T] also implement those traits allowing users to use either owned, borrowed and heap-owned values.

The implementation leverages as_slice and as_mut_slice.

Applied to alloc-next, thanks!

author reviewer
#3 lore raw

PATCH v4 2/7 rust: sync: implement `Borrow` and `BorrowMut` for `Arc` types

In reply to Alexandre Courbot

Implement Borrow<T> and BorrowMut<T> for UniqueArc<T>, and Borrow<T> for Arc<T>. This allows these containers to be used in generic APIs asking for types implementing those traits. T and &mut T also implement those traits allowing users to use either owned, shared or borrowed values.

ForeignOwnable makes a call to its own borrow method which must be disambiguated.

---
 rust/kernel/sync/arc.rs | 78 ++++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 77 insertions(+), 1 deletion(-)
rust/kernel/sync/arc.rs +77 -1
index c7af0aa48a0a049bfeeba3a81080355f4d381738..499175f637a78f15d522007f2ebbbee9c4eb6c91 100644
@@ -25,6 +25,7 @@
 };
 use core::{
     alloc::Layout,
+    borrow::{Borrow, BorrowMut},
     fmt,
     marker::PhantomData,
     mem::{ManuallyDrop, MaybeUninit},
@@ -406,7 +407,7 @@ unsafe fn borrow<'a>(ptr: *mut Self::PointedTo) -> ArcBorrow<'a, T> {
     unsafe fn borrow_mut<'a>(ptr: *mut Self::PointedTo) -> ArcBorrow<'a, T> {
         // SAFETY: The safety requirements for `borrow_mut` are a superset of the safety
         // requirements for `borrow`.
-        unsafe { Self::borrow(ptr) }
+        unsafe { <Self as ForeignOwnable>::borrow(ptr) }
     }
 }
 
@@ -426,6 +427,31 @@ fn as_ref(&self) -> &T {
     }
 }
 
+/// # Examples
+///
+/// ```
+/// # use core::borrow::Borrow;
+/// # use kernel::sync::Arc;
+/// struct Foo<B: Borrow<u32>>(B);
+///
+/// // Owned instance.
+/// let owned = Foo(1);
+///
+/// // Shared instance.
+/// let arc = Arc::new(1, GFP_KERNEL)?;
+/// let shared = Foo(arc.clone());
+///
+/// let i = 1;
+/// // Borrowed from `i`.
+/// let borrowed = Foo(&i);
+/// # Ok::<(), Error>(())
+/// ```
+impl<T: ?Sized> Borrow<T> for Arc<T> {
+    fn borrow(&self) -> &T {
+        self.deref()
+    }
+}
+
 impl<T: ?Sized> Clone for Arc<T> {
     fn clone(&self) -> Self {
         // SAFETY: By the type invariant, there is necessarily a reference to the object, so it is
@@ -834,6 +860,56 @@ fn deref_mut(&mut self) -> &mut Self::Target {
     }
 }
 
+/// # Examples
+///
+/// ```
+/// # use core::borrow::Borrow;
+/// # use kernel::sync::UniqueArc;
+/// struct Foo<B: Borrow<u32>>(B);
+///
+/// // Owned instance.
+/// let owned = Foo(1);
+///
+/// // Owned instance using `UniqueArc`.
+/// let arc = UniqueArc::new(1, GFP_KERNEL)?;
+/// let shared = Foo(arc);
+///
+/// let i = 1;
+/// // Borrowed from `i`.
+/// let borrowed = Foo(&i);
+/// # Ok::<(), Error>(())
+/// ```
+impl<T: ?Sized> Borrow<T> for UniqueArc<T> {
+    fn borrow(&self) -> &T {
+        self.deref()
+    }
+}
+
+/// # Examples
+///
+/// ```
+/// # use core::borrow::BorrowMut;
+/// # use kernel::sync::UniqueArc;
+/// struct Foo<B: BorrowMut<u32>>(B);
+///
+/// // Owned instance.
+/// let owned = Foo(1);
+///
+/// // Owned instance using `UniqueArc`.
+/// let arc = UniqueArc::new(1, GFP_KERNEL)?;
+/// let shared = Foo(arc);
+///
+/// let mut i = 1;
+/// // Borrowed from `i`.
+/// let borrowed = Foo(&mut i);
+/// # Ok::<(), Error>(())
+/// ```
+impl<T: ?Sized> BorrowMut<T> for UniqueArc<T> {
+    fn borrow_mut(&mut self) -> &mut T {
+        self.deref_mut()
+    }
+}
+
 impl<T: fmt::Display + ?Sized> fmt::Display for UniqueArc<T> {
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         fmt::Display::fmt(self.deref(), f)
Signature · 1 line
2.49.0
Applied
#4 lore raw

Re: [PATCH v4 2/7] rust: sync: implement `Borrow` and `BorrowMut` for `Arc` types

Quoted 7 lines · Alexandre Courbot

Implement Borrow<T> and BorrowMut<T> for UniqueArc<T>, and Borrow<T> for Arc<T>. This allows these containers to be used in generic APIs asking for types implementing those traits. T and &mut T also implement those traits allowing users to use either owned, shared or borrowed values.

Quoted 6 lines

ForeignOwnable makes a call to its own borrow method which must be disambiguated.

Applied to rust-next -- thanks everyone!

Cheers,
Miguel

author reviewer
#5 lore raw

PATCH v4 3/7 rust: alloc: implement `Borrow` and `BorrowMut` for `KBox`

In reply to Alexandre Courbot

Implement Borrow<T> and BorrowMut<T> for KBox<T>. This allows KBox<T> to be used in generic APIs asking for types implementing those traits. T and &mut T also implement those traits allowing users to use either owned, borrowed and heap-owned values.

---
 rust/kernel/alloc/kbox.rs | 57 +++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 57 insertions(+)
rust/kernel/alloc/kbox.rs +57 -0
index c386ff771d506a2eb4c211a93ea9b59bc04c93f5..ccf1df7da96cf9e879330385fa6f744d6f60c972 100644
@@ -6,6 +6,7 @@
 use super::allocator::{KVmalloc, Kmalloc, Vmalloc};
 use super::{AllocError, Allocator, Flags};
 use core::alloc::Layout;
+use core::borrow::{Borrow, BorrowMut};
 use core::fmt;
 use core::marker::PhantomData;
 use core::mem::ManuallyDrop;
@@ -499,6 +500,62 @@ fn deref_mut(&mut self) -> &mut T {
     }
 }
 
+/// # Examples
+///
+/// ```
+/// # use core::borrow::Borrow;
+/// # use kernel::alloc::KBox;
+/// struct Foo<B: Borrow<u32>>(B);
+///
+/// // Owned instance.
+/// let owned = Foo(1);
+///
+/// // Owned instance using `KBox`.
+/// let owned_kbox = Foo(KBox::new(1, GFP_KERNEL)?);
+///
+/// let i = 1;
+/// // Borrowed from `i`.
+/// let borrowed = Foo(&i);
+/// # Ok::<(), Error>(())
+/// ```
+impl<T, A> Borrow<T> for Box<T, A>
+where
+    T: ?Sized,
+    A: Allocator,
+{
+    fn borrow(&self) -> &T {
+        self.deref()
+    }
+}
+
+/// # Examples
+///
+/// ```
+/// # use core::borrow::BorrowMut;
+/// # use kernel::alloc::KBox;
+/// struct Foo<B: BorrowMut<u32>>(B);
+///
+/// // Owned instance.
+/// let owned = Foo(1);
+///
+/// // Owned instance using `KBox`.
+/// let owned_kbox = Foo(KBox::new(1, GFP_KERNEL)?);
+///
+/// let mut i = 1;
+/// // Borrowed from `i`.
+/// let borrowed = Foo(&mut i);
+/// # Ok::<(), Error>(())
+/// ```
+impl<T, A> BorrowMut<T> for Box<T, A>
+where
+    T: ?Sized,
+    A: Allocator,
+{
+    fn borrow_mut(&mut self) -> &mut T {
+        self.deref_mut()
+    }
+}
+
 impl<T, A> fmt::Display for Box<T, A>
 where
     T: ?Sized + fmt::Display,
Signature · 1 line
2.49.0
maintainer Applied
#6 lore raw

Re: [PATCH v4 3/7] rust: alloc: implement `Borrow` and `BorrowMut` for `KBox`

Quoted 8 lines · Alexandre Courbot

Implement Borrow<T> and BorrowMut<T> for KBox<T>. This allows KBox<T> to be used in generic APIs asking for types implementing those traits. T and &mut T also implement those traits allowing users to use either owned, borrowed and heap-owned values.

Applied to alloc-next, thanks!

author reviewer
#7 lore raw

PATCH v4 4/7 rust: str: make `from_bytes_with_nul_unchecked_mut` const

In reply to Alexandre Courbot

This method was probably kept non-const due to the absence of the const_mut_refs feature, but it has been enabled since the introduction of this code (and stabilized with Rust 1.83). Thus, make it const to match its non-const counterpart.

---
 rust/kernel/str.rs | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
rust/kernel/str.rs +1 -1
index a927db8e079c3597860880947a03959e1d6d712e..2640a050847e64bfd18c127a5a83b93f01f036bc 100644
@@ -288,7 +288,7 @@ pub const fn from_bytes_with_nul(bytes: &[u8]) -> Result<&Self, CStrConvertError
     /// `bytes` *must* end with a `NUL` byte, and should only have a single
     /// `NUL` byte (or the string will be truncated).
     #[inline]
-    pub unsafe fn from_bytes_with_nul_unchecked_mut(bytes: &mut [u8]) -> &mut CStr {
+    pub const unsafe fn from_bytes_with_nul_unchecked_mut(bytes: &mut [u8]) -> &mut CStr {
         // SAFETY: Properties of `bytes` guaranteed by the safety precondition.
         unsafe { &mut *(bytes as *mut [u8] as *mut CStr) }
     }
Signature · 1 line
2.49.0
reviewer Reviewed-by on v4 4/7
#8 lore raw

Re: [PATCH v4 4/7] rust: str: make `from_bytes_with_nul_unchecked_mut` const

Quoted 6 lines · Alexandre Courbot

This method was probably kept non-const due to the absence of the const_mut_refs feature, but it has been enabled since the introduction of this code (and stabilized with Rust 1.83). Thus, make it const to match its non-const counterpart.

---
Cheers,
Benno

Quoted 3 lines
---
 rust/kernel/str.rs | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
reviewer
#9 lore raw

Re: [PATCH v4 4/7] rust: str: make `from_bytes_with_nul_unchecked_mut` const

In reply to Alexandre Courbot
Quoted 6 lines · Alexandre Courbot

This method was probably kept non-const due to the absence of the const_mut_refs feature, but it has been enabled since the introduction of this code (and stabilized with Rust 1.83). Thus, make it const to match its non-const counterpart.

Ah on second thought, this and the next two patches are a bit redundant, since Tamir has a series [1] removing our CStr and using the one from core.

If you need this *now* and can't wait for Tamir's series to land, then we can do this and the other two changes, but othrwise I'd just use CStr from core.

It does seem like you need &mut CStr, which the one in core doesn't seem to provide... But our CStr also doesn't have IndexMut, so... how are you using it? Giving it to a C API?

In that case I don't know what we should do about [1]... @Miguel?

[1]: https://lore.kernel.org/all/[email protected]

---
Cheers,
Benno

author reviewer
#10 lore raw

Re: [PATCH v4 4/7] rust: str: make `from_bytes_with_nul_unchecked_mut` const

Quoted 16 lines · Benno Lossin
Quoted 6 lines · Alexandre Courbot

This method was probably kept non-const due to the absence of the const_mut_refs feature, but it has been enabled since the introduction of this code (and stabilized with Rust 1.83). Thus, make it const to match its non-const counterpart.

Ah on second thought, this and the next two patches are a bit redundant, since Tamir has a series [1] removing our CStr and using the one from core.

If you need this *now* and can't wait for Tamir's series to land, then we can do this and the other two changes, but othrwise I'd just use CStr from core.

Quoted 7 lines

It does seem like you need &mut CStr, which the one in core doesn't seem to provide... But our CStr also doesn't have IndexMut, so... how are you using it? Giving it to a C API?

In that case I don't know what we should do about [1]... @Miguel?

[1]: https://lore.kernel.org/all/[email protected]

Let's drop this part (patches 4..=7) for now to avoid interfering with Tamir's work - the CString implementation was more of a drive-by, the container types are more important to support. I will revisit after Tamir's series lands, if needed.

As Danilo took patches 1 and 3, this just leaves patch 2 to be picked up if it looks ok.

author reviewer
#11 lore raw

PATCH v4 5/7 rust: str: use transmute in `from_bytes_with_nul_unchecked_mut`

In reply to Alexandre Courbot

from_bytes_with_nul_unchecked also does this, so do the same for symmetry. This was probably not done due to the unavailability of the const_mut_refs feature at the time this code was introduced.

---
 rust/kernel/str.rs | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
rust/kernel/str.rs +1 -1
index 2640a050847e64bfd18c127a5a83b93f01f036bc..28f2f359ab23e6a926e88913e3cc9f481aa86037 100644
@@ -290,7 +290,7 @@ pub const fn from_bytes_with_nul(bytes: &[u8]) -> Result<&Self, CStrConvertError
     #[inline]
     pub const unsafe fn from_bytes_with_nul_unchecked_mut(bytes: &mut [u8]) -> &mut CStr {
         // SAFETY: Properties of `bytes` guaranteed by the safety precondition.
-        unsafe { &mut *(bytes as *mut [u8] as *mut CStr) }
+        unsafe { core::mem::transmute(bytes) }
     }
 
     /// Returns a C pointer to the string.
Signature · 1 line
2.49.0
author reviewer
#12 lore raw

PATCH v4 6/7 rust: str: implement `from_bytes_with_nul_mut`

In reply to Alexandre Courbot

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.

---
 rust/kernel/str.rs | 37 +++++++++++++++++++++++++++++++------
 1 file changed, 31 insertions(+), 6 deletions(-)
rust/kernel/str.rs +31 -6
index 28f2f359ab23e6a926e88913e3cc9f481aa86037..21d6f8801ea84686d4aa909fbb52578af96fe2d8 100644
@@ -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
Signature · 1 line
2.49.0
author reviewer
#13 lore raw

PATCH v4 7/7 rust: str: implement `Borrow` and `BorrowMut` for `CString`

In reply to Alexandre Courbot

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.

---
 rust/kernel/str.rs | 45 +++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 45 insertions(+)
rust/kernel/str.rs +45 -0
index 21d6f8801ea84686d4aa909fbb52578af96fe2d8..82924113bfecc41d9e16ba28d9dfb08d3a51d0bc 100644
@@ -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;
 
Signature · 1 line
2.49.0