Skip to content

Commit 9a22b83

Browse files
authored
Merge pull request #437 from YuhanLiin/spare-cap
Add spare_capacity_mut
2 parents 9a2e0af + 479ec57 commit 9a22b83

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
1313
- Added `String::from_utf16`.
1414
- Added `is_full`, `recent_index`, `oldest`, and `oldest_index` to `HistoryBuffer`
1515
- Added infallible conversions from arrays to `Vec`.
16+
- Added `Vec::spare_capacity_mut`.
1617

1718
### Changed
1819

src/vec.rs

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -867,6 +867,36 @@ impl<T, const N: usize> Vec<T, N> {
867867
// All item are processed. This can be optimized to `set_len` by LLVM.
868868
drop(g);
869869
}
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+
}
870900
}
871901

872902
// Trait implementations
@@ -1665,4 +1695,24 @@ mod tests {
16651695
// Validate full
16661696
assert!(v.is_full());
16671697
}
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+
}
16681718
}

0 commit comments

Comments
 (0)