1use std::{borrow::Cow, fmt};
6
7use chrono::TimeDelta;
8use num_traits::ToPrimitive as _;
9use rust_decimal::Decimal;
10
11use crate::{
12 into_caveat_all, 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#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
24pub enum WarningKind {
25 Invalid(String),
27
28 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#[derive(Debug)]
52pub enum Error {
53 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_all!(TimeDelta, Seconds);
74
75pub trait ToHoursDecimal {
77 fn to_hours_dec(&self) -> Decimal;
79}
80
81pub trait ToDuration {
83 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
103pub(crate) struct Seconds(TimeDelta);
106
107impl From<Seconds> for TimeDelta {
109 fn from(value: Seconds) -> Self {
110 value.0
111 }
112}
113
114impl json::FromJson<'_, '_> for Seconds {
121 type WarningKind = WarningKind;
122
123 fn from_json(elem: &'_ json::Element<'_>) -> Verdict<Self, Self::WarningKind> {
124 let warnings = warning::Set::new();
125 let Some(s) = elem.as_number_str() else {
126 return warnings.bail(WarningKind::InvalidType, elem);
127 };
128
129 let seconds = match s.parse::<u64>() {
131 Ok(n) => n,
132 Err(err) => {
133 return warnings.bail(WarningKind::Invalid(err.to_string()), elem);
134 }
135 };
136
137 let Ok(seconds) = i64::try_from(seconds) else {
140 return warnings.bail(
141 WarningKind::Invalid(
142 "The duration value is larger than an i64 can represent.".into(),
143 ),
144 elem,
145 );
146 };
147 let dt = TimeDelta::seconds(seconds);
148
149 Ok(Seconds(dt).into_caveat(warnings))
150 }
151}
152
153impl Cost for TimeDelta {
155 fn cost(&self, money: Money) -> Money {
156 let cost = self.to_hours_dec().saturating_mul(Decimal::from(money));
157 Money::from_decimal(cost)
158 }
159}
160
161impl SaturatingAdd for TimeDelta {
162 fn saturating_add(self, other: TimeDelta) -> TimeDelta {
163 self.checked_add(&other).unwrap_or(TimeDelta::MAX)
164 }
165}
166
167impl SaturatingSub for TimeDelta {
168 fn saturating_sub(self, other: TimeDelta) -> TimeDelta {
169 self.checked_sub(&other).unwrap_or_else(TimeDelta::zero)
170 }
171}
172
173#[allow(dead_code, reason = "used during debug sessions")]
175pub(crate) trait AsHms {
176 fn as_hms(&self) -> Hms;
178}
179
180impl AsHms for TimeDelta {
181 fn as_hms(&self) -> Hms {
182 Hms(*self)
183 }
184}
185
186impl AsHms for Decimal {
187 fn as_hms(&self) -> Hms {
189 Hms(self.to_duration())
190 }
191}
192
193pub(crate) struct Hms(pub TimeDelta);
195
196impl fmt::Debug for Hms {
198 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
199 fmt::Display::fmt(self, f)
200 }
201}
202
203impl fmt::Display for Hms {
204 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205 let duration = self.0;
206 let seconds = duration.num_seconds();
207
208 if seconds.is_negative() {
210 f.write_str("-")?;
211 }
212
213 let seconds = seconds.abs();
215
216 let seconds = seconds % SECS_IN_MIN;
217 let minutes = (seconds / SECS_IN_MIN) % MINS_IN_HOUR;
218 let hours = seconds / (SECS_IN_MIN * MINS_IN_HOUR);
219
220 write!(f, "{hours:0>2}:{minutes:0>2}:{seconds:0>2}")
221 }
222}
223
224#[cfg(test)]
225mod test {
226 use chrono::TimeDelta;
227
228 use crate::test::ApproxEq;
229
230 use super::Error;
231
232 #[test]
233 const fn error_should_be_send_and_sync() {
234 const fn f<T: Send + Sync>() {}
235
236 f::<Error>();
237 }
238
239 impl ApproxEq for TimeDelta {
240 fn approx_eq(&self, other: &Self) -> bool {
241 const TOLERANCE: i64 = 3;
242 approx_eq_time_delta(*self, *other, TOLERANCE)
243 }
244 }
245
246 pub fn approx_eq_time_delta(a: TimeDelta, b: TimeDelta, tolerance_secs: i64) -> bool {
248 let diff = a.num_seconds() - b.num_seconds();
249 diff.abs() <= tolerance_secs
250 }
251}
252
253#[cfg(test)]
254mod hour_decimal_tests {
255 use chrono::TimeDelta;
256 use rust_decimal::Decimal;
257 use rust_decimal_macros::dec;
258
259 use crate::duration::ToHoursDecimal;
260
261 use super::MILLIS_IN_SEC;
262
263 #[test]
264 fn zero_minutes_should_be_zero_hours() {
265 assert_eq!(TimeDelta::minutes(0).to_hours_dec(), dec!(0.0));
266 }
267
268 #[test]
269 fn thirty_minutes_should_be_fraction_of_hour() {
270 assert_eq!(TimeDelta::minutes(30).to_hours_dec(), dec!(0.5));
271 }
272
273 #[test]
274 fn sixty_minutes_should_be_fraction_of_hour() {
275 assert_eq!(TimeDelta::minutes(60).to_hours_dec(), dec!(1.0));
276 }
277
278 #[test]
279 fn ninety_minutes_should_be_fraction_of_hour() {
280 assert_eq!(TimeDelta::minutes(90).to_hours_dec(), dec!(1.5));
281 }
282
283 #[test]
284 fn as_seconds_dec_should_not_overflow() {
285 let number = Decimal::from(i64::MAX).checked_div(Decimal::from(MILLIS_IN_SEC));
286 assert!(number.is_some(), "should not overflow");
287 }
288}