Skip to content

Commit d544e21

Browse files
authored
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 #70967 (comment). r? @sfackler
2 parents 98a9397 + df3a30a commit d544e21

File tree

1 file changed

+42
-1
lines changed

1 file changed

+42
-1
lines changed

library/alloc/src/vec.rs

+42-1
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ use core::hash::{Hash, Hasher};
6565
use core::intrinsics::{arith_offset, assume};
6666
use core::iter::{FromIterator, FusedIterator, TrustedLen};
6767
use core::marker::PhantomData;
68-
use core::mem::{self, ManuallyDrop};
68+
use core::mem::{self, ManuallyDrop, MaybeUninit};
6969
use core::ops::Bound::{Excluded, Included, Unbounded};
7070
use core::ops::{self, Index, IndexMut, RangeBounds};
7171
use core::ptr::{self, NonNull};
@@ -1525,6 +1525,47 @@ impl<T> Vec<T> {
15251525
{
15261526
Box::leak(vec.into_boxed_slice())
15271527
}
1528+
1529+
/// Returns the remaining spare capacity of the vector as a slice of
1530+
/// `MaybeUninit<T>`.
1531+
///
1532+
/// The returned slice can be used to fill the vector with data (e.g. by
1533+
/// reading from a file) before marking the data as initialized using the
1534+
/// [`set_len`] method.
1535+
///
1536+
/// [`set_len`]: #method.set_len
1537+
///
1538+
/// # Examples
1539+
///
1540+
/// ```
1541+
/// #![feature(vec_spare_capacity, maybe_uninit_extra)]
1542+
///
1543+
/// // Allocate vector big enough for 10 elements.
1544+
/// let mut v = Vec::with_capacity(10);
1545+
///
1546+
/// // Fill in the first 3 elements.
1547+
/// let uninit = v.spare_capacity_mut();
1548+
/// uninit[0].write(0);
1549+
/// uninit[1].write(1);
1550+
/// uninit[2].write(2);
1551+
///
1552+
/// // Mark the first 3 elements of the vector as being initialized.
1553+
/// unsafe {
1554+
/// v.set_len(3);
1555+
/// }
1556+
///
1557+
/// assert_eq!(&v, &[0, 1, 2]);
1558+
/// ```
1559+
#[unstable(feature = "vec_spare_capacity", issue = "75017")]
1560+
#[inline]
1561+
pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
1562+
unsafe {
1563+
slice::from_raw_parts_mut(
1564+
self.as_mut_ptr().add(self.len) as *mut MaybeUninit<T>,
1565+
self.buf.capacity() - self.len,
1566+
)
1567+
}
1568+
}
15281569
}
15291570

15301571
impl<T: Clone> Vec<T> {

0 commit comments

Comments
 (0)