Skip to main content

refix_message/value/
date.rs

1use super::number;
2
3/// A FIX date, as in a UTCDateOnly or LocalMktDate field.
4#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
5pub struct Date {
6    year: u16,
7    month: u8,
8    day: u8,
9}
10
11impl Date {
12    /// The date `year`-`month`-`day`, if it exists and the year fits FIX's four digits.
13    pub const fn new(year: u16, month: u8, day: u8) -> Option<Self> {
14        let valid = year <= 9999
15            && matches!(month, 1..=12)
16            && day >= 1
17            && day <= days_in_month(year, month);
18        if valid {
19            Some(Self { year, month, day })
20        } else {
21            None
22        }
23    }
24
25    /// The year, such as `2026`.
26    pub const fn year(&self) -> u16 {
27        self.year
28    }
29
30    /// The month, from `1` for January to `12` for December.
31    pub const fn month(&self) -> u8 {
32        self.month
33    }
34
35    /// The day of the month, from `1`.
36    pub const fn day(&self) -> u8 {
37        self.day
38    }
39
40    /// Reads a FIX date such as `20261030`.
41    pub(crate) fn parse(text: &[u8]) -> Option<Self> {
42        if text.len() != 8 {
43            return None;
44        }
45        let year = u16::try_from(number(&text[0..4])?).ok()?;
46        let month = u8::try_from(number(&text[4..6])?).ok()?;
47        let day = u8::try_from(number(&text[6..8])?).ok()?;
48        Self::new(year, month, day)
49    }
50
51    /// Days from 1970-01-01, by Howard Hinnant's `days_from_civil`.
52    ///
53    /// See <https://howardhinnant.github.io/date_algorithms.html#days_from_civil>.
54    pub(super) fn days_since_epoch(self) -> i64 {
55        let month = i64::from(self.month);
56        let year = i64::from(self.year);
57        let year = if month <= 2 { year - 1 } else { year };
58        let era = year.div_euclid(400);
59        let year_of_era = year.rem_euclid(400);
60        let month_from_march = (month + 9) % 12;
61        let day_of_year = (153 * month_from_march + 2) / 5 + i64::from(self.day) - 1;
62        let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
63        // An era is 146,097 days, and the epoch is day 719,468 from 0000-03-01.
64        era * 146_097 + day_of_era - 719_468
65    }
66
67    /// The date `days` after 1970-01-01, by Howard Hinnant's `civil_from_days`.
68    ///
69    /// See <https://howardhinnant.github.io/date_algorithms.html#civil_from_days>.
70    pub(super) fn from_days_since_epoch(days: i64) -> Option<Self> {
71        // Counted from 0000-03-01, as in `days_since_epoch`.
72        let days = days.checked_add(719_468)?;
73        let era = days.div_euclid(146_097);
74        let day_of_era = days.rem_euclid(146_097);
75        let year_of_era =
76            (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
77        let day_of_year = day_of_era - (year_of_era * 365 + year_of_era / 4 - year_of_era / 100);
78        let month_from_march = (5 * day_of_year + 2) / 153;
79        let day = day_of_year - (153 * month_from_march + 2) / 5 + 1;
80        let month = if month_from_march < 10 {
81            month_from_march + 3
82        } else {
83            month_from_march - 9
84        };
85        let year = era * 400 + year_of_era + i64::from(month <= 2);
86        Self::new(
87            u16::try_from(year).ok()?,
88            u8::try_from(month).ok()?,
89            u8::try_from(day).ok()?,
90        )
91    }
92}
93
94/// The number of days in `month` of `year`.
95const fn days_in_month(year: u16, month: u8) -> u8 {
96    match month {
97        2 if is_leap_year(year) => 29,
98        2 => 28,
99        4 | 6 | 9 | 11 => 30,
100        _ => 31,
101    }
102}
103
104const fn is_leap_year(year: u16) -> bool {
105    year.is_multiple_of(4) && (!year.is_multiple_of(100) || year.is_multiple_of(400))
106}
107
108#[cfg(test)]
109mod tests {
110    use super::*;
111
112    fn date(year: u16, month: u8, day: u8) -> Date {
113        Date::new(year, month, day).unwrap()
114    }
115
116    fn parse(text: &str) -> Option<Date> {
117        Date::parse(text.as_bytes())
118    }
119
120    mod construction {
121        use super::*;
122
123        #[test]
124        fn keeps_its_parts() {
125            let value = date(2026, 10, 30);
126            assert_eq!((value.year(), value.month(), value.day()), (2026, 10, 30));
127        }
128
129        #[test]
130        fn accepts_february_29_only_in_leap_years() {
131            assert!(Date::new(2024, 2, 29).is_some());
132            assert!(Date::new(2000, 2, 29).is_some());
133            assert_eq!(Date::new(2023, 2, 29), None);
134            assert_eq!(Date::new(1900, 2, 29), None);
135        }
136
137        #[test]
138        fn rejects_days_that_do_not_exist() {
139            for (year, month, day) in [
140                (2026, 0, 1),
141                (2026, 13, 1),
142                (2026, 10, 0),
143                (2026, 10, 32),
144                (2026, 4, 31),
145            ] {
146                assert_eq!(Date::new(year, month, day), None, "{year}-{month}-{day}");
147            }
148        }
149
150        #[test]
151        fn takes_the_years_fix_can_write() {
152            assert!(Date::new(0, 1, 1).is_some());
153            assert!(Date::new(9999, 12, 31).is_some());
154            assert_eq!(Date::new(10000, 1, 1), None);
155        }
156    }
157
158    mod parsing {
159        use super::*;
160
161        #[test]
162        fn reads_a_date() {
163            assert_eq!(parse("20261030"), Some(date(2026, 10, 30)));
164        }
165
166        #[test]
167        fn reads_the_ends_of_the_fix_range() {
168            assert_eq!(parse("00000101"), Some(date(0, 1, 1)));
169            assert_eq!(parse("99991231"), Some(date(9999, 12, 31)));
170        }
171
172        #[test]
173        fn rejects_dates_that_do_not_exist() {
174            for text in ["20261301", "20261000", "20260431", "20230229"] {
175                assert_eq!(parse(text), None, "{text:?}");
176            }
177        }
178
179        #[test]
180        fn rejects_other_shapes() {
181            for text in [
182                "",
183                "2026103",
184                "202610301",
185                "2026-10-30",
186                "2026103a",
187                "+0261030",
188                "20261030-",
189            ] {
190                assert_eq!(parse(text), None, "{text:?}");
191            }
192        }
193    }
194
195    mod ordering {
196        use super::*;
197
198        #[test]
199        fn orders_chronologically() {
200            assert!(date(2025, 12, 31) < date(2026, 1, 1));
201            assert!(date(2026, 1, 31) < date(2026, 2, 1));
202            assert!(date(2026, 2, 1) < date(2026, 2, 2));
203        }
204    }
205
206    mod calendar {
207        use super::*;
208
209        #[test]
210        fn the_epoch_is_day_zero() {
211            assert_eq!(date(1970, 1, 1).days_since_epoch(), 0);
212            assert_eq!(date(1969, 12, 31).days_since_epoch(), -1);
213        }
214
215        #[test]
216        fn counts_days_from_the_epoch() {
217            assert_eq!(date(2000, 3, 1).days_since_epoch(), 11_017);
218            assert_eq!(date(2026, 10, 30).days_since_epoch(), 20_756);
219        }
220
221        #[test]
222        fn consecutive_dates_are_consecutive_days() {
223            for year in 1600..=2400 {
224                for month in 1..=12 {
225                    let last = date(year, month, days_in_month(year, month));
226                    let next = match month {
227                        12 => date(year + 1, 1, 1),
228                        _ => date(year, month + 1, 1),
229                    };
230                    assert_eq!(
231                        last.days_since_epoch() + 1,
232                        next.days_since_epoch(),
233                        "{year}-{month}"
234                    );
235                }
236            }
237        }
238
239        #[test]
240        fn counts_back_from_the_epoch() {
241            assert_eq!(Date::from_days_since_epoch(0), Some(date(1970, 1, 1)));
242            assert_eq!(Date::from_days_since_epoch(-1), Some(date(1969, 12, 31)));
243            assert_eq!(Date::from_days_since_epoch(11_017), Some(date(2000, 3, 1)));
244            assert_eq!(
245                Date::from_days_since_epoch(20_756),
246                Some(date(2026, 10, 30))
247            );
248        }
249
250        #[test]
251        fn round_trips_every_day_fix_can_write() {
252            let first = date(0, 1, 1).days_since_epoch();
253            let last = date(9999, 12, 31).days_since_epoch();
254            for days in first..=last {
255                let value = Date::from_days_since_epoch(days).unwrap();
256                assert_eq!(value.days_since_epoch(), days, "{value:?}");
257            }
258        }
259
260        #[test]
261        fn has_no_date_beyond_the_years_fix_can_write() {
262            let first = date(0, 1, 1).days_since_epoch();
263            let last = date(9999, 12, 31).days_since_epoch();
264            for days in [first - 1, last + 1, i64::MIN, i64::MAX] {
265                assert_eq!(Date::from_days_since_epoch(days), None, "{days}");
266            }
267        }
268
269        #[test]
270        fn february_has_29_days_in_leap_years() {
271            assert_eq!(days_in_month(2024, 2), 29);
272            assert_eq!(days_in_month(2000, 2), 29);
273            assert_eq!(days_in_month(2023, 2), 28);
274            assert_eq!(days_in_month(1900, 2), 28);
275        }
276
277        #[test]
278        fn other_months_have_fixed_lengths() {
279            assert_eq!(days_in_month(2026, 1), 31);
280            assert_eq!(days_in_month(2026, 4), 30);
281            assert_eq!(days_in_month(2026, 12), 31);
282        }
283    }
284}