diff options
author | Matthias Beyer <mail@beyermatthias.de> | 2016-05-28 20:12:55 +0200 |
---|---|---|
committer | Matthias Beyer <mail@beyermatthias.de> | 2016-05-28 20:53:30 +0200 |
commit | e25ab854ee541c785e37730f0ba300022bb87059 (patch) | |
tree | 9c811b77501160332a765a99aaff16fefe2867a7 /libimagtimeui | |
parent | d431d3cb8493f4fb893f9d8dc0beada129fac8af (diff) |
Impl Parse::parse for Date
Diffstat (limited to 'libimagtimeui')
-rw-r--r-- | libimagtimeui/src/date.rs | 62 |
1 files changed, 61 insertions, 1 deletions
diff --git a/libimagtimeui/src/date.rs b/libimagtimeui/src/date.rs index b003af89..ea28479c 100644 --- a/libimagtimeui/src/date.rs +++ b/libimagtimeui/src/date.rs @@ -26,8 +26,68 @@ impl Into<ChronoNaiveDate> for Date { impl Parse for Date { + /// Parse the date part of the full string into a Date object fn parse(s: &str) -> Option<Date> { - unimplemented!() + use std::str::FromStr; + use regex::Regex; + use parse::time_parse_regex; + + lazy_static! { + static ref R: Regex = Regex::new(time_parse_regex()).unwrap(); + } + + R.captures(s) + .and_then(|capts| { + let year = capts.name("Y").and_then(|o| FromStr::from_str(o).ok()); + let month = capts.name("M").and_then(|o| FromStr::from_str(o).ok()); + let day = capts.name("D").and_then(|o| FromStr::from_str(o).ok()); + + if year.is_none() { + debug!("No year"); + return None; + } + if month.is_none() { + debug!("No month"); + return None; + } + if day.is_none() { + debug!("No day"); + return None; + } + + Some(Date::new(year.unwrap(), month.unwrap(), day.unwrap())) + }) + + } + +} + +#[cfg(test)] +mod test { + use super::Date; + use parse::Parse; + + #[test] + fn test_valid() { + let s = "2016-02-01"; + let d = Date::parse(s); + + assert!(d.is_some()); + let d = d.unwrap(); + + assert_eq!(2016, d.year()); + assert_eq!(2, d.month()); + assert_eq!(1, d.day()); + } + + #[test] + fn test_invalid() { + assert!(Date::parse("2016-021-01").is_none()); + assert!(Date::parse("2016-02-012").is_none()); + assert!(Date::parse("2016-02-0").is_none()); + assert!(Date::parse("2016-0-02").is_none()); + assert!(Date::parse("2016-02").is_none()); + assert!(Date::parse("2016-2").is_none()); } } |