1use std::{cmp::Ordering, str::FromStr};
2
3use nom::{
4 bytes::complete::take,
5 character::complete::{char, digit1},
6 combinator::{all_consuming, cut, map_res, peek, verify},
7 Finish, Parser,
8};
9
10use super::{IResult, Span};
11
12#[derive(Debug, Copy, Clone, Eq, PartialEq)]
31pub struct Date {
32 pub year: u16,
34 pub month: u8,
36 pub day: u8,
38}
39
40impl Date {
41 #[must_use]
43 pub fn new(year: u16, month: u8, day: u8) -> Self {
44 Self { year, month, day }
45 }
46}
47
48impl PartialOrd for Date {
49 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
50 Some(self.cmp(other))
51 }
52}
53
54impl Ord for Date {
55 fn cmp(&self, other: &Self) -> Ordering {
56 self.year
57 .cmp(&other.year)
58 .then_with(|| self.month.cmp(&other.month))
59 .then_with(|| self.day.cmp(&other.day))
60 }
61}
62
63impl FromStr for Date {
64 type Err = crate::Error;
65
66 fn from_str(s: &str) -> Result<Self, Self::Err> {
67 let span = Span::new(s);
68 match all_consuming(parse).parse(span).finish() {
69 Ok((_, date)) => Ok(date),
70 Err(_) => Err(crate::Error::new(s, span)),
71 }
72 }
73}
74
75pub(super) fn parse(input: Span<'_>) -> IResult<'_, Date> {
76 let (input, _) = peek((digit1, char('-'), digit1, char('-'), digit1)).parse(input)?;
77 cut(do_parse).parse(input)
78}
79
80fn do_parse(input: Span<'_>) -> IResult<'_, Date> {
81 let (input, year) = year(input)?;
82 let (input, _) = char('-')(input)?;
83 let (input, month) = month(input)?;
84 let (input, _) = char('-')(input)?;
85 let (input, day) = day(input)?;
86 Ok((input, Date { year, month, day }))
87}
88
89fn year(input: Span<'_>) -> IResult<'_, u16> {
90 map_res(take(4usize), |s: Span<'_>| s.fragment().parse()).parse(input)
91}
92
93fn month(input: Span<'_>) -> IResult<'_, u8> {
94 verify(
95 map_res(take(2usize), |s: Span<'_>| s.fragment().parse()),
96 |&n| n > 0 && n < 13,
97 )
98 .parse(input)
99}
100
101fn day(input: Span<'_>) -> IResult<'_, u8> {
102 verify(
103 map_res(take(2usize), |s: Span<'_>| s.fragment().parse()),
104 |&n| n > 0 && n < 32,
105 )
106 .parse(input)
107}
108
109#[cfg(test)]
110mod tests {
111 use super::*;
112
113 #[test]
114 fn date_from_str_should_parse_valid_date() {
115 let date: Date = "2023-03-12".parse().unwrap();
116 assert_eq!(date.year, 2023);
117 assert_eq!(date.month, 3);
118 assert_eq!(date.day, 12);
119 }
120
121 #[test]
122 fn date_from_str_should_not_parse_invalid_date() {
123 let result: Result<Date, _> = "2023-03-12oops".parse();
124 assert!(result.is_err(), "{result:?}");
125 }
126}