Skip to main content

reliakit_primitives/
error.rs

1use core::fmt;
2
3/// Error returned when a primitive value fails validation.
4#[derive(Debug, Clone, PartialEq, Eq)]
5pub enum PrimitiveError {
6    /// The value was empty or contained only whitespace.
7    Empty,
8    /// The value was shorter than the minimum allowed length.
9    TooShort { min: usize, actual: usize },
10    /// The value was longer than the maximum allowed length.
11    TooLong { max: usize, actual: usize },
12    /// The value was outside the inclusive allowed range.
13    OutOfRange { min: u128, max: u128, actual: u128 },
14}
15
16/// Result alias used by Reliakit primitive constructors.
17pub 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}