未验证 提交 d544e21d 编写于 作者: M Manish Goregaokar 提交者: GitHub

Rollup merge of #75015 - Amanieu:vec_spare, r=sfackler

Add Vec::spare_capacity_mut

Returns the remaining spare capacity of the vector as a slice of `MaybeUninit<T>`.

As suggested by @sfackler in https://github.com/rust-lang/rust/pull/70967#issuecomment-612659006.

r? @sfackler
...@@ -65,7 +65,7 @@ ...@@ -65,7 +65,7 @@
use core::intrinsics::{arith_offset, assume}; use core::intrinsics::{arith_offset, assume};
use core::iter::{FromIterator, FusedIterator, TrustedLen}; use core::iter::{FromIterator, FusedIterator, TrustedLen};
use core::marker::PhantomData; 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::Bound::{Excluded, Included, Unbounded};
use core::ops::{self, Index, IndexMut, RangeBounds}; use core::ops::{self, Index, IndexMut, RangeBounds};
use core::ptr::{self, NonNull}; use core::ptr::{self, NonNull};
...@@ -1525,6 +1525,47 @@ pub fn leak<'a>(vec: Vec<T>) -> &'a mut [T] ...@@ -1525,6 +1525,47 @@ pub fn leak<'a>(vec: Vec<T>) -> &'a mut [T]
{ {
Box::leak(vec.into_boxed_slice()) Box::leak(vec.into_boxed_slice())
} }
/// Returns the remaining spare capacity of the vector as a slice of
/// `MaybeUninit<T>`.
///
/// The returned slice can be used to fill the vector with data (e.g. by
/// reading from a file) before marking the data as initialized using the
/// [`set_len`] method.
///
/// [`set_len`]: #method.set_len
///
/// # Examples
///
/// ```
/// #![feature(vec_spare_capacity, maybe_uninit_extra)]
///
/// // Allocate vector big enough for 10 elements.
/// let mut v = Vec::with_capacity(10);
///
/// // Fill in the first 3 elements.
/// let uninit = v.spare_capacity_mut();
/// uninit[0].write(0);
/// uninit[1].write(1);
/// uninit[2].write(2);
///
/// // Mark the first 3 elements of the vector as being initialized.
/// unsafe {
/// v.set_len(3);
/// }
///
/// assert_eq!(&v, &[0, 1, 2]);
/// ```
#[unstable(feature = "vec_spare_capacity", issue = "75017")]
#[inline]
pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
unsafe {
slice::from_raw_parts_mut(
self.as_mut_ptr().add(self.len) as *mut MaybeUninit<T>,
self.buf.capacity() - self.len,
)
}
}
} }
impl<T: Clone> Vec<T> { impl<T: Clone> Vec<T> {
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册