copy_stack_vec/vec/array/
insert.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::{error::Error, vec::CopyStackVec};
6
7impl<T: Copy, const N: usize> CopyStackVec<T, N> {
8    /// Inserts `value` at `index`, shifting elements to the right.
9    ///
10    /// - Returns [`Error::OutOfBounds`] if `index > len`.
11    /// - Returns [`Error::Full`] if at capacity.
12    ///
13    /// Uses `copy_within` for overlap-safe shifting.
14    #[inline]
15    pub fn insert(&mut self, index: usize, value: T) -> Result<(), Error> {
16        if index > self.len {
17            return Err(Error::OutOfBounds);
18        }
19        if self.len == N {
20            return Err(Error::Full);
21        }
22        let len = self.len;
23
24        // Shift right: [index..len) -> [index+1..len+1)
25        self.buf.copy_within(index..len, index + 1);
26        self.buf[index] = value;
27
28        self.len = len + 1;
29        Ok(())
30    }
31}