use std::error::Error; use std::fmt::Display; use std::fs; #[cfg(feature = "today")] use chrono::{Datelike, FixedOffset, Utc}; #[cfg(feature = "today")] const SERVER_UTC_OFFSET: i32 = -5; /// The first year of advent of code. pub const FIRST_YEAR: u16 = 2015; /// The last supported year. Purely a sanity bound for user input. pub const MAX_YEAR: u16 = 2099; /// The last day of advent for a given year. /// /// Since 2025, advent of code has 12 days. Before that, it had 25. pub const fn last_day(year: u16) -> u8 { if year < 2025 { 25 } else { 12 } } /// A valid puzzle day of a given year (i.e. a year from [`FIRST_YEAR`] and a day number in range 1 to [`last_day`]). /// /// # Display /// This value displays as a two digit day number. The year is available through [`Day::year`]. /// /// ``` /// # use advent_of_code::Day; /// let day = Day::new(2024, 8).unwrap(); /// assert_eq!(day.to_string(), "08"); /// assert_eq!(day.bin_name(), "2024-08"); /// ``` #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Day { year: u16, day: u8, } impl Day { /// Creates a [`Day`] from the provided values if they are in the valid range, /// returns [`None`] otherwise. pub const fn new(year: u16, day: u8) -> Option { if year < FIRST_YEAR || year > MAX_YEAR || day == 0 || day > last_day(year) { return None; } Some(Self { year, day }) } /// Like [`Day::new`], but returns a descriptive error. pub fn try_new(year: u16, day: u8) -> Result { Self::new(year, day).ok_or(InvalidDayError { year, day }) } /// The year of this puzzle. pub fn year(self) -> u16 { self.year } /// Converts the [`Day`] into the day number as an [`u8`]. pub fn into_inner(self) -> u8 { self.day } pub fn has_part_two(self) -> bool { self.day != last_day(self.year) } /// Name of the solution binary, e.g. `2025-01`. pub fn bin_name(self) -> String { format!("{}-{}", self.year, self) } /// Path of the solution binary source file. pub fn bin_path(self) -> String { format!("src/bin/{}/{}.rs", self.year, self) } } #[cfg(feature = "today")] impl Day { /// Returns the current day if it's between the 1st and the 12th of december, `None` otherwise. /// Accepts days up to the 25th if the year is before 2025. pub fn today() -> Option { let offset = FixedOffset::east_opt(SERVER_UTC_OFFSET * 3600)?; let today = Utc::now().with_timezone(&offset); if today.month() == 12 { Self::new(u16::try_from(today.year()).ok()?, u8::try_from(today.day()).ok()?) } else { None } } } impl Display for Day { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{:02}", self.day) } } impl PartialEq for Day { fn eq(&self, other: &u8) -> bool { self.day.eq(other) } } /* -------------------------------------------------------------------------- */ /// An error which is returned when a year / day combination is not a valid puzzle. #[derive(Debug)] pub struct InvalidDayError { year: u16, day: u8, } impl Error for InvalidDayError {} impl Display for InvalidDayError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if self.year < FIRST_YEAR || self.year > MAX_YEAR { write!( f, "expecting a year between {FIRST_YEAR} and {MAX_YEAR}, got {}", self.year ) } else { write!( f, "expecting a day number between 1 and {} for {}, got {}", last_day(self.year), self.year, self.day ) } } } /* -------------------------------------------------------------------------- */ /// An iterator that yields every day of advent of a year from the 1st to the 12th (or 25th before 2025). pub fn all_days(year: u16) -> AllDays { AllDays::new(year) } /// An iterator that yields every day of advent of a year from the 1st to the 12th (or 25th before 2025). pub struct AllDays { year: u16, current: u8, } impl AllDays { pub fn new(year: u16) -> Self { Self { year, current: 1 } } } impl Iterator for AllDays { type Item = Day; fn next(&mut self) -> Option { // NOTE: `Day::new` rejects invalid years and days beyond the last day of the year. let day = Day::new(self.year, self.current)?; self.current += 1; Some(day) } } /* -------------------------------------------------------------------------- */ /// Returns all years that have at least one scaffolded solution in `src/bin//.rs`, sorted ascending. pub fn scaffolded_years() -> Vec { let mut years: Vec = fs::read_dir("src/bin") .into_iter() .flatten() .flatten() .filter_map(|entry| { let year: u16 = entry.file_name().into_string().ok()?.parse().ok()?; let has_day = fs::read_dir(entry.path()).ok()?.flatten().any(|file| { file.file_name() .into_string() .ok() .and_then(|name| name.strip_suffix(".rs")?.parse().ok()) .is_some_and(|day| Day::new(year, day).is_some()) }); has_day.then_some(year) }) .collect(); years.sort_unstable(); years.dedup(); years } /* -------------------------------------------------------------------------- */ /// Creates a [`Day`] value in a const context. #[macro_export] macro_rules! day { ($year:expr, $day:expr) => { const { $crate::template::Day::new($year, $day).expect( "invalid year or day number, expecting a year from 2015 and a day between 1 and 12 (or 25 before 2025)", ) } }; } /* -------------------------------------------------------------------------- */ #[cfg(all(test, feature = "test_lib"))] mod tests { use super::{Day, all_days, last_day}; #[test] fn all_days_iterator_new_format() { let days: Vec = all_days(2025).collect(); assert_eq!(days.len(), 12); assert_eq!(days[0], Day::new(2025, 1).unwrap()); assert_eq!(days[11], Day::new(2025, 12).unwrap()); } #[test] fn all_days_iterator_old_format() { let days: Vec = all_days(2024).collect(); assert_eq!(days.len(), 25); assert_eq!(days[24], Day::new(2024, 25).unwrap()); } #[test] fn validates_days_per_year() { assert!(Day::new(2024, 25).is_some()); assert!(Day::new(2025, 25).is_none()); assert!(Day::new(2025, 13).is_none()); assert!(Day::new(2025, 0).is_none()); assert!(Day::new(2014, 1).is_none()); } #[test] fn has_part_two() { assert!(Day::new(2025, 1).unwrap().has_part_two()); assert!(Day::new(2025, 11).unwrap().has_part_two()); assert!(!Day::new(2025, 12).unwrap().has_part_two()); assert!(Day::new(2024, 24).unwrap().has_part_two()); assert!(!Day::new(2024, 25).unwrap().has_part_two()); assert_eq!(last_day(2015), 25); } #[test] fn bin_names() { let day = Day::new(2019, 3).unwrap(); assert_eq!(day.bin_name(), "2019-03"); assert_eq!(day.bin_path(), "src/bin/2019/03.rs"); } #[test] fn orders_by_year_then_day() { assert!(Day::new(2024, 25).unwrap() < Day::new(2025, 1).unwrap()); assert!(Day::new(2025, 2).unwrap() < Day::new(2025, 3).unwrap()); } } /* -------------------------------------------------------------------------- */