tempoch-core 0.4.1

Core astronomical time primitives for tempoch.
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
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Vallés Puig, Ramon

//! Generic time–scale parameterised instant.
//!
//! [`Time<S>`] is the core type of the time module.  It stores a scalar
//! quantity in [`Days`] whose *meaning* is determined by the compile-time
//! marker `S: TimeScale`.  All arithmetic (addition/subtraction of
//! durations, difference between instants), UTC conversion, serialisation,
//! and display are implemented generically — no code duplication.
//!
//! Domain-specific methods that only make sense for a particular scale
//! (e.g. [`Time::<JD>::julian_centuries()`]) are placed in inherent `impl`
//! blocks gated on the concrete marker type.

use chrono::{DateTime, Utc};
use qtty::*;
use std::marker::PhantomData;
use std::ops::{Add, AddAssign, Sub, SubAssign};

#[cfg(feature = "serde")]
use serde::{Deserialize, Deserializer, Serialize, Serializer};

// ═══════════════════════════════════════════════════════════════════════════
// TimeScale trait
// ═══════════════════════════════════════════════════════════════════════════

/// Marker trait for time scales.
///
/// A **time scale** defines:
///
/// 1. A human-readable **label** (e.g. `"JD"`, `"MJD"`, `"TAI"`).
/// 2. A pair of conversion functions between the scale's native quantity
///    (in [`Days`]) and **Julian Date in TT** (JD(TT)) — the canonical
///    internal representation used throughout the crate.
///
/// For pure *epoch counters* (JD, MJD, Unix Time, GPS) the conversions are
/// trivial constant offsets that the compiler will inline and fold away.
///
/// For *physical scales* (TT, TDB, TAI) the conversions may include
/// function-based corrections (e.g. the ≈1.7 ms TDB↔TT periodic term).
pub trait TimeScale: Copy + Clone + std::fmt::Debug + PartialEq + PartialOrd + 'static {
    /// Display label used by [`Time`] formatting.
    const LABEL: &'static str;

    /// Convert a quantity in this scale's native unit to an absolute JD(TT).
    fn to_jd_tt(value: Days) -> Days;

    /// Convert an absolute JD(TT) back to this scale's native quantity.
    fn from_jd_tt(jd_tt: Days) -> Days;
}

// ═══════════════════════════════════════════════════════════════════════════
// Error types
// ═══════════════════════════════════════════════════════════════════════════

/// Error returned when a `Time` value is non-finite (`NaN` or `±∞`).
///
/// Non-finite values break ordering, intersection, and arithmetic invariants,
/// so validated constructors ([`Time::try_new`], [`Time::try_from_days`])
/// reject them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NonFiniteTimeError;

impl std::fmt::Display for NonFiniteTimeError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "time value must be finite (not NaN or infinity)")
    }
}

impl std::error::Error for NonFiniteTimeError {}

// ═══════════════════════════════════════════════════════════════════════════
// Time<S> — the generic instant
// ═══════════════════════════════════════════════════════════════════════════

/// A point on time scale `S`.
///
/// Internally stores a single `Days` quantity whose interpretation depends on
/// `S: TimeScale`.  The struct is `Copy` and zero-cost: `PhantomData` is
/// zero-sized, so `Time<S>` is layout-identical to `Days` (a single `f64`).
#[repr(transparent)]
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
pub struct Time<S: TimeScale> {
    quantity: Days,
    _scale: PhantomData<S>,
}

impl<S: TimeScale> Time<S> {
    // ── constructors ──────────────────────────────────────────────────

    /// Create from a raw scalar (days since the scale's epoch).
    ///
    /// **Note:** this constructor accepts any `f64`, including `NaN` and `±∞`.
    /// Prefer [`try_new`](Self::try_new) when the value comes from untrusted
    /// or computed input.
    #[inline]
    pub const fn new(value: f64) -> Self {
        Self {
            quantity: Days::new(value),
            _scale: PhantomData,
        }
    }

