copy_stack_vec/vec/array/split_off.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 + Default, const N: usize> CopyStackVec<T, N> {
8 /// Splits the vector into two at index `at`.
9 ///
10 /// On success:
11 /// - `self` is left containing the prefix `[0..at)`,
12 /// - the returned vector contains the tail `[at..len)`.
13 ///
14 /// Returns [`Error::OutOfBounds`] if `at > self.len()`. On error, `self`
15 /// is left unchanged.
16 #[inline]
17 pub fn split_off(&mut self, at: usize) -> Result<Self, Error> {
18 let len = self.len;
19 if at > len {
20 return Err(Error::OutOfBounds);
21 }
22
23 let tail_len = len - at;
24 let mut other: CopyStackVec<T, N> = CopyStackVec::default();
25
26 if tail_len > 0 {
27 // This must fit by construction: tail_len <= len <= N and other is empty.
28 // We still propagate any error instead of panicking.
29 other.extend_from_slice(&self.as_slice()[at..len])?;
30 }
31
32 // Shrink self to the prefix.
33 self.len = at;
34
35 Ok(other)
36 }
37}