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
use std::fmt;

use crate::{get_digit_unchecked, ParseError};

/// A Date
///
/// Allowed formats:
/// * `YYYY-MM-DD`
///
/// Leap years are correct calculated according to the Gregorian calendar.
/// Thus `2000-02-29` is a valid date, but `2001-02-29` is not.
///
/// # Comparison
///
/// `Date` supports equality (`==`) and inequality (`>`, `<`, `>=`, `<=`) comparisons.
///
/// ```
/// use speedate::Date;
///
/// let d1 = Date::parse_str("2022-01-01").unwrap();
/// let d2 = Date::parse_str("2022-01-02").unwrap();
/// assert!(d2 > d1);
/// ```
#[derive(Debug, PartialEq, Eq, PartialOrd, Clone)]
pub struct Date {
    /// Year: four digits
    pub year: u16,
    /// Month: 1 to 12
    pub month: u8,
    /// Day: 1 to {28, 29, 30, 31} (based on month & year)
    pub day: u8,
}

impl fmt::Display for Date {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:04}-{:02}-{:02}", self.year, self.month, self.day)
    }
}

// 2e10 if greater than this, the number is in ms, if less than or equal, it's in seconds
// (in seconds this is 11th October 2603, in ms it's 20th August 1970)
const MS_WATERSHED: i64 = 20_000_000_000;
// 1600-01-01 as a unix timestamp used for from_timestamp below
const UNIX_1600: i64 = -11_676_096_000;
// 9999-12-31T23:59:59 as a unix timestamp, used as max allowed value below
const UNIX_9999: i64 = 253_402_300_799;

impl Date {
    /// Parse a date from a string
    ///
    /// # Arguments
    ///
    /// * `str` - The string to parse
    ///
    /// # Examples
    ///
    /// ```
    /// use speedate::Date;
    ///
    /// let d = Date::parse_str("2020-01-01").unwrap();
    /// assert_eq!(
    ///     d,
    ///     Date {
    ///         year: 2020,
    ///         month: 1,
    ///         day: 1
    ///     }
    /// );
    /// assert_eq!(d.to_string(), "2020-01-01");
    /// ```
    #[inline]
    pub fn parse_str(str: &str) -> Result<Self, ParseError> {
        Self::parse_bytes(str.as_bytes())
    }

    /// Parse a date from bytes
    ///
    /// # Arguments
    ///
    /// * `bytes` - The bytes to parse
    ///
    /// # Examples
    ///
    /// ```
    /// use speedate::Date;
    ///
    /// let d = Date::parse_bytes(b"2020-01-01").unwrap();
    /// assert_eq!(
    ///     d,
    ///     Date {
    ///         year: 2020,
    ///         month: 1,
    ///         day: 1
    ///     }
    /// );
    /// assert_eq!(d.to_string(), "2020-01-01");
    /// ```
    #[inline]
    pub fn parse_bytes(bytes: &[u8]) -> Result<Self, ParseError> {
        let d = Self::parse_bytes_partial(bytes)?;

        if bytes.len() > 10 {
            return Err(ParseError::ExtraCharacters);
        }

        Ok(d)
    }

    /// Create a date from a Unix Timestamp in seconds or milliseconds
    ///
    /// ("Unix Timestamp" means number of seconds or milliseconds since 1970-01-01)
    ///
    /// Input must be between `-11,676,096,000` (`1600-01-01`) and `253,402,300,799,000` (`9999-12-31`) inclusive.
    ///
    /// If the absolute value is > 2e10 (`20,000,000,000`) it is interpreted as being in milliseconds.
    ///
    /// That means:
    /// * `20_000_000_000` is `2603-10-11`
    /// * `20_000_000_001` is `1970-08-20`
    /// * `-20_000_000_000` gives an error - `DateTooSmall` as it would be before 1600
    /// * `-20_000_000_001` is `1969-05-14`
    ///
    /// # Arguments
    ///
    /// * `timestamp` - timestamp in either seconds or milliseconds
    ///
    /// # Examples
    ///
    /// ```
    /// use speedate::Date;
    ///
    /// let d = Date::from_timestamp(1_654_560_000).unwrap();
    /// assert_eq!(d.to_string(), "2022-06-07");
    /// ```
    pub fn from_timestamp(timestamp: i64) -> Result<Self, ParseError> {
        let (timestamp_second, _) = Self::timestamp_watershed(timestamp)?;
        Self::from_timestamp_calc(timestamp_second)
    }

    /// Unix timestamp in seconds (number of seconds between self and 1970-01-01)
    ///
    /// # Example
    ///
    /// ```
    /// use speedate::Date;
    ///
    /// let d = Date::parse_str("2022-06-07").unwrap();
    /// assert_eq!(d.timestamp(), 1_654_560_000);
    /// ```
    pub fn timestamp(&self) -> i64 {
        let days = (self.year - 1600) as i64 * 365
            + (self.ordinal_day() - 1) as i64
            + intervening_leap_years(self.year - 1600) as i64;
        days * 86400 + UNIX_1600
    }

    /// Day of the year, starting from 1.
    pub fn ordinal_day(&self) -> u16 {
        let leap_extra = if is_leap_year(self.year) { 1 } else { 0 };
        let day = self.day as u16;
        match self.month {
            1 => day,
            2 => day + 31,
            3 => day + 59 + leap_extra,
            4 => day + 90 + leap_extra,
            5 => day + 120 + leap_extra,
            6 => day + 151 + leap_extra,
            7 => day + 181 + leap_extra,
            8 => day + 212 + leap_extra,
            9 => day + 243 + leap_extra,
            10 => day + 273 + leap_extra,
            11 => day + 304 + leap_extra,
            _ => day + 334 + leap_extra,
        }
    }