    /// Create from a raw scalar, rejecting non-finite values.
    ///
    /// Returns [`NonFiniteTimeError`] if `value` is `NaN`, `+∞`, or `−∞`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use tempoch_core as tempoch;
    /// use tempoch::{Time, JD};
    ///
    /// assert!(Time::<JD>::try_new(2451545.0).is_ok());
    /// assert!(Time::<JD>::try_new(f64::NAN).is_err());
    /// assert!(Time::<JD>::try_new(f64::INFINITY).is_err());
    /// ```
    #[inline]
    pub fn try_new(value: f64) -> Result<Self, NonFiniteTimeError> {
        if value.is_finite() {
            Ok(Self::new(value))
        } else {
            Err(NonFiniteTimeError)
        }
    }

    /// Create from a [`Days`] quantity.
    ///
    /// **Note:** this constructor accepts any `f64`, including `NaN` and `±∞`.
    /// Prefer [`try_from_days`](Self::try_from_days) when the value comes from
    /// untrusted or computed input.
    #[inline]
    pub const fn from_days(days: Days) -> Self {
        Self {
            quantity: days,
            _scale: PhantomData,
        }
    }

    /// Create from a [`Days`] quantity, rejecting non-finite values.
    ///
    /// Returns [`NonFiniteTimeError`] if the underlying value is `NaN`,
    /// `+∞`, or `−∞`.
    #[inline]
    pub fn try_from_days(days: Days) -> Result<Self, NonFiniteTimeError> {
        Self::try_new(days.value())
    }

    // ── accessors ─────────────────────────────────────────────────────

    /// The underlying quantity in days.
    #[inline]
    pub const fn quantity(&self) -> Days {
        self.quantity
    }

    /// The underlying scalar value in days.
    #[inline]
    pub const fn value(&self) -> f64 {
        self.quantity.value()
    }

    /// Absolute Julian Day (TT) corresponding to this instant.
    #[inline]
    pub fn julian_day(&self) -> Days {
        S::to_jd_tt(self.quantity)
    }

    /// Absolute Julian Day (TT) as scalar.
    #[inline]
    pub fn julian_day_value(&self) -> f64 {
        self.julian_day().value()
    }

    /// Build an instant from an absolute Julian Day (TT).
    #[inline]
    pub fn from_julian_day(jd: Days) -> Self {
        Self::from_days(S::from_jd_tt(jd))
    }

    // ── cross-scale conversion (mirroring qtty's .to::<T>()) ─────────

    /// Convert this instant to another time scale.
    ///
    /// The conversion routes through the canonical JD(TT) intermediate:
    ///
    /// ```text
    /// self → JD(TT) → target
    /// ```
    ///
    /// For pure epoch-offset scales this compiles down to a single
    /// addition/subtraction.
    #[inline]
    pub fn to<T: TimeScale>(&self) -> Time<T> {
        Time::<T>::from_julian_day(S::to_jd_tt(self.quantity))
    }

    // ── UTC helpers ───────────────────────────────────────────────────

    /// Convert to a `chrono::DateTime<Utc>`.
    ///
    /// Inverts the ΔT correction to recover the UTC / UT timestamp.
    /// Returns `None` if the value falls outside chrono's representable range.
    pub fn to_utc(&self) -> Option<DateTime<Utc>> {
        use super::scales::UT;
        const UNIX_EPOCH_JD: f64 = 2_440_587.5;
        let jd_ut = self.to::<UT>().quantity();
        let seconds_since_epoch = (jd_ut - Days::new(UNIX_EPOCH_JD)).to::<Second>().value();
        let secs = seconds_since_epoch.floor() as i64;
        let nanos = ((seconds_since_epoch - secs as f64) * 1e9) as u32;
        DateTime::<Utc>::from_timestamp(secs, nanos)
    }

    /// Build an instant from a `chrono::DateTime<Utc>`.
    ///
    /// The UTC timestamp is interpreted as Universal Time (≈ UT1) and the
    /// epoch-dependent **ΔT** correction is applied automatically, so the
    /// resulting `Time<S>` is on the target scale's axis.
    pub fn from_utc(datetime: DateTime<Utc>) -> Self {
        use super::scales::UT;
        const UNIX_EPOCH_JD: f64 = 2_440_587.5;
        let seconds_since_epoch = Seconds::new(datetime.timestamp() as f64);
        let nanos = Seconds::new(datetime.timestamp_subsec_nanos() as f64 / 1e9);
        let jd_ut = Days::new(UNIX_EPOCH_JD) + (seconds_since_epoch + nanos).to::<Day>();
        Time::<UT>::from_days(jd_ut).to::<S>()
    }

