Add ArrayVec::spare_capacity_mut

This mirrors `Vec::spare_capacity_mut`. Description and example are
taken from this function, too.

CC #278
This commit is contained in:
Tobias Bucher
2024-10-16 18:27:32 +02:00
committed by bluss
parent 0aede877fe
commit 4ef0e89028
2 changed files with 39 additions and 2 deletions
+4 -2
View File
@@ -20,6 +20,8 @@ jobs:
- rust: 1.51.0 # MSRV - rust: 1.51.0 # MSRV
features: serde features: serde
experimental: false experimental: false
# doctest of `ArrayVec::spare_capacity_mut` has MSRV 1.55
test-args: --skip spare_capacity_mut
- rust: 1.70.0 - rust: 1.70.0
features: serde features: serde
experimental: false experimental: false
@@ -51,8 +53,8 @@ jobs:
- name: Tests - name: Tests
run: | run: |
cargo doc --verbose --features "${{ matrix.features }}" --no-deps cargo doc --verbose --features "${{ matrix.features }}" --no-deps
cargo test --verbose --features "${{ matrix.features }}" cargo test --verbose --features "${{ matrix.features }}" -- ${{ matrix.test-args }}
cargo test --release --verbose --features "${{ matrix.features }}" cargo test --release --verbose --features "${{ matrix.features }}" -- ${{ matrix.test-args }}
- name: Test run benchmarks - name: Test run benchmarks
if: matrix.bench != '' if: matrix.bench != ''
run: cargo test -v --benches run: cargo test -v --benches
+35
View File
@@ -535,6 +535,41 @@ impl<T, const CAP: usize> ArrayVec<T, CAP> {
drop(g); drop(g);
} }
/// Returns the remaining spare capacity of the vector as a slice of
/// `MaybeUninit<T>`.
///
/// The returned slice can be used to fill the vector with data (e.g. by
/// reading from a file) before marking the data as initialized using the
/// [`set_len`] method.
///
/// [`set_len`]: ArrayVec::set_len
///
/// # Examples
///
/// ```
/// use arrayvec::ArrayVec;
///
/// // Allocate vector big enough for 10 elements.
/// let mut v: ArrayVec<i32, 10> = ArrayVec::new();
///
/// // Fill in the first 3 elements.
/// let uninit = v.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 {
/// v.set_len(3);
/// }
///
/// assert_eq!(&v[..], &[0, 1, 2]);
/// ```
pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
let len = self.len();
&mut self.xs[len..]
}
/// Set the vectors length without dropping or moving out elements /// Set the vectors length without dropping or moving out elements
/// ///
/// This method is `unsafe` because it changes the notion of the /// This method is `unsafe` because it changes the notion of the