Skip to content

Commit 836e264

Browse files
committed
Add Vec::get_uninit_unchecked
1 parent 93dc97a commit 836e264

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

src/liballoc/vec.rs

+37-1
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ use core::hash::{self, Hash};
6666
use core::intrinsics::{arith_offset, assume};
6767
use core::iter::{FromIterator, FusedIterator, TrustedLen};
6868
use core::marker::PhantomData;
69-
use core::mem::{self, ManuallyDrop};
69+
use core::mem::{self, ManuallyDrop, MaybeUninit};
7070
use core::ops::Bound::{Excluded, Included, Unbounded};
7171
use core::ops::{self, Index, IndexMut, RangeBounds};
7272
use core::ptr::{self, NonNull};
@@ -854,6 +854,42 @@ impl<T> Vec<T> {
854854
ptr
855855
}
856856

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+
857893
/// Forces the length of the vector to `new_len`.
858894
///
859895
/// This is a low-level operation that maintains none of the normal

0 commit comments

Comments
 (0)