@@ -589,6 +589,39 @@ impl<T> Box<[T]> {
589
589
unsafe { RawVec :: with_capacity_zeroed ( len) . into_box ( len) }
590
590
}
591
591
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
+
592
625
/// Constructs a new boxed slice with uninitialized contents, with the memory
593
626
/// being filled with `0` bytes. Returns an error if the allocation fails
594
627
///
0 commit comments