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 [`SignedDuration`]. The [`ToDuration`] and [`ToHoursDecimal`] traits can be used
3//! to convert a [`SignedDuration`] into a [`Decimal`] and vice versa.
4
5#[cfg(test)]
6pub(crate) mod test;
7
8#[cfg(test)]
9mod test_from_schema;
10
11#[cfg(test)]
12mod test_hour_decimal;
13
14use std::fmt;
15
16use jiff::SignedDuration;
17use num_traits::ToPrimitive as _;
18use rust_decimal::Decimal;
19use rust_decimal_macros::dec;
20
21use crate::{
22    Cost, LowerSchema, Money, SaturatingAdd, SaturatingSub, json,
23    number::{self, FromDecimal as _, RoundDecimal as _, int_error_kind_as_str},
24    schema, warning,
25};
26
27pub(crate) const SECS_IN_MIN: i64 = 60;
28pub(crate) const MINS_IN_HOUR: i64 = 60;
29pub(crate) const MILLIS_IN_SEC: i64 = 1000;
30pub(crate) const NANOS_IN_HOUR: Decimal = dec!(36e11);
31const SECONDS_IN_HOUR: Decimal = dec!(3600);
32
33/// The warnings possible when parsing or linting a duration.
34#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
35pub enum Warning {
36    /// Unable to parse the duration.
37    Invalid(&'static str),
38
39    /// The JSON value given is not an int.
40    InvalidType {
41        /// The JSON kind found where an int was expected.
42        type_found: json::ValueKind,
43    },
44
45    /// A numeric overflow occurred while creating a duration.
46    Overflow,
47}
48
49impl Warning {
50    fn invalid_type(elem: &json::Element<'_>) -> Self {
51        Self::InvalidType {
52            type_found: elem.value().kind(),
53        }
54    }
55}
56
57impl fmt::Display for Warning {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        match self {
60            Self::Invalid(err) => write!(f, "Unable to parse the duration: {err}"),
61            Self::InvalidType { type_found } => {
62                write!(f, "The value should be an int but is `{type_found}`")
63            }
64            Self::Overflow => f.write_str("A numeric overflow occurred while creating a duration"),
65        }
66    }
67}
68
69impl crate::Warning for Warning {
70    fn id(&self) -> warning::Id {
71        match self {
72            Self::Invalid(_) => warning::Id::from_static("invalid"),
73            Self::InvalidType { type_found } => {
74                warning::Id::from_string(format!("invalid_type({type_found})"))
75            }
76            Self::Overflow => warning::Id::from_static("overflow"),
77        }
78    }
79}
80
81impl From<rust_decimal::Error> for Warning {
82    fn from(_: rust_decimal::Error) -> Self {
83        Self::Overflow
84    }
85}
86
87/// Convert a `SignedDuration` into a `Decimal` based amount of hours.
88pub trait ToHoursDecimal {
89    /// Return a `Decimal` based amount of hours.
90    fn to_hours_dec(&self) -> Decimal;
91    /// Return a `Decimal` based amount of hours, in the precision specified
92    /// by OCPI.
93    ///
94    /// Note this should only be used for output, for intermediate results use
95    /// `to_hours_dec`, to avoid rounding.
96    fn to_hours_dec_in_ocpi_precision(&self) -> Decimal {
97        self.to_hours_dec().round_to_ocpi_scale()
98    }
99}
100
101impl ToHoursDecimal for SignedDuration {
102    fn to_hours_dec(&self) -> Decimal {
103        let num_sec = Decimal::from(self.as_secs());
104        let num_nano = Decimal::from(self.subsec_nanos());
105        let sec_part = num_sec.checked_div(SECONDS_IN_HOUR).unwrap_or(Decimal::MAX);
106        let nano_part = num_nano.checked_div(NANOS_IN_HOUR).unwrap_or(Decimal::MAX);
107        sec_part.checked_add(nano_part).unwrap_or(Decimal::MAX)
108    }
109}
110
111/// Convert a `Decimal` amount of hours to a `SignedDuration`.
112pub trait ToDuration {
113    /// Convert a `Decimal` amount of hours to a `SignedDuration`.
114    fn to_duration(&self) -> SignedDuration;
115}
116
117impl ToDuration for Decimal {
118    /// Convert a `Decimal` amount of hours to a `SignedDuration`.
119    ///
120    /// Round to the maximal precision of `SignedDuration` which is nanoseconds.
121    fn to_duration(&self) -> SignedDuration {
122        let nanos = self
123            .saturating_mul(NANOS_IN_HOUR)
124            // Any sub-nanosecond fraction is preserved correctly.
125            // A fraction >= 0.5 nanosecond still rounds up, and a fraction < 0.5 nanosecond
126            // rounds down. Both of which represent rounding errors far smaller than any
127            // meaningful time unit.
128            .round_dp_with_strategy(0, rust_decimal::RoundingStrategy::MidpointAwayFromZero)
129            .to_i64()
130            .unwrap_or(i64::MAX);
131        SignedDuration::from_nanos(nanos)
132    }
133}
134
135/// A `SignedDuration` can't be parsed from JSON directly, you must first decide which unit of time
136/// to parse it as. The `Seconds` type is used to parse the JSON Element as an integer amount of
137/// seconds.
138#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
139pub(crate) struct Seconds(SignedDuration);
140
141impl number::IsZero for Seconds {
142    fn is_zero(&self) -> bool {
143        self.0.is_zero()
144    }
145}
146
147/// Once the `SignedDuration` has been parsed as seconds you can extract it from the newtype.
148impl From<Seconds> for SignedDuration {
149    fn from(value: Seconds) -> Self {
150        value.0
151    }
152}
153
154impl fmt::Debug for Seconds {
155    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
156        f.debug_tuple("Seconds").field(&self.0.as_secs()).finish()
157    }
158}
159
160impl fmt::Display for Seconds {
161    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162        write!(f, "{}", self.0.as_secs())
163    }
164}
165
166/// Parse a seconds `SignedDuration` from JSON.
167///
168/// Used to parse the `min_duration` and `max_duration` fields of the tariff Restriction.
169///
170/// * See: [OCPI spec 2.2.1: Tariff Restriction](<https://github.com/ocpi/ocpi/blob/a57ecb624fbe0f19537ac7956a11f3019a65018f/mod_tariffs.asciidoc#mod_tariffs_tariffrestrictions_class>).
171/// * See: [OCPI spec 2.1.1: Tariff Restriction](<https://github.com/ocpi/ocpi/blob/28ea45329a50c3dbfd790505b97860854db1d4a6/mod_tariffs.md#45-tariffrestrictions-class>).
172impl<'buf> LowerSchema<'buf, schema::Number<'buf>> for Seconds {
173    type Warning = Warning;
174
175    fn lower_schema(
176        source: &schema::Number<'buf>,
177        _warnings: &mut dyn warning::Gather<Warning>,
178    ) -> Result<Self, warning::Error<Warning>> {
179        // `Seconds` only accepts a JSON number, not a number encoded as a string.
180        // The schema walk has already checked that the literal is a JSON number,
181        // so `lower_schema` reads its `digits` directly.
182        let (elem, digits) = match source {
183            schema::Number::Number { elem, digits } => (elem, *digits),
184            schema::Number::StringEncoded { elem, value: _ } => {
185                return Err(warning::Error::new(elem, Warning::invalid_type(elem)));
186            }
187        };
188
189        // We only support positive durations in an OCPI object.
190        let seconds = match digits.parse::<u64>() {
191            Ok(n) => n,
192            Err(err) => {
193                return Err(warning::Error::new(
194                    elem,
195                    Warning::Invalid(int_error_kind_as_str(*err.kind())),
196                ));
197            }
198        };
199
200        // Then we convert the positive duration to an i64 as that is how `SignedDuration`
201        // represents seconds.
202        let Ok(seconds) = i64::try_from(seconds) else {
203            return Err(warning::Error::new(
204                elem,
205                Warning::Invalid("The duration value is larger than an i64 can represent."),
206            ));
207        };
208        let dt = SignedDuration::from_secs(seconds);
209
210        Ok(Seconds(dt))
211    }
212}
213
214/// A duration of time has a cost.
215impl Cost for SignedDuration {
216    fn cost(&self, money: Money) -> Money {
217        let cost = self.to_hours_dec().saturating_mul(Decimal::from(money));
218        Money::from_decimal(cost)
219    }
220}
221
222impl SaturatingAdd for SignedDuration {
223    fn saturating_add(self, other: SignedDuration) -> SignedDuration {
224        self.checked_add(other).unwrap_or(SignedDuration::MAX)
225    }
226}
227
228impl SaturatingSub for SignedDuration {
229    fn saturating_sub(self, other: SignedDuration) -> SignedDuration {
230        self.checked_sub(other).unwrap_or(SignedDuration::ZERO)
231    }
232}
233
234/// A debug helper trait to display durations as `HH:MM:SS`.
235#[expect(clippy::allow_attributes, reason = "used during debug sessions")]
236#[allow(dead_code, reason = "used during debug sessions")]
237pub(crate) trait AsHms {
238    /// Return a `Hms` formatter, that formats a `SignedDuration` into a `String` in `HH::MM::SS`
239    /// format.
240    fn as_hms(&self) -> Hms;
241}
242
243impl AsHms for SignedDuration {
244    fn as_hms(&self) -> Hms {
245        Hms(*self)
246    }
247}
248
249impl AsHms for Decimal {
250    /// Return a `Hms` formatter, that formats a `SignedDuration` into a `String` in `HH::MM::SS`
251    /// format.
252    fn as_hms(&self) -> Hms {
253        Hms(self.to_duration())
254    }
255}
256
257/// A utility for deserializing and displaying durations in `HH::MM::SS` format.
258#[derive(Copy, Clone)]
259pub struct Hms(pub SignedDuration);
260
261/// The Debug and Display impls are the same for `Hms` as I never want to see the `SignedDuration`
262/// representation.
263impl fmt::Debug for Hms {
264    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
265        fmt::Display::fmt(self, f)
266    }
267}
268
269impl fmt::Display for Hms {
270    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
271        const SECS_IN_MIN_UNSIGNED: u64 = SECS_IN_MIN.unsigned_abs();
272        const MINS_IN_HOUR_UNSIGNED: u64 = MINS_IN_HOUR.unsigned_abs();
273        const SECS_IN_HOUR_UNSIGNED: u64 = SECS_IN_MIN_UNSIGNED * MINS_IN_HOUR_UNSIGNED;
274
275        let duration = self.0;
276        let seconds = duration.as_secs();
277
278        // If the duration is negative write a single minus sign.
279        if seconds.is_negative() {
280            f.write_str("-")?;
281        }
282
283        // Avoid minus signs in the output.
284        // `abs` would panic on the `i64::MIN` seconds of `SignedDuration::MIN`, which
285        // `unsigned_abs` holds.
286        let seconds_total = seconds.unsigned_abs();
287
288        let seconds = seconds_total % SECS_IN_MIN_UNSIGNED;
289        let minutes = (seconds_total / SECS_IN_MIN_UNSIGNED) % MINS_IN_HOUR_UNSIGNED;
290        let hours = seconds_total / SECS_IN_HOUR_UNSIGNED;
291
292        write!(f, "{hours:0>2}:{minutes:0>2}:{seconds:0>2}")
293    }
294}
295
296#[cfg(test)]
297mod test_hms {
298    use jiff::SignedDuration;
299
300    use super::Hms;
301
302    #[test]
303    fn should_display_seconds() {
304        assert_eq!(Hms(SignedDuration::from_secs(0)).to_string(), "00:00:00");
305        assert_eq!(Hms(SignedDuration::from_secs(59)).to_string(), "00:00:59");
306    }
307
308    #[test]
309    fn should_display_minutes() {
310        assert_eq!(Hms(SignedDuration::from_secs(60)).to_string(), "00:01:00");
311        assert_eq!(Hms(SignedDuration::from_secs(3600)).to_string(), "01:00:00");
312    }
313
314    #[test]
315    fn should_display_hours() {
316        assert_eq!(Hms(SignedDuration::from_mins(60)).to_string(), "01:00:00");
317        assert_eq!(Hms(SignedDuration::from_mins(3600)).to_string(), "60:00:00");
318    }
319
320    #[test]
321    fn should_display_the_most_negative_duration() {
322        assert_eq!(
323            Hms(SignedDuration::MIN).to_string(),
324            "-2562047788015215:30:08"
325        );
326    }
327
328    #[test]
329    fn should_display_hours_mins_secs() {
330        assert_eq!(
331            Hms(SignedDuration::from_secs(87030)).to_string(),
332            "24:10:30"
333        );
334    }
335}
336
337#[cfg(test)]
338mod test_to_hours_decimal {
339    use jiff::SignedDuration;
340    use rust_decimal_macros::dec;
341
342    use crate::ToHoursDecimal as _;
343
344    #[test]
345    fn to_hours_dec_should_be_correct() {
346        let actual = SignedDuration::from_hours(1).to_hours_dec();
347        assert_eq!(actual, dec!(1.0));
348
349        let actual = SignedDuration::from_secs(3960).to_hours_dec();
350        assert_eq!(actual, dec!(1.1));
351
352        let actual = SignedDuration::from_secs(360).to_hours_dec();
353        assert_eq!(actual, dec!(0.1));
354
355        let actual = SignedDuration::from_secs(36).to_hours_dec();
356        assert_eq!(actual, dec!(0.01));
357
358        let actual = SignedDuration::from_millis(36).to_hours_dec();
359        assert_eq!(actual, dec!(0.00001));
360
361        let actual = SignedDuration::from_nanos(1).to_hours_dec();
362        assert_eq!(actual, dec!(2.777777777777778e-13));
363    }
364}
365
366#[cfg(test)]
367mod test_to_duration {
368    use jiff::SignedDuration;
369    use rust_decimal_macros::dec;
370
371    use crate::ToDuration as _;
372
373    #[test]
374    fn to_duration_should_be_correct() {
375        let actual = dec!(1.0).to_duration();
376        assert_eq!(actual, SignedDuration::from_hours(1));
377
378        let actual = dec!(1.1).to_duration();
379        assert_eq!(actual, SignedDuration::from_secs(3960));
380
381        let actual = dec!(0.1).to_duration();
382        assert_eq!(actual, SignedDuration::from_secs(360));
383
384        let actual = dec!(1e-14).to_duration();
385        assert_eq!(actual, SignedDuration::ZERO);
386
387        let actual = dec!(2.777e-13).to_duration();
388        assert_eq!(actual, SignedDuration::from_nanos(1));
389    }
390}