pgdatetime/
error.rs

1// Copyright 2020 CoD Technologies Corp.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Date and time error handling.
16
17use std::error::Error;
18use std::fmt;
19
20/// Error code of data time.
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub enum DateTimeErrorKind {
23    Empty(String),
24    Invalid(String),
25    Overflow,
26}
27
28/// An error that can be returned when uses date/time types.
29#[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}