drasi_core/evaluation/variable_value/
duration.rs

1// Copyright 2024 The Drasi Authors.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use chrono::Duration as ChronoDuration;
16use core::fmt::{self, Display};
17use std::hash::Hash;
18use std::ops;
19
20#[derive(Clone, Eq, Hash, PartialEq)]
21pub struct Duration {
22    duration: ChronoDuration,
23    year: i64,
24    month: i64,
25    // Rust does not support specifying the year or month as a duration (leap year concerns, etc.)
26    // so we need to store them separately.
27    // For years/months, we can't know the exact "duration" without knowing the starting date.
28    // For example, 1 month could be 28, 29, 30, or 31 days depending on the starting date and
29    // 1 year could be 365 or 366 days depending on the starting date.
30}
31
32impl ops::Add<Duration> for Duration {
33    type Output = Duration;
34    #[allow(clippy::unwrap_used)]
35    fn add(self, duration2: Duration) -> Duration {
36        let new_duration = self.duration().checked_add(duration2.duration()).unwrap();
37        let mut year = self.year() + duration2.year();
38        let mut month = self.month() + duration2.month();
39        if month > 12 {
40            year += 1;
41            month -= 12;
42        }
43        Duration::new(new_duration, year, month)
44    }
45}
46
47impl ops::Sub<Duration> for Duration {
48    type Output = Duration;
49    #[allow(clippy::unwrap_used)]
50    fn sub(self, duration2: Duration) -> Duration {
51        let new_duration = self.duration().checked_sub(duration2.duration()).unwrap();
52        let mut year = self.year() - duration2.year();
53        let mut month = self.month() - duration2.month();
54        if month < 1 {
55            year -= 1;
56            month += 12;
57        }
58        Duration::new(new_duration, year, month)
59    }
60}
61
62impl Duration {
63    pub fn new(duration: ChronoDuration, year: i64, month: i64) -> Self {
64        Duration {
65            duration,
66            year,
67            month,
68        }
69    }
70
71    pub fn duration(&self) -> &ChronoDuration {
72        &self.duration
73    }
74
75    pub fn year(&self) -> &i64 {
76        &self.year
77    }
78
79    pub fn month(&self) -> &i64 {
80        &self.month
81    }
82}
83
84impl Display for Duration {
85    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
86        self.duration.fmt(formatter)
87    }
88}