execution_time/traits/
duration_extension.rs

1use crate::{RoundFloat, Time};
2use std::time::Duration;
3
4// Constants for seconds in a day, an hour, and a minute to improve readability and performance.
5const SECONDS_IN_DAY: f64 = 86400.0;
6const SECONDS_IN_HOUR: f64 = 3600.0;
7const SECONDS_IN_MINUTE: f64 = 60.0;
8
9/// Trait to extend the `Duration` type with a method to convert it to a `Time` struct.
10pub trait DurationExtension {
11    /// Converts a `Duration` into a `Time` struct.
12    fn get_time(&self) -> Time;
13}
14
15impl DurationExtension for Duration {
16    fn get_time(&self) -> Time {
17        let all_seconds: f64 = self.as_secs_f64();
18
19        let remaining_day = all_seconds % SECONDS_IN_DAY;
20        let remaining_hour = remaining_day % SECONDS_IN_HOUR;
21
22        let days = (all_seconds / SECONDS_IN_DAY).floor() as u64;
23        let hours = (remaining_day / SECONDS_IN_HOUR).floor() as u8;
24        let minutes = (remaining_hour / SECONDS_IN_MINUTE).floor() as u8;
25        let seconds = (remaining_hour % SECONDS_IN_MINUTE).round_float(9);
26
27        Time {
28            days,
29            hours,
30            minutes,
31            seconds,
32        }
33    }
34}