fasttime 0.2.3

Small UTC date/time library based on Ben Joffe's fast 64-bit date algorithm
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
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
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
#![cfg_attr(not(any(feature = "std", test)), no_std)]

//! fasttime — small UTC date/time library built around Ben Joffe's
//! fast 64-bit days→date algorithm.
//!
//! Features:
//! - `no_std` compatible (only `core`; `std` is optional).
//! - `Date` / `Time` / `DateTime` (UTC).
//! - `Duration` with nanosecond precision.
//! - `UtcOffset` and `OffsetDateTime` (fixed offset, RFC 3339-style).
//! - ISO-like formatting via `Display`.
//! - Parsing of:
//!   - `Date`: "YYYY-MM-DD"
//!   - `Time`: "HH:MM:SS[.fffffffff]"
//!   - `DateTime` (UTC): "YYYY-MM-DDTHH:MM:SS[.fffffffff]Z"
//!   - `OffsetDateTime`: "YYYY-MM-DDTHH:MM:SS[.fffffffff][Z|±HH:MM]" (RFC 3339 subset).
//! - `DateTime::now_utc()` when the `std` feature is enabled.
//!
//! ## Python Bindings
//!
//! When built with the `python` feature, this crate provides Python bindings via PyO3.
//! See the `python/` directory for examples and documentation.

use core::cmp::Ordering;
use core::fmt;
use core::str::FromStr;

#[cfg(feature = "python")]
mod python;

/// Calendar weekday (ISO order, Monday = 1).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Weekday {
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday,
}

impl Weekday {
    pub fn number_from_monday(self) -> u8 {
        match self {
            Weekday::Monday => 1,
            Weekday::Tuesday => 2,
            Weekday::Wednesday => 3,
            Weekday::Thursday => 4,
            Weekday::Friday => 5,
            Weekday::Saturday => 6,
            Weekday::Sunday => 7,
        }
    }
}

/// Errors constructing or parsing a `Date`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DateError {
    /// Year/month/day combination is not a valid Gregorian date.
    InvalidDate,
    /// The date is outside the supported range.
    OutOfRange,
}

/// Gregorian calendar date (proleptic).
///
/// This is independent of any time zone; think "calendar day in UTC".
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Date {
    pub year: i32,
    pub month: u8, // 1..=12
    pub day: u8,   // 1..=31
}

impl Date {
    /// Construct a date, validating year/month/day.
    #[inline]
    pub fn from_ymd(year: i32, month: u8, day: u8) -> Result<Self, DateError> {
        if !(1..=12).contains(&month) {
            return Err(DateError::InvalidDate);
        }
        let dim = days_in_month(year, month);
        if day == 0 || day > dim {
            return Err(DateError::InvalidDate);
        }
        Ok(Date { year, month, day })
    }

    /// Construct a date with minimal checking; debug-only asserts.
    ///
    /// Panics in debug builds if the date is invalid.
    pub const fn from_ymd_unchecked(year: i32, month: u8, day: u8) -> Self {
        // These are simple invariants, checked in debug builds only.
        debug_assert!(month >= 1 && month <= 12);
        debug_assert!(day >= 1 && day <= 31);
        Date { year, month, day }
    }