    pub(crate) fn timestamp_watershed(timestamp: i64) -> Result<(i64, u32), ParseError> {
        let ts_abs = timestamp.checked_abs().ok_or(ParseError::DateTooSmall)?;
        let (mut seconds, mut microseconds) = if ts_abs > MS_WATERSHED {
            (timestamp / 1_000, timestamp % 1_000 * 1000)
        } else {
            (timestamp, 0)
        };
        if microseconds < 0 {
            seconds -= 1;
            microseconds += 1_000_000;
        }
        Ok((seconds, microseconds as u32))
    }

    pub(crate) fn from_timestamp_calc(timestamp_second: i64) -> Result<Self, ParseError> {
        if timestamp_second < UNIX_1600 {
            return Err(ParseError::DateTooSmall);
        }
        if timestamp_second > UNIX_9999 {
            return Err(ParseError::DateTooLarge);
        }
        let seconds_diff = timestamp_second - UNIX_1600;
        let delta_days = seconds_diff / 86_400;
        let delta_years = (delta_days / 365) as u16;
        let leap_years = intervening_leap_years(delta_years) as i64;

        // year day is the day of the year, starting from 1
        let mut ordinal_day: i16 = (delta_days % 365 - leap_years + 1) as i16;
        let mut year: u16 = 1600 + delta_years;
        let mut leap_year: bool = is_leap_year(year);
        while ordinal_day < 1 {
            year -= 1;
            leap_year = is_leap_year(year);
            ordinal_day += if leap_year { 366 } else { 365 };
        }
        let (month, day) = match leap_year {
            true => leap_year_month_day(ordinal_day),
            false => common_year_month_day(ordinal_day),
        };
        Ok(Self { year, month, day })
    }

    /// Parse a date from bytes, no check is performed for extract characters at the end of the string
    pub(crate) fn parse_bytes_partial(bytes: &[u8]) -> Result<Self, ParseError> {
        if bytes.len() < 10 {
            return Err(ParseError::TooShort);
        }
        let year: u16;
        let month: u8;
        let day: u8;
        unsafe {
            let y1 = get_digit_unchecked!(bytes, 0, InvalidCharYear) as u16;
            let y2 = get_digit_unchecked!(bytes, 1, InvalidCharYear) as u16;
            let y3 = get_digit_unchecked!(bytes, 2, InvalidCharYear) as u16;
            let y4 = get_digit_unchecked!(bytes, 3, InvalidCharYear) as u16;
            year = y1 * 1000 + y2 * 100 + y3 * 10 + y4;

            match bytes.get_unchecked(4) {
                b'-' => (),
                _ => return Err(ParseError::InvalidCharDateSep),
            }

            let m1 = get_digit_unchecked!(bytes, 5, InvalidCharMonth);
            let m2 = get_digit_unchecked!(bytes, 6, InvalidCharMonth);
            month = m1 * 10 + m2;

            match bytes.get_unchecked(7) {
                b'-' => (),
                _ => return Err(ParseError::InvalidCharDateSep),
            }

            let d1 = get_digit_unchecked!(bytes, 8, InvalidCharDay);
            let d2 = get_digit_unchecked!(bytes, 9, InvalidCharDay);
            day = d1 * 10 + d2;
        }

        // calculate the maximum number of days in the month, accounting for leap years in the
        // gregorian calendar
        let max_days = match month {
            1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
            4 | 6 | 9 | 11 => 30,
            2 => {
                if year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) {
                    29
                } else {
                    28
                }
            }
            _ => return Err(ParseError::OutOfRangeMonth),
        };

        if day < 1 || day > max_days {
            return Err(ParseError::OutOfRangeDay);
        }

        Ok(Self { year, month, day })
    }
}

fn is_leap_year(year: u16) -> bool {
    if year % 100 == 0 {
        year % 400 == 0
    } else {
        year % 4 == 0
    }
}

/// internal function to calculate the number of leap years since 1600, `delta_years` is the number of
/// years since 1600
fn intervening_leap_years(delta_years: u16) -> u16 {
    if delta_years == 0 {
        0
    } else {
        (delta_years - 1) / 4 - (delta_years - 1) / 100 + (delta_years - 1) / 400 + 1
    }
}

fn leap_year_month_day(day: i16) -> (u8, u8) {
    match day {
        1..=31 => (1, day as u8),
        32..=60 => (2, day as u8 - 31),
        61..=91 => (3, day as u8 - 60),
        92..=121 => (4, day as u8 - 91),
        122..=152 => (5, day as u8 - 121),
        153..=182 => (6, day as u8 - 152),
        183..=213 => (7, day as u8 - 182),
        214..=244 => (8, day as u8 - 213),
        245..=274 => (9, (day - 244) as u8),
        275..=305 => (10, (day - 274) as u8),
        306..=335 => (11, (day - 305) as u8),
        _ => (12, (day - 335) as u8),
    }
}

fn common_year_month_day(day: i16) -> (u8, u8) {
    match day {
        1..=31 => (1, day as u8),
        32..=59 => (2, day as u8 - 31),
        60..=90 => (3, day as u8 - 59),
        91..=120 => (4, day as u8 - 90),
        121..=151 => (5, day as u8 - 120),
        152..=181 => (6, day as u8 - 151),
        182..=212 => (7, day as u8 - 181),
        213..=243 => (8, day as u8 - 212),
        244..=273 => (9, (day - 243) as u8),
        274..=304 => (10, (day - 273) as u8),
        305..=334 => (11, (day - 304) as u8),
        _ => (12, (day - 334) as u8),
    }
}