twilight_model/util/datetime/
error.rs1use std::{
8 error::Error,
9 fmt::{Display, Formatter, Result as FmtResult},
10};
11use time::error::{ComponentRange as ComponentRangeError, Parse as ParseError};
12
13#[derive(Debug)]
15pub struct TimestampParseError {
16 kind: TimestampParseErrorType,
18 source: Option<Box<dyn Error + Send + Sync>>,
20}
21
22impl TimestampParseError {
23 pub(super) const FORMAT: TimestampParseError = TimestampParseError {
25 kind: TimestampParseErrorType::Format,
26 source: None,
27 };
28
29 #[must_use = "retrieving the type has no effect if left unused"]
31 pub const fn kind(&self) -> &TimestampParseErrorType {
32 &self.kind
33 }
34
35 #[allow(clippy::unused_self)]
37 #[must_use = "consuming the error and retrieving the source has no effect if left unused"]
38 pub fn into_source(self) -> Option<Box<dyn Error + Send + Sync>> {
39 self.source
40 }
41
42 #[must_use = "consuming the error into its parts has no effect if left unused"]
44 pub fn into_parts(
45 self,
46 ) -> (
47 TimestampParseErrorType,
48 Option<Box<dyn Error + Send + Sync>>,
49 ) {
50 (self.kind, self.source)
51 }
52
53 pub(super) fn from_component_range(source: ComponentRangeError) -> Self {
55 Self {
56 kind: TimestampParseErrorType::Range,
57 source: Some(Box::new(source)),
58 }
59 }
60
61 pub(super) fn from_parse(source: ParseError) -> Self {
63 Self {
64 kind: TimestampParseErrorType::Parsing,
65 source: Some(Box::new(source)),
66 }
67 }
68}
69
70impl Display for TimestampParseError {
71 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
72 match &self.kind {
73 TimestampParseErrorType::Format => {
74 f.write_str("provided value is not in an iso 8601 format")
75 }
76 TimestampParseErrorType::Parsing => f.write_str("timestamp parsing failed"),
77 TimestampParseErrorType::Range => {
78 f.write_str("value of a field is not in an acceptable range")
79 }
80 }
81 }
82}
83
84impl Error for TimestampParseError {}
85
86#[derive(Debug)]
88pub enum TimestampParseErrorType {
89 Format,
94 Parsing,
96 Range,
98}
99
100#[cfg(test)]
101mod tests {
102 use super::{TimestampParseError, TimestampParseErrorType};
103 use static_assertions::assert_impl_all;
104 use std::{error::Error, fmt::Debug};
105
106 assert_impl_all!(TimestampParseErrorType: Debug, Send, Sync);
107 assert_impl_all!(TimestampParseError: Error, Send, Sync);
108}