    /// Ben Joffe's fast 64-bit days→date algorithm, adapted to Rust.
    ///
    /// `days` is days since Unix epoch:
    ///
    /// - 1970-01-01 => 0
    /// - 1969-12-31 => -1
    #[inline]
    pub fn from_days_since_unix_epoch(days: i64) -> Result<Self, DateError> {
        // Constants from the article (x64 version).
        const ERAS: i64 = 4_726_498_270;
        const D_SHIFT: i64 = 146_097 * ERAS - 719_469;
        const Y_SHIFT: i64 = 400 * ERAS - 1;
        const C1: u64 = 505_054_698_555_331;
        const C2: u64 = 50_504_432_782_230_121;
        const C3: u64 = 8_619_973_866_219_416;

        let rev: i64 = D_SHIFT - days;

        // 64x64 → high 64 bit multiplies via u128 with explicit u64 casts.
        let cen: i64 = (((rev as u64 as u128) * (C1 as u128)) >> 64) as i64;
        let jul: i64 = rev + cen - cen / 4;

        let num: u128 = (jul as u64 as u128) * (C2 as u128);
        let yrs: i64 = Y_SHIFT - ((num >> 64) as i64);
        let low: u64 = num as u64;
        let ypt: i64 = ((782_432u128 * low as u128) >> 64) as i64;

        let bump = ypt < 126_464;
        let shift: i64 = if bump { 191_360 } else { 977_792 };

        let n: i64 = (yrs.rem_euclid(4)) * 512 + shift - ypt;

        let d: i64 = (((((n as u64) & 0xFFFF) as u128) * (C3 as u128)) >> 64) as i64;

        let day_i: i64 = d + 1;
        let month_i: i64 = n / 65_536;
        let year_i: i64 = yrs + if bump { 1 } else { 0 };

        if !(i32::MIN as i64..=i32::MAX as i64).contains(&year_i) {
            return Err(DateError::OutOfRange);
        }
        let year = year_i as i32;
        let month = month_i as u8;
        let day = day_i as u8;

        // Extra safety: validate
        if Date::from_ymd(year, month, day).is_err() {
            return Err(DateError::InvalidDate);
        }

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

    /// Convert to days since Unix epoch (1970-01-01 = 0).
    ///
    /// This uses a modified Neri-Schneider inverse civil→days formula
    /// (as described by Ben Joffe), exact for the proleptic Gregorian calendar.
    #[inline]
    pub fn days_since_unix_epoch(self) -> i64 {
        days_from_civil(self.year, self.month, self.day)
    }

    /// Day of week (Monday = 1).
    ///
    /// Unix epoch 1970-01-01 was a Thursday, so we just offset.
    pub fn weekday(self) -> Weekday {
        // 1970-01-01 was Thursday (4).
        let days = self.days_since_unix_epoch();
        let w = days.rem_euclid(7);
        match w {
            0 => Weekday::Thursday,
            1 => Weekday::Friday,
            2 => Weekday::Saturday,
            3 => Weekday::Sunday,
            4 => Weekday::Monday,
            5 => Weekday::Tuesday,
            6 => Weekday::Wednesday,
            _ => unreachable!(),
        }
    }

    /// Day of year, 1..=365 (or 366 for leap years).
    pub fn ordinal(self) -> u16 {
        let month = self.month;
        let day = self.day as u16;
        const CUM_DAYS: [u16; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
        let mut ord = CUM_DAYS[(month - 1) as usize] + day;
        if month > 2 && is_leap_year(self.year) {
            ord += 1;
        }
        ord
    }

    /// Add a number of days, returning a new `Date` or `OutOfRange`.
    pub fn add_days(self, days: i64) -> Result<Date, DateError> {
        let base = self.days_since_unix_epoch();
        Date::from_days_since_unix_epoch(base + days)
    }
}

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

impl Ord for Date {
    fn cmp(&self, other: &Self) -> Ordering {
        let days_self = self.days_since_unix_epoch();
        let days_other = other.days_since_unix_epoch();
        days_self.cmp(&days_other)
    }
}

impl fmt::Display for Date {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // ISO-like: YYYY-MM-DD with at least 4 digits of year.
        write!(f, "{:04}-{:02}-{:02}", self.year, self.month, self.day)
    }
}

impl FromStr for Date {
    type Err = DateError;

    /// Parse "YYYY-MM-DD" (no timezone).
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let bytes = s.as_bytes();
        if bytes.is_empty() {
            return Err(DateError::InvalidDate);
        }

        let mut start = 0;
        if bytes[0] == b'+' || bytes[0] == b'-' {
            start = 1;
            if start == bytes.len() {
                return Err(DateError::InvalidDate);
            }
        }

        let mut first = None;
        let mut second = None;
        for (i, &b) in bytes.iter().enumerate().skip(start) {
            if b == b'-' {
                if first.is_none() {
                    first = Some(i);
                } else if second.is_none() {
                    second = Some(i);
                } else {
                    return Err(DateError::InvalidDate);
                }
            }
        }

        let (first, second) = match (first, second) {
            (Some(first), Some(second)) => (first, second),
            _ => return Err(DateError::InvalidDate),
        };

        let y = parse_i32_bytes(&bytes[..first]).ok_or(DateError::InvalidDate)?;
        let m = parse_u32_bytes(&bytes[first + 1..second], 12).ok_or(DateError::InvalidDate)? as u8;
        let d = parse_u32_bytes(&bytes[second + 1..], 31).ok_or(DateError::InvalidDate)? as u8;
        Date::from_ymd(y, m, d)
    }
}

