lox-core 0.1.0-alpha.11

Common data types and utilities for the Lox ecosystem
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
// SPDX-FileCopyrightText: 2023 Angus Morrison <github@angus-morrison.com>
// SPDX-FileCopyrightText: 2023 Helge Eichhorn <git@helgeeichhorn.de>
//
// SPDX-License-Identifier: MPL-2.0

/*!
    `calendar_dates` exposes a concrete [Date] struct and the [CalendarDate] trait for working with
    human-readable dates.
*/

use std::{
    cmp::Ordering,
    fmt::{Display, Formatter},
    str::FromStr,
    sync::OnceLock,
};

use crate::time::deltas::TimeDelta;
use num::ToPrimitive;
use thiserror::Error;

use regex::Regex;

use super::julian_dates::{Epoch, JulianDate, Unit};
use crate::i64::consts::{SECONDS_PER_DAY, SECONDS_PER_HALF_DAY};

fn iso_regex() -> &'static Regex {
    static ISO: OnceLock<Regex> = OnceLock::new();
    ISO.get_or_init(|| Regex::new(r"(?<year>-?\d{4,})-(?<month>\d{2})-(?<day>\d{2})").unwrap())
}

/// Error type returned when attempting to construct a [Date] from invalid inputs.
#[derive(Debug, Clone, Error, PartialEq, Eq, PartialOrd, Ord)]
pub enum DateError {
    /// The given year, month, and day do not form a valid date.
    #[error("invalid date `{0}-{1}-{2}`")]
    InvalidDate(i64, u8, u8),
    /// The input string is not a valid ISO 8601 date.
    #[error("invalid ISO string `{0}`")]
    InvalidIsoString(String),
    /// Day 366 was requested for a non-leap year.
    #[error("day of year cannot be 366 for a non-leap year")]
    NonLeapYear,
}

/// The calendars supported by Lox.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Calendar {
    /// The Proleptic Julian calendar (year < 1).
    ProlepticJulian,
    /// The Julian calendar (year 1 to October 4, 1582).
    Julian,
    /// The Gregorian calendar (October 15, 1582 onwards).
    Gregorian,
}

/// A calendar date.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Date {
    calendar: Calendar,
    year: i64,
    month: u8,
    day: u8,
}

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

impl FromStr for Date {
    type Err = DateError;

    fn from_str(iso: &str) -> Result<Self, Self::Err> {
        Self::from_iso(iso)
    }
}

impl Default for Date {
    /// [Date] defaults to 2000-01-01 of the Gregorian calendar.
    fn default() -> Self {
        Self {
            calendar: Calendar::Gregorian,
            year: 2000,
            month: 1,
            day: 1,
        }
    }
}

impl PartialOrd for Date {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Date {
    // The implementation of `Ord` for `Date` assumes that the `Calendar`s of the inputs date are
    // the same. This assumption is true at 2024-03-30, since the `Date` constructor doesn't allow
    // the creation of overlapping dates in different calendars, and `Date`s are immutable.
    //
    // If this changes, the implementation of `Ord` for `Date` must be updated too.
    // See https://github.com/lox-space/lox/issues/87.
    fn cmp(&self, other: &Self) -> Ordering {
        match self.year.cmp(&other.year) {
            Ordering::Equal => match self.month.cmp(&other.month) {
                Ordering::Equal => self.day.cmp(&other.day),
                other => other,
            },
            other => other,
        }
    }
}

const LAST_PROLEPTIC_JULIAN_DAY_J2K: i64 = -730122;
const LAST_JULIAN_DAY_J2K: i64 = -152384;

impl Date {
    /// Returns the calendar system of this date.
    pub fn calendar(&self) -> Calendar {
        self.calendar
    }

    /// Returns the year.
    pub fn year(&self) -> i64 {
        self.year
    }

    /// Returns the month (1–12).
    pub fn month(&self) -> u8 {
        self.month
    }

    /// Returns the day of the month (1–31).
    pub fn day(&self) -> u8 {
        self.day
    }

