rust: a few common Borrow/BorrowMut implementations
Subsystems (3)
Alexandre Courbot
reviewerv3 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].
This second revision adds examples to each impl block as requested. I am personally not quite convinced that they are needed, as they just illustrate the basic usage of Borrow, but have added them to this revision so we can decide whether we want them or not.
[1] https://lore.kernel.org/rust-for-linux/[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 (4):
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: implement Borrow and BorrowMut for CString
rust/kernel/alloc/kbox.rs | 57 ++++++++++++++++++++++++++++++++++ rust/kernel/alloc/kvec.rs | 53 ++++++++++++++++++++++++++++++++ rust/kernel/str.rs | 45 +++++++++++++++++++++++++++ rust/kernel/sync/arc.rs | 78 ++++++++++++++++++++++++++++++++++++++++++++++- 4 files changed, 232 insertions(+), 1 deletion(-)
---
base-commit: 19272b37aa4f83ca52bdf9c16d5d81bdd1354494
change-id: 20250531-borrow_impls-8dfef3fcee93
Best regards,
Signature · 1 line
Alexandre Courbot <[email protected]>
Alexandre Courbot
reviewerPATCH v3 1/4 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
@@ -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 foo_array = Foo([1, 2, 3]); +/// +/// // Owned vector. +/// let foo_vec = Foo(KVec::from_elem(0, 3, GFP_KERNEL)?); +/// +/// let arr = [1, 2, 3]; +/// // Borrowed slice from `arr`. +/// let foo_borrowed = 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 foo_array = Foo([1, 2, 3]); +/// +/// // Owned vector. +/// let foo_vec = Foo(KVec::from_elem(0, 3, GFP_KERNEL)?); +/// +/// let mut arr = [1, 2, 3]; +/// // Borrowed slice from `arr`. +/// let foo_borrowed = 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
Alexandre Courbot
reviewerPATCH v3 2/4 rust: sync: implement `Borrow` and `BorrowMut` for `Arc` types
In reply to Alexandre CourbotImplement 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
@@ -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 foo_owned = Foo(1); +/// +/// // Shared instance. +/// let arc = Arc::new(1, GFP_KERNEL)?; +/// let foo_shared = Foo(arc.clone()); +/// +/// let i = 1; +/// // Borrowed from `i`. +/// let foo_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 foo_owned = Foo(1); +/// +/// // Owned instance using `UniqueArc`. +/// let arc = UniqueArc::new(1, GFP_KERNEL)?; +/// let foo_shared = Foo(arc); +/// +/// let i = 1; +/// // Borrowed from `i`. +/// let foo_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 foo_owned = Foo(1); +/// +/// // Owned instance using `UniqueArc`. +/// let arc = UniqueArc::new(1, GFP_KERNEL)?; +/// let foo_shared = Foo(arc); +/// +/// let mut i = 1; +/// // Borrowed from `i`. +/// let foo_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
Alexandre Courbot
reviewerPATCH v3 3/4 rust: alloc: implement `Borrow` and `BorrowMut` for `KBox`
In reply to Alexandre CourbotImplement 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
@@ -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 foo_owned = Foo(1); +/// +/// // Owned instance using `KBox`. +/// let foo_box = Foo(KBox::new(1, GFP_KERNEL)?); +/// +/// let i = 1; +/// // Borrowed from `i`. +/// let foo_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 foo_owned = Foo(1); +/// +/// // Owned instance using `KBox`. +/// let foo_box = Foo(KBox::new(1, GFP_KERNEL)?); +/// +/// let mut i = 1; +/// // Borrowed from `i`. +/// let foo_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
Alexandre Courbot
reviewerPATCH v3 4/4 rust: str: implement `Borrow` and `BorrowMut` for `CString`
In reply to Alexandre CourbotImplement 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
@@ -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 <&'aCStr >for CString {type Error =AllocError ;
Signature · 1 line
2.49.0
Re: [PATCH v3 4/4] rust: str: implement `Borrow` and `BorrowMut` for `CString`
Review
Quoted 3 lines · Alexandre Courbot
(quoted diff) +2
-0+/// // 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
Alexandre Courbot
reviewerRe: [PATCH v3 4/4] rust: str: implement `Borrow` and `BorrowMut` for `CString`
Quoted 6 lines · Miguel Ojeda
Review
Quoted 3 lines · Alexandre Courbot
(quoted diff) +2
-0+/// // 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...
Quoted 2 lines
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`
Quoted 3 lines · Alexandre Courbot
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
Quoted 2 lines
... 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
Alexandre Courbot
reviewerRe: [PATCH v3 4/4] rust: str: implement `Borrow` and `BorrowMut` for `CString`
Quoted 8 lines · Miguel Ojeda
Quoted 3 lines · Alexandre Courbot
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
Quoted 8 lines
--> 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!