/// Errors constructing or parsing a `Time`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TimeError {
    InvalidTime,
}

/// Time of day in nanoseconds since midnight.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Time {
    pub hour: u8,        // 0..=23
    pub minute: u8,      // 0..=59
    pub second: u8,      // 0..=59 (no leap seconds)
    pub nanosecond: u32, // 0..1_000_000_000
}

impl Time {
    #[inline]
    pub fn from_hms_nano(
        hour: u8,
        minute: u8,
        second: u8,
        nanosecond: u32,
    ) -> Result<Self, TimeError> {
        if hour > 23 || minute > 59 || second > 59 || nanosecond >= 1_000_000_000 {
            return Err(TimeError::InvalidTime);
        }
        Ok(Time {
            hour,
            minute,
            second,
            nanosecond,
        })
    }

    /// Total seconds since midnight (ignores nanoseconds).
    #[inline]
    pub fn seconds_since_midnight(self) -> u32 {
        (self.hour as u32) * 3600 + (self.minute as u32) * 60 + (self.second as u32)
    }

    /// Total nanoseconds since midnight.
    #[inline]
    pub fn nanos_since_midnight(self) -> u64 {
        self.seconds_since_midnight() as u64 * 1_000_000_000 + self.nanosecond as u64
    }

    /// Build from seconds and nanoseconds since midnight.
    #[inline]
    pub fn from_seconds_nanos(secs: u32, nanos: u32) -> Result<Self, TimeError> {
        if secs >= 86_400 || nanos >= 1_000_000_000 {
            return Err(TimeError::InvalidTime);
        }
        let hour = (secs / 3600) as u8;
        let rem = secs % 3600;
        let minute = (rem / 60) as u8;
        let second = (rem % 60) as u8;
        Time::from_hms_nano(hour, minute, second, nanos)
    }
}

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

impl Ord for Time {
    fn cmp(&self, other: &Self) -> Ordering {
        let nanos_self = self.nanos_since_midnight();
        let nanos_other = other.nanos_since_midnight();
        nanos_self.cmp(&nanos_other)
    }
}

impl fmt::Display for Time {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.nanosecond == 0 {
            write!(f, "{:02}:{:02}:{:02}", self.hour, self.minute, self.second)
        } else {
            // Print fractional seconds, trimming trailing zeros.
            let mut frac = [b'0'; 9];
            let mut ns = self.nanosecond;
            for i in (0..9).rev() {
                frac[i] = b'0' + (ns % 10) as u8;
                ns /= 10;
            }
            // find last non-zero
            let mut end = 9;
            while end > 0 && frac[end - 1] == b'0' {
                end -= 1;
            }
            let frac_str = core::str::from_utf8(&frac[..end]).unwrap_or("0");
            write!(
                f,
                "{:02}:{:02}:{:02}.{}",
                self.hour, self.minute, self.second, frac_str
            )
        }
    }
}

impl FromStr for Time {
    type Err = TimeError;

    /// Parse "HH:MM:SS[.fffffffff]".
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let bytes = s.as_bytes();
        let (hms_bytes, frac_bytes) = match bytes.iter().position(|&b| b == b'.') {
            Some(idx) => (&bytes[..idx], Some(&bytes[idx + 1..])),
            None => (bytes, None),
        };

        let mut first = None;
        let mut second = None;
        for (i, &b) in hms_bytes.iter().enumerate() {
            if b == b':' {
                if first.is_none() {
                    first = Some(i);
                } else if second.is_none() {
                    second = Some(i);
                } else {
                    return Err(TimeError::InvalidTime);
                }
            }
        }

        let (first, second) = match (first, second) {
            (Some(first), Some(second)) => (first, second),
            _ => return Err(TimeError::InvalidTime),
        };

        let h = parse_u32_bytes(&hms_bytes[..first], 23).ok_or(TimeError::InvalidTime)? as u8;
        let m =
            parse_u32_bytes(&hms_bytes[first + 1..second], 59).ok_or(TimeError::InvalidTime)? as u8;
        let sec =
            parse_u32_bytes(&hms_bytes[second + 1..], 59).ok_or(TimeError::InvalidTime)? as u8;

