@@ -66,7 +66,7 @@ use core::hash::{self, Hash};
66
66
use core:: intrinsics:: { arith_offset, assume} ;
67
67
use core:: iter:: { FromIterator , FusedIterator , TrustedLen } ;
68
68
use core:: marker:: PhantomData ;
69
- use core:: mem:: { self , ManuallyDrop } ;
69
+ use core:: mem:: { self , ManuallyDrop , MaybeUninit } ;
70
70
use core:: ops:: Bound :: { Excluded , Included , Unbounded } ;
71
71
use core:: ops:: { self , Index , IndexMut , RangeBounds } ;
72
72
use core:: ptr:: { self , NonNull } ;
@@ -854,6 +854,42 @@ impl<T> Vec<T> {
854
854
ptr
855
855
}
856
856
857
+ /// Returns a mutable reference to an element, without doing bounds
858
+ /// checking.
859
+ ///
860
+ /// This is generally not recommended, use with caution!
861
+ /// Calling this method with an out-of-allocation index is *[undefined behavior]*
862
+ /// even if the resulting reference is not used.
863
+ ///
864
+ /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
865
+ ///
866
+ /// # Examples
867
+ ///
868
+ /// ```
869
+ /// #![feature(vec_get_uninit_unchecked, maybe_uninit_extra)]
870
+ ///
871
+ /// // Allocate vector big enough for 4 elements.
872
+ /// let size = 4;
873
+ /// let mut x = Vec::with_capacity(4);
874
+ ///
875
+ /// // Initialize elements via raw pointer writes, then set length.
876
+ /// unsafe {
877
+ /// for i in 0..size {
878
+ /// x.get_uninit_unchecked(i).write(i as i32);
879
+ /// }
880
+ /// x.set_len(size);
881
+ /// }
882
+ /// assert_eq!(&*x, &[0, 1, 2, 3]);
883
+ /// ```
884
+ #[ unstable( feature = "vec_get_uninit_unchecked" , issue = "none" ) ]
885
+ pub fn get_uninit_unchecked ( & mut self , index : usize ) -> & mut MaybeUninit < T > {
886
+ if cfg ! ( debug_assertions) && index >= self . capacity ( ) {
887
+ panic ! ( "Out of allocation access" )
888
+ } else {
889
+ unsafe { & mut * ( self . as_mut_ptr ( ) . add ( index) as * mut MaybeUninit < T > ) }
890
+ }
891
+ }
892
+
857
893
/// Forces the length of the vector to `new_len`.
858
894
///
859
895
/// This is a low-level operation that maintains none of the normal
0 commit comments