reliakit_primitives/
error.rs1use core::fmt;
2
3#[derive(Debug, Clone, PartialEq, Eq)]
5pub enum PrimitiveError {
6 Empty,
8 TooShort { min: usize, actual: usize },
10 TooLong { max: usize, actual: usize },
12 OutOfRange { min: u128, max: u128, actual: u128 },
14}
15
16pub type PrimitiveResult<T> = Result<T, PrimitiveError>;
18
19impl fmt::Display for PrimitiveError {
20 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
21 match self {
22 Self::Empty => f.write_str("value must not be empty"),
23 Self::TooShort { min, actual } => {
24 write!(
25 f,
26 "value is too short: minimum is {min}, actual is {actual}"
27 )
28 }
29 Self::TooLong { max, actual } => {
30 write!(f, "value is too long: maximum is {max}, actual is {actual}")
31 }
32 Self::OutOfRange { min, max, actual } => {
33 write!(
34 f,
35 "value is out of range: expected {min}..={max}, actual is {actual}"
36 )
37 }
38 }
39 }
40}
41
42#[cfg(feature = "std")]
43impl std::error::Error for PrimitiveError {}
44
45#[cfg(test)]
46mod tests {
47 use super::PrimitiveError;
48 use alloc::string::ToString;
49
50 #[test]
51 fn display_empty() {
52 assert_eq!(PrimitiveError::Empty.to_string(), "value must not be empty");
53 }
54
55 #[test]
56 fn display_too_short() {
57 assert_eq!(
58 PrimitiveError::TooShort { min: 3, actual: 1 }.to_string(),
59 "value is too short: minimum is 3, actual is 1"
60 );
61 }
62
63 #[test]
64 fn display_too_long() {
65 assert_eq!(
66 PrimitiveError::TooLong { max: 5, actual: 8 }.to_string(),
67 "value is too long: maximum is 5, actual is 8"
68 );
69 }
70
71 #[test]
72 fn display_out_of_range() {
73 assert_eq!(
74 PrimitiveError::OutOfRange {
75 min: 1,
76 max: 100,
77 actual: 200
78 }
79 .to_string(),
80 "value is out of range: expected 1..=100, actual is 200"
81 );
82 }
83}