1#[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#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
30pub enum Warning {
31 Invalid(&'static str),
33
34 InvalidType { type_found: json::ValueKind },
36
37 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
79pub trait ToHoursDecimal {
81 fn to_hours_dec(&self) -> Decimal;
83}
84
85pub trait ToDuration {
87 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
109pub(crate) struct Seconds(TimeDelta);
112
113impl From<Seconds> for TimeDelta {
115 fn from(value: Seconds) -> Self {
116 value.0
117 }
118}
119
120impl 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 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 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
157impl 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#[allow(dead_code, reason = "used during debug sessions")]
179pub(crate) trait AsHms {
180 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 fn as_hms(&self) -> Hms {
193 Hms(self.to_duration())
194 }
195}
196
197pub struct Hms(pub TimeDelta);
199
200impl 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 seconds.is_negative() {
214 f.write_str("-")?;
215 }
216
217 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}