@@ -87,6 +87,46 @@ impl<T, const CAP: usize> ArrayVec<T, CAP> {
8787 }
8888 }
8989
90+ /// Initialize an empty `ArrayVec` in-place.
91+ ///
92+ /// Useful when you want to store a huge `ArrayVec` in some pre-initialized memory and
93+ /// don't want to create and move it from the stack.
94+ /// This is very cheap as all elements are uninitialized when the vec is empty.
95+ ///
96+ /// ```
97+ /// use arrayvec::ArrayVec;
98+ /// use std::mem::MaybeUninit;
99+ ///
100+ /// let mut place = MaybeUninit::<ArrayVec<_, 10>>::uninit();
101+ /// let vec = ArrayVec::new_in_place(&mut place);
102+ /// assert_eq!(vec.len(), 0);
103+ /// assert_eq!(vec.capacity(), 10);
104+ /// vec.push(42);
105+ /// assert_eq!(vec, [42].as_slice());
106+ /// ```
107+ ///
108+ /// ### Creating an `ArrayVec` on the Heap
109+ ///
110+ /// The return value is the same reference as passed to the function. Thus you can just
111+ /// ignore that and assume that your [`MaybeUninit`] is initialized.
112+ ///
113+ /// ```
114+ /// use arrayvec::ArrayVec;
115+ /// use std::mem::MaybeUninit;
116+ ///
117+ /// let mut place = Box::new_uninit();
118+ /// ArrayVec::new_in_place(&mut place);
119+ /// let vec: Box<ArrayVec<u32, 10>> = unsafe { place.assume_init() };
120+ /// assert_eq!(vec.len(), 0);
121+ /// assert_eq!(vec.capacity(), 10);
122+ /// ```
123+ #[ inline]
124+ pub fn new_in_place ( uninit : & mut MaybeUninit < Self > ) -> & mut Self {
125+ let ptr = uninit. as_mut_ptr ( ) ;
126+ unsafe { ptr:: addr_of_mut!( ( * ptr) . len) . write ( 0 ) ; }
127+ unsafe { uninit. assume_init_mut ( ) }
128+ }
129+
90130 /// Create a new empty `ArrayVec` (const fn).
91131 ///
92132 /// The maximum capacity is given by the generic parameter `CAP`.
0 commit comments