dos-date-time 0.3.0

An MS-DOS date and time library
Documentation
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
// SPDX-FileCopyrightText: 2025 Shun Sakai
//
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! The [MS-DOS date].
//!
//! [MS-DOS date]: https://learn.microsoft.com/en-us/windows/win32/sysinfo/ms-dos-date-and-time

mod cmp;
mod consts;
mod convert;
mod fmt;

use time::Month;

use crate::error::{DateRangeError, DateRangeErrorKind};

/// `Date` is a type that represents the [MS-DOS date].
///
/// This is a packed 16-bit unsigned integer value.
///
/// See the [format specification] for [Kaitai Struct] for more details on the
/// structure of the MS-DOS date.
///
/// [MS-DOS date]: https://learn.microsoft.com/en-us/windows/win32/sysinfo/ms-dos-date-and-time
/// [format specification]: https://formats.kaitai.io/dos_datetime/
/// [Kaitai Struct]: https://kaitai.io/
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[repr(transparent)]
pub struct Date(u16);

impl Date {
    #[expect(clippy::missing_panics_doc)]
    /// Creates a new `Date` with the given underlying [`u16`] value.
    ///
    /// Returns [`None`] if the given value is not a valid MS-DOS date.
    ///
    /// # Examples
    ///
    /// ```
    /// # use dos_date_time::Date;
    /// #
    /// assert_eq!(Date::new(0b0000_0000_0010_0001), Some(Date::MIN));
    /// assert_eq!(Date::new(0b1111_1111_1001_1111), Some(Date::MAX));
    ///
    /// // The Day field is 0.
    /// assert_eq!(Date::new(0b0000_0000_0010_0000), None);
    /// ```
    #[must_use]
    pub fn new(date: u16) -> Option<Self> {
        let (year, month, day) = (
            (1980 + (date >> 9)).into(),
            u8::try_from((date >> 5) & 0x0F)
                .expect("month should be in the range of `u8`")
                .try_into()
                .ok()?,
            (date & 0x1F)
                .try_into()
                .expect("day should be in the range of `u8`"),
        );
        let date = time::Date::from_calendar_date(year, month, day).ok()?;
        Self::from_date(date).ok()
    }

    /// Creates a new `Date` with the given underlying [`u16`] value.
    ///
    /// # Safety
    ///
    /// The given value must be a valid MS-DOS date.
    #[must_use]
    pub const unsafe fn new_unchecked(date: u16) -> Self {
        Self(date)
    }

    #[expect(clippy::missing_panics_doc)]
    /// Creates a new `Date` with the given [`time::Date`].
    ///
    /// # Errors
    ///
    /// Returns [`Err`] if `date` is an invalid as the MS-DOS date.
    ///
    /// # Examples
    ///
    /// ```
    /// # use dos_date_time::{Date, time::macros::date};
    /// #
    /// assert_eq!(Date::from_date(date!(1980-01-01)), Ok(Date::MIN));
    /// assert_eq!(Date::from_date(date!(2107-12-31)), Ok(Date::MAX));
    ///
    /// // Before `1980-01-01`.
    /// assert!(Date::from_date(date!(1979-12-31)).is_err());
    /// // After `2107-12-31`.
    /// assert!(Date::from_date(date!(2108-01-01)).is_err());
    /// ```
    pub fn from_date(date: time::Date) -> Result<Self, DateRangeError> {
        match date.year() {
            ..=1979 => Err(DateRangeErrorKind::Negative.into()),
            2108.. => Err(DateRangeErrorKind::Overflow.into()),
            year => {
                let (year, month, day) = (
                    u16::try_from(year - 1980).expect("year should be in the range of `u16`"),
                    u16::from(u8::from(date.month())),
                    u16::from(date.day()),
                );
                let date = (year << 9) | (month << 5) | day;
                // SAFETY: `date` is a valid as the MS-DOS date.
                Ok(unsafe { Self::new_unchecked(date) })
            }
        }
    }

    /// Returns [`true`] if `self` is a valid MS-DOS date, and [`false`]
    /// otherwise.
    #[must_use]
    pub fn is_valid(self) -> bool {
        Self::new(self.to_raw()).is_some()
    }

    /// Returns this `Date` as the underlying [`u16`] value.
    ///
    /// # Examples
    ///
    /// ```
    /// # use dos_date_time::Date;
    /// #
    /// assert_eq!(Date::MIN.to_raw(), 0b0000_0000_0010_0001);
    /// assert_eq!(Date::MAX.to_raw(), 0b1111_1111_1001_1111);
    /// ```
    #[must_use]
    pub const fn to_raw(self) -> u16 {
        self.0
    }

