1use core::fmt;
15
16#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
18pub struct Date {
19 pub year: u16,
21 pub month: u8,
23 pub day: u8,
25}
26
27impl Date {
28 pub(crate) fn from_type_g(b0: u8, b1: u8) -> Self {
30 let year = ((b0 & 0xE0) >> 5) | ((b1 & 0xF0) >> 1);
31 Self { year: century(year, 0), month: b1 & 0x0F, day: b0 & 0x1F }
32 }
33
34 pub fn add_months(self, months: i32) -> Option<Self> {
39 if !self.is_valid() {
40 return None;
41 }
42 let last = self.day >= days_in(self.year, self.month);
43 let total = (i64::from(self.year) * 12 + i64::from(self.month) - 1).checked_add(i64::from(months))?;
44 let year = u16::try_from(total.div_euclid(12)).ok()?;
45 let month = u8::try_from(total.rem_euclid(12) + 1).ok()?;
46 let len = days_in(year, month);
47 let day = if last { len } else { self.day.min(len) };
48 Some(Self { year, month, day })
49 }
50
51 pub const fn is_valid(&self) -> bool {
53 let leap = (self.year % 4 == 0 && self.year % 100 != 0) || self.year % 400 == 0;
54 let days = match self.month {
55 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
56 4 | 6 | 9 | 11 => 30,
57 2 if leap => 29,
58 2 => 28,
59 _ => return false,
60 };
61 self.day >= 1 && self.day <= days
62 }
63}
64
65const fn days_in(year: u16, month: u8) -> u8 {
66 let leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
67 match month {
68 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
69 4 | 6 | 9 | 11 => 30,
70 2 if leap => 29,
71 2 => 28,
72 _ => 0,
73 }
74}
75
76const fn century(year: u8, hundred: u8) -> u16 {
83 let y = year as u16;
84 if hundred == 0 && y <= 80 { 2000 + y } else { 1900 + 100 * hundred as u16 + y }
85}
86
87impl fmt::Display for Date {
88 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89 write!(f, "{:04}-{:02}-{:02}", self.year, self.month, self.day)?;
90 if !self.is_valid() {
91 f.write_str(" (invalid)")?;
92 }
93 Ok(())
94 }
95}
96
97#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
99pub struct Time {
100 pub hour: u8,
102 pub minute: u8,
104 pub second: u8,
106}
107
108impl Time {
109 pub(crate) const fn from_type_j(b0: u8, b1: u8, b2: u8) -> Self {
111 Self { second: b0 & 0x3F, minute: b1 & 0x3F, hour: b2 & 0x1F }
112 }
113
114 pub const fn is_valid(&self) -> bool {
116 self.hour < 24 && self.minute < 60 && self.second < 60
117 }
118}
119
120impl fmt::Display for Time {
121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122 write!(f, "{:02}:{:02}:{:02}", self.hour, self.minute, self.second)
123 }
124}
125
126#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
128#[allow(clippy::struct_excessive_bools)] pub struct DateTime {
130 pub date: Date,
132 pub time: Time,
134 pub has_seconds: bool,
136 pub invalid: bool,
138 pub summer_time: bool,
140 pub leap_year: bool,
142 pub weekday: u8,
144 pub week: u8,
146}
147
148impl DateTime {
149 pub(crate) fn from_type_f(b: [u8; 4]) -> Self {
151 let [b0, b1, b2, b3] = b;
152 let mut date = Date::from_type_g(b2, b3);
153 date.year = century(((b2 & 0xE0) >> 5) | ((b3 & 0xF0) >> 1), (b1 >> 5) & 0x03);
154 Self {
155 date,
156 time: Time { hour: b1 & 0x1F, minute: b0 & 0x3F, second: 0 },
157 has_seconds: false,
158 invalid: b0 & 0x80 != 0,
159 summer_time: b1 & 0x80 != 0,
160 leap_year: false,
161 weekday: 0,
162 week: 0,
163 }
164 }
165
166 pub(crate) fn from_type_i(b: [u8; 6]) -> Self {
171 let [b0, b1, b2, b3, b4, b5] = b;
172 let date = Date::from_type_g(b3, b4);
173 Self {
174 date,
175 time: Time { hour: b2 & 0x1F, minute: b1 & 0x3F, second: b0 & 0x3F },
176 has_seconds: true,
177 invalid: b1 & 0x80 != 0,
178 summer_time: b0 & 0x40 != 0,
179 leap_year: b0 & 0x80 != 0,
180 weekday: b2 >> 5,
181 week: b5 & 0x3F,
182 }
183 }
184
185 pub fn new(year: u16, month: u8, day: u8, hour: u8, minute: u8) -> Option<Self> {
189 let t = Self {
190 date: Date { year, month, day },
191 time: Time { hour, minute, second: 0 },
192 has_seconds: false,
193 invalid: false,
194 summer_time: false,
195 leap_year: false,
196 weekday: 0,
197 week: 0,
198 };
199 (t.is_valid() && (1981..=2299).contains(&year)).then_some(t)
200 }
201
202 pub fn to_type_f(&self) -> [u8; 4] {
205 let (y, h) = match self.date.year {
206 2000..=2080 => (self.date.year - 2000, 0),
207 year => ((year.saturating_sub(1900)) % 100, (year.saturating_sub(1900) / 100).min(3)),
208 };
209 #[allow(clippy::cast_possible_truncation)] let (y, h) = (y as u8, h as u8);
211 let Time { hour, minute, .. } = self.time;
212 [
213 (minute & 0x3F) | if self.invalid { 0x80 } else { 0 },
214 (hour & 0x1F) | (h << 5) | if self.summer_time { 0x80 } else { 0 },
215 (self.date.day & 0x1F) | ((y & 0x07) << 5),
216 (self.date.month & 0x0F) | ((y & 0x78) << 1),
217 ]
218 }
219
220 pub const fn is_valid(&self) -> bool {
222 !self.invalid && self.date.is_valid() && self.time.is_valid()
223 }
224}
225
226impl fmt::Display for DateTime {
227 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
228 let Date { year, month, day } = self.date;
229 let Time { hour, minute, second } = self.time;
230 write!(f, "{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}")?;
231 if self.has_seconds {
232 write!(f, ":{second:02}")?;
233 }
234 if self.summer_time {
235 f.write_str(" (summer time)")?;
236 }
237 if !self.is_valid() {
238 f.write_str(" (invalid)")?;
239 }
240 Ok(())
241 }
242}
243
244#[cfg(test)]
245mod tests {
246 extern crate std;
247 use super::*;
248 use std::string::ToString;
249
250 #[test]
251 fn type_g() {
252 let d = Date::from_type_g(0b0101_1011, 0b0011_1011);
254 assert_eq!(d.to_string(), "2026-11-27");
255 assert!(d.is_valid());
256 let bad = Date::from_type_g(0xFF, 0xFF);
257 assert!(!bad.is_valid());
258 assert!(bad.to_string().ends_with("(invalid)"));
259 }
260
261 #[test]
262 fn type_f_flags_and_century() {
263 let t = DateTime::from_type_f([30, 14, 0b0101_1011, 0b0011_1011]);
264 assert_eq!(t.to_string(), "2026-11-27 14:30");
265 let t = DateTime::from_type_f([0x1E | 0x80, 0x0E | 0x80, 0b0101_1011, 0b0011_1011]);
266 assert!(t.invalid && t.summer_time);
267 assert_eq!(t.to_string(), "2026-11-27 14:30 (summer time) (invalid)");
268 assert_eq!(century(99, 0), 1999);
271 assert_eq!(century(80, 0), 2080);
272 let t = DateTime::from_type_f([0x32, 0x37, 0x1F, 0x15]);
273 assert_eq!(t.to_string(), "2008-05-31 23:50");
274 }
275
276 #[test]
277 fn month_steps_keep_the_month_end() {
278 let d = Date { year: 2008, month: 1, day: 31 };
279 let steps: std::vec::Vec<std::string::String> =
280 (1..=4).map(|k| d.add_months(k).unwrap().to_string()).collect();
281 assert_eq!(steps, ["2008-02-29", "2008-03-31", "2008-04-30", "2008-05-31"]);
282 assert_eq!(Date { year: 2008, month: 5, day: 31 }.add_months(-4).unwrap().to_string(), "2008-01-31");
283 assert_eq!(Date { year: 2020, month: 11, day: 15 }.add_months(3).unwrap().to_string(), "2021-02-15");
284 assert_eq!(Date { year: 2020, month: 13, day: 1 }.add_months(1), None);
286 assert_eq!(d.add_months(i32::MAX), None);
287 assert_eq!(d.add_months(i32::MIN), None);
288 assert!(DateTime::new(2299, 12, 31, 23, 59).is_some());
290 assert!(DateTime::new(2300, 1, 1, 0, 0).is_none());
291 let t = DateTime::new(2250, 6, 1, 12, 0).unwrap();
292 assert_eq!(DateTime::from_type_f(t.to_type_f()).date.year, 2250);
293 }
294
295 #[test]
296 fn type_f_round_trips() {
297 for bytes in [
298 [0x32, 0x37, 0x1F, 0x15],
299 [30, 14, 0b0101_1011, 0b0011_1011],
300 [0x1E | 0x80, 0x0E | 0x80, 0x5B, 0x3B],
301 ] {
302 let t = DateTime::from_type_f(bytes);
303 assert_eq!(DateTime::from_type_f(t.to_type_f()), t, "{bytes:02x?}");
304 }
305 }
306
307 #[test]
308 fn type_i_real_vector() {
309 let t = DateTime::from_type_i([0xB2, 0x36, 0x0D, 0x01, 0x02, 0x00]);
311 assert_eq!(t.to_string(), "2000-02-01 13:54:50");
312 assert!(t.leap_year && !t.summer_time && !t.invalid);
313 }
314
315 #[test]
316 fn type_j_and_i() {
317 assert_eq!(Time::from_type_j(5, 4, 3).to_string(), "03:04:05");
318 let t = DateTime::from_type_i([59, 30, 0x0E | (5 << 5), 0b0101_1011, 0b0011_1011, 48]);
319 assert_eq!(t.to_string(), "2026-11-27 14:30:59");
320 assert_eq!((t.weekday, t.week), (5, 48));
321 }
322}