Skip to content

Commit 1c21373

Browse files
committed
add Box::try_new_uninit_slice for symmetry
1 parent 55def12 commit 1c21373

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

library/alloc/src/boxed.rs

+33
Original file line numberDiff line numberDiff line change
@@ -589,6 +589,39 @@ impl<T> Box<[T]> {
589589
unsafe { RawVec::with_capacity_zeroed(len).into_box(len) }
590590
}
591591

592+
/// Constructs a new boxed slice with uninitialized contents. Returns an error if
593+
/// the allocation fails
594+
///
595+
/// # Examples
596+
///
597+
/// ```
598+
/// #![feature(allocator_api, new_uninit)]
599+
///
600+
/// let mut values = Box::<[u32]>::try_new_uninit_slice(3)?;
601+
/// let values = unsafe {
602+
/// // Deferred initialization:
603+
/// values[0].as_mut_ptr().write(1);
604+
/// values[1].as_mut_ptr().write(2);
605+
/// values[2].as_mut_ptr().write(3);
606+
/// values.assume_init()
607+
/// };
608+
///
609+
/// assert_eq!(*values, [1, 2, 3]);
610+
/// # Ok::<(), std::alloc::AllocError>(())
611+
/// ```
612+
#[unstable(feature = "allocator_api", issue = "32838")]
613+
#[inline]
614+
pub fn try_new_uninit_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError> {
615+
unsafe {
616+
let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
617+
Ok(l) => l,
618+
Err(_) => return Err(AllocError),
619+
};
620+
let ptr = Global.allocate(layout)?;
621+
Ok(RawVec::from_raw_parts_in(ptr.as_mut_ptr() as *mut _, len, Global).into_box(len))
622+
}
623+
}
624+
592625
/// Constructs a new boxed slice with uninitialized contents, with the memory
593626
/// being filled with `0` bytes. Returns an error if the allocation fails
594627
///

0 commit comments

Comments
 (0)