rhit/
time.rs

1use {
2    crate::ParseDateTimeError,
3    std::{fmt, str::FromStr},
4};
5
6/// a time, only valid in the context of the local set of log files.
7/// It's implicitely in the timezone of the log files
8/// (assuming all the files have the same one).
9#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
10pub struct Time {
11    pub hour: u8, // in [0,23]
12    pub minute: u8, // in [0,59]
13    pub second: u8,   // in [0,59]
14}
15impl Time {
16    pub fn new(
17        hour: u8,
18        minute: u8,
19        second: u8,
20    ) -> Result<Self, ParseDateTimeError> {
21        if second > 59 {
22            return Err(ParseDateTimeError::InvalidSecond(second));
23        }
24        if minute > 59 {
25            return Err(ParseDateTimeError::InvalidMinute(minute));
26        }
27        if hour > 23 {
28            return Err(ParseDateTimeError::InvalidHour(hour));
29        }
30        Ok(Self { hour, minute, second })
31    }
32}
33
34impl FromStr for Time {
35    type Err = ParseDateTimeError;
36    fn from_str(s: &str) -> Result<Self, Self::Err> {
37        if s.len()<2 {
38            return Err(ParseDateTimeError::UnexpectedEnd);
39        }
40        let hour = s[0..2].parse()?;
41        let mut minute = 0;
42        let mut second = 0;
43        if s.len()>4 {
44            minute = s[3..5].parse()?;
45            if s.len()>6 {
46                second = s[6..7].parse()?;
47            }
48        }
49        Time::new(hour, minute, second)
50    }
51}
52
53impl fmt::Display for Time {
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        write!(f, "{:0>2}:{:0>2}:{:0>2}", self.hour, self.minute, self.second)
56    }
57}