Skip to content

Commit

Permalink
Add ArrayVec::spare_capacity_mut
Browse files Browse the repository at this point in the history
This mirrors `Vec::spare_capacity_mut`. Description and example are
taken from this function, too.

CC bluss#278
  • Loading branch information
tbu- committed Oct 16, 2024
1 parent 0aede87 commit d15276f
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
6 changes: 4 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ jobs:
- rust: 1.51.0 # MSRV
features: serde
experimental: false
# doctest of `ArrayVec::spare_capacity_mut` has MSRV 1.55
test-args: --skip spare_capacity_mut
- rust: 1.70.0
features: serde
experimental: false
Expand Down Expand Up @@ -51,8 +53,8 @@ jobs:
- name: Tests
run: |
cargo doc --verbose --features "${{ matrix.features }}" --no-deps
cargo test --verbose --features "${{ matrix.features }}"
cargo test --release --verbose --features "${{ matrix.features }}"
cargo test --verbose --features "${{ matrix.features }}" -- ${{ matrix.test-args }}
cargo test --release --verbose --features "${{ matrix.features }}" -- ${{ matrix.test-args }}
- name: Test run benchmarks
if: matrix.bench != ''
run: cargo test -v --benches
Expand Down
35 changes: 35 additions & 0 deletions src/arrayvec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -535,6 +535,41 @@ impl<T, const CAP: usize> ArrayVec<T, CAP> {
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`]: Vec::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 vector’s length without dropping or moving out elements
///
/// This method is `unsafe` because it changes the notion of the
Expand Down

0 comments on commit d15276f

Please sign in to comment.