Skip to content

Commit 4ef0e89

Browse files
tbu-bluss
authored andcommitted
Add ArrayVec::spare_capacity_mut
This mirrors `Vec::spare_capacity_mut`. Description and example are taken from this function, too. CC bluss#278
1 parent 0aede87 commit 4ef0e89

File tree

2 files changed

+39
-2
lines changed

2 files changed

+39
-2
lines changed

.github/workflows/ci.yml

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ jobs:
2020
- rust: 1.51.0 # MSRV
2121
features: serde
2222
experimental: false
23+
# doctest of `ArrayVec::spare_capacity_mut` has MSRV 1.55
24+
test-args: --skip spare_capacity_mut
2325
- rust: 1.70.0
2426
features: serde
2527
experimental: false
@@ -51,8 +53,8 @@ jobs:
5153
- name: Tests
5254
run: |
5355
cargo doc --verbose --features "${{ matrix.features }}" --no-deps
54-
cargo test --verbose --features "${{ matrix.features }}"
55-
cargo test --release --verbose --features "${{ matrix.features }}"
56+
cargo test --verbose --features "${{ matrix.features }}" -- ${{ matrix.test-args }}
57+
cargo test --release --verbose --features "${{ matrix.features }}" -- ${{ matrix.test-args }}
5658
- name: Test run benchmarks
5759
if: matrix.bench != ''
5860
run: cargo test -v --benches

src/arrayvec.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -535,6 +535,41 @@ impl<T, const CAP: usize> ArrayVec<T, CAP> {
535535
drop(g);
536536
}
537537

538+
/// Returns the remaining spare capacity of the vector as a slice of
539+
/// `MaybeUninit<T>`.
540+
///
541+
/// The returned slice can be used to fill the vector with data (e.g. by
542+
/// reading from a file) before marking the data as initialized using the
543+
/// [`set_len`] method.
544+
///
545+
/// [`set_len`]: ArrayVec::set_len
546+
///
547+
/// # Examples
548+
///
549+
/// ```
550+
/// use arrayvec::ArrayVec;
551+
///
552+
/// // Allocate vector big enough for 10 elements.
553+
/// let mut v: ArrayVec<i32, 10> = ArrayVec::new();
554+
///
555+
/// // Fill in the first 3 elements.
556+
/// let uninit = v.spare_capacity_mut();
557+
/// uninit[0].write(0);
558+
/// uninit[1].write(1);
559+
/// uninit[2].write(2);
560+
///
561+
/// // Mark the first 3 elements of the vector as being initialized.
562+
/// unsafe {
563+
/// v.set_len(3);
564+
/// }
565+
///
566+
/// assert_eq!(&v[..], &[0, 1, 2]);
567+
/// ```
568+
pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
569+
let len = self.len();
570+
&mut self.xs[len..]
571+
}
572+
538573
/// Set the vector’s length without dropping or moving out elements
539574
///
540575
/// This method is `unsafe` because it changes the notion of the

0 commit comments

Comments
 (0)