1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
use std::{ fmt, num::ParseIntError, ops::{Deref, DerefMut}, str::FromStr, }; use chrono::NaiveDateTime as ChronoNaiveDateTime; use pest::Parser as _; use serde::{ de::{self, Visitor}, Deserialize, Deserializer, }; use crate::{ date_and_time_parser::{DateAndTimeParser, Rule}, MAX_DATETIME_UNIX_TIMESTAMP, }; #[derive(PartialEq, Debug, Clone)] pub struct NaiveDateTime(pub ChronoNaiveDateTime); impl From<ChronoNaiveDateTime> for NaiveDateTime { fn from(inner: ChronoNaiveDateTime) -> Self { Self(inner) } } impl Deref for NaiveDateTime { type Target = ChronoNaiveDateTime; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for NaiveDateTime { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } #[derive(thiserror::Error, Debug)] pub enum ParseError { #[error("FormatMismatch {0}")] FormatMismatch(String), #[error("ValueInvalid {0}")] ValueInvalid(String), #[error("Unknown")] Unknown, } impl FromStr for NaiveDateTime { type Err = ParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { let pair = DateAndTimeParser::parse(Rule::datetime, s) .map_err(|err| ParseError::FormatMismatch(err.to_string()))? .next() .ok_or(ParseError::Unknown)? .into_inner() .next() .ok_or(ParseError::Unknown)?; match pair.as_rule() { Rule::datetime_simple => { ChronoNaiveDateTime::parse_from_str(pair.as_str(), "%Y-%m-%d %H:%M:%S") .map(Into::into) .map_err(|err| ParseError::ValueInvalid(err.to_string())) } Rule::datetime_iso => { ChronoNaiveDateTime::parse_from_str(pair.as_str(), "%Y-%m-%dT%H:%M:%SZ") .map(Into::into) .map_err(|err| ParseError::ValueInvalid(err.to_string())) } Rule::datetime_unix_timestamp => { let v: u64 = pair .as_str() .parse() .map_err(|err: ParseIntError| ParseError::ValueInvalid(err.to_string()))?; if v > MAX_DATETIME_UNIX_TIMESTAMP { return Err(ParseError::ValueInvalid( "Override the max Unix Timestamp".to_string(), )); } Ok(ChronoNaiveDateTime::from_timestamp(v as i64, 0).into()) } _ => Err(ParseError::Unknown), } } } struct NaiveDateTimeVisitor; impl<'de> Visitor<'de> for NaiveDateTimeVisitor { type Value = NaiveDateTime; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("format simple or iso or unix_timestamp") } fn visit_str<E>(self, string: &str) -> Result<Self::Value, E> where E: de::Error, { string .parse() .map_err(|err: ParseError| de::Error::custom(err.to_string())) } } impl<'de> Deserialize<'de> for NaiveDateTime { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_str(NaiveDateTimeVisitor) } } pub fn deserialize<'de, D>(d: D) -> Result<ChronoNaiveDateTime, D::Error> where D: de::Deserializer<'de>, { d.deserialize_str(NaiveDateTimeVisitor).map(|x| x.0) } #[cfg(test)] mod tests { use super::*; use std::{error, fs, path::PathBuf}; use chrono::NaiveDate; #[test] fn test_parse() -> Result<(), Box<dyn error::Error>> { assert_eq!( "2021-03-01 01:02:03".parse::<NaiveDateTime>()?, NaiveDate::from_ymd(2021, 3, 1).and_hms(1, 2, 3).into() ); assert_eq!( "2021-03-01T01:02:03Z".parse::<NaiveDateTime>()?, NaiveDate::from_ymd(2021, 3, 1).and_hms(1, 2, 3).into() ); assert_eq!( "1614560523".parse::<NaiveDateTime>()?, NaiveDate::from_ymd(2021, 3, 1).and_hms(1, 2, 3).into() ); match format!("").parse::<NaiveDateTime>() { Ok(_) => assert!(false), Err(ParseError::FormatMismatch(err)) if err.ends_with("= expected datetime") => {} Err(err) => assert!(false, "{:?}", err), } match format!( "{}", NaiveDate::from_ymd(2106, 1, 1).and_hms(0, 0, 0).timestamp() ) .parse::<NaiveDateTime>() { Ok(_) => assert!(false), Err(ParseError::ValueInvalid(err)) if err == "Override the max Unix Timestamp" => {} Err(err) => assert!(false, "{:?}", err), } Ok(()) } #[derive(Deserialize)] struct Row { #[serde(deserialize_with = "crate::datetime::deserialize")] datetime_utc: chrono::NaiveDateTime, #[allow(dead_code)] datetime_shanghai: NaiveDateTime, } #[test] fn test_de() -> Result<(), Box<dyn error::Error>> { let deserializer = de::IntoDeserializer::<de::value::Error>::into_deserializer; assert_eq!( super::deserialize(deserializer("2021-03-01 01:02:03")).unwrap(), NaiveDate::from_ymd(2021, 3, 1).and_hms(1, 2, 3) ); for format in ["simple", "iso", "unix_timestamp"].iter() { let content = fs::read_to_string( PathBuf::new().join(format!("tests/files/datetime_{}.txt", format)), )?; let line = content.lines().next().unwrap(); let Row { datetime_utc, datetime_shanghai: _, } = serde_json::from_str(line)?; assert_eq!( datetime_utc, NaiveDate::from_ymd(2021, 3, 1).and_hms(1, 2, 3) ); } Ok(()) } }