1use core::str::FromStr;
6
7use crate::{AsCalendar, Calendar, Date, Iso, RangeError};
8use icu_locale_core::preferences::extensions::unicode::keywords::CalendarAlgorithm;
9use ixdtf::parsers::records::IxdtfParseRecord;
10use ixdtf::parsers::IxdtfParser;
11use ixdtf::ParseError as Rfc9557Error;
12
13#[derive(Debug, displaydoc::Display)]
15#[non_exhaustive]
16pub enum ParseError {
17    #[displaydoc("Syntax error in the RFC 9557 string: {0}")]
19    Syntax(Rfc9557Error),
20    #[displaydoc("Value out of range: {0}")]
22    Range(RangeError),
23    MissingFields,
25    UnknownCalendar,
27    #[displaydoc("Expected calendar {0:?} but found calendar {1:?}")]
29    MismatchedCalendar(CalendarAlgorithm, CalendarAlgorithm),
30}
31
32impl From<RangeError> for ParseError {
33    fn from(value: RangeError) -> Self {
34        Self::Range(value)
35    }
36}
37
38impl From<Rfc9557Error> for ParseError {
39    fn from(value: Rfc9557Error) -> Self {
40        Self::Syntax(value)
41    }
42}
43
44impl FromStr for Date<Iso> {
45    type Err = ParseError;
46    fn from_str(rfc_9557_str: &str) -> Result<Self, Self::Err> {
47        Self::try_from_str(rfc_9557_str, Iso)
48    }
49}
50
51impl<A: AsCalendar> Date<A> {
52    pub fn try_from_str(rfc_9557_str: &str, calendar: A) -> Result<Self, ParseError> {
78        Self::try_from_utf8(rfc_9557_str.as_bytes(), calendar)
79    }
80
81    pub fn try_from_utf8(rfc_9557_str: &[u8], calendar: A) -> Result<Self, ParseError> {
90        let ixdtf_record = IxdtfParser::from_utf8(rfc_9557_str).parse()?;
91        Self::try_from_ixdtf_record(&ixdtf_record, calendar)
92    }
93
94    #[doc(hidden)]
95    pub fn try_from_ixdtf_record(
96        ixdtf_record: &IxdtfParseRecord,
97        calendar: A,
98    ) -> Result<Self, ParseError> {
99        let date_record = ixdtf_record.date.ok_or(ParseError::MissingFields)?;
100        let iso = Date::try_new_iso(date_record.year, date_record.month, date_record.day)?;
101
102        if let Some(ixdtf_calendar) = ixdtf_record.calendar {
103            if let Some(expected_calendar) = calendar.as_calendar().calendar_algorithm() {
104                if let Some(parsed_calendar) =
105                    icu_locale_core::extensions::unicode::Value::try_from_utf8(ixdtf_calendar)
106                        .ok()
107                        .and_then(|v| CalendarAlgorithm::try_from(&v).ok())
108                {
109                    if parsed_calendar != expected_calendar {
110                        return Err(ParseError::MismatchedCalendar(
111                            expected_calendar,
112                            parsed_calendar,
113                        ));
114                    }
115                }
116            }
117        }
118        Ok(iso.to_calendar(calendar))
119    }
120}