Skip to main content

rstl_queue/
error.rs

1use core::fmt;
2
3#[derive(Debug, Clone, PartialEq, Eq)]
4pub enum QueueError {
5    InvalidCapacity {
6        capacity: usize,
7    },
8    InsufficientCapacity {
9        current_size: usize,
10        requested_capacity: usize,
11    },
12}
13
14impl fmt::Display for QueueError {
15    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
16        match self {
17            Self::InvalidCapacity { capacity } => {
18                write!(
19                    f,
20                    "[CircularQueue] capacity is expected to be a positive integer, but got ({capacity})."
21                )
22            }
23            Self::InsufficientCapacity {
24                current_size,
25                requested_capacity,
26            } => {
27                write!(
28                    f,
29                    "[CircularQueue] failed to resize, the new queue space is insufficient. current size ({current_size}), requested capacity ({requested_capacity})."
30                )
31            }
32        }
33    }
34}
35
36impl std::error::Error for QueueError {}
37
38#[cfg(test)]
39mod tests {
40    use std::error::Error as StdError;
41
42    use super::QueueError;
43
44    #[test]
45    fn display_should_format_invalid_capacity() {
46        let err = QueueError::InvalidCapacity { capacity: 0 };
47
48        assert_eq!(
49            err.to_string(),
50            "[CircularQueue] capacity is expected to be a positive integer, but got (0)."
51        );
52    }
53
54    #[test]
55    fn display_should_format_insufficient_capacity() {
56        let err = QueueError::InsufficientCapacity {
57            current_size: 3,
58            requested_capacity: 2,
59        };
60
61        assert_eq!(
62            err.to_string(),
63            "[CircularQueue] failed to resize, the new queue space is insufficient. current size (3), requested capacity (2)."
64        );
65    }
66
67    #[test]
68    fn error_source_should_be_none() {
69        let err = QueueError::InvalidCapacity { capacity: 1 };
70
71        assert!(StdError::source(&err).is_none());
72    }
73}