rust: a few common Borrow/BorrowMut implementations
Subsystems (3)
Alexandre Courbot
reviewercover 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 series provides just the Borrow and BorrowMut implementations, but another common use of Borrow in the standard library is to use the borrowed type for key lookups in collections. For this to work, a few consistency traits (Eq, Hash, and Ord) need to be implemented. I am not sure whether we want this on kernel types as well, but please let me know if we do and I will add them in the next revision.
[1] https://lore.kernel.org/rust-for-linux/[email protected]/
---
Alexandre Courbot (4):
rust: alloc: implement Borrow and BorrowMut for Vec
rust: alloc: implement Borrow and BorrowMut for Arc types
rust: alloc: implement Borrow and BorrowMut for KBox
rust: alloc: implement Borrow and BorrowMut for CString
rust/kernel/alloc/kbox.rs | 21 +++++++++++++++++++++ rust/kernel/alloc/kvec.rs | 19 +++++++++++++++++++ rust/kernel/str.rs | 13 +++++++++++++ rust/kernel/sync/arc.rs | 21 ++++++++++++++++++++- 4 files changed, 73 insertions(+), 1 deletion(-)
---
base-commit: 7a17bbc1d952057898cb0739e60665908fbb8c72
change-id: 20250531-borrow_impls-8dfef3fcee93
Best regards,
Signature · 1 line
Alexandre Courbot <[email protected]>
Alexandre Courbot
reviewerPATCH 1/4 rust: alloc: implement `Borrow` and `BorrowMut` for `Vec`
Implement these two common traits, which allow generic types to store either an owned value or a reference to it.
The implementation leverages as_slice and as_mut_slice.
--- rust/kernel/alloc/kvec.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+)
rust/kernel/alloc/kvec.rs +19 -0
@@ -8,6 +8,7 @@ AllocError, Allocator, Box, Flags, };use core::{ + borrow::{Borrow ,BorrowMut }, fmt, marker::PhantomData , mem::{ManuallyDrop ,MaybeUninit },
@@ -890,6 +891,24 @@ fn deref_mut(&mut self) -> &mut [T] { } } +impl <T ,A >Borrow <[T ]>for Vec <T ,A > +where +A :Allocator , +{ +fn borrow (&self) -> &[T ] { + self.as_slice () + } +} + +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
Benno Lossin
reviewerRe: [PATCH 1/4] rust: alloc: implement `Borrow` and `BorrowMut` for `Vec`
Quoted 2 lines · Alexandre Courbot
Implement these two common traits, which allow generic types to store either an owned value or a reference to it.
I don't understand the second part of the sentence.
Quoted 6 lines
The implementation leverages
as_sliceandas_mut_slice.Signed-off-by Alexandre Courbot <[email protected]>--- rust/kernel/alloc/kvec.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+)
The code itself looks good.
---
Cheers,
Benno
Alexandre Courbot
reviewerRe: [PATCH 1/4] rust: alloc: implement `Borrow` and `BorrowMut` for `Vec`
Hi Benno,
Quoted 5 lines · Benno Lossin
Quoted 2 lines · Alexandre Courbot
Implement these two common traits, which allow generic types to store either an owned value or a reference to it.
I don't understand the second part of the sentence.
I want to say that Borrow allows you to do something like:
struct Foo<B: Borrow<u32>>(B);
// `foo1` owns its value...
let foo1 = Foo(0x12);
let i = 0x24;
// ... but `foo2` just borrows it, subject to the lifetime of `i`.
let foo2 = Foo(&i);And the implementations in this series also let you do:
// `foo3`'s value is owned, but heap-allocated
let foo3 = Arc::new(KBox::new(0x56, GFP_KERNEL)?);
let j = Arc::new(0x78, GFP_KERNEL)?;
// `foo4`'s value is shared and its lifetime runtime-managed.
let foo4 = Foo(j.clone());Re: [PATCH 1/4] rust: alloc: implement `Borrow` and `BorrowMut` for `Vec`
Quoted 20 lines · Alexandre Courbot
Hi Benno,
Quoted 5 lines · Benno Lossin
Quoted 2 lines · Alexandre Courbot
Implement these two common traits, which allow generic types to store either an owned value or a reference to it.
I don't understand the second part of the sentence.
I want to say that Borrow allows you to do something like:
struct Foo<B: Borrow<u32>>(B); // `foo1` owns its value... let foo1 = Foo(0x12); let i = 0x24; // ... but `foo2` just borrows it, subject to the lifetime of `i`. let foo2 = Foo(&i);
Quoted 8 lines
And the implementations in this series also let you do:
// `foo3`'s value is owned, but heap-allocated let foo3 = Arc::new(KBox::new(0x56, GFP_KERNEL)?); let j = Arc::new(0x78, GFP_KERNEL)?; // `foo4`'s value is shared and its lifetime runtime-managed. let foo4 = Foo(j.clone());
Maybe you could put these in the "# Examples" section before impl blocks. E.g
/// # Examples /// ``` /// <you case above> /// ``` impl<T, A> Borrow<[T]> for Vec<T, A> ...
Regards,
Boqun
Benno Lossin
reviewerRe: [PATCH 1/4] rust: alloc: implement `Borrow` and `BorrowMut` for `Vec`
Quoted 28 lines · Boqun Feng
Quoted 18 lines · Alexandre Courbot
Quoted 5 lines · Benno Lossin
Quoted 2 lines · Alexandre Courbot
Implement these two common traits, which allow generic types to store either an owned value or a reference to it.
I don't understand the second part of the sentence.
I want to say that Borrow allows you to do something like:
struct Foo<B: Borrow<u32>>(B); // `foo1` owns its value... let foo1 = Foo(0x12); let i = 0x24; // ... but `foo2` just borrows it, subject to the lifetime of `i`. let foo2 = Foo(&i);Quoted 8 lines
And the implementations in this series also let you do:
// `foo3`'s value is owned, but heap-allocated let foo3 = Arc::new(KBox::new(0x56, GFP_KERNEL)?); let j = Arc::new(0x78, GFP_KERNEL)?; // `foo4`'s value is shared and its lifetime runtime-managed. let foo4 = Foo(j.clone());
Quoted 8 lines
Maybe you could put these in the "# Examples" section before impl blocks. E.g
/// # Examples /// ``` /// <you case above> /// ``` impl<T, A> Borrow<[T]> for Vec<T, A> ...
Does that get rendered in the docs? If not, I don't think we should do it.
---
Cheers,
Benno
Re: [PATCH 1/4] rust: alloc: implement `Borrow` and `BorrowMut` for `Vec`
Quoted 32 lines · Benno Lossin
Quoted 31 lines · Boqun Feng
Quoted 18 lines · Alexandre Courbot
Quoted 5 lines · Benno Lossin
Quoted 2 lines · Alexandre Courbot
Implement these two common traits, which allow generic types to store either an owned value or a reference to it.
I don't understand the second part of the sentence.
I want to say that Borrow allows you to do something like:
struct Foo<B: Borrow<u32>>(B); // `foo1` owns its value... let foo1 = Foo(0x12); let i = 0x24; // ... but `foo2` just borrows it, subject to the lifetime of `i`. let foo2 = Foo(&i);Quoted 8 lines
And the implementations in this series also let you do:
// `foo3`'s value is owned, but heap-allocated let foo3 = Arc::new(KBox::new(0x56, GFP_KERNEL)?); let j = Arc::new(0x78, GFP_KERNEL)?; // `foo4`'s value is shared and its lifetime runtime-managed. let foo4 = Foo(j.clone());Maybe you could put these in the "# Examples" section before impl blocks. E.g
Quoted 8 lines
Quoted 5 lines
/// # Examples /// ``` /// <you case above> /// ``` impl<T, A> Borrow<[T]> for Vec<T, A> ...Does that get rendered in the docs? If not, I don't think we should do it.
It does. I just tried myself, in the "Trait Implementations" section, if you provide a doc comment for an impl block, it will show under the "impl line" of corresponding to that impl block, including ```code```.
Regards,
Boqun
Quoted 4 lines
---
Cheers,
Benno
Alexandre Courbot
reviewerRe: [PATCH 1/4] rust: alloc: implement `Borrow` and `BorrowMut` for `Vec`
In reply to Boqun FengQuoted 30 lines · Boqun Feng
Quoted 20 lines · Alexandre Courbot
Hi Benno,
Quoted 5 lines · Benno Lossin
Quoted 2 lines · Alexandre Courbot
Implement these two common traits, which allow generic types to store either an owned value or a reference to it.
I don't understand the second part of the sentence.
I want to say that Borrow allows you to do something like:
struct Foo<B: Borrow<u32>>(B); // `foo1` owns its value... let foo1 = Foo(0x12); let i = 0x24; // ... but `foo2` just borrows it, subject to the lifetime of `i`. let foo2 = Foo(&i);Quoted 8 lines
And the implementations in this series also let you do:
// `foo3`'s value is owned, but heap-allocated let foo3 = Arc::new(KBox::new(0x56, GFP_KERNEL)?); let j = Arc::new(0x78, GFP_KERNEL)?; // `foo4`'s value is shared and its lifetime runtime-managed. let foo4 = Foo(j.clone());
Quoted 8 lines
Maybe you could put these in the "# Examples" section before impl blocks. E.g
/// # Examples /// ``` /// <you case above> /// ``` impl<T, A> Borrow<[T]> for Vec<T, A> ...
I've started doing this, but it felt like I was writing down the obvious as this kind of use is precisely what Borrow is intended for. I think Benno's suggestion for the commit log addresses your request for clarification, but let me add these on v2 anyway - we can always remove them if we conclude they are unnecessary.
Benno Lossin
reviewerRe: [PATCH 1/4] rust: alloc: implement `Borrow` and `BorrowMut` for `Vec`
In reply to Alexandre CourbotQuoted 20 lines · Alexandre Courbot
Hi Benno,
Quoted 5 lines · Benno Lossin
Quoted 2 lines · Alexandre Courbot
Implement these two common traits, which allow generic types to store either an owned value or a reference to it.
I don't understand the second part of the sentence.
I want to say that Borrow allows you to do something like:
struct Foo<B: Borrow<u32>>(B); // `foo1` owns its value... let foo1 = Foo(0x12); let i = 0x24; // ... but `foo2` just borrows it, subject to the lifetime of `i`. let foo2 = Foo(&i);
Quoted 8 lines
And the implementations in this series also let you do:
// `foo3`'s value is owned, but heap-allocated let foo3 = Arc::new(KBox::new(0x56, GFP_KERNEL)?); let j = Arc::new(0x78, GFP_KERNEL)?; // `foo4`'s value is shared and its lifetime runtime-managed. let foo4 = Foo(j.clone());
How about something like:
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.
Also note this paragraph from the docs:
In particular `Eq`, `Ord` and `Hash` must be equivalent for borrowed
and owned values: `x.borrow() == y.borrow()` should give the same
result as `x == y`.(This holds for the types that you implement it for, but I wanted to mention it)
---
Cheers,
Benno
Alexandre Courbot
reviewerRe: [PATCH 1/4] rust: alloc: implement `Borrow` and `BorrowMut` for `Vec`
Quoted 30 lines · Benno Lossin
Quoted 20 lines · Alexandre Courbot
Hi Benno,
Quoted 5 lines · Benno Lossin
Quoted 2 lines · Alexandre Courbot
Implement these two common traits, which allow generic types to store either an owned value or a reference to it.
I don't understand the second part of the sentence.
I want to say that Borrow allows you to do something like:
struct Foo<B: Borrow<u32>>(B); // `foo1` owns its value... let foo1 = Foo(0x12); let i = 0x24; // ... but `foo2` just borrows it, subject to the lifetime of `i`. let foo2 = Foo(&i);Quoted 8 lines
And the implementations in this series also let you do:
// `foo3`'s value is owned, but heap-allocated let foo3 = Arc::new(KBox::new(0x56, GFP_KERNEL)?); let j = Arc::new(0x78, GFP_KERNEL)?; // `foo4`'s value is shared and its lifetime runtime-managed. let foo4 = Foo(j.clone());
Quoted 6 lines
How about something like:
Implement
Borrow<[T]>andBorrowMut<[T]>forVec<T>. This allowsVec<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.
This is super clear, and I think I'll just reuse this message as-is if that's ok with you. Thanks!
Benno Lossin
reviewerRe: [PATCH 1/4] rust: alloc: implement `Borrow` and `BorrowMut` for `Vec`
Quoted 33 lines · Alexandre Courbot
Quoted 32 lines · Benno Lossin
Quoted 20 lines · Alexandre Courbot
Hi Benno,
Quoted 5 lines · Benno Lossin
Quoted 2 lines · Alexandre Courbot
Implement these two common traits, which allow generic types to store either an owned value or a reference to it.
I don't understand the second part of the sentence.
I want to say that Borrow allows you to do something like:
struct Foo<B: Borrow<u32>>(B); // `foo1` owns its value... let foo1 = Foo(0x12); let i = 0x24; // ... but `foo2` just borrows it, subject to the lifetime of `i`. let foo2 = Foo(&i);Quoted 8 lines
And the implementations in this series also let you do:
// `foo3`'s value is owned, but heap-allocated let foo3 = Arc::new(KBox::new(0x56, GFP_KERNEL)?); let j = Arc::new(0x78, GFP_KERNEL)?; // `foo4`'s value is shared and its lifetime runtime-managed. let foo4 = Foo(j.clone());How about something like:
Quoted 7 lines
Quoted 4 lines
Implement
Borrow<[T]>andBorrowMut<[T]>forVec<T>. This allowsVec<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.This is super clear, and I think I'll just reuse this message as-is if that's ok with you. Thanks!
Sure!
---
Cheers,
Benno
Alexandre Courbot
reviewerPATCH 2/4 rust: alloc: implement `Borrow` and `BorrowMut` for `Arc` types
In reply to Alexandre CourbotImplement these two common traits, which allow generic types to store either an owned value or a reference to it, leveraging the Deref implementation.
Arc can only implement Borrow, but UniqueArc is able to support both.
ForeignOwnable makes a call to its own borrow method which must be disambiguated.
--- rust/kernel/sync/arc.rs | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-)
rust/kernel/sync/arc.rs +20 -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,12 @@ fn as_ref(&self) -> &T { } } +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 +841,18 @@ fn deref_mut(&mut self) -> &mut Self::Target { } } +impl <T : ?Sized >Borrow <T >for UniqueArc <T > { +fn borrow (&self) -> &T { + self.deref () + } +} + +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
reviewerRe: [PATCH 2/4] rust: alloc: implement `Borrow` and `BorrowMut` for `Arc` types
Typical noticed-as-I-sent mistake: the prefix should be "rust: sync:", not "rust: alloc:" (also wrong on patch 4). Not resending just for that, will fix for v2.
Benno Lossin
reviewerRe: [PATCH 2/4] rust: alloc: implement `Borrow` and `BorrowMut` for `Arc` types
In reply to Alexandre CourbotQuoted 3 lines · Alexandre Courbot
Implement these two common traits, which allow generic types to store either an owned value or a reference to it, leveraging the
Derefimplementation.
Same here.
---
Cheers,
Benno
Quoted 11 lines
Arccan only implementBorrow, butUniqueArcis able to support both.
ForeignOwnablemakes a call to its ownborrowmethod which must be disambiguated.Signed-off-by Alexandre Courbot <[email protected]>--- rust/kernel/sync/arc.rs | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-)
Alexandre Courbot
reviewerPATCH 3/4 rust: alloc: implement `Borrow` and `BorrowMut` for `KBox`
In reply to Alexandre CourbotImplement these two common traits, which allow generic types to store either an owned value or a reference to it, leveraging the Deref implementation.
--- rust/kernel/alloc/kbox.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+)
rust/kernel/alloc/kbox.rs +21 -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,26 @@ fn deref_mut(&mut self) -> &mut T { } } +impl <T ,A >Borrow <T >for Box <T ,A > +where +T : ?Sized , +A :Allocator , +{ +fn borrow (&self) -> &T { + self.deref () + } +} + +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 4/4 rust: alloc: implement `Borrow` and `BorrowMut` for `CString`
In reply to Alexandre CourbotImplement these two common traits, which allow generic types to store either an owned value or a reference to it, leveraging the Deref implementation.
--- rust/kernel/str.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+)
rust/kernel/str.rs +13 -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,18 @@ fn deref_mut(&mut self) -> &mut Self::Target { } } +impl Borrow <CStr >for CString { +fn borrow (&self) -> &CStr { + self.deref () + } +} + +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
Quoted 13 lines · Alexandre Courbot
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, andCString. I came across the need for this while experimenting with the scatterlist abstraction series [1].This series provides just the
BorrowandBorrowMutimplementations, but another common use ofBorrowin the standard library is to use the borrowed type for key lookups in collections. For this to work, a few consistency traits (Eq,Hash, andOrd) need to be implemented. I am not sure whether we want this on kernel types as well, but please let me know if we do and I will add them in the next revision.
Quoted 3 lines
[1] https://lore.kernel.org/rust-for-linux/[email protected]/
Signed-off-by Alexandre Courbot <[email protected]>