    /// Construct a new [Date] from a year, month and day. The [Calendar] is inferred from the input
    /// fields.
    ///
    /// # Errors
    ///
    /// - [DateError::InvalidDate] if the input fields do not represent a valid date.
    pub fn new(year: i64, month: u8, day: u8) -> Result<Self, DateError> {
        if !(1..=12).contains(&month) {
            Err(DateError::InvalidDate(year, month, day))
        } else {
            let calendar = calendar(year, month, day);
            let check = Date::from_days_since_j2000(j2000_day_number(calendar, year, month, day));

            if check.year() != year || check.month() != month || check.day() != day {
                Err(DateError::InvalidDate(year, month, day))
            } else {
                Ok(Date {
                    calendar,
                    year,
                    month,
                    day,
                })
            }
        }
    }

    /// Constructs a new [Date] without validation. The [Calendar] is inferred.
    pub const fn new_unchecked(year: i64, month: u8, day: u8) -> Self {
        let calendar = calendar(year, month, day);
        Date {
            calendar,
            year,
            month,
            day,
        }
    }

    /// Constructs a new [Date] from an ISO 8601 string.
    ///
    /// # Errors
    ///
    /// - [DateError::InvalidIsoString] if the input string does not contain a valid ISO 8601 date.
    /// - [DateError::InvalidDate] if the date parsed from the ISO 8601 string is invalid.
    pub fn from_iso(iso: &str) -> Result<Self, DateError> {
        let caps = iso_regex()
            .captures(iso)
            .ok_or(DateError::InvalidIsoString(iso.to_owned()))?;
        let year: i64 = caps["year"]
            .parse()
            .map_err(|_| DateError::InvalidIsoString(iso.to_owned()))?;
        let month = caps["month"]
            .parse()
            .map_err(|_| DateError::InvalidIsoString(iso.to_owned()))?;
        let day = caps["day"]
            .parse()
            .map_err(|_| DateError::InvalidIsoString(iso.to_owned()))?;
        Date::new(year, month, day)
    }

    /// Constructs a new [Date] from a signed number of days since J2000. The [Calendar] is
    /// inferred.
    pub fn from_days_since_j2000(days: i64) -> Self {
        let calendar = if days < LAST_JULIAN_DAY_J2K {
            if days > LAST_PROLEPTIC_JULIAN_DAY_J2K {
                Calendar::Julian
            } else {
                Calendar::ProlepticJulian
            }
        } else {
            Calendar::Gregorian
        };

        let year = find_year(calendar, days);
        let leap = is_leap_year(calendar, year);
        let day_of_year = (days - last_day_of_year_j2k(calendar, year - 1)) as u16;
        let month = find_month(day_of_year, leap);
        let day = find_day(day_of_year, month, leap).unwrap_or_else(|err| {
            unreachable!("{} is not a valid day of the year: {}", day_of_year, err)
        });

        Date {
            calendar,
            year,
            month,
            day,
        }
    }

    /// Constructs a new [Date] from a signed number of seconds since J2000. The [Calendar] is
    /// inferred.
    pub fn from_seconds_since_j2000(seconds: i64) -> Self {
        let seconds = seconds + SECONDS_PER_HALF_DAY;
        let mut time = seconds % SECONDS_PER_DAY;
        if time < 0 {
            time += SECONDS_PER_DAY;
        }
        let days = (seconds - time) / SECONDS_PER_DAY;
        Self::from_days_since_j2000(days)
    }

    /// Constructs a new [Date] from a year and a day number within that year. The [Calendar] is
    /// inferred.
    ///
    /// # Errors
    ///
    /// - [DateError::NonLeapYear] if the input day number is 366 and the year is not a leap year.
    pub fn from_day_of_year(year: i64, day_of_year: u16) -> Result<Self, DateError> {
        let calendar = calendar(year, 1, 1);
        let leap = is_leap_year(calendar, year);
        let month = find_month(day_of_year, leap);
        let day = find_day(day_of_year, month, leap)?;

        Ok(Date {
            calendar,
            year,
            month,
            day,
        })
    }

    /// Returns the day number of `self` relative to J2000.
    pub const fn j2000_day_number(&self) -> i64 {
        j2000_day_number(self.calendar, self.year, self.month, self.day)
    }

