1use chrono::{DateTime, Local};
3use tracing::warn;
4
5pub fn parse_from_hmstr(time_str: &Option<String>) -> Option<DateTime<Local>> {
11 if let Some(ref s) = time_str {
12 let splitted: Vec<&str> = s.split(':').collect();
13 let hh: u32 = match splitted[0].parse() {
14 Ok(h) => h,
15 Err(_) => {
16 warn!("Unable to get hour from {:?}", &time_str);
17 return None;
18 }
19 };
20 let mm = if splitted.len() < 2 {
21 0
22 } else {
23 match splitted[1].parse() {
24 Ok(m) => m,
25 Err(_) => {
26 warn!("Unable to get minutes from {:?}", &time_str);
27 0
28 }
29 }
30 };
31 let res = Local::now().date().and_hms(hh, mm, 0);
32 Some(res)
33 } else {
34 None
35 }
36}
37
38#[cfg(test)]
39mod should {
40 use super::*;
41 use test_log::test; #[test]
44 fn return_none_if_unparsable() {
45 assert_eq!(None, parse_from_hmstr(&None));
46 assert_eq!(None, parse_from_hmstr(&Some("biii".to_string())));
47 assert_eq!(None, parse_from_hmstr(&Some(":12:30".to_string())));
48 }
49 #[test]
50 fn return_hour_if_mn_is_unparsable() {
51 let expect = Local::now().date().and_hms(12, 00, 0);
52 assert_eq!(Some(expect), parse_from_hmstr(&Some("12:3O".to_string())));
53 assert_eq!(Some(expect), parse_from_hmstr(&Some("12".to_string())));
54 }
55 #[test]
56 fn return_expected_date() {
57 let expect = Local::now().date().and_hms(7, 1, 0);
58 assert_eq!(Some(expect), parse_from_hmstr(&Some("07:01".to_string())));
59 assert_eq!(Some(expect), parse_from_hmstr(&Some("7:1".to_string())));
60 let expect = Local::now().date().and_hms(23, 39, 0);
61 assert_eq!(Some(expect), parse_from_hmstr(&Some("23:39".to_string())));
62 }
63}