    // ── min / max ─────────────────────────────────────────────────────

    /// Element-wise minimum.
    #[inline]
    pub const fn min(self, other: Self) -> Self {
        Self::from_days(self.quantity.min_const(other.quantity))
    }

    /// Element-wise maximum.
    #[inline]
    pub const fn max(self, other: Self) -> Self {
        Self::from_days(self.quantity.max_const(other.quantity))
    }

    /// Mean (midpoint) between two instants on the same time scale.
    #[inline]
    pub const fn mean(self, other: Self) -> Self {
        Self::from_days(self.quantity.const_add(other.quantity).const_div(2.0))
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Generic trait implementations
// ═══════════════════════════════════════════════════════════════════════════

// ── Display ───────────────────────────────────────────────────────────────

impl<S: TimeScale> std::fmt::Display for Time<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Format: "JD 2451545.0" — scale label followed by the raw day value.
        // The `d` unit suffix is intentionally omitted: for time scales the
        // scale label already conveys the scale (JD, MJD, TT, …) and the
        // trailing `d` was redundant and visually confusing.
        // All format flags (precision, width, …) are forwarded to the f64
        // value so that e.g. `format!("{:.9}", my_jd)` works directly.
        write!(f, "{} ", S::LABEL)?;
        std::fmt::Display::fmt(&self.quantity.value(), f)
    }
}

// ── Serde ─────────────────────────────────────────────────────────────────

#[cfg(feature = "serde")]
impl<S: TimeScale> Serialize for Time<S> {
    fn serialize<Ser>(&self, serializer: Ser) -> Result<Ser::Ok, Ser::Error>
    where
        Ser: Serializer,
    {
        serializer.serialize_f64(self.value())
    }
}

#[cfg(feature = "serde")]
impl<'de, S: TimeScale> Deserialize<'de> for Time<S> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let v = f64::deserialize(deserializer)?;
        if !v.is_finite() {
            return Err(serde::de::Error::custom(
                "time value must be finite (not NaN or infinity)",
            ));
        }
        Ok(Self::new(v))
    }
}

// ── Arithmetic ────────────────────────────────────────────────────────────

impl<S: TimeScale> Add<Days> for Time<S> {
    type Output = Self;
    #[inline]
    fn add(self, rhs: Days) -> Self::Output {
        Self::from_days(self.quantity + rhs)
    }
}

impl<S: TimeScale> AddAssign<Days> for Time<S> {
    #[inline]
    fn add_assign(&mut self, rhs: Days) {
        self.quantity += rhs;
    }
}

impl<S: TimeScale> Sub<Days> for Time<S> {
    type Output = Self;
    #[inline]
    fn sub(self, rhs: Days) -> Self::Output {
        Self::from_days(self.quantity - rhs)
    }
}

impl<S: TimeScale> SubAssign<Days> for Time<S> {
    #[inline]
    fn sub_assign(&mut self, rhs: Days) {
        self.quantity -= rhs;
    }
}

impl<S: TimeScale> Sub for Time<S> {
    type Output = Days;
    #[inline]
    fn sub(self, rhs: Self) -> Self::Output {
        self.quantity - rhs.quantity
    }
}

impl<S: TimeScale> std::ops::Div<Days> for Time<S> {
    type Output = f64;
    #[inline]
    fn div(self, rhs: Days) -> Self::Output {
        (self.quantity / rhs).simplify().value()
    }
}

impl<S: TimeScale> std::ops::Div<f64> for Time<S> {
    type Output = f64;
    #[inline]
    fn div(self, rhs: f64) -> Self::Output {
        (self.quantity / rhs).value()
    }
}

// ── From/Into Days ────────────────────────────────────────────────────────

impl<S: TimeScale> From<Days> for Time<S> {
    #[inline]
    fn from(days: Days) -> Self {
        Self::from_days(days)
    }
}

