Skip to content

Commit 89a3e93

Browse files
BennoLossinmatthewtgilbride
authored andcommitted
rust: kernel: add drop_contents to BoxExt
Sometimes (see [1]) it is necessary to drop the value inside of a `Box<T>`, but retain the allocation. For example to reuse the allocation in the future. Introduce a new function `drop_contents` that turns a `Box<T>` into `Box<MaybeUninit<T>>` by dropping the value. Signed-off-by: Benno Lossin <[email protected]> Link: https://lore.kernel.org/rust-for-linux/[email protected]/ [1]
1 parent 28d3fa7 commit 89a3e93

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

rust/kernel/alloc/box_ext.rs

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
55
use super::{AllocError, Flags};
66
use alloc::boxed::Box;
7-
use core::mem::MaybeUninit;
7+
use core::{mem::MaybeUninit, ptr};
88

99
/// Extensions to [`Box`].
1010
pub trait BoxExt<T>: Sized {
@@ -17,6 +17,20 @@ pub trait BoxExt<T>: Sized {
1717
///
1818
/// The allocation may fail, in which case an error is returned.
1919
fn new_uninit(flags: Flags) -> Result<Box<MaybeUninit<T>>, AllocError>;
20+
21+
/// Drops the contents, but keeps the allocation.
22+
///
23+
/// # Examples
24+
///
25+
/// ```
26+
/// use kernel::alloc::flags;
27+
///
28+
/// let value = Box::new([0; 32], flags::GFP_KERNEL);
29+
/// let value = value.unwrap().drop_contents();
30+
/// // Now we can re-use `value`:
31+
/// Box::write(value, [1; 32]);
32+
/// ```
33+
fn drop_contents(self) -> Box<MaybeUninit<T>>;
2034
}
2135

2236
impl<T> BoxExt<T> for Box<T> {
@@ -53,4 +67,12 @@ impl<T> BoxExt<T> for Box<T> {
5367
// zero-sized types, we use `NonNull::dangling`.
5468
Ok(unsafe { Box::from_raw(ptr) })
5569
}
70+
71+
fn drop_contents(self) -> Box<MaybeUninit<T>> {
72+
let ptr = Box::into_raw(self);
73+
// SAFETY: `ptr` is valid, because it came from `Box::into_raw`.
74+
unsafe { ptr::drop_in_place(ptr) };
75+
// SAFETY: `ptr` is valid, because it came from `Box::into_raw`.
76+
unsafe { Box::from_raw(ptr.cast()) }
77+
}
5678
}

0 commit comments

Comments
 (0)