Skip to content

Commit 25a238e

Browse files
authored
Rollup merge of rust-lang#88906 - Kixunil:box-maybe-uninit-write, r=dtolnay
Implement write() method for Box<MaybeUninit<T>> This adds method similar to `MaybeUninit::write` main difference being it returns owned `Box`. This can be used to elide copy from stack safely, however it's not currently tested that the optimization actually occurs. Analogous methods are not provided for `Rc` and `Arc` as those need to handle the possibility of sharing. Some version of them may be added in the future. This was discussed in rust-lang#63291 which this change extends.
2 parents c1033e1 + ec19cc4 commit 25a238e

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

alloc/src/boxed.rs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -763,6 +763,42 @@ impl<T, A: Allocator> Box<mem::MaybeUninit<T>, A> {
763763
let (raw, alloc) = Box::into_raw_with_allocator(self);
764764
unsafe { Box::from_raw_in(raw as *mut T, alloc) }
765765
}
766+
767+
/// Writes the value and converts to `Box<T, A>`.
768+
///
769+
/// This method converts the box similarly to [`Box::assume_init`] but
770+
/// writes `value` into it before conversion thus guaranteeing safety.
771+
/// In some scenarios use of this method may improve performance because
772+
/// the compiler may be able to optimize copying from stack.
773+
///
774+
/// # Examples
775+
///
776+
/// ```
777+
/// #![feature(new_uninit)]
778+
///
779+
/// let big_box = Box::<[usize; 1024]>::new_uninit();
780+
///
781+
/// let mut array = [0; 1024];
782+
/// for (i, place) in array.iter_mut().enumerate() {
783+
/// *place = i;
784+
/// }
785+
///
786+
/// // The optimizer may be able to elide this copy, so previous code writes
787+
/// // to heap directly.
788+
/// let big_box = Box::write(big_box, array);
789+
///
790+
/// for (i, x) in big_box.iter().enumerate() {
791+
/// assert_eq!(*x, i);
792+
/// }
793+
/// ```
794+
#[unstable(feature = "new_uninit", issue = "63291")]
795+
#[inline]
796+
pub fn write(mut boxed: Self, value: T) -> Box<T, A> {
797+
unsafe {
798+
(*boxed).write(value);
799+
boxed.assume_init()
800+
}
801+
}
766802
}
767803

768804
impl<T, A: Allocator> Box<[mem::MaybeUninit<T>], A> {

0 commit comments

Comments
 (0)