xsd_types/lexical/
date.rs

1use static_regular_grammar::RegularGrammar;
2
3use crate::{lexical::parse_timezone, utils::byte_index_of};
4
5use super::{Lexical, LexicalFormOf};
6
7/// Date.
8///
9/// ```abnf
10/// date = year "-" month "-" day [timezone]
11///
12/// year = [ "-" ] year-number
13///
14/// year-number = *3DIGIT NZDIGIT
15///             / *2DIGIT NZDIGIT DIGIT
16///             / *1DIGIT NZDIGIT 2DIGIT
17///             / NZDIGIT 3*DIGIT
18///
19/// month = "0" NZDIGIT
20///       / "1" ( "0" / "1" / "2" )
21///
22/// day = "0" NZDIGIT
23///     / ("1" / "2") DIGIT
24///     / "3" ("0" / "1")
25///
26/// minute = ("0" / "1" / "2" / "3" / "4" / "5") DIGIT
27///
28/// timezone = ("+" / "-") ((("0" DIGIT / "1" ("0" / "1" / "2" / "3")) ":" minute) / "14:00")
29///          / %s"Z"
30///
31/// NZDIGIT = "1" / "2" / "3" / "4" / "5" / "6" / "7" / "8" / "9"
32/// ```
33#[derive(RegularGrammar, PartialEq, Eq, PartialOrd, Ord, Hash)]
34#[grammar(sized(DateBuf, derive(PartialEq, Eq, PartialOrd, Ord, Hash)))]
35pub struct Date(str);
36
37impl Date {
38	pub fn parts(&self) -> Parts {
39		let year_end = byte_index_of(self.0.as_bytes(), 4, b'-').unwrap();
40		let month_end = year_end + 3;
41		let day_end = month_end + 3;
42
43		Parts {
44			year: &self.0[..year_end],
45			month: &self.0[(year_end + 1)..month_end],
46			day: &self.0[(month_end + 1)..day_end],
47			timezone: if day_end == self.0.len() {
48				None
49			} else {
50				Some(&self.0[day_end..])
51			},
52		}
53	}
54}
55
56impl Lexical for Date {
57	type Error = InvalidDate<String>;
58
59	fn parse(value: &str) -> Result<&Self, Self::Error> {
60		Self::new(value).map_err(|_| InvalidDate(value.to_owned()))
61	}
62}
63
64impl LexicalFormOf<crate::Date> for Date {
65	type ValueError = crate::InvalidDateValue;
66
67	fn try_as_value(&self) -> Result<crate::Date, Self::ValueError> {
68		self.parts().to_date()
69	}
70}
71
72#[derive(Debug, PartialEq, Eq)]
73pub struct Parts<'a> {
74	year: &'a str,
75	month: &'a str,
76	day: &'a str,
77	timezone: Option<&'a str>,
78}
79
80impl<'a> Parts<'a> {
81	pub fn new(year: &'a str, month: &'a str, day: &'a str, timezone: Option<&'a str>) -> Self {
82		Self {
83			year,
84			month,
85			day,
86			timezone,
87		}
88	}
89
90	fn to_date(&self) -> Result<crate::Date, crate::InvalidDateValue> {
91		let date = chrono::NaiveDate::from_ymd_opt(
92			self.year.parse().unwrap(),
93			self.month.parse().unwrap(),
94			self.day.parse().unwrap(),
95		)
96		.ok_or(crate::InvalidDateValue)?;
97
98		Ok(crate::Date::new(date, self.timezone.map(parse_timezone)))
99	}
100}
101
102#[cfg(test)]
103mod tests {
104	use super::*;
105
106	#[test]
107	fn parsing() {
108		let vectors = [
109			(
110				"2002-05-31+01:00",
111				Parts::new("2002", "05", "31", Some("+01:00")),
112			),
113			(
114				"2002-10-10-05:00",
115				Parts::new("2002", "10", "10", Some("-05:00")),
116			),
117			(
118				"202002-10-10-05:00",
119				Parts::new("202002", "10", "10", Some("-05:00")),
120			),
121		];
122
123		for (input, parts) in vectors {
124			let lexical_repr = Date::new(input).unwrap();
125			assert_eq!(lexical_repr.parts(), parts);
126
127			let value = lexical_repr.try_as_value().unwrap();
128			assert_eq!(value.to_string().as_str(), input)
129		}
130	}
131}