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// TODO: should be a const trait once `const trait impl` is stabilized
36pub trait TimeUnitTrait: Copy + Clone + Debug + PartialEq + Eq + Hash + PartialOrd + Ord {
37 /// Returns the corresponding `TimeUnit` enum variant for this time unit.
38 ///
39 /// # Returns
40 ///
41 /// A `TimeUnit` enum variant representing the specific time unit.
42 fn unit() -> TimeUnit;
43}
44
45define_timeunit!(
46 Year,
47 Month,
48 Day,
49 Hour,
50 Minute,
51 Second,
52 Millisecond,
53 Microsecond,
54 Nanosecond
55);
56
57impl Default for TimeUnit {
58 #[inline]
59 fn default() -> Self {
60 TimeUnit::Nanosecond
61 }
62}