tea_time/
timeunit.rs

1use std::fmt::Debug;
2use std::hash::Hash;
3
4macro_rules! define_timeunit {
5    ($($name: ident),*) => {
6        $(
7            #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
8            #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
9            pub struct $name;
10
11            impl TimeUnitTrait for $name {
12                #[inline]
13                fn unit() -> TimeUnit {
14                    TimeUnit::$name
15                }
16            }
17        )*
18
19        /// Represents different units of time.
20        ///
21        /// This enum includes various time units from years down to nanoseconds,
22        /// allowing for flexible time representations and calculations.
23        #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
24        pub enum TimeUnit {
25            $($name),*
26        }
27    };
28}
29
30/// A trait for types representing time units.
31///
32/// This trait is implemented by types that represent specific units of time,
33/// such as years, months, days, hours, etc. It provides a common interface
34/// for these types and ensures they have certain properties and behaviors.
35
36// TODO: should be a const trait once `const trait impl` is stabilized
37pub trait TimeUnitTrait: Copy + Clone + Debug + PartialEq + Eq + Hash + PartialOrd + Ord {
38    /// Returns the corresponding `TimeUnit` enum variant for this time unit.
39    ///
40    /// # Returns
41    ///
42    /// A `TimeUnit` enum variant representing the specific time unit.
43    fn unit() -> TimeUnit;
44}
45
46define_timeunit!(
47    Year,
48    Month,
49    Day,
50    Hour,
51    Minute,
52    Second,
53    Millisecond,
54    Microsecond,
55    Nanosecond
56);
57
58impl Default for TimeUnit {
59    #[inline]
60    fn default() -> Self {
61        TimeUnit::Nanosecond
62    }
63}