@@ -867,6 +867,36 @@ impl<T, const N: usize> Vec<T, N> {
867
867
// All item are processed. This can be optimized to `set_len` by LLVM.
868
868
drop ( g) ;
869
869
}
870
+
871
+ /// Returns the remaining spare capacity of the vector as a slice of `MaybeUninit<T>`.
872
+ ///
873
+ /// The returned slice can be used to fill the vector with data before marking the data as
874
+ /// initialized using the `set_len` method.
875
+ ///
876
+ /// # Examples
877
+ ///
878
+ /// ```
879
+ /// use heapless::Vec;
880
+ ///
881
+ /// // Allocate vector big enough for 10 elements.
882
+ /// let mut v: Vec<_, 10> = Vec::new();
883
+ ///
884
+ /// // Fill in the first 3 elements.
885
+ /// let uninit = v.spare_capacity_mut();
886
+ /// uninit[0].write(0);
887
+ /// uninit[1].write(1);
888
+ /// uninit[2].write(2);
889
+ ///
890
+ /// // Mark the first 3 elements of the vector as being initialized.
891
+ /// unsafe {
892
+ /// v.set_len(3);
893
+ /// }
894
+ ///
895
+ /// assert_eq!(&v, &[0, 1, 2]);
896
+ /// ```
897
+ pub fn spare_capacity_mut ( & mut self ) -> & mut [ MaybeUninit < T > ] {
898
+ & mut self . buffer [ self . len ..]
899
+ }
870
900
}
871
901
872
902
// Trait implementations
@@ -1665,4 +1695,24 @@ mod tests {
1665
1695
// Validate full
1666
1696
assert ! ( v. is_full( ) ) ;
1667
1697
}
1698
+
1699
+ #[ test]
1700
+ fn spare_capacity_mut ( ) {
1701
+ let mut v: Vec < _ , 4 > = Vec :: new ( ) ;
1702
+ let uninit = v. spare_capacity_mut ( ) ;
1703
+ assert_eq ! ( uninit. len( ) , 4 ) ;
1704
+ uninit[ 0 ] . write ( 1 ) ;
1705
+ uninit[ 1 ] . write ( 2 ) ;
1706
+ uninit[ 2 ] . write ( 3 ) ;
1707
+ unsafe { v. set_len ( 3 ) } ;
1708
+ assert_eq ! ( v. as_slice( ) , & [ 1 , 2 , 3 ] ) ;
1709
+
1710
+ let uninit = v. spare_capacity_mut ( ) ;
1711
+ assert_eq ! ( uninit. len( ) , 1 ) ;
1712
+ uninit[ 0 ] . write ( 4 ) ;
1713
+ unsafe { v. set_len ( 4 ) } ;
1714
+ assert_eq ! ( v. as_slice( ) , & [ 1 , 2 , 3 , 4 ] ) ;
1715
+
1716
+ assert ! ( v. spare_capacity_mut( ) . is_empty( ) ) ;
1717
+ }
1668
1718
}
0 commit comments