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
use static_regular_grammar::RegularGrammar;

use crate::{utils::byte_index_of, InvalidTimeValue};

use super::{date_time::parse_seconds_decimal, parse_timezone, Lexical, LexicalFormOf};

/// Time.
///
/// ```abnf
/// xsd-time = time [timezone]
///
/// time = hour ":" minute ":" second ["." fraction]
///      / "24:00:00" ["." 1*"0"]
///
/// hour = ("0" / "1") DIGIT
///      / "2" ("0" / "1" / "2" / "3")
///
/// minute = ("0" / "1" / "2" / "3" / "4" / "5") DIGIT
///
/// second = ("0" / "1" / "2" / "3" / "4" / "5") DIGIT
///
/// fraction = 1*DIGIT
///
/// timezone = ("+" / "-") ((("0" DIGIT / "1" ("0" / "1" / "2" / "3")) ":" minute) / "14:00")
///          / %s"Z"
/// ```
#[derive(RegularGrammar, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[grammar(sized(TimeBuf, derive(PartialEq, Eq, PartialOrd, Ord, Hash)))]
pub struct Time(str);

impl Time {
	fn parts(&self) -> Parts {
		let seconds_end =
			byte_index_of(self.0.as_bytes(), 8, [b'+', b'-', b'Z']).unwrap_or(self.0.len());
		Parts {
			hours: &self.0[..2],
			minutes: &self.0[3..5],
			seconds: &self.0[6..seconds_end],
			timezone: if seconds_end == self.0.len() {
				None
			} else {
				Some(&self.0[seconds_end..])
			},
		}
	}
}

impl Lexical for Time {
	type Error = InvalidTime<String>;

	fn parse(value: &str) -> Result<&Self, Self::Error> {
		Self::new(value).map_err(|_| InvalidTime(value.to_owned()))
	}
}

impl LexicalFormOf<crate::Time> for Time {
	type ValueError = InvalidTimeValue;

	fn try_as_value(&self) -> Result<crate::Time, Self::ValueError> {
		self.parts().to_time()
	}
}

#[derive(Debug, PartialEq, Eq)]
pub struct Parts<'a> {
	pub hours: &'a str,
	pub minutes: &'a str,
	pub seconds: &'a str,
	pub timezone: Option<&'a str>,
}

impl<'a> Parts<'a> {
	pub fn new(
		hours: &'a str,
		minutes: &'a str,
		seconds: &'a str,
		timezone: Option<&'a str>,
	) -> Self {
		Self {
			hours,
			minutes,
			seconds,
			timezone,
		}
	}

	fn to_time(&self) -> Result<crate::Time, crate::InvalidTimeValue> {
		let (seconds, nanoseconds) = parse_seconds_decimal(self.seconds);

		let time = chrono::NaiveTime::from_hms_nano_opt(
			self.hours.parse().unwrap(),
			self.minutes.parse().unwrap(),
			seconds,
			nanoseconds,
		)
		.ok_or(crate::InvalidTimeValue)?;

		Ok(crate::Time::new(time, self.timezone.map(parse_timezone)))
	}
}

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

	#[test]
	fn parsing() {
		let vectors = [
			(
				"13:07:12+01:00",
				Parts::new("13", "07", "12", Some("+01:00")),
			),
			(
				"12:00:00-05:00",
				Parts::new("12", "00", "00", Some("-05:00")),
			),
			(
				"12:00:00.00001-05:00",
				Parts::new("12", "00", "00.00001", Some("-05:00")),
			),
		];

		for (input, parts) in vectors {
			let lexical_repr = Time::new(input).unwrap();
			assert_eq!(lexical_repr.parts(), parts);

			let value = lexical_repr.try_as_value().unwrap();
			assert_eq!(value.to_string().as_str(), input)
		}
	}
}