From 095c17ce93bb01f7c5ee458d3e2e034b62c7ec12 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sosth=C3=A8ne=20Gu=C3=A9don?= Date: Sun, 21 Jan 2024 13:52:48 +0100 Subject: [PATCH] VecView: Add spare_capacity_mut --- src/vec.rs | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/src/vec.rs b/src/vec.rs index 4a6adf26a5..036a4381ac 100644 --- a/src/vec.rs +++ b/src/vec.rs @@ -795,6 +795,37 @@ impl VecView { // All item are processed. This can be optimized to `set_len` by LLVM. drop(g); } + + /// Returns the remaining spare capacity of the vector as a slice of `MaybeUninit`. + /// + /// The returned slice can be used to fill the vector with data before marking the data as + /// initialized using the `set_len` method. + /// + /// # Examples + /// + /// ``` + /// use heapless::{Vec, VecView}; + /// + /// // Allocate vector big enough for 10 elements. + /// let mut v: Vec<_, 10> = Vec::new(); + /// let view: &mut VecView<_> = &mut v; + /// + /// // Fill in the first 3 elements. + /// let uninit = view.spare_capacity_mut(); + /// uninit[0].write(0); + /// uninit[1].write(1); + /// uninit[2].write(2); + /// + /// // Mark the first 3 elements of the vector as being initialized. + /// unsafe { + /// view.set_len(3); + /// } + /// + /// assert_eq!(view, &[0, 1, 2]); + /// ``` + pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit] { + &mut self.buffer[self.len..] + } } impl Vec { @@ -1453,7 +1484,7 @@ impl Vec { /// assert_eq!(&v, &[0, 1, 2]); /// ``` pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit] { - &mut self.buffer[self.len..] + self.as_mut_view().spare_capacity_mut() } }