From d15276f3211b5aa91adbe606e7a9271aa15670ae Mon Sep 17 00:00:00 2001 From: Tobias Bucher Date: Wed, 16 Oct 2024 18:27:32 +0200 Subject: [PATCH] Add `ArrayVec::spare_capacity_mut` This mirrors `Vec::spare_capacity_mut`. Description and example are taken from this function, too. CC #278 --- .github/workflows/ci.yml | 6 ++++-- src/arrayvec.rs | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 10fb573..a390ff5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 @@ -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 diff --git a/src/arrayvec.rs b/src/arrayvec.rs index e87b3ef..094660a 100644 --- a/src/arrayvec.rs +++ b/src/arrayvec.rs @@ -535,6 +535,41 @@ impl ArrayVec { 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 (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 = 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] { + 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