        let nanos = if let Some(fr) = frac_bytes {
            parse_fraction_nanos(fr).ok_or(TimeError::InvalidTime)?
        } else {
            0
        };

        Time::from_hms_nano(h, m, sec, nanos)
    }
}

/// Signed duration with nanosecond precision.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Duration {
    nanos: i128,
}

impl Duration {
    pub const ZERO: Duration = Duration { nanos: 0 };

    #[inline(always)]
    pub fn seconds(secs: i64) -> Duration {
        Duration {
            nanos: (secs as i128) * 1_000_000_000,
        }
    }

    pub fn milliseconds(ms: i64) -> Duration {
        Duration {
            nanos: (ms as i128) * 1_000_000,
        }
    }

    pub fn microseconds(us: i64) -> Duration {
        Duration {
            nanos: (us as i128) * 1_000,
        }
    }

    pub fn nanoseconds(ns: i128) -> Duration {
        Duration { nanos: ns }
    }

    pub fn total_seconds(self) -> f64 {
        self.nanos as f64 / 1_000_000_000.0
    }

    #[inline(always)]
    pub fn total_nanos(self) -> i128 {
        self.nanos
    }
}

impl core::ops::Add for Duration {
    type Output = Duration;
    fn add(self, rhs: Duration) -> Duration {
        Duration {
            nanos: self.nanos + rhs.nanos,
        }
    }
}

impl core::ops::Sub for Duration {
    type Output = Duration;
    fn sub(self, rhs: Duration) -> Duration {
        Duration {
            nanos: self.nanos - rhs.nanos,
        }
    }
}

impl core::ops::Neg for Duration {
    type Output = Duration;
    fn neg(self) -> Duration {
        Duration { nanos: -self.nanos }
    }
}

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

impl Ord for Duration {
    fn cmp(&self, other: &Self) -> Ordering {
        self.nanos.cmp(&other.nanos)
    }
}

/// Combined UTC date and time (no time zone).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct DateTime {
    pub date: Date,
    pub time: Time,
}

impl DateTime {
    #[inline(always)]
    pub fn new(date: Date, time: Time) -> DateTime {
        DateTime { date, time }
    }

    /// Build from Unix timestamp (seconds since 1970-01-01T00:00:00Z)
    /// plus an additional nanoseconds offset (can be negative or >1e9).
    #[inline]
    pub fn from_unix_timestamp(secs: i64, nanos: i32) -> Result<DateTime, DateError> {
        // Normalize (secs, nanos) pair.
        let mut s = secs as i128;
        let mut n = nanos as i128;
        s += n.div_euclid(1_000_000_000);
        n = n.rem_euclid(1_000_000_000);
        let s_i64 = s as i64;

        let days = s_i64.div_euclid(86_400);
        let secs_of_day = s_i64.rem_euclid(86_400);
        let date = Date::from_days_since_unix_epoch(days)?;
        let time = Time::from_seconds_nanos(secs_of_day as u32, n as u32)
            .map_err(|_| DateError::InvalidDate)?;
        Ok(DateTime { date, time })
    }

    /// Seconds since Unix epoch (1970-01-01T00:00:00Z).
    #[inline]
    pub fn unix_timestamp(self) -> i64 {
        let days = self.date.days_since_unix_epoch();
        let day_secs = self.time.seconds_since_midnight() as i64;
        days * 86_400 + day_secs
    }

    /// Nanoseconds since Unix epoch, as i128.
    #[inline]
    pub fn unix_timestamp_nanos(self) -> i128 {
        self.unix_timestamp() as i128 * 1_000_000_000 + self.time.nanosecond as i128
    }

    /// Add a duration, returning a new `DateTime` (or `OutOfRange` on overflow).
    pub fn add_duration(self, dur: Duration) -> Result<DateTime, DateError> {
        let t = self.unix_timestamp_nanos() + dur.total_nanos();
        let secs = t.div_euclid(1_000_000_000);
        let nanos = t.rem_euclid(1_000_000_000);
        DateTime::from_unix_timestamp(secs as i64, nanos as i32)
    }

    /// Difference between two instants (self - other).
    #[inline(always)]
    pub fn difference(self, other: DateTime) -> Duration {
        Duration::nanoseconds(self.unix_timestamp_nanos() - other.unix_timestamp_nanos())
    }

