weekday/
str.rs

1// TODO, https://github.com/iamkun/dayjs/tree/dev/src/locale
2
3use core::{convert::TryFrom, fmt, str::FromStr};
4
5use crate::{Weekday, WEEKDAYS};
6
7static EN_NAMES: &[&str] = &[
8    "Monday",
9    "Tuesday",
10    "Wednesday",
11    "Thursday",
12    "Friday",
13    "Saturday",
14    "Sunday",
15];
16static EN_ABBREVIATIONS: &[&str] = &["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
17static EN_MINIMAL_ABBREVIATIONS: &[&str] = &["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"];
18
19impl FromStr for Weekday {
20    type Err = &'static str;
21
22    fn from_str(s: &str) -> Result<Self, Self::Err> {
23        Self::from_en_str(s)
24    }
25}
26impl TryFrom<&str> for Weekday {
27    type Error = &'static str;
28
29    fn try_from(s: &str) -> Result<Self, Self::Error> {
30        s.parse()
31    }
32}
33impl fmt::Display for Weekday {
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        write!(f, "{}", self.to_en_str())
36    }
37}
38
39impl Weekday {
40    pub fn en_name(&self) -> &str {
41        EN_NAMES[(self.to_owned() as u8 - 1) as usize]
42    }
43    pub fn en_abbreviation(&self) -> &str {
44        EN_ABBREVIATIONS[(self.to_owned() as u8 - 1) as usize]
45    }
46    pub fn en_minimal_abbreviation(&self) -> &str {
47        EN_MINIMAL_ABBREVIATIONS[(self.to_owned() as u8 - 1) as usize]
48    }
49
50    pub fn from_en_str(s: &str) -> Result<Self, &'static str> {
51        if let Some(i) = EN_ABBREVIATIONS
52            .iter()
53            .position(|x| x == &s || format!("{x}.") == s)
54        {
55            Ok(WEEKDAYS[i].to_owned())
56        } else if let Some(i) = EN_NAMES.iter().position(|x| x == &s) {
57            Ok(WEEKDAYS[i].to_owned())
58        } else if let Some(i) = EN_MINIMAL_ABBREVIATIONS
59            .iter()
60            .position(|x| x == &s || format!("{x}.") == s)
61        {
62            Ok(WEEKDAYS[i].to_owned())
63        } else {
64            Err("unknown")
65        }
66    }
67    pub fn to_en_str(&self) -> &str {
68        self.en_abbreviation()
69    }
70}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75
76    #[test]
77    fn en() {
78        assert_eq!(Weekday::Mon.en_name(), "Monday");
79        assert_eq!(Weekday::Mon.en_abbreviation(), "Mon");
80        assert_eq!(Weekday::Mon.en_minimal_abbreviation(), "Mo");
81
82        assert_eq!(Weekday::try_from("Mon").unwrap(), Weekday::Mon);
83        assert_eq!("Monday".parse::<Weekday>().unwrap(), Weekday::Mon);
84        assert_eq!("Mon".parse::<Weekday>().unwrap(), Weekday::Mon);
85        assert_eq!("Mon.".parse::<Weekday>().unwrap(), Weekday::Mon);
86        assert_eq!("Mo".parse::<Weekday>().unwrap(), Weekday::Mon);
87        assert_eq!("Mo.".parse::<Weekday>().unwrap(), Weekday::Mon);
88        assert_eq!(Weekday::Mon.to_string(), "Mon");
89    }
90}