Skip to main content

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
5#[cfg(test)]
6pub(crate) mod test;
7
8#[cfg(test)]
9mod test_hour_decimal;
10
11use std::fmt;
12
13use chrono::TimeDelta;
14use num_traits::ToPrimitive as _;
15use rust_decimal::Decimal;
16
17use crate::{
18    into_caveat_all, json,
19    number::{int_error_kind_as_str, FromDecimal as _, RoundDecimal},
20    warning::{self, IntoCaveat as _},
21    Cost, Money, SaturatingAdd, SaturatingSub, Verdict,
22};
23
24pub(crate) const SECS_IN_MIN: i64 = 60;
25pub(crate) const MINS_IN_HOUR: i64 = 60;
26pub(crate) const MILLIS_IN_SEC: i64 = 1000;
27
28/// The warnings possible when parsing or linting a duration.
29#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
30pub enum Warning {
31    /// Unable to parse the duration.
32    Invalid(&'static str),
33
34    /// The JSON value given is not an int.
35    InvalidType { type_found: json::ValueKind },
36
37    /// A numeric overflow occurred while creating a duration.
38    Overflow,
39}
40
41impl Warning {
42    fn invalid_type(elem: &json::Element<'_>) -> Self {
43        Self::InvalidType {
44            type_found: elem.value().kind(),
45        }
46    }
47}
48
49impl fmt::Display for Warning {
50    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51        match self {
52            Self::Invalid(err) => write!(f, "Unable to parse the duration: {err}"),
53            Self::InvalidType { type_found } => {
54                write!(f, "The value should be an int but is `{type_found}`")
55            }
56            Self::Overflow => f.write_str("A numeric overflow occurred while creating a duration"),
57        }
58    }
59}
60
61impl crate::Warning for Warning {
62    fn id(&self) -> warning::Id {
63        match self {
64            Self::Invalid(_) => warning::Id::from_static("invalid"),
65            Self::InvalidType { .. } => warning::Id::from_static("invalid_type"),
66            Self::Overflow => warning::Id::from_static("overflow"),
67        }
68    }
69}
70
71impl From<rust_decimal::Error> for Warning {
72    fn from(_: rust_decimal::Error) -> Self {
73        Self::Overflow
74    }
75}
76
77into_caveat_all!(TimeDelta, Seconds);
78
79/// Convert a `TimeDelta` into a `Decimal` based amount of hours.
80pub trait ToHoursDecimal {
81    /// Return a `Decimal` based amount of hours.
82    fn to_hours_dec(&self) -> Decimal;
83}
84
85/// Convert a `Decimal` amount of hours to a `TimeDelta`.
86pub trait ToDuration {
87    /// Convert a `Decimal` amount of hours to a `TimeDelta`.
88    fn to_duration(&self) -> TimeDelta;
89}
90
91impl ToHoursDecimal for TimeDelta {
92    fn to_hours_dec(&self) -> Decimal {
93        let div = Decimal::from(MILLIS_IN_SEC * SECS_IN_MIN * MINS_IN_HOUR);
94        let num = Decimal::from(self.num_milliseconds());
95        num.checked_div(div)
96            .unwrap_or(Decimal::MAX)
97            .round_to_ocpi_scale()
98    }
99}
100
101impl ToDuration for Decimal {
102    fn to_duration(&self) -> TimeDelta {
103        let factor = Decimal::from(MILLIS_IN_SEC * SECS_IN_MIN * MINS_IN_HOUR);
104        let millis = self.saturating_mul(factor).to_i64().unwrap_or(i64::MAX);
105        TimeDelta::milliseconds(millis)
106    }
107}
108
109/// A `TimeDelta` can't be parsed from JSON directly, you must first decide which unit of time to
110/// parse it as. The `Seconds` type is used to parse the JSON Element as an integer amount of seconds.
111pub(crate) struct Seconds(TimeDelta);
112
113/// Once the `TimeDelta` has been parsed as seconds you can extract it from the newtype.
114impl From<Seconds> for TimeDelta {
115    fn from(value: Seconds) -> Self {
116        value.0
117    }
118}
119
120/// Parse a seconds `TimeDelta` from JSON.
121///
122/// Used to parse the `min_duration` and `max_duration` fields of the tariff Restriction.
123///
124/// * 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>)
125/// * 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>)
126impl json::FromJson<'_, '_> for Seconds {
127    type Warning = Warning;
128
129    fn from_json(elem: &'_ json::Element<'_>) -> Verdict<Self, Self::Warning> {
130        let warnings = warning::Set::new();
131        let Some(s) = elem.as_number_str() else {
132            return warnings.bail(Warning::invalid_type(elem), elem);
133        };
134
135        // We only support positive durations in an OCPI object.
136        let seconds = match s.parse::<u64>() {
137            Ok(n) => n,
138            Err(err) => {
139                return warnings.bail(Warning::Invalid(int_error_kind_as_str(*err.kind())), elem);
140            }
141        };
142
143        // Then we convert the positive duration to an i64 as that is how `chrono::TimeDelta`
144        // represents seconds.
145        let Ok(seconds) = i64::try_from(seconds) else {
146            return warnings.bail(
147                Warning::Invalid("The duration value is larger than an i64 can represent."),
148                elem,
149            );
150        };
151        let dt = TimeDelta::seconds(seconds);
152
153        Ok(Seconds(dt).into_caveat(warnings))
154    }
155}
156
157/// A duration of time has a cost.
158impl Cost for TimeDelta {
159    fn cost(&self, money: Money) -> Money {
160        let cost = self.to_hours_dec().saturating_mul(Decimal::from(money));
161        Money::from_decimal(cost)
162    }
163}
164
165impl SaturatingAdd for TimeDelta {
166    fn saturating_add(self, other: TimeDelta) -> TimeDelta {
167        self.checked_add(&other).unwrap_or(TimeDelta::MAX)
168    }
169}
170
171impl SaturatingSub for TimeDelta {
172    fn saturating_sub(self, other: TimeDelta) -> TimeDelta {
173        self.checked_sub(&other).unwrap_or_else(TimeDelta::zero)
174    }
175}
176
177/// A debug helper trait to display durations as `HH:MM:SS`.
178#[allow(dead_code, reason = "used during debug sessions")]
179pub(crate) trait AsHms {
180    /// Return a `Hms` formatter, that formats a `TimeDelta` into a `String` in `HH::MM::SS` format.
181    fn as_hms(&self) -> Hms;
182}
183
184impl AsHms for TimeDelta {
185    fn as_hms(&self) -> Hms {
186        Hms(*self)
187    }
188}
189
190impl AsHms for Decimal {
191    /// Return a `Hms` formatter, that formats a `TimeDelta` into a `String` in `HH::MM::SS` format.
192    fn as_hms(&self) -> Hms {
193        Hms(self.to_duration())
194    }
195}
196
197/// A utility for displaying durations in `HH::MM::SS` format.
198pub struct Hms(pub TimeDelta);
199
200/// The Debug and Display impls are the same for `Hms` as I never want to see the `TimeDelta` representation.
201impl fmt::Debug for Hms {
202    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
203        fmt::Display::fmt(self, f)
204    }
205}
206
207impl fmt::Display for Hms {
208    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
209        let duration = self.0;
210        let seconds = duration.num_seconds();
211
212        // If the duration is negative write a single minus sign.
213        if seconds.is_negative() {
214            f.write_str("-")?;
215        }
216
217        // Avoid minus signs in the output.
218        let seconds = seconds.abs();
219
220        let seconds = seconds % SECS_IN_MIN;
221        let minutes = (seconds / SECS_IN_MIN) % MINS_IN_HOUR;
222        let hours = seconds / (SECS_IN_MIN * MINS_IN_HOUR);
223
224        write!(f, "{hours:0>2}:{minutes:0>2}:{seconds:0>2}")
225    }
226}