1use std::error::Error;
18use std::fmt;
19
20#[derive(Debug, Clone, PartialEq, Eq)]
22pub enum DateTimeErrorKind {
23 Empty(String),
24 Invalid(String),
25 Overflow,
26}
27
28#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct DateTimeError {
31 kind: DateTimeErrorKind,
32}
33
34impl fmt::Display for DateTimeError {
35 #[inline]
36 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
37 match self.kind {
38 DateTimeErrorKind::Empty(ref s) => {
39 write!(f, "cannot parse date from empty string :{:?}", s)
40 }
41 DateTimeErrorKind::Invalid(ref s) => write!(f, "invalid :{:?}", s),
42 DateTimeErrorKind::Overflow => write!(f, "value overflows date format"),
43 }
44 }
45}
46
47impl Error for DateTimeError {}
48
49impl DateTimeError {
50 #[inline]
51 pub(crate) const fn new(kind: DateTimeErrorKind) -> Self {
52 DateTimeError { kind }
53 }
54
55 #[inline]
56 pub(crate) const fn empty(s: String) -> Self {
57 Self::new(DateTimeErrorKind::Empty(s))
58 }
59
60 #[inline]
61 pub(crate) fn is_invalid(&self) -> bool {
62 matches!(self.kind, DateTimeErrorKind::Invalid(ref _s))
63 }
64
65 #[inline]
66 pub(crate) const fn invalid(s: String) -> Self {
67 Self::new(DateTimeErrorKind::Invalid(s))
68 }
69
70 #[inline]
71 pub(crate) const fn overflow() -> Self {
72 Self::new(DateTimeErrorKind::Overflow)
73 }
74}
75
76#[cfg(test)]
77mod tests {
78 use crate::DateTimeError;
79
80 #[test]
81 fn test_error_string() -> Result<(), DateTimeError> {
82 let invalid = DateTimeError::invalid("test valid".to_string());
83 let empty = DateTimeError::empty("date is empty".to_string());
84 let overflow = DateTimeError::overflow();
85
86 let s = format!("{}", invalid);
87 assert_eq!(s, "invalid :\"test valid\"");
88
89 let s = format!("{}", empty);
90 assert_eq!(s, "cannot parse date from empty string :\"date is empty\"");
91
92 let s = format!("{}", overflow);
93 assert_eq!(s, "value overflows date format");
94 Ok(())
95 }
96}