    /// Get the current UTC `DateTime` (requires `std` feature).
    #[cfg(feature = "std")]
    pub fn now_utc() -> Result<Self, DateError> {
        use std::time::{SystemTime, UNIX_EPOCH};
        let now = SystemTime::now();
        match now.duration_since(UNIX_EPOCH) {
            Ok(dur) => {
                DateTime::from_unix_timestamp(dur.as_secs() as i64, dur.subsec_nanos() as i32)
            }
            Err(e) => {
                let dur = e.duration();
                let secs = dur.as_secs() as i64;
                let nanos = dur.subsec_nanos() as i32;
                DateTime::from_unix_timestamp(-secs, -nanos)
            }
        }
    }
}

impl fmt::Display for DateTime {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // ISO 8601 / RFC 3339 UTC: YYYY-MM-DDTHH:MM:SS[.frac]Z
        write!(f, "{}T{}Z", self.date, self.time)
    }
}

impl FromStr for DateTime {
    type Err = ();

    /// Parse "YYYY-MM-DDTHH:MM:SS[.fffffffff]Z" (UTC only).
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let s = s
            .strip_suffix('Z')
            .or_else(|| s.strip_suffix('z'))
            .ok_or(())?;
        let (date_str, time_str) = s.split_once('T').or_else(|| s.split_once(' ')).ok_or(())?;
        let date = date_str.parse::<Date>().map_err(|_| ())?;
        let time = time_str.parse::<Time>().map_err(|_| ())?;
        Ok(DateTime { date, time })
    }
}

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

impl Ord for DateTime {
    fn cmp(&self, other: &Self) -> Ordering {
        self.unix_timestamp_nanos()
            .cmp(&other.unix_timestamp_nanos())
    }
}

/// Error constructing a UTC offset.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UtcOffsetError {
    OutOfRange,
}

/// Fixed offset from UTC, in seconds (e.g. +02:00).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct UtcOffset {
    seconds: i32,
}

impl UtcOffset {
    /// Construct from a total number of seconds, roughly in [-24h, +24h].
    pub fn from_seconds(seconds: i32) -> Result<Self, UtcOffsetError> {
        // Rough sanity bounds: [-24h, +24h].
        if !(-86_400..=86_400).contains(&seconds) {
            return Err(UtcOffsetError::OutOfRange);
        }
        Ok(UtcOffset { seconds })
    }

    /// Construct from hours and minutes, with `sign_positive` sign.
    ///
    /// For example:
    /// - `from_hours_minutes(true, 2, 0)` => +02:00
    /// - `from_hours_minutes(false, 5, 30)` => -05:30
    pub fn from_hours_minutes(
        sign_positive: bool,
        hours: u8,
        minutes: u8,
    ) -> Result<Self, UtcOffsetError> {
        if hours > 23 || minutes > 59 {
            return Err(UtcOffsetError::OutOfRange);
        }
        let total = (hours as i32) * 3600 + (minutes as i32) * 60;
        let total = if sign_positive { total } else { -total };
        Self::from_seconds(total)
    }

    #[inline(always)]
    pub fn as_seconds(self) -> i32 {
        self.seconds
    }

    #[inline(always)]
    pub fn is_utc(self) -> bool {
        self.seconds == 0
    }
}

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

impl Ord for UtcOffset {
    fn cmp(&self, other: &Self) -> Ordering {
        self.seconds.cmp(&other.seconds)
    }
}

impl fmt::Display for UtcOffset {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut secs = self.seconds;
        let sign = if secs >= 0 { '+' } else { '-' };
        if secs < 0 {
            secs = -secs;
        }
        let hours = secs / 3600;
        let minutes = (secs % 3600) / 60;
        write!(f, "{}{:02}:{:02}", sign, hours, minutes)
    }
}

/// Date-time with a fixed offset from UTC (RFC 3339-style).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct OffsetDateTime {
    /// Instant in UTC.
    pub utc: DateTime,
    /// Fixed offset.
    pub offset: UtcOffset,
}

impl OffsetDateTime {
    /// Construct from a UTC instant and an offset.
    pub fn from_utc(utc: DateTime, offset: UtcOffset) -> Self {
        OffsetDateTime { utc, offset }
    }

