Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions library/alloc/src/boxed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -619,6 +619,37 @@ impl<T, A: Allocator> Box<T, A> {
pub fn into_inner(boxed: Self) -> T {
*boxed
}

/// Consumes the `Box` without consuming its allocation, returning the wrapped value and a `Box`
/// to the uninitialized memory where the wrapped value used to live.
///
/// This can be used together with [`write`](Box::write) to reuse the allocation for multiple
/// boxed values.
///
/// # Examples
///
/// ```
/// #![feature(box_take)]
///
/// let c = Box::new(5);
///
/// // take the value out of the box
/// let (value, uninit) = Box::take(c);
/// assert_eq!(value, 5);
///
/// // reuse the box for a second value
/// let c = Box::write(uninit, 6);
/// assert_eq!(*c, 6);
/// ```
#[unstable(feature = "box_take", issue = "147212")]
pub fn take(boxed: Self) -> (T, Box<mem::MaybeUninit<T>, A>) {
unsafe {
let (raw, alloc) = Box::into_raw_with_allocator(boxed);
let value = raw.read();
let uninit = Box::from_raw_in(raw.cast::<mem::MaybeUninit<T>>(), alloc);
(value, uninit)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you use Box::into_non_null_with_allocator and NonNull::cast_uninit?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure! However since this has already been r+'ed, I think I'll save that change for the inevitable renaming of the function, since as far as I can tell the semantics are identical from the outside.

}
}
}

impl<T> Box<[T]> {
Expand Down
Loading