copy_stack_vec/vec/array/
remove.rs

1// This file is part of copy-stack-vec.
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4// Crate imports
5use crate::vec::CopyStackVec;
6
7impl<T: Copy, const N: usize> CopyStackVec<T, N> {
8    /// Removes and returns the element at `index`, shifting subsequent elements left.
9    ///
10    /// Returns `None` if `index >= len`. Uses `copy_within` for overlap-safe shifting.
11    #[inline]
12    pub fn remove(&mut self, index: usize) -> Option<T> {
13        if index >= self.len {
14            return None;
15        }
16        let len = self.len;
17
18        // Read the element at `index` as a `T`.
19        let out = self.buf[index];
20
21        // Shift left: [index+1..len) -> [index..len-1)
22        if index + 1 < len {
23            self.buf.copy_within(index + 1..len, index);
24        }
25
26        self.len = len - 1;
27        Some(out)
28    }
29
30    /// Removes and returns the element at `index` by swapping with the last element.
31    ///
32    /// Preserves neither order nor contiguity of the last two elements. Returns `None`
33    /// when `index >= len`. Removing the last element avoids a swap.
34    #[inline]
35    pub fn swap_remove(&mut self, index: usize) -> Option<T> {
36        if index >= self.len {
37            return None;
38        }
39        self.len -= 1;
40        let last = self.len;
41
42        // Read out the element at `index` as a `T`.
43        let out = self.buf[index];
44
45        // If it's not the last element, move the last slot into the hole.
46        if index != last {
47            self.buf[index] = self.buf[last];
48        }
49
50        Some(out)
51    }
52}