Skip to content

Commit 45077aa

Browse files
committed
Reflect suggested changes* Add unsafe* Use debug_assert instead of cfg* Improve the explanation in the assertion* UB and memory leak notes
1 parent 836e264 commit 45077aa

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

src/liballoc/vec.rs

+15-6
Original file line numberDiff line numberDiff line change
@@ -860,8 +860,15 @@ impl<T> Vec<T> {
860860
/// This is generally not recommended, use with caution!
861861
/// Calling this method with an out-of-allocation index is *[undefined behavior]*
862862
/// even if the resulting reference is not used.
863+
/// When you asign [`MaybeUninit::uninit()`] to the index in bounds, it is
864+
/// *[undefined behavior]* to call other methods or drop the vector before using [`set_len`]
865+
/// to make the index out of bounds.
866+
/// You can have a memory leak if you forget to use [`set_len`] to make the index in bounds
867+
/// after asigning value to the reference out of bounds.
863868
///
864869
/// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
870+
/// [`MaybeUninit::uninit()`]: ../mem/union.MaybeUninit.html#method.uninit
871+
/// [`set_len`]: #method.set_len
865872
///
866873
/// # Examples
867874
///
@@ -882,12 +889,14 @@ impl<T> Vec<T> {
882889
/// assert_eq!(&*x, &[0, 1, 2, 3]);
883890
/// ```
884891
#[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-
}
892+
pub unsafe fn get_uninit_unchecked(&mut self, index: usize) -> &mut MaybeUninit<T> {
893+
debug_assert!(
894+
index < self.capacity(),
895+
"index out of allocation: the capacity is {} but the index is {}",
896+
self.capacity(),
897+
index
898+
);
899+
&mut *(self.as_mut_ptr().add(index) as *mut MaybeUninit<T>)
891900
}
892901

893902
/// Forces the length of the vector to `new_len`.

0 commit comments

Comments
 (0)