lib/
utils.rs

1//! Simple utilities functions
2use chrono::{DateTime, Local};
3use tracing::warn;
4
5/// Parse a string with the expected format "hh:mm" and return a [`DateTime<Local>`]
6/// for the current day at time "hh:mm"
7///
8/// If `mm` is not parsable we return a datetime set at `hh:00`.
9
10pub 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; // Automatically trace tests
42
43    #[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}