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
use crate::{FormatFloatValue, FormatIntegerValue, SECONDS_DECIMAL_PLACES};

/// Represents a time duration split into days, hours, minutes, and seconds.
///
/// This struct holds the components of a time duration for formatting and display.
pub struct Time {
    pub days: u64,
    pub hours: u8,
    pub minutes: u8,
    pub seconds: f64,
}

impl Time {
    /// Formats the time elapsed 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 and always displays seconds.
    ///
    /// # Returns
    ///
    /// A formatted time string.
    pub fn format_time(&self) -> String {
        let mut parts = Vec::new();

        // Add days to output if they are greater than 0
        if self.days > 0 {
            parts.push(self.days.format_unit("day", "days"));
        }

        // Add hours to 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("hour", "hours"));
        }

        // Add minutes to 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("minute", "minutes"));
        }

        // Always add seconds to output
        parts.push(
            self.seconds
                .format_unit(SECONDS_DECIMAL_PLACES, "second", "seconds"),
        );

        parts.join(", ")
    }
}