1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
use core::alloc::LayoutError;
use core::fmt;

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum StorageError {
    AllocError,
    CapacityLimit,
    LayoutError(LayoutError),
    Unsupported,
}

impl StorageError {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::AllocError => "Allocation error",
            Self::CapacityLimit => "Exceeded storage capacity limit",
            Self::LayoutError(_) => "Layout error",
            Self::Unsupported => "Unsupported",
        }
    }

    #[cold]
    #[inline(never)]
    pub fn panic(self) -> ! {
        panic!("{}", self.as_str());
    }
}

impl fmt::Display for StorageError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl From<LayoutError> for StorageError {
    fn from(err: LayoutError) -> Self {
        Self::LayoutError(err)
    }
}

#[cfg(feature = "std")]
impl std::error::Error for StorageError {}

#[derive(Clone)]
pub struct InsertionError<T> {
    pub(crate) error: StorageError,
    pub(crate) value: T,
}

impl<T> InsertionError<T> {
    pub(crate) fn new(error: StorageError, value: T) -> Self {
        Self { error, value }
    }

    pub fn as_str(&self) -> &'static str {
        "Insertion error"
    }

    pub fn error(&self) -> &StorageError {
        &self.error
    }

    pub fn into_value(self) -> T {
        self.value
    }

    #[cold]
    #[inline(never)]
    pub fn panic(self) -> ! {
        panic!("{}: {}", self.as_str(), self.error.as_str());
    }
}

impl<T> fmt::Debug for InsertionError<T> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("InsertionError")
            .field("error", &self.error)
            .finish_non_exhaustive()
    }
}

impl<T> fmt::Display for InsertionError<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_fmt(format_args!("{}: {}", self.as_str(), self.error))
    }
}

#[cfg(feature = "std")]
impl<T> std::error::Error for InsertionError<T> {}