ocpi_tariffs/
duration.rs

1//! The OCPI spec represents some durations as fractional hours, where this crate represents all
2//! durations using [`TimeDelta`]. The [`ToDuration`] and [`ToHoursDecimal`] traits can be used to
3//! convert a [`TimeDelta`] into a [`Decimal`] and vice versa.
4
5use std::{borrow::Cow, fmt};
6
7use chrono::TimeDelta;
8use num_traits::ToPrimitive as _;
9use rust_decimal::Decimal;
10
11use crate::{
12    into_caveat, json,
13    number::FromDecimal as _,
14    warning::{self, IntoCaveat as _},
15    Cost, Money, SaturatingAdd, SaturatingSub, Verdict,
16};
17
18pub(crate) const SECS_IN_MIN: i64 = 60;
19pub(crate) const MINS_IN_HOUR: i64 = 60;
20pub(crate) const MILLIS_IN_SEC: i64 = 1000;
21
22/// The warnings possible when parsing or linting a duration.
23#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
24pub enum WarningKind {
25    /// Unable to parse the duration.
26    Invalid(String),
27
28    /// The JSON value given is not an int.
29    InvalidType,
30}
31
32impl fmt::Display for WarningKind {
33    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34        match self {
35            WarningKind::Invalid(err) => write!(f, "Unable to parse the duration: {err}"),
36            WarningKind::InvalidType => write!(f, "The value should be a string."),
37        }
38    }
39}
40
41impl warning::Kind for WarningKind {
42    fn id(&self) -> Cow<'static, str> {
43        match self {
44            WarningKind::Invalid(_) => "invalid".into(),
45            WarningKind::InvalidType => "invalid_type".into(),
46        }
47    }
48}
49
50/// Possible errors when pricing a charge session.
51#[derive(Debug)]
52pub enum Error {
53    /// A numeric overflow occurred while creating a duration.
54    Overflow,
55}
56
57impl From<rust_decimal::Error> for Error {
58    fn from(_: rust_decimal::Error) -> Self {
59        Self::Overflow
60    }
61}
62
63impl std::error::Error for Error {}
64
65impl fmt::Display for Error {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        match self {
68            Self::Overflow => f.write_str("A numeric overflow occurred while creating a duration"),
69        }
70    }
71}
72
73into_caveat!(TimeDelta);
74
75/// Convert a `TimeDelta` into a `Decimal` based amount of hours.
76pub trait ToHoursDecimal {
77    /// Return a `Decimal` based amount of hours.
78    fn to_hours_dec(&self) -> Decimal;
79}
80
81/// Convert a `Decimal` amount of hours to a `TimeDelta`.
82pub trait ToDuration {
83    /// Convert a `Decimal` amount of hours to a `TimeDelta`.
84    fn to_duration(&self) -> TimeDelta;
85}
86
87impl ToHoursDecimal for TimeDelta {
88    fn to_hours_dec(&self) -> Decimal {
89        let div = Decimal::from(MILLIS_IN_SEC * SECS_IN_MIN * MINS_IN_HOUR);
90        let num = Decimal::from(self.num_milliseconds());
91        num.checked_div(div).unwrap_or(Decimal::MAX)
92    }
93}
94
95impl ToDuration for Decimal {
96    fn to_duration(&self) -> TimeDelta {
97        let factor = Decimal::from(MILLIS_IN_SEC * SECS_IN_MIN * MINS_IN_HOUR);
98        let millis = self.saturating_mul(factor).to_i64().unwrap_or(i64::MAX);
99        TimeDelta::milliseconds(millis)
100    }
101}
102
103/// Parse a `chrono::TimeDelta` from JSON.
104///
105/// Used to parse the `min_duration` and `max_duration` fields of the tariff Restriction.
106///
107/// * See: [OCPI spec 2.2.1: Tariff Restriction](<https://github.com/ocpi/ocpi/blob/release-2.2.1-bugfixes/mod_tariffs.asciidoc#146-tariffrestrictions-class>)
108/// * See: [OCPI spec 2.1.1: Tariff Restriction](<https://github.com/ocpi/ocpi/blob/release-2.1.1-bugfixes/mod_tariffs.md#45-tariffrestrictions-class>)
109impl json::FromJson<'_, '_> for TimeDelta {
110    type WarningKind = WarningKind;
111
112    fn from_json(elem: &'_ json::Element<'_>) -> Verdict<Self, Self::WarningKind> {
113        let mut warnings = warning::Set::new();
114        let Some(s) = elem.as_number_str() else {
115            warnings.with_elem(WarningKind::InvalidType, elem);
116            return Err(warnings);
117        };
118
119        // We only support positive durations in an OCPI object.
120        let seconds = match s.parse::<u64>() {
121            Ok(n) => n,
122            Err(err) => {
123                warnings.with_elem(WarningKind::Invalid(err.to_string()), elem);
124                return Err(warnings);
125            }
126        };
127
128        // Then we convert the positive duration to an i64 as that is how `chrono::TimeDelta`
129        // represents seconds.
130        let Ok(seconds) = i64::try_from(seconds) else {
131            warnings.with_elem(
132                WarningKind::Invalid(
133                    "The duration value is larger than an i64 can represent.".into(),
134                ),
135                elem,
136            );
137            return Err(warnings);
138        };
139        let duration = TimeDelta::seconds(seconds);
140
141        Ok(duration.into_caveat(warnings))
142    }
143}
144
145/// A duration of time has a cost.
146impl Cost for TimeDelta {
147    fn cost(&self, money: Money) -> Money {
148        let cost = self.to_hours_dec().saturating_mul(Decimal::from(money));
149        Money::from_decimal(cost)
150    }
151}
152
153impl SaturatingAdd for TimeDelta {
154    fn saturating_add(self, other: TimeDelta) -> TimeDelta {
155        self.checked_add(&other).unwrap_or(TimeDelta::MAX)
156    }
157}
158
159impl SaturatingSub for TimeDelta {
160    fn saturating_sub(self, other: TimeDelta) -> TimeDelta {
161        self.checked_sub(&other).unwrap_or_else(TimeDelta::zero)
162    }
163}
164
165/// A debug helper trait to display durations as HH:MM:SS.
166#[allow(dead_code, reason = "used during debug sessions")]
167pub(crate) trait AsHms {
168    /// Return a `Hms` formatter, that formats a `TimeDelta` into a `String` in `HH::MM::SS` format.
169    fn as_hms(&self) -> Hms;
170}
171
172impl AsHms for TimeDelta {
173    fn as_hms(&self) -> Hms {
174        Hms(*self)
175    }
176}
177
178impl AsHms for Decimal {
179    /// Return a `Hms` formatter, that formats a `TimeDelta` into a `String` in `HH::MM::SS` format.
180    fn as_hms(&self) -> Hms {
181        Hms(self.to_duration())
182    }
183}
184
185/// A debug utility for displaying durations in `HH::MM::SS` format.
186pub(crate) struct Hms(pub TimeDelta);
187
188/// The Debug and Display impls are the same for Hms as I never want to see the `TimeDelta` representation.
189impl fmt::Debug for Hms {
190    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191        fmt::Display::fmt(self, f)
192    }
193}
194
195impl fmt::Display for Hms {
196    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197        let duration = self.0;
198        let seconds = duration.num_seconds();
199
200        // If the duration is negative write a single minus sign.
201        if seconds.is_negative() {
202            f.write_str("-")?;
203        }
204
205        // Avoid minus signs in the output.
206        let seconds = seconds.abs();
207
208        let seconds = seconds % SECS_IN_MIN;
209        let minutes = (seconds / SECS_IN_MIN) % MINS_IN_HOUR;
210        let hours = seconds / (SECS_IN_MIN * MINS_IN_HOUR);
211
212        write!(f, "{hours:0>2}:{minutes:0>2}:{seconds:0>2}")
213    }
214}
215
216#[cfg(test)]
217mod test {
218    use chrono::TimeDelta;
219
220    use crate::test::ApproxEq;
221
222    use super::Error;
223
224    #[test]
225    const fn error_should_be_send_and_sync() {
226        const fn f<T: Send + Sync>() {}
227
228        f::<Error>();
229    }
230
231    impl ApproxEq for TimeDelta {
232        fn approx_eq(&self, other: &Self) -> bool {
233            const TOLERANCE: i64 = 3;
234            approx_eq_time_delta(*self, *other, TOLERANCE)
235        }
236    }
237
238    /// Approximately compare two `TimeDelta` values.
239    pub fn approx_eq_time_delta(a: TimeDelta, b: TimeDelta, tolerance_secs: i64) -> bool {
240        let diff = a.num_seconds() - b.num_seconds();
241        diff.abs() <= tolerance_secs
242    }
243}
244
245#[cfg(test)]
246mod hour_decimal_tests {
247    use chrono::TimeDelta;
248    use rust_decimal::Decimal;
249    use rust_decimal_macros::dec;
250
251    use crate::duration::ToHoursDecimal;
252
253    use super::MILLIS_IN_SEC;
254
255    #[test]
256    fn zero_minutes_should_be_zero_hours() {
257        assert_eq!(TimeDelta::minutes(0).to_hours_dec(), dec!(0.0));
258    }
259
260    #[test]
261    fn thirty_minutes_should_be_fraction_of_hour() {
262        assert_eq!(TimeDelta::minutes(30).to_hours_dec(), dec!(0.5));
263    }
264
265    #[test]
266    fn sixty_minutes_should_be_fraction_of_hour() {
267        assert_eq!(TimeDelta::minutes(60).to_hours_dec(), dec!(1.0));
268    }
269
270    #[test]
271    fn ninety_minutes_should_be_fraction_of_hour() {
272        assert_eq!(TimeDelta::minutes(90).to_hours_dec(), dec!(1.5));
273    }
274
275    #[test]
276    fn as_seconds_dec_should_not_overflow() {
277        let number = Decimal::from(i64::MAX).checked_div(Decimal::from(MILLIS_IN_SEC));
278        assert!(number.is_some(), "should not overflow");
279    }
280}