execution_time/
time.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
use crate::{FormatFloatValue, FormatIntegerValue, RoundFloat, Unit};
use std::time::Duration;

// Constants for seconds in a day, an hour, and a minute to improve readability.
const SECONDS_IN_DAY: f64 = 86400.0;
const SECONDS_IN_HOUR: f64 = 3600.0;
const SECONDS_IN_MINUTE: f64 = 60.0;

// Set a small margin of error
const EPSILON: f64 = 1e-10;

/// Represents a time duration split into days, hours, minutes, and seconds.
///
/// This struct holds the components of a time duration for formatting and display purposes.
#[derive(Debug, Default, PartialEq)]
pub struct Time {
    pub days: u64,
    pub hours: u8,
    pub minutes: u8,
    pub seconds: f64,
}

impl Time {
    /// Creates a `Time` struct from a `Duration`.
    ///
    /// `Duration` represents a span of time composed of whole seconds and a
    /// fractional part represented in nanoseconds.  
    ///
    /// This function converts
    /// that representation into days, hours, minutes, and seconds.
    pub fn new(duration: Duration) -> Time {
        let dur_secs: f64 = duration.as_secs_f64();

        let remaining_day = dur_secs % SECONDS_IN_DAY;
        let remaining_hour = remaining_day % SECONDS_IN_HOUR;

        let days = (dur_secs / SECONDS_IN_DAY).floor() as u64;
        let hours = (remaining_day / SECONDS_IN_HOUR).floor() as u8;
        let minutes = (remaining_hour / SECONDS_IN_MINUTE).floor() as u8;
        let seconds = (remaining_hour % SECONDS_IN_MINUTE).round_float(9);

        Time {
            days,
            hours,
            minutes,
            seconds,
        }
    }

    /// Formats the time duration into a human-readable string.
    ///
    /// This method combines the time components (days, hours, minutes, seconds) into a
    /// single, formatted string.  It includes only non-zero components, except for seconds,
    /// which are always included.
    ///
    /// # Returns
    ///
    /// A formatted time string.
    pub fn format_time(&self) -> String {
        let mut parts = Vec::new();

        // Add days to the output if they are greater than 0.
        if self.days > 0 {
            parts.push(self.days.format_unit(Unit::Day));
        }

        // Add hours to the output if they are greater than 0, or if days have already been added.
        if self.hours > 0 || !parts.is_empty() {
            parts.push(self.hours.format_unit(Unit::Hour));
        }

        // Add minutes to the output if they are greater than 0, or if hours or days have already been added.
        if self.minutes > 0 || !parts.is_empty() {
            parts.push(self.minutes.format_unit(Unit::Minute));
        }

        let decimal: usize = self.calculate_decimal();

        // Always add seconds to the output.
        parts.push(self.seconds.format_float_unit(decimal, Unit::Second));

        parts.join(", ")
    }

    fn calculate_decimal(&self) -> usize {
        let sec = self.seconds;

        if sec < EPSILON {
            // Handles the case where 'sec' is approximately zero
            1
        } else if sec >= 1.0 {
            3
        } else if sec >= 0.001 {
            6
        } else {
            9
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn time_new() {
        let duration = Duration::from_secs(86400 + 3600 + 60 + 1); // 1 day, 1 hour, 1 minute, 1 second
        let time = Time::new(duration);
        assert_eq!(time.days, 1);
        assert_eq!(time.hours, 1);
        assert_eq!(time.minutes, 1);
        assert_eq!(time.seconds, 1.0);

        let duration = Duration::from_secs_f64(3661.5); // 1 hour, 1 minute, 1.5 seconds
        let time = Time::new(duration);
        assert_eq!(time.days, 0);
        assert_eq!(time.hours, 1);
        assert_eq!(time.minutes, 1);
        assert_eq!(time.seconds, 1.5);

        let duration = Duration::from_secs(0);
        let time = Time::new(duration);
        assert_eq!(time.days, 0);
        assert_eq!(time.hours, 0);
        assert_eq!(time.minutes, 0);
        assert_eq!(time.seconds, 0.0);

        let duration = Duration::from_secs_f64(SECONDS_IN_DAY * 2.5);
        let time = Time::new(duration);
        assert_eq!(time.days, 2);
        assert_eq!(time.hours, 12);
        assert_eq!(time.minutes, 0);
        assert_eq!(time.seconds, 0.0);
    }

    #[test]
    fn times_format() {
        let time = Time {
            days: 1,
            hours: 2,
            minutes: 3,
            seconds: 4.567,
        };
        assert_eq!(
            time.format_time(),
            "1 day, 2 hours, 3 minutes, 4.567 seconds"
        );

        let time = Time {
            days: 0,
            hours: 2,
            minutes: 3,
            seconds: 4.567,
        };
        assert_eq!(time.format_time(), "2 hours, 3 minutes, 4.567 seconds");

        let time = Time {
            days: 0,
            hours: 0,
            minutes: 3,
            seconds: 4.567,
        };
        assert_eq!(time.format_time(), "3 minutes, 4.567 seconds");

        let time = Time {
            days: 0,
            hours: 0,
            minutes: 0,
            seconds: 4.567,
        };
        assert_eq!(time.format_time(), "4.567 seconds");

        let time = Time {
            days: 1,
            hours: 0,
            minutes: 0,
            seconds: 0.0,
        };

        assert_eq!(time.format_time(), "1 day, 0 hour, 0 minute, 0.0 second");

        let time = Time {
            days: 1,
            hours: 2,
            minutes: 0,
            seconds: 0.0,
        };
        assert_eq!(time.format_time(), "1 day, 2 hours, 0 minute, 0.0 second");
    }

    #[test]
    fn format_time_default() {
        let time = Time {
            days: 0,
            hours: 0,
            minutes: 0,
            seconds: 0.0,
        };
        let time_default = Time::default();

        assert_eq!(time, time_default);
        assert_eq!(time.format_time(), "0.0 second");
    }
}