copy_stack_vec/
error.rs

1// This file is part of copy-stack-vec.
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! Error types for `CopyStackVec`.
5//!
6//! These errors represent capacity and bounds conditions.
7//! They are `Copy` and implement `core::error::Error` (on recent toolchains).
8
9// Core imports
10use core::{error::Error as CoreError, fmt};
11
12/// Errors returned by operations on [`CopyStackVec`](crate::CopyStackVec).
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14#[non_exhaustive]
15pub enum Error {
16    /// The operation would exceed the fixed capacity (`N`).
17    Full,
18    /// An index or position was out of the current logical bounds.
19    OutOfBounds,
20    /// An operation required `len == N`, which was not met.
21    ///
22    /// Currently used by [`CopyStackVec::try_into_array`] when the vector is not full.
23    InvalidLen,
24}
25
26impl fmt::Display for Error {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        match self {
29            Self::Full => f.write_str("capacity exceeded"),
30            Self::OutOfBounds => f.write_str("index out of bounds"),
31            Self::InvalidLen => f.write_str("invalid length"),
32        }
33    }
34}
35
36impl CoreError for Error {}
37
38#[cfg(test)]
39mod tests {
40    // Imports
41    use crate::Error;
42    use alloc::string::{String, ToString};
43    use core::error::Error as CoreError;
44
45    fn takes_error(e: &dyn CoreError) -> String {
46        e.to_string()
47    }
48
49    #[test]
50    fn test_error_is_core_error() {
51        let s = takes_error(&Error::OutOfBounds);
52        assert!(s.contains("out of bounds"));
53    }
54}