@@ -65,7 +65,7 @@ use core::hash::{Hash, Hasher};
65
65
use core:: intrinsics:: { arith_offset, assume} ;
66
66
use core:: iter:: { FromIterator , FusedIterator , TrustedLen } ;
67
67
use core:: marker:: PhantomData ;
68
- use core:: mem:: { self , ManuallyDrop } ;
68
+ use core:: mem:: { self , ManuallyDrop , MaybeUninit } ;
69
69
use core:: ops:: Bound :: { Excluded , Included , Unbounded } ;
70
70
use core:: ops:: { self , Index , IndexMut , RangeBounds } ;
71
71
use core:: ptr:: { self , NonNull } ;
@@ -1525,6 +1525,47 @@ impl<T> Vec<T> {
1525
1525
{
1526
1526
Box :: leak ( vec. into_boxed_slice ( ) )
1527
1527
}
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
+ }
1528
1569
}
1529
1570
1530
1571
impl < T : Clone > Vec < T > {
0 commit comments