    /// Gets the year of this `Date`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use dos_date_time::Date;
    /// #
    /// assert_eq!(Date::MIN.year(), 1980);
    /// assert_eq!(Date::MAX.year(), 2107);
    /// ```
    #[must_use]
    pub const fn year(self) -> u16 {
        1980 + (self.to_raw() >> 9)
    }

    #[expect(clippy::missing_panics_doc)]
    /// Gets the month of this `Date`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use dos_date_time::{Date, time::Month};
    /// #
    /// assert_eq!(Date::MIN.month(), Month::January);
    /// assert_eq!(Date::MAX.month(), Month::December);
    /// ```
    #[must_use]
    pub fn month(self) -> Month {
        u8::try_from((self.to_raw() >> 5) & 0x0F)
            .expect("month should be in the range of `u8`")
            .try_into()
            .expect("month should be in the range of `Month`")
    }

    #[expect(clippy::missing_panics_doc)]
    /// Gets the day of this `Date`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use dos_date_time::Date;
    /// #
    /// assert_eq!(Date::MIN.day(), 1);
    /// assert_eq!(Date::MAX.day(), 31);
    /// ```
    #[must_use]
    pub fn day(self) -> u8 {
        (self.to_raw() & 0x1F)
            .try_into()
            .expect("day should be in the range of `u8`")
    }
}

impl Default for Date {
    /// Returns the default value of "1980-01-01".
    ///
    /// # Examples
    ///
    /// ```
    /// # use dos_date_time::Date;
    /// #
    /// assert_eq!(Date::default(), Date::MIN);
    /// ```
    fn default() -> Self {
        Self::MIN
    }
}

#[cfg(test)]
mod tests {
    use core::mem;
    #[cfg(feature = "std")]
    use std::{
        collections::hash_map::DefaultHasher,
        hash::{Hash, Hasher},
    };

    use time::macros::date;

    use super::*;

    #[test]
    fn size_of() {
        assert_eq!(mem::size_of::<Date>(), mem::size_of::<u16>());
    }

    #[test]
    fn align_of() {
        assert_eq!(mem::align_of::<Date>(), mem::align_of::<u16>());
    }

    #[test]
    fn clone() {
        assert_eq!(Date::MIN.clone(), Date::MIN);
    }

    #[test]
    fn copy() {
        let a = Date::MIN;
        let b = a;
        assert_eq!(a, b);
    }

    #[cfg(feature = "std")]
    #[test]
    fn hash() {
        assert_ne!(
            {
                let mut hasher = DefaultHasher::new();
                Date::MIN.hash(&mut hasher);
                hasher.finish()
            },
            {
                let mut hasher = DefaultHasher::new();
                Date::MAX.hash(&mut hasher);
                hasher.finish()
            }
        );
    }

    #[test]
    fn new() {
        assert_eq!(Date::new(0b0000_0000_0010_0001).unwrap(), Date::MIN);
        assert_eq!(Date::new(0b1111_1111_1001_1111).unwrap(), Date::MAX);
    }

    #[test]
    fn new_with_invalid_date() {
        // The Day field is 0.
        assert!(Date::new(0b0000_0000_0010_0000).is_none());
        // The Day field is 30, which is after the last day of February.
        assert!(Date::new(0b0000_0000_0101_1110).is_none());
        // The Month field is 0.
        assert!(Date::new(0b0000_0000_0000_0001).is_none());
        // The Month field is 13.
        assert!(Date::new(0b0000_0001_1010_0001).is_none());
    }

    #[test]
    fn new_unchecked() {
        assert_eq!(
            unsafe { Date::new_unchecked(0b0000_0000_0010_0001) },
            Date::MIN
        );
        assert_eq!(
            unsafe { Date::new_unchecked(0b1111_1111_1001_1111) },
            Date::MAX
        );
    }

    #[test]
    const fn new_unchecked_is_const_fn() {
        const _: Date = unsafe { Date::new_unchecked(0b0000_0000_0010_0001) };
    }

    #[test]
    fn from_date_before_dos_date_epoch() {
        assert_eq!(
            Date::from_date(date!(1979-12-31)).unwrap_err(),
            DateRangeErrorKind::Negative.into()
        );
        assert_eq!(
            Date::from_date(date!(1979-12-31)).unwrap_err(),
            DateRangeErrorKind::Negative.into()
        );
    }

