Skip to content

Commit 769e324

Browse files
Gnurouojeda
authored andcommitted
rust: alloc: implement Borrow and BorrowMut for KBox
Implement `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. Reviewed-by: Alice Ryhl <[email protected]> Reviewed-by: Benno Lossin <[email protected]> Signed-off-by: Alexandre Courbot <[email protected]> Link: https://lore.kernel.org/r/[email protected] Signed-off-by: Miguel Ojeda <[email protected]>
1 parent d6763e0 commit 769e324

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

rust/kernel/alloc/kbox.rs

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
use super::allocator::{KVmalloc, Kmalloc, Vmalloc};
77
use super::{AllocError, Allocator, Flags};
88
use core::alloc::Layout;
9+
use core::borrow::{Borrow, BorrowMut};
910
use core::fmt;
1011
use core::marker::PhantomData;
1112
use core::mem::ManuallyDrop;
@@ -499,6 +500,62 @@ where
499500
}
500501
}
501502

503+
/// # Examples
504+
///
505+
/// ```
506+
/// # use core::borrow::Borrow;
507+
/// # use kernel::alloc::KBox;
508+
/// struct Foo<B: Borrow<u32>>(B);
509+
///
510+
/// // Owned instance.
511+
/// let owned = Foo(1);
512+
///
513+
/// // Owned instance using `KBox`.
514+
/// let owned_kbox = Foo(KBox::new(1, GFP_KERNEL)?);
515+
///
516+
/// let i = 1;
517+
/// // Borrowed from `i`.
518+
/// let borrowed = Foo(&i);
519+
/// # Ok::<(), Error>(())
520+
/// ```
521+
impl<T, A> Borrow<T> for Box<T, A>
522+
where
523+
T: ?Sized,
524+
A: Allocator,
525+
{
526+
fn borrow(&self) -> &T {
527+
self.deref()
528+
}
529+
}
530+
531+
/// # Examples
532+
///
533+
/// ```
534+
/// # use core::borrow::BorrowMut;
535+
/// # use kernel::alloc::KBox;
536+
/// struct Foo<B: BorrowMut<u32>>(B);
537+
///
538+
/// // Owned instance.
539+
/// let owned = Foo(1);
540+
///
541+
/// // Owned instance using `KBox`.
542+
/// let owned_kbox = Foo(KBox::new(1, GFP_KERNEL)?);
543+
///
544+
/// let mut i = 1;
545+
/// // Borrowed from `i`.
546+
/// let borrowed = Foo(&mut i);
547+
/// # Ok::<(), Error>(())
548+
/// ```
549+
impl<T, A> BorrowMut<T> for Box<T, A>
550+
where
551+
T: ?Sized,
552+
A: Allocator,
553+
{
554+
fn borrow_mut(&mut self) -> &mut T {
555+
self.deref_mut()
556+
}
557+
}
558+
502559
impl<T, A> fmt::Display for Box<T, A>
503560
where
504561
T: ?Sized + fmt::Display,

0 commit comments

Comments
 (0)