Skip to content

Commit 095c17c

Browse files
VecView: Add spare_capacity_mut
1 parent f488596 commit 095c17c

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

src/vec.rs

+32-1
Original file line numberDiff line numberDiff line change
@@ -795,6 +795,37 @@ impl<T> VecView<T> {
795795
// All item are processed. This can be optimized to `set_len` by LLVM.
796796
drop(g);
797797
}
798+
799+
/// Returns the remaining spare capacity of the vector as a slice of `MaybeUninit<T>`.
800+
///
801+
/// The returned slice can be used to fill the vector with data before marking the data as
802+
/// initialized using the `set_len` method.
803+
///
804+
/// # Examples
805+
///
806+
/// ```
807+
/// use heapless::{Vec, VecView};
808+
///
809+
/// // Allocate vector big enough for 10 elements.
810+
/// let mut v: Vec<_, 10> = Vec::new();
811+
/// let view: &mut VecView<_> = &mut v;
812+
///
813+
/// // Fill in the first 3 elements.
814+
/// let uninit = view.spare_capacity_mut();
815+
/// uninit[0].write(0);
816+
/// uninit[1].write(1);
817+
/// uninit[2].write(2);
818+
///
819+
/// // Mark the first 3 elements of the vector as being initialized.
820+
/// unsafe {
821+
/// view.set_len(3);
822+
/// }
823+
///
824+
/// assert_eq!(view, &[0, 1, 2]);
825+
/// ```
826+
pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
827+
&mut self.buffer[self.len..]
828+
}
798829
}
799830

800831
impl<T, const N: usize> Vec<T, N> {
@@ -1453,7 +1484,7 @@ impl<T, const N: usize> Vec<T, N> {
14531484
/// assert_eq!(&v, &[0, 1, 2]);
14541485
/// ```
14551486
pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
1456-
&mut self.buffer[self.len..]
1487+
self.as_mut_view().spare_capacity_mut()
14571488
}
14581489
}
14591490

0 commit comments

Comments
 (0)