Commit c09a8ac1 authored by Alexandre Courbot's avatar Alexandre Courbot Committed by Danilo Krummrich
Browse files

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`.

Reviewed-by: default avatarAlice Ryhl <aliceryhl@google.com>
Reviewed-by: default avatarBenno Lossin <lossin@kernel.org>
Signed-off-by: default avatarAlexandre Courbot <acourbot@nvidia.com>
Link: https://lore.kernel.org/r/20250616-borrow_impls-v4-1-36f9beb3fe6a@nvidia.com


Signed-off-by: default avatarDanilo Krummrich <dakr@kernel.org>
parent 47d81019
Loading
Loading
Loading
Loading
+53 −0
Original line number Diff line number Diff line
@@ -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>