punch_clock/
period.rs

1use std::{
2    fmt::{Display, Formatter, Result as FmtResult},
3    str::FromStr,
4};
5
6/// Represents a period of time relative to now.
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub enum Period {
9    /// The period of time that began at the start of the first tracked event.
10    All,
11    /// The period of time that began at midnight at the start of the current day.
12    Today,
13    /// The period of time 24 hours in length that ended at midnight at the start of the current
14    /// day.
15    Yesterday,
16    /// The period of time that began at midnight at the start of the last Monday that occurred
17    /// (including the current day).
18    Week,
19    /// The period of time 7 days (168 hours) in length that ended at midnight at the start of the
20    /// last Monday that occurred.
21    LastWeek,
22    /// The period of time that began at midnight at the start of the last day that occurred whose
23    /// number was 1 (including the current day).
24    Month,
25    /// The period of time between the midnights at the beginning of the last two occurrences of
26    /// days whose numbers were 1 (including the current day).
27    LastMonth,
28}
29
30impl FromStr for Period {
31    type Err = String;
32
33    fn from_str(raw: &str) -> Result<Self, Self::Err> {
34        match raw {
35            "all" | "a" => Ok(Period::All),
36            "today" | "t" => Ok(Period::Today),
37            "yesterday" | "y" => Ok(Period::Yesterday),
38            "week" | "this week" | "w" | "tw" => Ok(Period::Week),
39            "last week" | "lastweek" | "lw" => Ok(Period::LastWeek),
40            "month" | "this month" | "m" | "tm" => Ok(Period::Month),
41            "last month" | "lastmonth" | "lm" => Ok(Period::LastMonth),
42            _ => Err("Time period not recognised.".into()),
43        }
44    }
45}
46
47impl Display for Period {
48    fn fmt(&self, f: &mut Formatter) -> FmtResult {
49        match self {
50            Period::All => write!(f, "All-Time"),
51            Period::Today => write!(f, "Today"),
52            Period::Yesterday => write!(f, "Yesterday"),
53            Period::Week => write!(f, "This Week"),
54            Period::LastWeek => write!(f, "Last Week"),
55            Period::Month => write!(f, "This Month"),
56            Period::LastMonth => write!(f, "Last Month"),
57        }
58    }
59}