    /// Construct from a local date+time with offset, converting to UTC.
    pub fn from_local(date: Date, time: Time, offset: UtcOffset) -> Result<Self, DateError> {
        let local = DateTime::new(date, time);
        let utc = local.add_duration(Duration::seconds(-(offset.as_seconds() as i64)))?;
        Ok(OffsetDateTime { utc, offset })
    }

    /// Local date/time as seen in this offset.
    pub fn to_local(&self) -> Result<DateTime, DateError> {
        self.utc
            .add_duration(Duration::seconds(self.offset.as_seconds() as i64))
    }

    /// Seconds since Unix epoch (1970-01-01T00:00:00Z).
    #[inline(always)]
    pub fn unix_timestamp(&self) -> i64 {
        self.utc.unix_timestamp()
    }

    /// Nanoseconds since Unix epoch.
    #[inline(always)]
    pub fn unix_timestamp_nanos(&self) -> i128 {
        self.utc.unix_timestamp_nanos()
    }

    /// Add a duration, keeping the same offset.
    pub fn add_duration(&self, dur: Duration) -> Result<Self, DateError> {
        let utc = self.utc.add_duration(dur)?;
        Ok(OffsetDateTime {
            utc,
            offset: self.offset,
        })
    }

    /// Difference between two instants (self - other).
    #[inline(always)]
    pub fn difference(&self, other: OffsetDateTime) -> Duration {
        self.utc.difference(other.utc)
    }
}

impl fmt::Display for OffsetDateTime {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // RFC 3339: local "YYYY-MM-DDTHH:MM:SS[.frac]" + offset.
        let local = self
            .to_local()
            .expect("OffsetDateTime local representation out of range");
        write!(f, "{}T{}", local.date, local.time)?;
        if self.offset.is_utc() {
            write!(f, "Z")
        } else {
            write!(f, "{}", self.offset)
        }
    }
}

impl FromStr for OffsetDateTime {
    type Err = ();

    /// Parse RFC 3339-style:
    /// "YYYY-MM-DDTHH:MM:SS[.fffffffff][Z|±HH:MM]"
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let s = s.trim();
        let (date_part, rest) = s.split_once('T').or_else(|| s.split_once(' ')).ok_or(())?;
        let date: Date = date_part.parse().map_err(|_| ())?;

        // Parse time + offset.
        let (time_part, offset_part) = if rest.ends_with('Z') || rest.ends_with('z') {
            (&rest[..rest.len() - 1], "Z")
        } else {
            let idx = rest.rfind(['+', '-']).ok_or(())?;
            (&rest[..idx], &rest[idx..])
        };

        let time: Time = time_part.parse().map_err(|_| ())?;
        let offset = parse_rfc3339_offset(offset_part).map_err(|_| ())?;
        OffsetDateTime::from_local(date, time, offset).map_err(|_| ())
    }
}

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

impl Ord for OffsetDateTime {
    fn cmp(&self, other: &Self) -> Ordering {
        self.utc.cmp(&other.utc)
    }
}

// ===== Internal helpers =====

const POW10_U32: [u32; 10] = [
    1,
    10,
    100,
    1_000,
    10_000,
    100_000,
    1_000_000,
    10_000_000,
    100_000_000,
    1_000_000_000,
];

fn parse_i32_bytes(bytes: &[u8]) -> Option<i32> {
    if bytes.is_empty() {
        return None;
    }
    let mut idx = 0;
    let mut neg = false;
    match bytes[0] {
        b'+' => idx = 1,
        b'-' => {
            idx = 1;
            neg = true;
        }
        _ => {}
    }
    if idx == bytes.len() {
        return None;
    }

    let limit: i64 = if neg {
        i32::MAX as i64 + 1
    } else {
        i32::MAX as i64
    };
    let mut val: i64 = 0;
    for &b in &bytes[idx..] {
        if !b.is_ascii_digit() {
            return None;
        }
        let digit = (b - b'0') as i64;
        if val > limit / 10 || (val == limit / 10 && digit > limit % 10) {
            return None;
        }
        val = val * 10 + digit;
    }

    if neg {
        val = -val;
    }
    Some(val as i32)
}