impl<S: TimeScale> From<Time<S>> for Days {
    #[inline]
    fn from(time: Time<S>) -> Self {
        time.quantity
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// TimeInstant trait
// ═══════════════════════════════════════════════════════════════════════════

/// Trait for types that represent a point in time.
///
/// Types implementing this trait can be used as time instants in `Interval<T>`
/// and provide conversions to/from UTC plus basic arithmetic operations.
pub trait TimeInstant: Copy + Clone + PartialEq + PartialOrd + Sized {
    /// The duration type used for arithmetic operations.
    type Duration;

    /// Convert this time instant to UTC DateTime.
    fn to_utc(&self) -> Option<DateTime<Utc>>;

    /// Create a time instant from UTC DateTime.
    fn from_utc(datetime: DateTime<Utc>) -> Self;

    /// Compute the difference between two time instants.
    fn difference(&self, other: &Self) -> Self::Duration;

    /// Add a duration to this time instant.
    fn add_duration(&self, duration: Self::Duration) -> Self;

    /// Subtract a duration from this time instant.
    fn sub_duration(&self, duration: Self::Duration) -> Self;
}

impl<S: TimeScale> TimeInstant for Time<S> {
    type Duration = Days;

    #[inline]
    fn to_utc(&self) -> Option<DateTime<Utc>> {
        Time::to_utc(self)
    }

    #[inline]
    fn from_utc(datetime: DateTime<Utc>) -> Self {
        Time::from_utc(datetime)
    }

    #[inline]
    fn difference(&self, other: &Self) -> Self::Duration {
        *self - *other
    }

    #[inline]
    fn add_duration(&self, duration: Self::Duration) -> Self {
        *self + duration
    }

    #[inline]
    fn sub_duration(&self, duration: Self::Duration) -> Self {
        *self - duration
    }
}

impl TimeInstant for DateTime<Utc> {
    type Duration = chrono::Duration;

    fn to_utc(&self) -> Option<DateTime<Utc>> {
        Some(*self)
    }

    fn from_utc(datetime: DateTime<Utc>) -> Self {
        datetime
    }

    fn difference(&self, other: &Self) -> Self::Duration {
        *self - *other
    }

    fn add_duration(&self, duration: Self::Duration) -> Self {
        *self + duration
    }

    fn sub_duration(&self, duration: Self::Duration) -> Self {
        *self - duration
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Tests
// ═══════════════════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::super::scales::{JD, MJD};
    use super::*;
    use chrono::TimeZone;

    #[test]
    fn test_julian_day_creation() {
        let jd = Time::<JD>::new(2_451_545.0);
        assert_eq!(jd.quantity(), Days::new(2_451_545.0));
    }

    #[test]
    fn test_jd_utc_roundtrip() {
        // from_utc applies ΔT (UT→TT); to_utc inverts it (TT→UT).
        let datetime = DateTime::from_timestamp(946_728_000, 0).unwrap();
        let jd = Time::<JD>::from_utc(datetime);
        let back = jd.to_utc().expect("to_utc");
        let delta_ns =
            back.timestamp_nanos_opt().unwrap() - datetime.timestamp_nanos_opt().unwrap();
        assert!(delta_ns.abs() < 1_000, "roundtrip error: {} ns", delta_ns);
    }

    #[test]
    fn test_from_utc_applies_delta_t() {
        // 2000-01-01 12:00:00 UTC → JD(UT)=2451545.0; ΔT≈63.83 s
        let datetime = DateTime::from_timestamp(946_728_000, 0).unwrap();
        let jd = Time::<JD>::from_utc(datetime);
        let delta_t_secs = (jd.quantity() - Days::new(2_451_545.0)).to::<Second>();
        assert!(
            (delta_t_secs - Seconds::new(63.83)).abs() < Seconds::new(1.0),
            "ΔT correction = {} s, expected ~63.83 s",
            delta_t_secs
        );
    }

    #[test]
    fn test_julian_conversions() {
        let jd = Time::<JD>::J2000 + Days::new(365_250.0);
        assert!((jd.julian_millennias() - Millennia::new(1.0)).abs() < 1e-12);
        assert!((jd.julian_centuries() - Centuries::new(10.0)).abs() < Centuries::new(1e-12));
        assert!((jd.julian_years() - JulianYears::new(1000.0)).abs() < JulianYears::new(1e-9));
    }

    #[test]
    fn test_tt_to_tdb_and_min_max() {
        let jd_tdb = Time::<JD>::tt_to_tdb(Time::<JD>::J2000);
        assert!((jd_tdb - Time::<JD>::J2000).abs() < 1e-6);

        let earlier = Time::<JD>::J2000;
        let later = earlier + Days::new(1.0);
        assert_eq!(earlier.min(later), earlier);
        assert_eq!(earlier.max(later), later);
    }

    #[test]
    fn test_const_min_max() {
        const A: Time<JD> = Time::<JD>::new(10.0);
        const B: Time<JD> = Time::<JD>::new(14.0);
        const MIN: Time<JD> = A.min(B);
        const MAX: Time<JD> = A.max(B);
        assert_eq!(MIN.quantity(), Days::new(10.0));
        assert_eq!(MAX.quantity(), Days::new(14.0));
    }

    #[test]
    fn test_mean_and_const_mean() {
        let a = Time::<JD>::new(10.0);
        let b = Time::<JD>::new(14.0);
        assert_eq!(a.mean(b).quantity(), Days::new(12.0));
        assert_eq!(b.mean(a).quantity(), Days::new(12.0));

        const MID: Time<JD> = Time::<JD>::new(10.0).mean(Time::<JD>::new(14.0));
        assert_eq!(MID.quantity(), Days::new(12.0));
    }

    #[test]
    fn test_into_days() {
        let jd = Time::<JD>::new(2_451_547.5);
        let days: Days = jd.into();
        assert_eq!(days, 2_451_547.5);

        let roundtrip = Time::<JD>::from(days);
        assert_eq!(roundtrip, jd);
    }

    #[test]
    fn test_into_julian_years() {
        let jd = Time::<JD>::J2000 + Days::new(365.25 * 2.0);
        let years: JulianYears = jd.into();
        assert!((years - JulianYears::new(2.0)).abs() < JulianYears::new(1e-12));

        let roundtrip = Time::<JD>::from(years);
        assert!((roundtrip.quantity() - jd.quantity()).abs() < Days::new(1e-12));
    }

    #[test]
    fn time_has_days_layout() {
        assert_eq!(std::mem::size_of::<Time<JD>>(), std::mem::size_of::<Days>());
        assert_eq!(
            std::mem::align_of::<Time<JD>>(),
            std::mem::align_of::<Days>()
        );
    }

    #[test]
    fn test_into_centuries() {
        let jd = Time::<JD>::J2000 + Days::new(36_525.0 * 3.0);
        let centuries: Centuries = jd.into();
        assert!((centuries - Centuries::new(3.0)).abs() < Centuries::new(1e-12));

        let roundtrip = Time::<JD>::from(centuries);
        assert!((roundtrip.quantity() - jd.quantity()).abs() < Days::new(1e-12));
    }

    #[test]
    fn test_into_millennia() {
        let jd = Time::<JD>::J2000 + Days::new(365_250.0 * 1.5);
        let millennia: Millennia = jd.into();
        assert!((millennia - Millennia::new(1.5)).abs() < Millennia::new(1e-12));

        let roundtrip = Time::<JD>::from(millennia);
        assert!((roundtrip.quantity() - jd.quantity()).abs() < Days::new(1e-9));
    }

    #[test]
    fn test_mjd_creation() {
        let mjd = Time::<MJD>::new(51_544.5);
        assert_eq!(mjd.quantity(), Days::new(51_544.5));
    }

    #[test]
    fn test_mjd_into_jd() {
        let mjd = Time::<MJD>::new(51_544.5);
        let jd: Time<JD> = mjd.into();
        assert_eq!(jd.quantity(), Days::new(2_451_545.0));
    }

    #[test]
    fn test_mjd_utc_roundtrip() {
        let datetime = DateTime::from_timestamp(946_728_000, 0).unwrap();
        let mjd = Time::<MJD>::from_utc(datetime);
        let back = mjd.to_utc().expect("to_utc");
        let delta_ns =
            back.timestamp_nanos_opt().unwrap() - datetime.timestamp_nanos_opt().unwrap();
        assert!(delta_ns.abs() < 1_000, "roundtrip error: {} ns", delta_ns);
    }

    #[test]
    fn test_mjd_from_utc_applies_delta_t() {
        // MJD epoch is JD − 2400000.5; ΔT should shift value by ~63.83/86400 days
        let datetime = DateTime::from_timestamp(946_728_000, 0).unwrap();
        let mjd = Time::<MJD>::from_utc(datetime);
        let delta_t_secs = (mjd.quantity() - Days::new(51_544.5)).to::<Second>();
        assert!(
            (delta_t_secs - Seconds::new(63.83)).abs() < Seconds::new(1.0),
            "ΔT correction = {} s, expected ~63.83 s",
            delta_t_secs
        );
    }

    #[test]
    fn test_mjd_add_days() {
        let mjd = Time::<MJD>::new(59_000.0);
        let result = mjd + Days::new(1.5);
        assert_eq!(result.quantity(), Days::new(59_001.5));
    }

    #[test]
    fn test_mjd_sub_days() {
        let mjd = Time::<MJD>::new(59_000.0);
        let result = mjd - Days::new(1.5);
        assert_eq!(result.quantity(), Days::new(58_998.5));
    }

    #[test]
    fn test_mjd_sub_mjd() {
        let mjd1 = Time::<MJD>::new(59_001.0);
        let mjd2 = Time::<MJD>::new(59_000.0);
        let diff = mjd1 - mjd2;
        assert_eq!(diff, 1.0);
    }

    #[test]
    fn test_mjd_comparison() {
        let mjd1 = Time::<MJD>::new(59_000.0);
        let mjd2 = Time::<MJD>::new(59_001.0);
        assert!(mjd1 < mjd2);
        assert!(mjd2 > mjd1);
    }

    #[test]
    fn test_display_jd() {
        let jd = Time::<JD>::new(2_451_545.0);
        let s = format!("{jd}");
        assert!(s.contains("Julian Day"));
    }

    #[test]
    fn test_try_new_finite() {
        let jd = Time::<JD>::try_new(2_451_545.0);
        assert!(jd.is_ok());
        assert_eq!(jd.unwrap().value(), 2_451_545.0);
    }

    #[test]
    fn test_try_new_nan() {
        assert!(Time::<JD>::try_new(f64::NAN).is_err());
    }

    #[test]
    fn test_try_new_infinity() {
        assert!(Time::<JD>::try_new(f64::INFINITY).is_err());
        assert!(Time::<JD>::try_new(f64::NEG_INFINITY).is_err());
    }

    #[test]
    fn test_try_from_days() {
        assert!(Time::<JD>::try_from_days(Days::new(100.0)).is_ok());
        assert!(Time::<JD>::try_from_days(Days::new(f64::NAN)).is_err());
    }

    #[test]
    fn test_display_mjd() {
        let mjd = Time::<MJD>::new(51_544.5);
        let s = format!("{mjd}");
        assert!(s.contains("MJD"));
    }

    #[test]
    fn test_add_assign_sub_assign() {
        let mut jd = Time::<JD>::new(2_451_545.0);
        jd += Days::new(1.0);
        assert_eq!(jd.quantity(), Days::new(2_451_546.0));
        jd -= Days::new(0.5);
        assert_eq!(jd.quantity(), Days::new(2_451_545.5));
    }

    #[test]
    fn test_add_years() {
        let jd = Time::<JD>::new(2_450_000.0);
        let with_years = jd + Years::new(1.0);
        let span: Days = with_years - jd;
        assert!((span - Time::<JD>::JULIAN_YEAR).abs() < Days::new(1e-9));
    }

    #[test]
    fn test_div_days_and_f64() {
        let jd = Time::<JD>::new(100.0);
        assert!((jd / Days::new(2.0) - 50.0).abs() < 1e-12);
        assert!((jd / 4.0 - 25.0).abs() < 1e-12);
    }

    #[test]
    fn test_to_method_jd_mjd() {
        let jd = Time::<JD>::new(2_451_545.0);
        let mjd = jd.to::<MJD>();
        assert!((mjd.quantity() - Days::new(51_544.5)).abs() < Days::new(1e-10));
    }

    #[test]
    fn timeinstant_for_julian_date_handles_arithmetic() {
        let jd = Time::<JD>::new(2_451_545.0);
        let other = jd + Days::new(2.0);

        assert_eq!(jd.difference(&other), Days::new(-2.0));
        assert_eq!(
            jd.add_duration(Days::new(1.5)).quantity(),
            Days::new(2_451_546.5)
        );
        assert_eq!(
            other.sub_duration(Days::new(0.5)).quantity(),
            Days::new(2_451_546.5)
        );
    }

    #[test]
    fn timeinstant_for_modified_julian_date_roundtrips_utc() {
        let dt = DateTime::from_timestamp(946_684_800, 123_000_000).unwrap(); // 2000-01-01T00:00:00.123Z
        let mjd = Time::<MJD>::from_utc(dt);
        let back = mjd.to_utc().expect("mjd to utc");

        assert_eq!(mjd.difference(&mjd), Days::new(0.0));
        assert_eq!(
            mjd.add_duration(Days::new(1.0)).quantity(),
            mjd.quantity() + Days::new(1.0)
        );
        assert_eq!(
            mjd.sub_duration(Days::new(0.5)).quantity(),
            mjd.quantity() - Days::new(0.5)
        );
        let delta_ns = back.timestamp_nanos_opt().unwrap() - dt.timestamp_nanos_opt().unwrap();
        assert!(delta_ns.abs() < 10_000, "nanos differ by {}", delta_ns);
    }

    #[test]
    fn timeinstant_for_datetime_uses_chrono_durations() {
        let base = Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap();
        let later = Utc.with_ymd_and_hms(2024, 1, 2, 6, 0, 0).unwrap();
        let diff = later.difference(&base);

        assert_eq!(diff.num_hours(), 30);
        assert_eq!(
            base.add_duration(diff + chrono::Duration::hours(6)),
            later + chrono::Duration::hours(6)
        );
        assert_eq!(later.sub_duration(diff), base);
        assert_eq!(TimeInstant::to_utc(&later), Some(later));
    }

    // ── New coverage tests ────────────────────────────────────────────

    #[test]
    fn test_non_finite_error_display() {
        let err = NonFiniteTimeError;
        let msg = format!("{err}");
        assert!(msg.contains("finite"), "unexpected: {msg}");
    }

    #[test]
    fn test_julian_day_and_julian_day_value() {
        // MJD 51544.5 == JD 2451545.0 (J2000.0 in TT).
        let mjd = Time::<MJD>::new(51_544.5);
        let jd_days = mjd.julian_day();
        assert!(
            (jd_days - Days::new(2_451_545.0)).abs() < Days::new(1e-10),
            "julian_day mismatch: {jd_days}"
        );
        assert!(
            (mjd.julian_day_value() - 2_451_545.0).abs() < 1e-10,
            "julian_day_value mismatch: {}",
            mjd.julian_day_value()
        );
    }

    #[test]
    fn test_timeinstant_trait_to_utc_and_from_utc_for_time() {
        // Call to_utc / from_utc through the TimeInstant trait (UFCS) so that
        // the forwarding wrapper functions in the TimeInstant impl are covered.
        let jd = Time::<JD>::new(2_451_545.0);
        let utc: Option<_> = TimeInstant::to_utc(&jd);
        assert!(utc.is_some());
        let back: Time<JD> = TimeInstant::from_utc(utc.unwrap());
        assert!((back.value() - jd.value()).abs() < 1e-6);
    }

    #[test]
    fn test_datetime_timeinstant_from_utc() {
        // Exercises TimeInstant::from_utc for DateTime<Utc>.
        let dt = DateTime::from_timestamp(0, 0).unwrap();
        let back: DateTime<Utc> = TimeInstant::from_utc(dt);
        assert_eq!(back, dt);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_serde_serialize_time() {
        let jd = Time::<JD>::new(2_451_545.0);
        let json = serde_json::to_string(&jd).unwrap();
        assert!(json.contains("2451545"), "serialized: {json}");
        let back: Time<JD> = serde_json::from_str(&json).unwrap();
        assert_eq!(jd.value(), back.value());
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_serde_deserialize_nan_rejected() {
        use serde::{de::IntoDeserializer, Deserialize};
        let result: Result<Time<JD>, serde::de::value::Error> =
            Time::<JD>::deserialize(f64::NAN.into_deserializer());
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains("finite"), "unexpected error: {msg}");
    }
}