From ba5b4de68ddda3f343284e33a9a58471e9ceac26 Mon Sep 17 00:00:00 2001 From: Astro Date: Mon, 24 May 2021 23:16:44 +0200 Subject: [PATCH] ics: refactor into Timestamp::from_str() --- libticker/src/ics/mod.rs | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/libticker/src/ics/mod.rs b/libticker/src/ics/mod.rs index 71c537e..d84e0a9 100644 --- a/libticker/src/ics/mod.rs +++ b/libticker/src/ics/mod.rs @@ -1,4 +1,5 @@ use std::collections::HashMap; +use std::str::FromStr; use chrono::{NaiveDate, NaiveDateTime}; mod tokenizer; @@ -36,13 +37,7 @@ impl<'a> GetValue<'a, String> for Object { impl<'a> GetValue<'a, Timestamp> for Object { fn get(&self, key: &'_ str) -> Option { let s = self.get(key)?; - NaiveDateTime::parse_from_str(s, "%Y%m%dT%H%M%SZ") - .or_else(|_| NaiveDateTime::parse_from_str(s, "%Y%m%dT%H%M%S")) - .map(Timestamp::DateTime) - .or_else(|_| - NaiveDate::parse_from_str(s, "%Y%m%d") - .map(Timestamp::Date) - ) + Timestamp::from_str(s) .map_err(|e| println!("Cannot parse date: {:?}", e)) .ok() } @@ -54,6 +49,21 @@ pub enum Timestamp { DateTime(NaiveDateTime), } +impl FromStr for Timestamp { + type Err = String; + + fn from_str(s: &'_ str) -> Result { + NaiveDateTime::parse_from_str(s, "%Y%m%dT%H%M%SZ") + .or_else(|_| NaiveDateTime::parse_from_str(s, "%Y%m%dT%H%M%S")) + .map(Timestamp::DateTime) + .or_else(|_| + NaiveDate::parse_from_str(s, "%Y%m%d") + .map(Timestamp::Date) + ) + .map_err(|e| format!("Cannot parse date: {:?}", e)) + } +} + impl Timestamp { pub fn or_hms(self, hour: u32, min: u32, sec: u32) -> NaiveDateTime { match self {