fn parse_u32_bytes(bytes: &[u8], max: u32) -> Option<u32> {
    if bytes.is_empty() {
        return None;
    }
    let mut val: u32 = 0;
    for &b in bytes {
        if !b.is_ascii_digit() {
            return None;
        }
        let digit = (b - b'0') as u32;
        if val > max / 10 || (val == max / 10 && digit > max % 10) {
            return None;
        }
        val = val * 10 + digit;
    }
    Some(val)
}

fn parse_fraction_nanos(bytes: &[u8]) -> Option<u32> {
    let len = bytes.len();
    if len == 0 || len > 9 {
        return None;
    }
    let mut val: u32 = 0;
    for &b in bytes {
        if !b.is_ascii_digit() {
            return None;
        }
        val = val * 10 + (b - b'0') as u32;
    }
    let scale = 9 - len;
    Some(val * POW10_U32[scale])
}

/// Errors parsing an RFC 3339 UTC offset.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Rfc3339OffsetError {
    InvalidFormat,
    OutOfRange,
}

pub fn parse_rfc3339_offset(s: &str) -> Result<UtcOffset, Rfc3339OffsetError> {
    if s == "Z" || s == "z" {
        return UtcOffset::from_seconds(0).map_err(|_| Rfc3339OffsetError::OutOfRange);
    }
    let bytes = s.as_bytes();
    if bytes.len() < 3 {
        return Err(Rfc3339OffsetError::InvalidFormat);
    }
    let sign_positive = match bytes[0] {
        b'+' => true,
        b'-' => false,
        _ => return Err(Rfc3339OffsetError::InvalidFormat),
    };
    let body = &bytes[1..];

    let mut colon = None;
    for (idx, &b) in body.iter().enumerate() {
        if b == b':' {
            colon = Some(idx);
            break;
        }
    }

    let (h_bytes, m_bytes) = if let Some(colon_idx) = colon {
        let h = &body[..colon_idx];
        let m = &body[colon_idx + 1..];
        if h.is_empty() || h.len() > 2 || m.len() > 2 {
            return Err(Rfc3339OffsetError::InvalidFormat);
        }
        (h, m)
    } else if body.len() == 2 {
        (&body[..2], &[][..])
    } else if body.len() == 4 {
        (&body[..2], &body[2..])
    } else {
        return Err(Rfc3339OffsetError::InvalidFormat);
    };

    if h_bytes.len() > 2 || m_bytes.len() > 2 {
        return Err(Rfc3339OffsetError::InvalidFormat);
    }

    let hours = parse_u32_bytes(h_bytes, 99).ok_or(Rfc3339OffsetError::InvalidFormat)? as u8;
    let minutes = if m_bytes.is_empty() {
        0
    } else {
        parse_u32_bytes(m_bytes, 99).ok_or(Rfc3339OffsetError::InvalidFormat)? as u8
    };
    UtcOffset::from_hours_minutes(sign_positive, hours, minutes)
        .map_err(|_| Rfc3339OffsetError::OutOfRange)
}

fn is_leap_year(year: i32) -> bool {
    let century_candidate = year % 25 == 0;
    (year & if century_candidate { 15 } else { 3 }) == 0
}

fn days_in_month(year: i32, month: u8) -> u8 {
    if month == 2 {
        return if is_leap_year(year) { 29 } else { 28 };
    }
    if !(1..=12).contains(&month) {
        return 0;
    }
    // Branch-free month length for all non-February months.
    (month ^ (month >> 3)) | 30
}

// Modified Neri-Schneider inverse (civil → days), as documented by Ben Joffe.
// Returns days since Unix epoch for a given Gregorian date.
#[inline]
fn days_from_civil(y: i32, m: u8, d: u8) -> i64 {
    // Large enough so shifted years are non-negative for the full i32 range.
    const S: i64 = 5_368_710;
    const YEAR_SHIFT: i64 = 400 * S;
    const RATA_SHIFT: i64 = 719_468 + 146_097 * S + 1;

    let bump = m <= 2;
    let year = y as i64 + YEAR_SHIFT - if bump { 1 } else { 0 };
    let cent = year / 100;
    let phase = if bump { 8_829 } else { -2_919 };

    let y_days = year * 365 + year / 4 - cent + cent / 4;
    let m_days = (979 * (m as i64) + phase) / 32;
    y_days + m_days + d as i64 - RATA_SHIFT
}