Skip to main content

nfl_model/models/
season_week.rs

1use std::{
2    cmp::Ordering,
3    hash::{Hash, Hasher},
4};
5
6use sqlx::{Database, Decode, Encode, Type, encode::IsNull, error::BoxDynError};
7
8use crate::{Season, SeasonType, Week};
9
10/// An NFL week identified by season year and absolute week number.
11///
12/// Weeks 1–18 are regular season and weeks 19–22 are postseason, so a week's classification is
13/// derived from its number rather than stored alongside it.
14///
15/// Equality, ordering, hashing, and SQLx integer storage use the value returned by
16/// [`encode`](Self::encode).
17///
18/// # Examples
19///
20/// ```
21/// use nfl_model::{Season, SeasonWeek, Week};
22///
23/// let week = SeasonWeek {
24///     season: Season(2026),
25///     week: Week(1),
26/// };
27/// assert_eq!(week.encode(), 2_026_001);
28/// assert_eq!(SeasonWeek::decode(2_026_001), Some(week));
29/// assert!(!week.postseason());
30/// ```
31#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
32pub struct SeasonWeek {
33    /// Year identifying the NFL season, including for postseason games in the next calendar year.
34    pub season: Season,
35    /// Absolute week number: 1–18 for the regular season, 19–22 for the postseason.
36    pub week: Week,
37}
38
39impl SeasonWeek {
40    /// Create a validated week from a season and an absolute week number.
41    ///
42    /// Accepts weeks 1–22, where 1–18 are regular season and 19–22 are postseason (wild card,
43    /// divisional, championship, and Super Bowl). Returns `None` for 0 and for anything above 22.
44    pub fn new(season: Season, week: Week) -> Option<Self> {
45        match week.0 {
46            1..=22 => Some(Self { season, week }),
47            _ => None,
48        }
49    }
50
51    /// Create a validated week in the default [`Season`].
52    ///
53    /// Accepts weeks 1–22 like [`new`](Self::new); use `new` to pick the season explicitly.
54    pub fn from_week(week: Week) -> Option<Self> {
55        Self::new(Season::default(), week)
56    }
57
58    /// Whether this week is a postseason week (week 19 or later).
59    pub fn postseason(&self) -> bool {
60        self.week.0 > 18
61    }
62
63    /// Enumerate the weeks of a season in schedule-independent order: weeks 1–22.
64    ///
65    /// Postseason weeks keep the supplied season year even when played in the next calendar
66    /// year. Order reflects this canonical enumeration, not the NFL schedule.
67    pub fn for_season(season: Season) -> impl Iterator<Item = Self> {
68        (1..=22).map(move |week| Self {
69            season,
70            week: Week(week),
71        })
72    }
73
74    /// Encode as `season * 1_000 + postseason * 100 + week`.
75    ///
76    /// The classification digit is `0` for regular-season weeks and `1` for postseason weeks.
77    pub fn encode(&self) -> u32 {
78        u32::from(self.season.0) * 1_000
79            + u32::from(self.postseason()) * 100
80            + u32::from(self.week.0)
81    }
82
83    /// Decode a value in the integer format produced by [`encode`](Self::encode).
84    ///
85    /// Returns `None` if the classification digit is neither `0` nor `1` or the week is not a
86    /// valid week for that classification. Stored postseason aliases 1–3 normalize to canonical
87    /// weeks 19–21.
88    pub fn decode(value: u32) -> Option<Self> {
89        let year = (value / 1_000) as u16;
90        let choice = ((value / 100) % 10) as u8;
91        let week = (value % 100) as u8;
92
93        let season_type = SeasonType::try_from(choice).ok()?;
94
95        let week = match (season_type, week) {
96            (SeasonType::Reg, 1..=18) => Week(week),
97            (SeasonType::Post, 1..=3) => Week(week + 18),
98            (SeasonType::Post, 19..=22) => Week(week),
99            _ => return None,
100        };
101
102        Self::new(Season(year), week)
103    }
104}
105
106impl PartialEq for SeasonWeek {
107    fn eq(&self, other: &Self) -> bool {
108        self.encode() == other.encode()
109    }
110}
111
112impl Eq for SeasonWeek {}
113
114impl Hash for SeasonWeek {
115    fn hash<H: Hasher>(&self, state: &mut H) {
116        self.encode().hash(state);
117    }
118}
119
120impl PartialOrd for SeasonWeek {
121    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
122        Some(self.cmp(other))
123    }
124}
125
126impl Ord for SeasonWeek {
127    fn cmp(&self, other: &Self) -> Ordering {
128        self.encode().cmp(&other.encode())
129    }
130}
131
132// Make SeasonWeek encode/decode to an i64 for SQLx (sqlite) storage in an integer
133
134impl<DB> Type<DB> for SeasonWeek
135where
136    DB: Database,
137    i64: Type<DB>,
138{
139    fn type_info() -> DB::TypeInfo {
140        <i64 as Type<DB>>::type_info()
141    }
142
143    fn compatible(ty: &DB::TypeInfo) -> bool {
144        <i64 as Type<DB>>::compatible(ty)
145    }
146}
147
148impl<'q, DB> Encode<'q, DB> for SeasonWeek
149where
150    DB: Database,
151    i64: Encode<'q, DB>,
152{
153    fn encode_by_ref(&self, buf: &mut DB::ArgumentBuffer) -> Result<IsNull, BoxDynError> {
154        let encoded = i64::from(self.encode());
155        <i64 as Encode<DB>>::encode_by_ref(&encoded, buf)
156    }
157}
158
159impl<'r, DB> Decode<'r, DB> for SeasonWeek
160where
161    DB: Database,
162    i64: Decode<'r, DB>,
163{
164    fn decode(value: DB::ValueRef<'r>) -> Result<Self, BoxDynError> {
165        let encoded = <i64 as Decode<DB>>::decode(value)?;
166        let encoded = u32::try_from(encoded)?;
167
168        SeasonWeek::decode(encoded).ok_or_else(|| {
169            Box::new(std::io::Error::new(
170                std::io::ErrorKind::InvalidData,
171                format!("invalid encoded SeasonWeek: {encoded}"),
172            )) as BoxDynError
173        })
174    }
175}
176
177#[cfg(test)]
178mod tests {
179    use super::SeasonWeek;
180    use crate::{Season, Week};
181    use std::collections::HashSet;
182    use std::collections::hash_map::DefaultHasher;
183    use std::hash::{Hash, Hasher};
184
185    fn week(season: u16, week: u8) -> SeasonWeek {
186        SeasonWeek::new(Season(season), Week(week)).expect("valid season week")
187    }
188
189    #[test]
190    fn new_accepts_absolute_weeks_one_through_twenty_two() {
191        for (input, expected, postseason) in [
192            (0u8, None, false),
193            (1, Some(1), false),
194            (18, Some(18), false),
195            (19, Some(19), true),
196            (22, Some(22), true),
197            (23, None, false),
198            (255, None, false),
199        ] {
200            let created = SeasonWeek::new(Season(2026), Week(input));
201
202            match expected {
203                Some(expected) => {
204                    let created = created.expect("valid week");
205                    assert_eq!(created.season.0, 2026);
206                    assert_eq!(created.week.0, expected);
207                    assert_eq!(created.postseason(), postseason);
208                }
209                None => assert_eq!(created, None, "week {input} must be rejected"),
210            }
211        }
212    }
213
214    #[test]
215    fn for_season_enumerates_weeks_one_through_twenty_two() {
216        let weeks: Vec<_> = SeasonWeek::for_season(Season(2026)).collect();
217
218        assert_eq!(weeks.len(), 22);
219        for (index, week) in weeks.iter().enumerate() {
220            assert_eq!(week.week.0 as usize, index + 1);
221            assert_eq!(week.season.0, 2026);
222            assert_eq!(week.postseason(), index + 1 > 18);
223        }
224    }
225
226    #[test]
227    fn encode_and_decode_round_trip() {
228        for (encoded, canonical_week) in [(2_026_018u32, 18u8), (2_026_119, 19), (2_026_122, 22)] {
229            let decoded = SeasonWeek::decode(encoded).expect("decodable");
230            assert_eq!(decoded.season.0, 2026);
231            assert_eq!(decoded.week.0, canonical_week);
232            assert_eq!(decoded.encode(), encoded);
233        }
234
235        assert_eq!(week(2026, 18).encode(), 2_026_018);
236        assert_eq!(week(2026, 19).encode(), 2_026_119);
237        assert_eq!(week(2026, 22).encode(), 2_026_122);
238    }
239
240    #[test]
241    fn decode_normalizes_stored_postseason_aliases() {
242        for (stored, canonical) in [(2_026_101u32, 19u8), (2_026_102, 20), (2_026_103, 21)] {
243            let decoded = SeasonWeek::decode(stored).expect("decodable alias");
244            assert_eq!(decoded.week.0, canonical);
245            assert_eq!(decoded, week(2026, canonical));
246            assert_eq!(decoded.encode(), 2_026_100 + u32::from(canonical));
247        }
248    }
249
250    #[test]
251    fn decode_rejects_invalid_classification_and_week() {
252        for encoded in [
253            2_026_104u32, // postseason alias above 3
254            2_026_019,    // regular season has 18 weeks
255            2_026_118,    // postseason week 18 is canonicalized as regular season
256            2_026_123,    // week 23
257            2_026_201,    // invalid classification digit
258        ] {
259            assert_eq!(
260                SeasonWeek::decode(encoded),
261                None,
262                "{encoded} must be rejected"
263            );
264        }
265    }
266
267    #[test]
268    fn alias_decoded_values_match_constructed_canonical_values() {
269        let alias = SeasonWeek::decode(2_026_101).unwrap();
270        let canonical = week(2026, 19);
271
272        assert_eq!(alias, canonical);
273        assert_eq!(hash(&alias), hash(&canonical));
274
275        let set: HashSet<SeasonWeek> = [alias, canonical].into_iter().collect();
276        assert_eq!(set.len(), 1);
277    }
278
279    fn hash(week: &SeasonWeek) -> u64 {
280        let mut hasher = DefaultHasher::new();
281        week.hash(&mut hasher);
282        hasher.finish()
283    }
284
285    #[test]
286    fn ordering_follows_chronological_weeks_and_seasons() {
287        assert!(week(2026, 18) < week(2026, 19));
288        assert!(week(2026, 19) < week(2026, 22));
289        assert!(week(2026, 22) < week(2027, 1));
290        assert!(SeasonWeek::decode(2_026_101).unwrap() < week(2026, 20));
291    }
292
293    #[tokio::test]
294    async fn sqlite_bound_query_round_trips_encoded_weeks() {
295        let pool = sqlx::SqlitePool::connect("sqlite::memory:")
296            .await
297            .expect("open in-memory sqlite");
298
299        let (stored,) = sqlx::query_as::<_, (SeasonWeek,)>("SELECT ?")
300            .bind(week(2026, 22))
301            .fetch_one(&pool)
302            .await
303            .expect("decode valid week");
304        assert_eq!(stored, week(2026, 22));
305        assert_eq!(stored.encode(), 2_026_122);
306
307        let invalid = sqlx::query_as::<_, (SeasonWeek,)>("SELECT ?")
308            .bind(2_026_019i64)
309            .fetch_one(&pool)
310            .await;
311        assert!(invalid.is_err(), "invalid encoded week must fail to decode");
312
313        pool.close().await;
314    }
315}