reliakit_collections/
error.rs1use core::fmt;
2
3#[non_exhaustive]
5#[derive(Debug, Clone, PartialEq, Eq)]
6pub enum CollectionError {
7 TooFew {
9 min: usize,
11 actual: usize,
13 },
14 TooMany {
16 max: usize,
18 actual: usize,
20 },
21 InvalidBounds {
23 min: usize,
25 max: usize,
27 },
28 ZeroCapacity,
30 Duplicate,
32}
33
34pub type CollectionResult<T = ()> = Result<T, CollectionError>;
36
37impl fmt::Display for CollectionError {
38 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39 match self {
40 Self::TooFew { min, actual } => {
41 write!(
42 f,
43 "collection is too small: minimum is {min}, actual is {actual}"
44 )
45 }
46 Self::TooMany { max, actual } => {
47 write!(
48 f,
49 "collection is too large: maximum is {max}, actual is {actual}"
50 )
51 }
52 Self::InvalidBounds { min, max } => {
53 write!(f, "invalid bounds: MIN ({min}) must not exceed MAX ({max})")
54 }
55 Self::ZeroCapacity => write!(f, "capacity must be greater than zero"),
56 Self::Duplicate => write!(f, "collection contains a duplicate key or element"),
57 }
58 }
59}
60
61#[cfg(feature = "std")]
62impl std::error::Error for CollectionError {}
63
64#[cfg(test)]
65mod tests {
66 use super::CollectionError;
67 use alloc::string::ToString;
68
69 #[test]
70 fn display_too_few() {
71 assert_eq!(
72 CollectionError::TooFew { min: 2, actual: 0 }.to_string(),
73 "collection is too small: minimum is 2, actual is 0"
74 );
75 }
76
77 #[test]
78 fn display_too_many() {
79 assert_eq!(
80 CollectionError::TooMany { max: 5, actual: 6 }.to_string(),
81 "collection is too large: maximum is 5, actual is 6"
82 );
83 }
84
85 #[test]
86 fn display_invalid_bounds() {
87 assert_eq!(
88 CollectionError::InvalidBounds { min: 5, max: 3 }.to_string(),
89 "invalid bounds: MIN (5) must not exceed MAX (3)"
90 );
91 }
92
93 #[test]
94 fn display_zero_capacity() {
95 assert_eq!(
96 CollectionError::ZeroCapacity.to_string(),
97 "capacity must be greater than zero"
98 );
99 }
100
101 #[test]
102 fn display_duplicate() {
103 assert_eq!(
104 CollectionError::Duplicate.to_string(),
105 "collection contains a duplicate key or element"
106 );
107 }
108}