    /// Converts this date to a [`TimeDelta`] relative to J2000.
    pub const fn to_delta(&self) -> TimeDelta {
        let seconds = self.j2000_day_number() * SECONDS_PER_DAY - SECONDS_PER_HALF_DAY;
        TimeDelta::from_seconds(seconds)
    }
}

impl JulianDate for Date {
    fn julian_date(&self, epoch: Epoch, unit: Unit) -> f64 {
        self.to_delta().julian_date(epoch, unit)
    }
}

fn find_year(calendar: Calendar, j2000day: i64) -> i64 {
    match calendar {
        Calendar::ProlepticJulian => -((-4 * j2000day - 2920488) / 1461),
        Calendar::Julian => -((-4 * j2000day - 2921948) / 1461),
        Calendar::Gregorian => {
            let year = (400 * j2000day + 292194288) / 146097;
            if j2000day <= last_day_of_year_j2k(Calendar::Gregorian, year - 1) {
                year - 1
            } else {
                year
            }
        }
    }
}

const fn last_day_of_year_j2k(calendar: Calendar, year: i64) -> i64 {
    match calendar {
        Calendar::ProlepticJulian => 365 * year + (year + 1) / 4 - 730123,
        Calendar::Julian => 365 * year + year / 4 - 730122,
        Calendar::Gregorian => 365 * year + year / 4 - year / 100 + year / 400 - 730120,
    }
}

const fn is_leap_year(calendar: Calendar, year: i64) -> bool {
    match calendar {
        Calendar::ProlepticJulian | Calendar::Julian => year % 4 == 0,
        Calendar::Gregorian => year % 4 == 0 && (year % 400 == 0 || year % 100 != 0),
    }
}

const PREVIOUS_MONTH_END_DAY_LEAP: [u16; 12] =
    [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335];

const PREVIOUS_MONTH_END_DAY: [u16; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];

fn find_month(day_in_year: u16, is_leap: bool) -> u8 {
    let offset = if is_leap { 313 } else { 323 };
    let month = if day_in_year < 32 {
        1
    } else {
        (10 * day_in_year + offset) / 306
    };
    month
        .to_u8()
        .unwrap_or_else(|| unreachable!("month could not be represented as u8: {}", month))
}

fn find_day(day_in_year: u16, month: u8, is_leap: bool) -> Result<u8, DateError> {
    if !is_leap && day_in_year > 365 {
        Err(DateError::NonLeapYear)
    } else {
        let previous_days = if is_leap {
            PREVIOUS_MONTH_END_DAY_LEAP
        } else {
            PREVIOUS_MONTH_END_DAY
        };
        let day = day_in_year - previous_days[(month - 1) as usize];
        Ok(day
            .to_u8()
            .unwrap_or_else(|| unreachable!("day could not be represented as u8: {}", day)))
    }
}

const fn find_day_in_year(month: u8, day: u8, is_leap: bool) -> u16 {
    let previous_days = if is_leap {
        PREVIOUS_MONTH_END_DAY_LEAP
    } else {
        PREVIOUS_MONTH_END_DAY
    };
    day as u16 + previous_days[(month - 1) as usize]
}

const fn calendar(year: i64, month: u8, day: u8) -> Calendar {
    if year < 1583 {
        if year < 1 {
            Calendar::ProlepticJulian
        } else if year < 1582 || month < 10 || (month < 11 && day < 5) {
            Calendar::Julian
        } else {
            Calendar::Gregorian
        }
    } else {
        Calendar::Gregorian
    }
}

const fn j2000_day_number(calendar: Calendar, year: i64, month: u8, day: u8) -> i64 {
    let d1 = last_day_of_year_j2k(calendar, year - 1);
    let d2 = find_day_in_year(month, day, is_leap_year(calendar, year));
    d1 + d2 as i64
}

/// `CalendarDate` allows any date-time format to report its date in a human-readable way.
pub trait CalendarDate {
    /// Returns the date component.
    fn date(&self) -> Date;

    /// Returns the year.
    fn year(&self) -> i64 {
        self.date().year()
    }

    /// Returns the month (1–12).
    fn month(&self) -> u8 {
        self.date().month()
    }

    /// Returns the day of the month (1–31).
    fn day(&self) -> u8 {
        self.date().day()
    }

    /// Returns the day number within the year (1–366).
    fn day_of_year(&self) -> u16 {
        let date = self.date();
        let leap = is_leap_year(date.calendar(), date.year());
        find_day_in_year(date.month(), date.day(), leap)
    }
}

#[cfg(test)]
mod tests {
    use crate::f64::consts::{DAYS_PER_JULIAN_CENTURY, SECONDS_PER_JULIAN_CENTURY};
    use rstest::rstest;

    use super::*;

