Skip to content

Commit 5d2eee8

Browse files
authored
Unrolled build for #147227
Rollup merge of #147227 - edwloef:box_take, r=joboet implement `Box::take` Tracking issue: #147212 I'm not entirely sure about the wording of the doc comment, if anyone has any suggestions that'd be great :)
2 parents 4b9c62b + 8dfea22 commit 5d2eee8

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

library/alloc/src/boxed.rs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -619,6 +619,37 @@ 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+
/// This can be used together with [`write`](Box::write) to reuse the allocation for multiple
627+
/// boxed values.
628+
///
629+
/// # Examples
630+
///
631+
/// ```
632+
/// #![feature(box_take)]
633+
///
634+
/// let c = Box::new(5);
635+
///
636+
/// // take the value out of the box
637+
/// let (value, uninit) = Box::take(c);
638+
/// assert_eq!(value, 5);
639+
///
640+
/// // reuse the box for a second value
641+
/// let c = Box::write(uninit, 6);
642+
/// assert_eq!(*c, 6);
643+
/// ```
644+
#[unstable(feature = "box_take", issue = "147212")]
645+
pub fn take(boxed: Self) -> (T, Box<mem::MaybeUninit<T>, A>) {
646+
unsafe {
647+
let (raw, alloc) = Box::into_raw_with_allocator(boxed);
648+
let value = raw.read();
649+
let uninit = Box::from_raw_in(raw.cast::<mem::MaybeUninit<T>>(), alloc);
650+
(value, uninit)
651+
}
652+
}
622653
}
623654

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

0 commit comments

Comments
 (0)