diff options
| author | Amanieu d'Antras <amanieu@gmail.com> | 2020-08-01 17:03:04 +0100 |
|---|---|---|
| committer | Amanieu d'Antras <amanieu@gmail.com> | 2020-08-01 18:24:35 +0100 |
| commit | df3a30aee4fe514c1fd1193d3a7e739b1a66ab8f (patch) | |
| tree | 935c8bdf9b37940501bb4a26111b179b24c8caf3 | |
| parent | cfdf9d335501cc0a53ae69c940095cca7d4be0f8 (diff) | |
| download | rust-df3a30aee4fe514c1fd1193d3a7e739b1a66ab8f.tar.gz rust-df3a30aee4fe514c1fd1193d3a7e739b1a66ab8f.zip | |
Add Vec::spare_capacity_mut
| -rw-r--r-- | library/alloc/src/vec.rs | 43 |
1 files changed, 42 insertions, 1 deletions
diff --git a/library/alloc/src/vec.rs b/library/alloc/src/vec.rs index f5a3d0cd4af..159f45ffce1 100644 --- a/library/alloc/src/vec.rs +++ b/library/alloc/src/vec.rs @@ -65,7 +65,7 @@ use core::hash::{Hash, Hasher}; 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}; @@ -1525,6 +1525,47 @@ impl<T> Vec<T> { { 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> { |
