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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
#[allow(unused_imports)]
/*
* Hifitime
* Copyright (C) 2017-onward Christopher Rabotin <christopher.rabotin@gmail.com> et al. (cf. https://github.com/nyx-space/hifitime/graphs/contributors)
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* Documentation: https://nyxspace.com/
*/
use crate::errors::DurationError;
#[allow(unused_imports)]
use crate::parser::Token;
#[allow(unused_imports)]
use crate::{
Duration, Epoch, HifitimeError, ParsingError, TimeScale, Unit, DAYS_PER_YEAR_NLD,
HIFITIME_REF_YEAR, NANOSECONDS_PER_DAY, NANOSECONDS_PER_HOUR, NANOSECONDS_PER_MINUTE,
NANOSECONDS_PER_SECOND, NANOSECONDS_PER_SECOND_U32,
};
#[allow(unused_imports)]
use core::str::FromStr;
impl Epoch {
const DAYS_FROM_J1900_TO_UNIX_EPOCH: i128 = 25_567;
// Integer civil date conversion adapted from Howard Hinnant's `civil_from_days`
// algorithm, using a J1900 day count instead of the original Unix-epoch day count:
// https://howardhinnant.github.io/date_algorithms.html#civil_from_days
//
// The derivation works in a March-based year, where March is month 0 and February
// is month 11. That moves leap day to the end of the year, which makes the
// Gregorian pattern regular enough to recover year/month/day with integer math:
// - shift the serial day count to 0000-03-01,
// - split it into a 400-year Gregorian era (`146_097` days),
// - recover the year-of-era, then the day-of-year,
// - map the March-based day-of-year back to month/day.
fn civil_from_days_since_j1900(days_since_j1900: i128) -> (i32, u8, u8) {
// Translate our J1900 serial day into the same `z` Hinnant starts from
// (days since 1970-01-01), then apply the standard shift to 0000-03-01.
let z = days_since_j1900 - Self::DAYS_FROM_J1900_TO_UNIX_EPOCH;
let z = z + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
// `doe` is the day-of-era in [0, 146096]. `yoe` is the year-of-era in [0, 399].
// The correction terms account for the leap-day structure inside one Gregorian
// era: every 4th year is leap, century years are not, and every 400th year is.
let yoe = (doe - doe.div_euclid(1_460) + doe.div_euclid(36_524) - doe.div_euclid(146_096))
.div_euclid(365);
let mut year = yoe + era * 400;
let doy = doe - (365 * yoe + yoe.div_euclid(4) - yoe.div_euclid(100));
// `mp` is a March-based month index in [0, 11]. The `(5 * doy + 2) / 153`
// expression is the inverse of the March-based day-of-year table used in
// `days_from_civil`; the divisor `153` comes from the repeating 31/30 month
// pattern over five-month blocks in that shifted calendar.
let mp = (5 * doy + 2).div_euclid(153);
let day = doy - (153 * mp + 2).div_euclid(5) + 1;
let month = mp + if mp < 10 { 3 } else { -9 };
// January and February belong to the following civil year, because internally
// the year still begins on March 1.
if month <= 2 {
year += 1;
}
(
year as i32,
u8::try_from(month).expect("month must fit in u8"),
u8::try_from(day).expect("day must fit in u8"),
)
}
pub(crate) fn compute_gregorian(
duration: Duration,
time_scale: TimeScale,
) -> (i32, u8, u8, u8, u8, u8, u32) {
let duration_wrt_ref = duration + time_scale.gregorian_epoch_offset();
let (days, ns_of_day) = if duration_wrt_ref.signum() < 0 {
let magnitude = (-duration_wrt_ref).total_nanoseconds();
let whole_days = magnitude.div_euclid(i128::from(NANOSECONDS_PER_DAY));
let rem_ns = magnitude.rem_euclid(i128::from(NANOSECONDS_PER_DAY));
if rem_ns == 0 {
(-whole_days, 0)
} else {
(-whole_days - 1, i128::from(NANOSECONDS_PER_DAY) - rem_ns)
}
} else {
let total_ns = duration_wrt_ref.total_nanoseconds();
(
total_ns.div_euclid(i128::from(NANOSECONDS_PER_DAY)),
total_ns.rem_euclid(i128::from(NANOSECONDS_PER_DAY)),
)
};
let (year, month, day) = Self::civil_from_days_since_j1900(days);
let hours = ns_of_day.div_euclid(i128::from(NANOSECONDS_PER_HOUR));
let rem_after_hours = ns_of_day.rem_euclid(i128::from(NANOSECONDS_PER_HOUR));
let minutes = rem_after_hours.div_euclid(i128::from(NANOSECONDS_PER_MINUTE));
let rem_after_minutes = rem_after_hours.rem_euclid(i128::from(NANOSECONDS_PER_MINUTE));
let seconds = rem_after_minutes.div_euclid(i128::from(NANOSECONDS_PER_SECOND));
let nanos = rem_after_minutes.rem_euclid(i128::from(NANOSECONDS_PER_SECOND));
(
year,
month,
day,
hours as u8,
minutes as u8,
seconds as u8,
nanos as u32,
)
}
#[cfg(feature = "std")]
#[must_use]
/// Converts the Epoch to Gregorian in the provided time scale and in the ISO8601 format with the time scale appended to the string
pub fn to_gregorian_str(&self, time_scale: TimeScale) -> String {
let (y, mm, dd, hh, min, s, nanos) =
Self::compute_gregorian(self.to_duration_in_time_scale(time_scale), time_scale);
if nanos == 0 {
format!("{y:04}-{mm:02}-{dd:02}T{hh:02}:{min:02}:{s:02} {time_scale}")
} else {
format!("{y:04}-{mm:02}-{dd:02}T{hh:02}:{min:02}:{s:02}.{nanos:09} {time_scale}")
}
}
#[must_use]
/// Converts the Epoch to the Gregorian UTC equivalent as (year, month, day, hour, minute, second, nanoseconds).
///
/// # Example
/// ```
/// use hifitime::Epoch;
///
/// let dt_tai = Epoch::from_tai_parts(1, 537582752000000000);
///
/// let dt_str = "2017-01-14T00:31:55 UTC";
/// let dt = Epoch::from_gregorian_str(dt_str).unwrap();
///
/// let (y, m, d, h, min, s, _) = dt_tai.to_gregorian_utc();
/// assert_eq!(y, 2017);
/// assert_eq!(m, 1);
/// assert_eq!(d, 14);
/// assert_eq!(h, 0);
/// assert_eq!(min, 31);
/// assert_eq!(s, 55);
/// #[cfg(feature = "std")]
/// {
/// assert_eq!("2017-01-14T00:31:55 UTC", format!("{dt_tai:?}"));
/// // dt_tai is initialized from TAI, so the default print is the Gregorian in that time system
/// assert_eq!("2017-01-14T00:32:32 TAI", format!("{dt_tai}"));
/// // But dt is initialized from UTC, so the default print and the debug print are both in UTC.
/// assert_eq!("2017-01-14T00:31:55 UTC", format!("{dt}"));
/// }
/// ```
pub fn to_gregorian_utc(&self) -> (i32, u8, u8, u8, u8, u8, u32) {
let ts = TimeScale::UTC;
Self::compute_gregorian(self.to_duration_in_time_scale(ts), ts)
}
#[must_use]
/// Converts the Epoch to the Gregorian TAI equivalent as (year, month, day, hour, minute, second, nanoseconds).
///
/// # Example
/// ```
/// use hifitime::Epoch;
/// let dt = Epoch::from_gregorian_tai_at_midnight(1972, 1, 1);
/// let (y, m, d, h, min, s, _) = dt.to_gregorian_tai();
/// assert_eq!(y, 1972);
/// assert_eq!(m, 1);
/// assert_eq!(d, 1);
/// assert_eq!(h, 0);
/// assert_eq!(min, 0);
/// assert_eq!(s, 0);
/// ```
pub fn to_gregorian_tai(&self) -> (i32, u8, u8, u8, u8, u8, u32) {
let ts = TimeScale::TAI;
Self::compute_gregorian(self.to_duration_in_time_scale(ts), ts)
}
#[must_use]
/// Converts the Epoch to the Gregorian in the provided time scale as (year, month, day, hour, minute, second, nanoseconds).
///
/// # Example
/// ```
/// use hifitime::{Epoch, TimeScale};
/// let dt = Epoch::from_gregorian_tai_at_midnight(1972, 1, 1);
/// let (y, m, d, h, min, s, n) = dt.to_gregorian(TimeScale::TAI);
/// assert_eq!(y, 1972);
/// assert_eq!(m, 1);
/// assert_eq!(d, 1);
/// assert_eq!(h, 0);
/// assert_eq!(min, 0);
/// assert_eq!(s, 0);
/// assert_eq!(n, 0);
///
/// // The epoch will be converted to UTC prior to returning the Gregorian parts.
/// let (y, m, d, h, min, s, n) = dt.to_gregorian(TimeScale::UTC);
/// assert_eq!(y, 1971);
/// assert_eq!(m, 12);
/// assert_eq!(d, 31);
/// assert_eq!(h, 23);
/// assert_eq!(min, 59);
/// assert_eq!(s, 50);
/// assert_eq!(n, 0);
/// ```
pub fn to_gregorian(&self, time_scale: TimeScale) -> (i32, u8, u8, u8, u8, u8, u32) {
Self::compute_gregorian(self.to_duration_in_time_scale(time_scale), time_scale)
}
/// Attempts to build an Epoch from the provided Gregorian date and time in TAI.
pub fn maybe_from_gregorian_tai(
year: i32,
month: u8,
day: u8,
hour: u8,
minute: u8,
second: u8,
nanos: u32,
) -> Result<Self, HifitimeError> {
Self::maybe_from_gregorian(
year,
month,
day,
hour,
minute,
second,
nanos,
TimeScale::TAI,
)
}
/// Attempts to build an Epoch from the provided Gregorian date and time in the provided time scale.
///
/// Note:
/// The month is ONE indexed, i.e. January is month 1 and December is month 12.
#[allow(clippy::too_many_arguments)]
pub fn maybe_from_gregorian(
year: i32,
month: u8,
day: u8,
hour: u8,
minute: u8,
second: u8,
nanos: u32,
time_scale: TimeScale,
) -> Result<Self, HifitimeError> {
if !is_gregorian_valid(year, month, day, hour, minute, second, nanos)
|| (second == 60 && !time_scale.uses_leap_seconds())
{
return Err(HifitimeError::InvalidGregorianDate);
}
let mut duration_wrt_ref = match year.checked_sub(HIFITIME_REF_YEAR) {
None => {
return Err(HifitimeError::Duration {
source: DurationError::Underflow,
})
}
Some(years_since_ref) => match years_since_ref.checked_mul(DAYS_PER_YEAR_NLD as i32) {
None => {
return Err(HifitimeError::Duration {
source: DurationError::Overflow,
})
}
Some(days) => {
// Initialize the duration as the number of days since the reference year (may be negative).
Unit::Day * i64::from(days)
}
},
};
// Now add the leap days for all the years prior to the current year
if year >= HIFITIME_REF_YEAR {
// Add days until, but not including, current year.
let mut y = HIFITIME_REF_YEAR;
#[cfg_attr(kani, kani::loop_invariant(y >= HIFITIME_REF_YEAR && y <= year))]
while y < year {
if is_leap_year(y) {
duration_wrt_ref += Unit::Day;
}
y += 1;
}
} else {
// Remove days
let mut y = year;
#[cfg_attr(kani, kani::loop_invariant(y >= year && y <= HIFITIME_REF_YEAR))]
while y < HIFITIME_REF_YEAR {
if is_leap_year(y) {
duration_wrt_ref -= Unit::Day;
}
y += 1;
}
}
// Add the seconds for the months prior to the current month.
// Correctly accounts for the number of days based on whether this is a leap year or not.
let cumul_days = if is_leap_year(year) {
CUMULATIVE_DAYS_FOR_MONTH_LEAP_YEARS
} else {
CUMULATIVE_DAYS_FOR_MONTH
};
// Add the number of days based on the input month
duration_wrt_ref += Unit::Day * i64::from(cumul_days[(month - 1) as usize]);
// Add the number of days based on the input day and time.
duration_wrt_ref += Unit::Day * i64::from(day - 1)
+ Unit::Hour * i64::from(hour)
+ Unit::Minute * i64::from(minute)
+ Unit::Second * i64::from(second)
+ Unit::Nanosecond * i64::from(nanos);
if second == 60 {
// Herein lies the whole ambiguity of leap seconds. Two different UTC dates exist at the
// same number of second after J1900.0.
duration_wrt_ref -= Unit::Second;
}
// Account for this time scale's Gregorian offset.
duration_wrt_ref -= time_scale.gregorian_epoch_offset();
Ok(Self {
duration: duration_wrt_ref,
time_scale,
})
}
#[must_use]
/// Builds an Epoch from the provided Gregorian date and time in TAI. If invalid date is provided, this function will panic.
/// Use maybe_from_gregorian_tai if unsure.
#[cfg_attr(kani, kani::ensures(|result| result.time_scale == crate::TimeScale::TAI))]
pub fn from_gregorian_tai(
year: i32,
month: u8,
day: u8,
hour: u8,
minute: u8,
second: u8,
nanos: u32,
) -> Self {
Self::maybe_from_gregorian_tai(year, month, day, hour, minute, second, nanos)
.expect("invalid Gregorian date")
}
#[must_use]
/// Initialize from the Gregorian date at midnight in TAI.
#[cfg_attr(kani, kani::ensures(|result| result.time_scale == crate::TimeScale::TAI))]
pub fn from_gregorian_tai_at_midnight(year: i32, month: u8, day: u8) -> Self {
Self::maybe_from_gregorian_tai(year, month, day, 0, 0, 0, 0)
.expect("invalid Gregorian date")
}
#[must_use]
/// Initialize from the Gregorian date at noon in TAI
#[cfg_attr(kani, kani::ensures(|result| result.time_scale == crate::TimeScale::TAI))]
pub fn from_gregorian_tai_at_noon(year: i32, month: u8, day: u8) -> Self {
Self::maybe_from_gregorian_tai(year, month, day, 12, 0, 0, 0)
.expect("invalid Gregorian date")
}
#[must_use]
/// Initialize from the Gregorian date and time (without the nanoseconds) in TAI
#[cfg_attr(kani, kani::ensures(|result| result.time_scale == crate::TimeScale::TAI))]
pub fn from_gregorian_tai_hms(
year: i32,
month: u8,
day: u8,
hour: u8,
minute: u8,
second: u8,
) -> Self {
Self::maybe_from_gregorian_tai(year, month, day, hour, minute, second, 0)
.expect("invalid Gregorian date")
}
/// Attempts to build an Epoch from the provided Gregorian date and time in UTC.
pub fn maybe_from_gregorian_utc(
year: i32,
month: u8,
day: u8,
hour: u8,
minute: u8,
second: u8,
nanos: u32,
) -> Result<Self, HifitimeError> {
Self::maybe_from_gregorian(
year,
month,
day,
hour,
minute,
second,
nanos,
TimeScale::UTC,
)
}
#[must_use]
/// Builds an Epoch from the provided Gregorian date and time in UTC. If invalid date is provided, this function will panic.
/// Use maybe_from_gregorian_utc if unsure.
#[cfg_attr(kani, kani::ensures(|result| result.time_scale == crate::TimeScale::UTC))]
pub fn from_gregorian_utc(
year: i32,
month: u8,
day: u8,
hour: u8,
minute: u8,
second: u8,
nanos: u32,
) -> Self {
Self::maybe_from_gregorian_utc(year, month, day, hour, minute, second, nanos)
.expect("invalid Gregorian date")
}
#[must_use]
/// Initialize from Gregorian date in UTC at midnight
#[cfg_attr(kani, kani::ensures(|result| result.time_scale == crate::TimeScale::UTC))]
pub fn from_gregorian_utc_at_midnight(year: i32, month: u8, day: u8) -> Self {
Self::maybe_from_gregorian_utc(year, month, day, 0, 0, 0, 0)
.expect("invalid Gregorian date")
}
#[must_use]
/// Initialize from Gregorian date in UTC at noon
#[cfg_attr(kani, kani::ensures(|result| result.time_scale == crate::TimeScale::UTC))]
pub fn from_gregorian_utc_at_noon(year: i32, month: u8, day: u8) -> Self {
Self::maybe_from_gregorian_utc(year, month, day, 12, 0, 0, 0)
.expect("invalid Gregorian date")
}
#[must_use]
/// Initialize from the Gregorian date and time (without the nanoseconds) in UTC
#[cfg_attr(kani, kani::ensures(|result| result.time_scale == crate::TimeScale::UTC))]
pub fn from_gregorian_utc_hms(
year: i32,
month: u8,
day: u8,
hour: u8,
minute: u8,
second: u8,
) -> Self {
Self::maybe_from_gregorian_utc(year, month, day, hour, minute, second, 0)
.expect("invalid Gregorian date")
}
#[allow(clippy::too_many_arguments)]
#[must_use]
/// Builds an Epoch from the provided Gregorian date and time in the provided time scale. If invalid date is provided, this function will panic.
/// Use maybe_from_gregorian if unsure.
#[cfg_attr(kani, kani::ensures(|result| result.time_scale == time_scale))]
pub fn from_gregorian(
year: i32,
month: u8,
day: u8,
hour: u8,
minute: u8,
second: u8,
nanos: u32,
time_scale: TimeScale,
) -> Self {
Self::maybe_from_gregorian(year, month, day, hour, minute, second, nanos, time_scale)
.expect("invalid Gregorian date")
}
#[must_use]
/// Initialize from Gregorian date in UTC at midnight
pub fn from_gregorian_at_midnight(
year: i32,
month: u8,
day: u8,
time_scale: TimeScale,
) -> Self {
Self::maybe_from_gregorian(year, month, day, 0, 0, 0, 0, time_scale)
.expect("invalid Gregorian date")
}
#[must_use]
/// Initialize from Gregorian date in UTC at noon
pub fn from_gregorian_at_noon(year: i32, month: u8, day: u8, time_scale: TimeScale) -> Self {
Self::maybe_from_gregorian(year, month, day, 12, 0, 0, 0, time_scale)
.expect("invalid Gregorian date")
}
#[must_use]
/// Initialize from the Gregorian date and time (without the nanoseconds) in UTC
pub fn from_gregorian_hms(
year: i32,
month: u8,
day: u8,
hour: u8,
minute: u8,
second: u8,
time_scale: TimeScale,
) -> Self {
Self::maybe_from_gregorian(year, month, day, hour, minute, second, 0, time_scale)
.expect("invalid Gregorian date")
}
/// Converts a Gregorian date time in ISO8601 or RFC3339 format into an Epoch, accounting for the time zone designator and the time scale.
///
/// # Definition
/// 1. Time Zone Designator: this is either a `Z` (lower or upper case) to specify UTC, or an offset in hours and minutes off of UTC, such as `+01:00` for UTC plus one hour and zero minutes.
/// 2. Time system (or time "scale"): UTC, TT, TAI, TDB, ET, etc.
///
/// Converts an ISO8601 or RFC3339 datetime representation to an Epoch.
/// If no time scale is specified, then UTC is assumed.
/// A time scale may be specified _in addition_ to the format unless
/// The `T` which separates the date from the time can be replaced with a single whitespace character (`\W`).
/// The offset is also optional, cf. the examples below.
///
/// # Example
/// ```
/// use hifitime::Epoch;
/// let dt = Epoch::from_gregorian_utc(2017, 1, 14, 0, 31, 55, 0);
/// assert_eq!(
/// dt,
/// Epoch::from_gregorian_str("2017-01-14T00:31:55 UTC").unwrap()
/// );
/// assert_eq!(
/// dt,
/// Epoch::from_gregorian_str("2017-01-14T00:31:55.0000 UTC").unwrap()
/// );
/// assert_eq!(
/// dt,
/// Epoch::from_gregorian_str("2017-01-14T00:31:55").unwrap()
/// );
/// assert_eq!(
/// dt,
/// Epoch::from_gregorian_str("2017-01-14 00:31:55").unwrap()
/// );
/// // Regression test for #90
/// assert_eq!(
/// Epoch::from_gregorian_utc(2017, 1, 14, 0, 31, 55, 811000000),
/// Epoch::from_gregorian_str("2017-01-14 00:31:55.811 UTC").unwrap()
/// );
/// assert_eq!(
/// Epoch::from_gregorian_utc(2017, 1, 14, 0, 31, 55, 811200000),
/// Epoch::from_gregorian_str("2017-01-14 00:31:55.8112 UTC").unwrap()
/// );
/// // Example from https://www.w3.org/TR/NOTE-datetime
/// assert_eq!(
/// Epoch::from_gregorian_utc_hms(1994, 11, 5, 13, 15, 30),
/// Epoch::from_gregorian_str("1994-11-05T13:15:30Z").unwrap()
/// );
/// assert_eq!(
/// Epoch::from_gregorian_utc_hms(1994, 11, 5, 13, 15, 30),
/// Epoch::from_gregorian_str("1994-11-05T08:15:30-05:00").unwrap()
/// );
/// ```
#[cfg(not(kani))]
pub fn from_gregorian_str(s_in: &str) -> Result<Self, HifitimeError> {
// All of the integers in a date: year, month, day, hour, minute, second, subsecond, offset hours, offset minutes
use snafu::ResultExt;
use crate::errors::ParseSnafu;
let mut decomposed = [0_i32; 9];
// The parsed time scale, defaults to UTC
let mut ts = TimeScale::UTC;
// The offset sign, defaults to positive.
let mut offset_sign = 1;
// Previous index of interest in the string
let mut prev_idx = 0;
let mut cur_token = Token::Year;
let s = s_in.trim();
for (idx, char) in s.char_indices() {
if !char.is_numeric() || idx == s.len() - 1 {
if cur_token == Token::Timescale {
// Then we match the timescale directly.
if idx != s.len() - 1 {
// We have some remaining characters, so let's parse those in the only formats we know.
ts = TimeScale::from_str(s[idx..].trim()).with_context(|_| ParseSnafu {
details: "parsing as Gregorian date with time scale",
})?;
}
break;
}
let prev_token = cur_token;
let pos = cur_token.gregorian_position().unwrap();
let end_idx = if idx != s.len() - 1 || !char.is_numeric() {
// Only advance the token if we aren't at the end of the string
cur_token.advance_with(char)?;
idx
} else {
idx + 1
};
if prev_idx > end_idx {
return Err(HifitimeError::Parse {
source: ParsingError::ISO8601,
details: "parsing as Gregorian",
});
}
match lexical_core::parse(&s.as_bytes()[prev_idx..end_idx]) {
Ok(val) => {
// Check that this valid is OK for the token we're reading it as.
prev_token.value_ok(val)?;
// If these are the subseconds, we must convert them to nanoseconds
if prev_token == Token::Subsecond {
if end_idx - prev_idx != 9 {
decomposed[pos] =
val * 10_i32.pow((9 - (end_idx - prev_idx)) as u32);
} else {
decomposed[pos] = val;
}
} else {
decomposed[pos] = val
}
}
Err(err) => {
return Err(HifitimeError::Parse {
source: ParsingError::Lexical { err },
details: "parsing as Gregorian",
})
}
}
prev_idx = idx + 1;
// If we are about to parse an hours offset, we need to set the sign now.
if cur_token == Token::OffsetHours {
if &s[idx..idx + 1] == "-" {
offset_sign = -1;
}
prev_idx += 1;
}
}
}
let tz = if offset_sign > 0 {
// We oppose the sign in the string to undo the offset
-(i64::from(decomposed[7]) * Unit::Hour + i64::from(decomposed[8]) * Unit::Minute)
} else {
i64::from(decomposed[7]) * Unit::Hour + i64::from(decomposed[8]) * Unit::Minute
};
let epoch = Self::maybe_from_gregorian(
decomposed[0],
decomposed[1].try_into().unwrap(),
decomposed[2].try_into().unwrap(),
decomposed[3].try_into().unwrap(),
decomposed[4].try_into().unwrap(),
decomposed[5].try_into().unwrap(),
decomposed[6].try_into().unwrap(),
ts,
)?;
Ok(epoch + tz)
}
}
#[must_use]
/// Returns true if the provided Gregorian date is valid. Leap second days may have 60 seconds.
pub const fn is_gregorian_valid(
year: i32,
month: u8,
day: u8,
hour: u8,
minute: u8,
second: u8,
nanos: u32,
) -> bool {
let max_seconds = if (month == 12 || month == 6)
&& day == usual_days_per_month(month)
&& hour == 23
&& minute == 59
&& ((month == 6 && july_years(year)) || (month == 12 && january_years(year + 1)))
{
60
} else {
59
};
// General incorrect date times
if month == 0
|| month > 12
|| day == 0
|| day > 31
|| hour > 24
|| minute > 59
|| second > max_seconds
|| nanos > NANOSECONDS_PER_SECOND_U32
{
return false;
}
let days_per_month = if month == 2 && is_leap_year(year) {
29
} else {
usual_days_per_month(month)
};
if day > days_per_month {
return false;
}
true
}
/// Years when January had the leap second
const fn january_years(year: i32) -> bool {
matches!(
year,
1972 | 1973
| 1974
| 1975
| 1976
| 1977
| 1978
| 1979
| 1980
| 1988
| 1990
| 1991
| 1996
| 1999
| 2006
| 2009
| 2017
)
}
/// Years when July had the leap second
const fn july_years(year: i32) -> bool {
matches!(
year,
1972 | 1981 | 1982 | 1983 | 1985 | 1992 | 1993 | 1994 | 1997 | 2012 | 2015
)
}
/// Returns the usual days in a given month (ONE indexed, i.e. January is month ONE and December is month 12)
///
/// # Warning
/// This will return 0 days if the month is invalid.
const fn usual_days_per_month(month: u8) -> u8 {
match month {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 => 28,
_ => 0,
}
}
/// Calculates the prefix-sum of days counted up to the month start
const CUMULATIVE_DAYS_FOR_MONTH: [u16; 12] = {
let mut days = [0; 12];
let mut month = 1;
while month < 12 {
days[month] = days[month - 1] + usual_days_per_month(month as u8) as u16;
month += 1;
}
days
};
/// Calculates the prefix-sum of days counted up to the month start, for leap years only
const CUMULATIVE_DAYS_FOR_MONTH_LEAP_YEARS: [u16; 12] = {
let mut days = [0; 12];
let mut month = 1;
while month < 12 {
days[month] = days[month - 1] + usual_days_per_month(month as u8) as u16;
if month == 2 {
days[month] += 1;
}
month += 1;
}
days
};
/// `is_leap_year` returns whether the provided year is a leap year or not.
/// Tests for this function are part of the Datetime tests.
pub(crate) const fn is_leap_year(year: i32) -> bool {
(year % 4 == 0 && year % 100 != 0) || year % 400 == 0
}
#[cfg(test)]
mod ut_gregorian {
use crate::epoch::gregorian::{is_leap_year, CUMULATIVE_DAYS_FOR_MONTH};
#[test]
fn cumulative_days_for_month() {
assert_eq!(
CUMULATIVE_DAYS_FOR_MONTH,
[0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
)
}
#[test]
fn leap_year() {
assert!(!is_leap_year(2019));
assert!(!is_leap_year(2001));
assert!(!is_leap_year(1000));
// List of leap years from https://kalender-365.de/leap-years.php .
let leap_years: [i32; 146] = [
1804, 1808, 1812, 1816, 1820, 1824, 1828, 1832, 1836, 1840, 1844, 1848, 1852, 1856,
1860, 1864, 1868, 1872, 1876, 1880, 1884, 1888, 1892, 1896, 1904, 1908, 1912, 1916,
1920, 1924, 1928, 1932, 1936, 1940, 1944, 1948, 1952, 1956, 1960, 1964, 1968, 1972,
1976, 1980, 1984, 1988, 1992, 1996, 2000, 2004, 2008, 2012, 2016, 2020, 2024, 2028,
2032, 2036, 2040, 2044, 2048, 2052, 2056, 2060, 2064, 2068, 2072, 2076, 2080, 2084,
2088, 2092, 2096, 2104, 2108, 2112, 2116, 2120, 2124, 2128, 2132, 2136, 2140, 2144,
2148, 2152, 2156, 2160, 2164, 2168, 2172, 2176, 2180, 2184, 2188, 2192, 2196, 2204,
2208, 2212, 2216, 2220, 2224, 2228, 2232, 2236, 2240, 2244, 2248, 2252, 2256, 2260,
2264, 2268, 2272, 2276, 2280, 2284, 2288, 2292, 2296, 2304, 2308, 2312, 2316, 2320,
2324, 2328, 2332, 2336, 2340, 2344, 2348, 2352, 2356, 2360, 2364, 2368, 2372, 2376,
2380, 2384, 2388, 2392, 2396, 2400,
];
for year in leap_years.iter() {
assert!(is_leap_year(*year));
}
}
}
#[cfg(kani)]
#[allow(non_snake_case)]
mod kani_harnesses {
use super::*;
#[kani::proof]
fn kani_harness_january_years() {
let year: i32 = kani::any();
let _ = january_years(year);
}
#[kani::proof]
fn kani_harness_july_years() {
let year: i32 = kani::any();
let _ = july_years(year);
}
#[kani::proof]
fn kani_harness_usual_days_per_month() {
let month: u8 = kani::any();
let _ = usual_days_per_month(month);
}
#[kani::proof]
fn kani_harness_is_leap_year() {
let year: i32 = kani::any();
let _ = is_leap_year(year);
}
}