Skip to content

Commit de91157

Browse files
committed
add Box::try_new_zeroed_slice()
Currently there is no API that allows fallible zero-allocation of a Vec. Vec.try_reserve is not appropriate for this job since it doesn't know whether it should zero or arbitrary uninitialized memory is fine. Since Box currently holds most of the zeroing/uninit/slice allocation APIs it's the best place to add yet another entry into this feature matrix.
1 parent 6fe0886 commit de91157

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

library/alloc/src/boxed.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -589,6 +589,38 @@ impl<T> Box<[T]> {
589589
pub fn new_zeroed_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
590590
unsafe { RawVec::with_capacity_zeroed(len).into_box(len) }
591591
}
592+
593+
/// Constructs a new boxed slice with uninitialized contents, with the memory
594+
/// being filled with `0` bytes. Returns an error if the allocation fails
595+
///
596+
/// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
597+
/// of this method.
598+
///
599+
/// # Examples
600+
///
601+
/// ```
602+
/// #![feature(allocator_api, new_uninit)]
603+
///
604+
/// let values = Box::<[u32]>::try_new_zeroed_slice(3)?;
605+
/// let values = unsafe { values.assume_init() };
606+
///
607+
/// assert_eq!(*values, [0, 0, 0]);
608+
/// # Ok::<(), std::alloc::AllocError>(())
609+
/// ```
610+
///
611+
/// [zeroed]: mem::MaybeUninit::zeroed
612+
#[unstable(feature = "allocator_api", issue = "32838")]
613+
#[inline]
614+
pub fn try_new_zeroed_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_zeroed(layout)?;
621+
Ok(RawVec::from_raw_parts_in(ptr.as_mut_ptr() as *mut _, len, Global).into_box(len))
622+
}
623+
}
592624
}
593625

594626
impl<T, A: Allocator> Box<[T], A> {

0 commit comments

Comments
 (0)