1#[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#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
35pub enum Warning {
36 Invalid(&'static str),
38
39 InvalidType {
41 type_found: json::ValueKind,
43 },
44
45 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
87pub trait ToHoursDecimal {
89 fn to_hours_dec(&self) -> Decimal;
91 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
111pub trait ToDuration {
113 fn to_duration(&self) -> SignedDuration;
115}
116
117impl ToDuration for Decimal {
118 fn to_duration(&self) -> SignedDuration {
122 let nanos = self
123 .saturating_mul(NANOS_IN_HOUR)
124 .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#[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
147impl 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
166impl<'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 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 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 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
214impl 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#[expect(clippy::allow_attributes, reason = "used during debug sessions")]
236#[allow(dead_code, reason = "used during debug sessions")]
237pub(crate) trait AsHms {
238 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 fn as_hms(&self) -> Hms {
253 Hms(self.to_duration())
254 }
255}
256
257#[derive(Copy, Clone)]
259pub struct Hms(pub SignedDuration);
260
261impl 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 seconds.is_negative() {
280 f.write_str("-")?;
281 }
282
283 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}