Skip to main content

aoc_toolkit/application/
calendar.rs

1use chrono::{Datelike, FixedOffset, Utc};
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4pub enum DayAvailability {
5    OutsideEdition,
6    Locked,
7    Unlocked,
8}
9
10#[derive(Debug, Clone, Copy)]
11pub(crate) struct CalendarDate {
12    pub year: usize,
13    pub month: u32,
14    pub day: usize,
15}
16
17impl CalendarDate {
18    pub(crate) fn today() -> Self {
19        let offset = FixedOffset::west_opt(5 * 3600).expect("UTC-5 is a valid offset");
20
21        let now = Utc::now().with_timezone(&offset);
22
23        Self {
24            year: usize::try_from(now.year()).expect("Expected a positive calendar year"),
25            month: now.month(),
26            day: now.day() as usize,
27        }
28    }
29
30    pub(crate) fn unlocked_days(&self, year: usize) -> usize {
31        if year > self.year || year < 2015 {
32            return 0;
33        }
34
35        let total = CalendarDate::edition_days(year);
36
37        if year < self.year {
38            return total;
39        }
40
41        if self.month != 12 {
42            return 0;
43        }
44
45        self.day.min(total)
46    }
47
48    pub(crate) fn day_availability(&self, year: usize, day: usize) -> DayAvailability {
49        if !(1..=CalendarDate::edition_days(year)).contains(&day) {
50            return DayAvailability::OutsideEdition;
51        }
52
53        if day > self.unlocked_days(year) {
54            return DayAvailability::Locked;
55        }
56
57        DayAvailability::Unlocked
58    }
59
60    pub(crate) fn edition_days(year: usize) -> usize {
61        match year {
62            2015..=2024 => 25,
63            2025.. => 12,
64            _ => 0,
65        }
66    }
67}
68
69#[cfg(test)]
70mod tests {
71    use super::{CalendarDate, DayAvailability};
72
73    #[test]
74    fn classifies_days_by_edition_length_and_unlock_date() {
75        use DayAvailability::{Locked, OutsideEdition, Unlocked};
76
77        let december = CalendarDate {
78            year: 2026,
79            month: 12,
80            day: 3,
81        };
82        let november = CalendarDate {
83            year: 2026,
84            month: 11,
85            day: 30,
86        };
87
88        for (date, year, day, expected) in [
89            (december, 2014, 1, OutsideEdition),
90            (december, 2024, 25, Unlocked),
91            (december, 2024, 26, OutsideEdition),
92            (december, 2025, 12, Unlocked),
93            (december, 2025, 13, OutsideEdition),
94            (december, 2026, 0, OutsideEdition),
95            (december, 2026, 3, Unlocked),
96            (december, 2026, 4, Locked),
97            (december, 2026, 13, OutsideEdition),
98            (december, 2027, 1, Locked),
99            (november, 2026, 1, Locked),
100        ] {
101            assert_eq!(date.day_availability(year, day), expected, "{year}/{day}");
102        }
103    }
104}