Skip to content

Add Vec::get_uninit_unchecked #70967

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 37 additions & 1 deletion src/liballoc/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ use core::hash::{self, Hash};
use core::intrinsics::{arith_offset, assume};
use core::iter::{FromIterator, FusedIterator, TrustedLen};
use core::marker::PhantomData;
use core::mem::{self, ManuallyDrop};
use core::mem::{self, ManuallyDrop, MaybeUninit};
use core::ops::Bound::{Excluded, Included, Unbounded};
use core::ops::{self, Index, IndexMut, RangeBounds};
use core::ptr::{self, NonNull};
Expand Down Expand Up @@ -854,6 +854,42 @@ impl<T> Vec<T> {
ptr
}

/// Returns a mutable reference to an element, without doing bounds
/// checking.
///
/// This is generally not recommended, use with caution!
/// Calling this method with an out-of-allocation index is *[undefined behavior]*
/// even if the resulting reference is not used.
///
/// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
///
/// # Examples
///
/// ```
/// #![feature(vec_get_uninit_unchecked, maybe_uninit_extra)]
///
/// // Allocate vector big enough for 4 elements.
/// let size = 4;
/// let mut x = Vec::with_capacity(4);
///
/// // Initialize elements via raw pointer writes, then set length.
/// unsafe {
/// for i in 0..size {
/// x.get_uninit_unchecked(i).write(i as i32);
/// }
/// x.set_len(size);
/// }
/// assert_eq!(&*x, &[0, 1, 2, 3]);
/// ```
#[unstable(feature = "vec_get_uninit_unchecked", issue = "none")]
pub fn get_uninit_unchecked(&mut self, index: usize) -> &mut MaybeUninit<T> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
pub fn get_uninit_unchecked(&mut self, index: usize) -> &mut MaybeUninit<T> {
pub unsafe fn get_uninit_unchecked(&mut self, index: usize) -> &mut MaybeUninit<T> {

There are two ways in which you can violate soundness with this method:

  1. You provide index where index >= self.capacity().
  2. You do let elem = vec.get_uninit_unchecked(index); *elem = MaybeUninit::uninit(); drop(vec[index]);.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, you can have a memory leak if you forget to use vec.set_len(...) afterwards in some circumstances; also worth noting in docs.

if cfg!(debug_assertions) && index >= self.capacity() {
panic!("Out of allocation access")
} else {
unsafe { &mut *(self.as_mut_ptr().add(index) as *mut MaybeUninit<T>) }
}
}

/// Forces the length of the vector to `new_len`.
///
/// This is a low-level operation that maintains none of the normal
Expand Down