Skip to contentSkip to conversation

rust: a few common Borrow/BorrowMut implementations

PATCH Superseded Alexandre Courbot 4 participants 17 messages Jun 1, 2025 – Jun 13, 2025

Subsystems (3)

v1 of 4 Superseded Latest is v4 →

lore
Share & tools
lore

Alexandre Courbot

author reviewer
#0 lore raw

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 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]>
author reviewer
#1 lore raw

PATCH 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
index 1a0dd852a468ccda6ea1b521bc1e7dbc8d7fc79c..45f813f69fe0f338a83c577752dd3ba1b3b2003f 100644
@@ -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
reviewer
#2 lore raw

Re: [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_slice and as_mut_slice.

---
 rust/kernel/alloc/kvec.rs | 19 +++++++++++++++++++
 1 file changed, 19 insertions(+)

The code itself looks good.

---
Cheers,
Benno

author reviewer
#3 lore raw

Re: [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());
#4 lore raw

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

reviewer
#5 lore raw

Re: [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

#6 lore raw

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

author reviewer
#7 lore raw

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

In reply to Boqun Feng
Quoted 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.

reviewer
#8 lore raw

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

In reply to Alexandre Courbot
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:

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

author reviewer
#9 lore raw

Re: [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]> 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.

This is super clear, and I think I'll just reuse this message as-is if that's ok with you. Thanks!

reviewer
#10 lore raw

Re: [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]> 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.

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

author reviewer
#11 lore raw

PATCH 2/4 rust: alloc: implement `Borrow` and `BorrowMut` for `Arc` types

In reply to Alexandre Courbot

Implement 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
index c7af0aa48a0a049bfeeba3a81080355f4d381738..40507e8901c349ba5f782457c203ff4cc181dd6c 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,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
author reviewer
#12 lore raw

Re: [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.

reviewer
#13 lore raw

Re: [PATCH 2/4] rust: alloc: implement `Borrow` and `BorrowMut` for `Arc` types

In reply to Alexandre Courbot
Quoted 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 Deref implementation.

Same here.

---
Cheers,
Benno

Quoted 11 lines

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(-)
author reviewer
#14 lore raw

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

In reply to Alexandre Courbot

Implement 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
index c386ff771d506a2eb4c211a93ea9b59bc04c93f5..73e66b4118b723a5e54de53144e4c1884098342f 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,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
author reviewer
#15 lore raw

PATCH 4/4 rust: alloc: implement `Borrow` and `BorrowMut` for `CString`

In reply to Alexandre Courbot

Implement 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
index a927db8e079c3597860880947a03959e1d6d712e..f5da512ebcfef6c8d5227e8177ae32f6194ecffb 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};
 
@@ -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<&'a CStr> for CString {
     type Error = AllocError;
 
Signature · 1 line
2.49.0
maintainer Reviewed-by on the v1 series
#16 lore raw
In reply to Alexandre Courbot
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, 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.

Quoted 3 lines

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