Skip to content

Commit cd6dad6

Browse files
committed
Make Vec::split_at_spare_mut public
This commit introduces a new method to the public API, under `vec_split_at_spare` feature gate: ```rust impl<T, A: Allocator> impl Vec<T, A> { pub fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit<T>]); } ``` The method returns 2 slices, one slice references the content of the vector, and the other references the remaining spare capacity. The method was previously implemented while adding `Vec::extend_from_within`, and used to implement `Vec::spare_capacity_mut` (as the later is just a subset of former one).
1 parent 3182375 commit cd6dad6

File tree

1 file changed

+38
-1
lines changed

1 file changed

+38
-1
lines changed

library/alloc/src/vec/mod.rs

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1828,8 +1828,45 @@ impl<T, A: Allocator> Vec<T, A> {
18281828
self.split_at_spare_mut().1
18291829
}
18301830

1831+
/// Returns vector content as a slice of `T`, among with the remaining spare
1832+
/// capacity of the vector as a slice of `MaybeUninit<T>`.
1833+
///
1834+
/// The returned spare capacity slice can be used to fill the vector with data
1835+
/// (e.g. by reading from a file) before marking the data as initialized using
1836+
/// the [`set_len`] method.
1837+
///
1838+
/// [`set_len`]: Vec::set_len
1839+
///
1840+
/// # Examples
1841+
///
1842+
/// ```
1843+
/// #![feature(vec_split_at_spare, maybe_uninit_extra)]
1844+
///
1845+
/// let mut v = vec![1, 1, 2];
1846+
///
1847+
/// // Reserve additional space big enough for 10 elements.
1848+
/// v.reserve(10);
1849+
///
1850+
/// let (init, uninit) = v.split_at_spare_mut();
1851+
/// let sum = init.iter().copied().sum::<u32>();
1852+
///
1853+
/// // Fill in the next 4 elements.
1854+
/// uninit[0].write(sum);
1855+
/// uninit[1].write(sum * 2);
1856+
/// uninit[2].write(sum * 3);
1857+
/// uninit[3].write(sum * 4);
1858+
///
1859+
/// // Mark the 4 elements of the vector as being initialized.
1860+
/// unsafe {
1861+
/// let len = v.len();
1862+
/// v.set_len(len + 4);
1863+
/// }
1864+
///
1865+
/// assert_eq!(&v, &[1, 1, 2, 4, 8, 12, 16]);
1866+
/// ```
1867+
#[unstable(feature = "vec_split_at_spare", issue = "none")]
18311868
#[inline]
1832-
fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit<T>]) {
1869+
pub fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit<T>]) {
18331870
let ptr = self.as_mut_ptr();
18341871

18351872
// Safety:

0 commit comments

Comments
 (0)