Skip to content

Commit 33eb060

Browse files
committed
implement Box::take
1 parent 1e1a394 commit 33eb060

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

library/alloc/src/boxed.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -619,6 +619,29 @@ impl<T, A: Allocator> Box<T, A> {
619619
pub fn into_inner(boxed: Self) -> T {
620620
*boxed
621621
}
622+
623+
/// Consumes the `Box` without consuming its allocation, returning the wrapped value and a `Box`
624+
/// to the uninitialized memory where the wrapped value used to live.
625+
///
626+
/// # Examples
627+
///
628+
/// ```
629+
/// #![feature(box_take)]
630+
///
631+
/// let c = Box::new(5);
632+
///
633+
/// let (value, uninit) = Box::take(c);
634+
/// assert_eq!(value, 5);
635+
/// ```
636+
#[unstable(feature = "box_take", issue = "147212")]
637+
pub fn take(boxed: Self) -> (T, Box<mem::MaybeUninit<T>, A>) {
638+
unsafe {
639+
let (raw, alloc) = Box::into_raw_with_allocator(boxed);
640+
let value = raw.read();
641+
let uninit = Box::from_raw_in(raw.cast::<mem::MaybeUninit<T>>(), alloc);
642+
(value, uninit)
643+
}
644+
}
622645
}
623646

624647
impl<T> Box<[T]> {

0 commit comments

Comments
 (0)