-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathday.rs
More file actions
194 lines (164 loc) · 5.48 KB
/
day.rs
File metadata and controls
194 lines (164 loc) · 5.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
use std::error::Error;
use std::fmt::Display;
use std::str::FromStr;
#[cfg(feature = "today")]
use chrono::{Datelike, FixedOffset, Utc};
#[cfg(feature = "today")]
const SERVER_UTC_OFFSET: i32 = -5;
/// A valid day number of advent (i.e. an integer in range 1 to 12).
/// Before the year 2025, allow integers up to 25.
///
/// # Display
/// This value displays as a two digit number.
///
/// ```
/// # use advent_of_code::Day;
/// let day = Day::new(8).unwrap();
/// assert_eq!(day.to_string(), "08")
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Day(u8);
macro_rules! day_count {
() => {
match const_str::parse!(env!("AOC_YEAR"), u16) < 2025 {
true => 25u8,
false => 12u8,
}
}
}
impl Day {
/// Creates a [`Day`] from the provided value if it's in the valid range,
/// returns [`None`] otherwise.
pub const fn new(day: u8) -> Option<Self> {
if day == 0 || day > day_count!() {
return None;
}
Some(Self(day))
}
/// Converts the [`Day`] into an [`u8`].
pub fn into_inner(self) -> u8 {
self.0
}
}
#[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<Self> {
let offset = FixedOffset::east_opt(SERVER_UTC_OFFSET * 3600)?;
let today = Utc::now().with_timezone(&offset);
if today.month() == 12 && today.day() <= day_count!() as u32 {
Self::new(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.0)
}
}
impl PartialEq<u8> for Day {
fn eq(&self, other: &u8) -> bool {
self.0.eq(other)
}
}
impl PartialOrd<u8> for Day {
fn partial_cmp(&self, other: &u8) -> Option<std::cmp::Ordering> {
self.0.partial_cmp(other)
}
}
/* -------------------------------------------------------------------------- */
impl FromStr for Day {
type Err = DayFromStrError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let day = s.parse().map_err(|_| DayFromStrError)?;
Self::new(day).ok_or(DayFromStrError)
}
}
/// An error which can be returned when parsing a [`Day`].
#[derive(Debug)]
pub struct DayFromStrError;
impl Error for DayFromStrError {}
impl Display for DayFromStrError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&format!("expecting a day number between 1 and {}", day_count!()))
}
}
/* -------------------------------------------------------------------------- */
/// An iterator that yields every day of advent from the 1st to the 12th (or 25th before 2025).
pub fn all_days() -> AllDays {
AllDays::new()
}
/// An iterator that yields every day of advent from the 1st to the 12th (or 25th before 2025).
pub struct AllDays {
current: u8,
}
impl AllDays {
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
Self { current: 1 }
}
}
impl Iterator for AllDays {
type Item = Day;
fn next(&mut self) -> Option<Self::Item> {
if self.current > day_count!() {
return None;
}
// NOTE: the iterator starts at 1, and we have verified that the value is not above 12 (or 25).
let day = Day(self.current);
self.current += 1;
Some(day)
}
}
/* -------------------------------------------------------------------------- */
/// Creates a [`Day`] value in a const context.
#[macro_export]
macro_rules! day {
($day:expr) => {
const {
$crate::template::Day::new($day)
.expect("invalid day number, expecting a value between 1 and 12 (or 25 before 2025)")
}
};
}
/* -------------------------------------------------------------------------- */
#[cfg(feature = "test_lib")]
mod tests {
use super::{Day, all_days};
#[test]
fn all_days_iterator() {
let mut iter = all_days();
assert_eq!(iter.next(), Some(Day(1)));
assert_eq!(iter.next(), Some(Day(2)));
assert_eq!(iter.next(), Some(Day(3)));
assert_eq!(iter.next(), Some(Day(4)));
assert_eq!(iter.next(), Some(Day(5)));
assert_eq!(iter.next(), Some(Day(6)));
assert_eq!(iter.next(), Some(Day(7)));
assert_eq!(iter.next(), Some(Day(8)));
assert_eq!(iter.next(), Some(Day(9)));
assert_eq!(iter.next(), Some(Day(10)));
assert_eq!(iter.next(), Some(Day(11)));
assert_eq!(iter.next(), Some(Day(12)));
if day_count!() > 12 {
assert_eq!(iter.next(), Some(Day(13)));
assert_eq!(iter.next(), Some(Day(14)));
assert_eq!(iter.next(), Some(Day(15)));
assert_eq!(iter.next(), Some(Day(16)));
assert_eq!(iter.next(), Some(Day(17)));
assert_eq!(iter.next(), Some(Day(18)));
assert_eq!(iter.next(), Some(Day(19)));
assert_eq!(iter.next(), Some(Day(20)));
assert_eq!(iter.next(), Some(Day(21)));
assert_eq!(iter.next(), Some(Day(22)));
assert_eq!(iter.next(), Some(Day(23)));
assert_eq!(iter.next(), Some(Day(24)));
assert_eq!(iter.next(), Some(Day(25)));
}
assert_eq!(iter.next(), None);
}
}
/* -------------------------------------------------------------------------- */