mirror of
git://git.yoctoproject.org/linux-yocto.git
synced 2026-01-27 12:47:24 +01:00
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: Alice Ryhl <aliceryhl@google.com> Reviewed-by: Benno Lossin <lossin@kernel.org> Signed-off-by: Alexandre Courbot <acourbot@nvidia.com> Link: https://lore.kernel.org/r/20250616-borrow_impls-v4-1-36f9beb3fe6a@nvidia.com Signed-off-by: Danilo Krummrich <dakr@kernel.org>
This commit is contained in:
parent
47d8101924
commit
c09a8ac1cd
|
|
@ -8,6 +8,7 @@ use super::{
|
|||
AllocError, Allocator, Box, Flags,
|
||||
};
|
||||
use core::{
|
||||
borrow::{Borrow, BorrowMut},
|
||||
fmt,
|
||||
marker::PhantomData,
|
||||
mem::{ManuallyDrop, MaybeUninit},
|
||||
|
|
@ -890,6 +891,58 @@ where
|
|||
}
|
||||
}
|
||||
|
||||
/// # 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>
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user