1use {
2 crate::ParseDateTimeError,
3 std::{fmt, str::FromStr},
4};
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
10pub struct Time {
11 pub hour: u8, pub minute: u8, pub second: u8, }
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}