    #[rstest]
    #[case::equal_same_calendar(Date { calendar: Calendar::Gregorian, year: 2000, month: 1, day: 1}, Date { calendar: Calendar::Gregorian, year: 2000, month: 1, day: 1}, Ordering::Equal)]
    #[case::equal_different_calendar(Date { calendar: Calendar::Gregorian, year: 2000, month: 1, day: 1}, Date { calendar: Calendar::Julian, year: 2000, month: 1, day: 1}, Ordering::Equal)]
    #[case::less_than_year(Date { calendar: Calendar::Gregorian, year: 1999, month: 1, day: 1}, Date { calendar: Calendar::Gregorian, year: 2000, month: 1, day: 1}, Ordering::Less)]
    #[case::less_than_month(Date { calendar: Calendar::Gregorian, year: 2000, month: 1, day: 1}, Date { calendar: Calendar::Gregorian, year: 2000, month: 2, day: 1}, Ordering::Less)]
    #[case::less_than_day(Date { calendar: Calendar::Gregorian, year: 2000, month: 1, day: 1}, Date { calendar: Calendar::Gregorian, year: 2000, month: 1, day: 2}, Ordering::Less)]
    #[case::greater_than_year(Date { calendar: Calendar::Gregorian, year: 2001, month: 1, day: 1}, Date { calendar: Calendar::Gregorian, year: 2000, month: 1, day: 1}, Ordering::Greater)]
    #[case::greater_than_month(Date { calendar: Calendar::Gregorian, year: 2000, month: 2, day: 1}, Date { calendar: Calendar::Gregorian, year: 2000, month: 1, day: 1}, Ordering::Greater)]
    #[case::greater_than_day(Date { calendar: Calendar::Gregorian, year: 2000, month: 1, day: 2}, Date { calendar: Calendar::Gregorian, year: 2000, month: 1, day: 1}, Ordering::Greater)]
    fn test_date_ord(#[case] lhs: Date, #[case] rhs: Date, #[case] expected: Ordering) {
        assert_eq!(expected, lhs.cmp(&rhs));
    }

    #[rstest]
    #[case::j2000("2000-01-01", Date { calendar: Calendar::Gregorian, year: 2000, month: 1, day: 1})]
    #[case::j2000("0000-01-01", Date { calendar: Calendar::ProlepticJulian, year: 0, month: 1, day: 1})]
    fn test_date_iso(#[case] str: &str, #[case] expected: Date) {
        let actual = Date::from_iso(str).expect("date should parse");
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_date_unchecked() {
        let date = Date::new_unchecked(2026, 2, 11);
        assert_eq!(date.calendar, Calendar::Gregorian);
        assert_eq!(date.year, 2026);
        assert_eq!(date.month, 2);
        assert_eq!(date.day, 11);
    }

    #[test]
    fn test_date_from_day_of_year() {
        let date = Date::from_day_of_year(2000, 366).unwrap();
        assert_eq!(date.year(), 2000);
        assert_eq!(date.month(), 12);
        assert_eq!(date.day(), 31);
    }

    #[test]
    fn test_date_from_invalid_day_of_year() {
        let actual = Date::from_day_of_year(2001, 366);
        let expected = Err(DateError::NonLeapYear);
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_date_jd_epoch() {
        let date = Date::default();
        assert_eq!(date.days_since_julian_epoch(), 2451544.5);
    }

    #[test]
    fn test_date_julian_date() {
        let date = Date::default();
        assert_eq!(date.days_since_julian_epoch(), 2451544.5);

        let date = Date::new(2100, 1, 1).unwrap();
        assert_eq!(
            date.seconds_since_j2000(),
            SECONDS_PER_JULIAN_CENTURY - SECONDS_PER_HALF_DAY as f64
        );
        assert_eq!(date.days_since_j2000(), DAYS_PER_JULIAN_CENTURY - 0.5);
        assert_eq!(
            date.centuries_since_j2000(),
            1.0 - 0.5 / DAYS_PER_JULIAN_CENTURY
        );
        assert_eq!(
            date.centuries_since_j1950(),
            1.5 - 0.5 / DAYS_PER_JULIAN_CENTURY
        );
        assert_eq!(
            date.centuries_since_modified_julian_epoch(),
            2.411211498973306 - 0.5 / DAYS_PER_JULIAN_CENTURY
        );
        assert_eq!(
            date.centuries_since_julian_epoch(),
            68.11964407939767 - 0.5 / DAYS_PER_JULIAN_CENTURY
        );
    }
}