    #[test]
    fn from_date() {
        assert_eq!(Date::from_date(date!(1980-01-01)).unwrap(), Date::MIN);
        assert_eq!(Date::from_date(date!(1980-01-01)).unwrap(), Date::MIN);
        // <https://devblogs.microsoft.com/oldnewthing/20030905-02/?p=42653>.
        assert_eq!(
            Date::from_date(date!(2002-11-26)).unwrap(),
            Date::new(0b0010_1101_0111_1010).unwrap()
        );
        // <https://github.com/zip-rs/zip/blob/v0.6.4/src/types.rs#L553-L569>.
        assert_eq!(
            Date::from_date(date!(2018-11-17)).unwrap(),
            Date::new(0b0100_1101_0111_0001).unwrap()
        );
        assert_eq!(Date::from_date(date!(2107-12-31)).unwrap(), Date::MAX);
        assert_eq!(Date::from_date(date!(2107-12-31)).unwrap(), Date::MAX);
    }

    #[test]
    fn from_date_with_too_big_date() {
        assert_eq!(
            Date::from_date(date!(2108-01-01)).unwrap_err(),
            DateRangeErrorKind::Overflow.into()
        );
    }

    #[test]
    fn is_valid() {
        assert!(Date::MIN.is_valid());
        // <https://devblogs.microsoft.com/oldnewthing/20030905-02/?p=42653>.
        assert!(Date::new(0b0010_1101_0111_1010).unwrap().is_valid());
        // <https://github.com/zip-rs/zip/blob/v0.6.4/src/types.rs#L553-L569>.
        assert!(Date::new(0b0100_1101_0111_0001).unwrap().is_valid());
        assert!(Date::MAX.is_valid());
    }

    #[test]
    fn is_valid_with_invalid_date() {
        // The Day field is 0.
        assert!(!unsafe { Date::new_unchecked(0b0000_0000_0010_0000) }.is_valid());
        // The Day field is 30, which is after the last day of February.
        assert!(!unsafe { Date::new_unchecked(0b0000_0000_0101_1110) }.is_valid());
        // The Month field is 0.
        assert!(!unsafe { Date::new_unchecked(0b0000_0000_0000_0001) }.is_valid());
        // The Month field is 13.
        assert!(!unsafe { Date::new_unchecked(0b0000_0001_1010_0001) }.is_valid());
    }

    #[test]
    fn to_raw() {
        assert_eq!(Date::MIN.to_raw(), 0b0000_0000_0010_0001);
        // <https://devblogs.microsoft.com/oldnewthing/20030905-02/?p=42653>.
        assert_eq!(
            Date::new(0b0010_1101_0111_1010).unwrap().to_raw(),
            0b0010_1101_0111_1010
        );
        // <https://github.com/zip-rs/zip/blob/v0.6.4/src/types.rs#L553-L569>.
        assert_eq!(
            Date::new(0b0100_1101_0111_0001).unwrap().to_raw(),
            0b0100_1101_0111_0001
        );
        assert_eq!(Date::MAX.to_raw(), 0b1111_1111_1001_1111);
    }

    #[test]
    const fn to_raw_is_const_fn() {
        const _: u16 = Date::MIN.to_raw();
    }

    #[test]
    fn year() {
        assert_eq!(Date::MIN.year(), 1980);
        // <https://devblogs.microsoft.com/oldnewthing/20030905-02/?p=42653>.
        assert_eq!(Date::new(0b0010_1101_0111_1010).unwrap().year(), 2002);
        // <https://github.com/zip-rs/zip/blob/v0.6.4/src/types.rs#L553-L569>.
        assert_eq!(Date::new(0b0100_1101_0111_0001).unwrap().year(), 2018);
        assert_eq!(Date::MAX.year(), 2107);
    }

    #[test]
    const fn year_is_const_fn() {
        const _: u16 = Date::MIN.year();
    }

    #[test]
    fn month() {
        assert_eq!(Date::MIN.month(), Month::January);
        // <https://devblogs.microsoft.com/oldnewthing/20030905-02/?p=42653>.
        assert_eq!(
            Date::new(0b0010_1101_0111_1010).unwrap().month(),
            Month::November
        );
        // <https://github.com/zip-rs/zip/blob/v0.6.4/src/types.rs#L553-L569>.
        assert_eq!(
            Date::new(0b0100_1101_0111_0001).unwrap().month(),
            Month::November
        );
        assert_eq!(Date::MAX.month(), Month::December);
    }

    #[test]
    fn day() {
        assert_eq!(Date::MIN.day(), 1);
        // <https://devblogs.microsoft.com/oldnewthing/20030905-02/?p=42653>.
        assert_eq!(Date::new(0b0010_1101_0111_1010).unwrap().day(), 26);
        // <https://github.com/zip-rs/zip/blob/v0.6.4/src/types.rs#L553-L569>.
        assert_eq!(Date::new(0b0100_1101_0111_0001).unwrap().day(), 17);
        assert_eq!(Date::MAX.day(), 31);
    }

    #[test]
    fn default() {
        assert_eq!(Date::default(), Date::MIN);
    }
}