gnss-time 0.5.2

Type-safe GNSS time scales: GPS, GLONASS, Galileo, BeiDou, TAI, UTC — no_std by default
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
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
//! # GNSS time scale conversion
//!
//! Type-safe conversion between GNSS time scales.
//!
//! This module provides:
//!
//! - [`IntoScale`] — conversions with fixed offsets
//! - [`IntoScaleWith`] — conversions requiring leap-second data
//! - [`ConvertResult`] — representation of leap-second ambiguity
//!
//! ## Overview
//!
//! | Source → Target | Trait                           | Leap seconds |
//! |----------------|----------------------------------|--------------|
//! | GPS → TAI      | [`IntoScale`]                    | No           |
//! | GPS → Galileo  | [`IntoScale`]                    | No           |
//! | GPS → BeiDou   | [`IntoScale`]                    | No           |
//! | UTC ↔ GPS      | [`IntoScaleWith`]                | Yes          |
//! | GPS ↔ GLONASS  | [`IntoScaleWith`]                | Yes          |
//!
//! Fixed-offset conversions are lossless and do not require external data.
//! Leap-second-aware conversions require a [`LeapSecondsProvider`].
//!
//! ## Usage
//!
//! Fixed-offset conversions:
//!
//! ```rust
//! use gnss_time::{DurationParts, Galileo, Gps, IntoScale, Tai, Time};
//!
//! let gps = Time::<Gps>::from_week_tow(
//!     2345,
//!     DurationParts {
//!         seconds: 0,
//!         nanos: 0,
//!     },
//! )
//! .unwrap();
//! let tai: Time<Tai> = gps.into_scale().unwrap();
//! let gal: Time<Galileo> = gps.into_scale().unwrap();
//! ```
//!
//! Leap-second-aware conversions:
//!
//! ```rust
//! use gnss_time::{DurationParts, Gps, IntoScaleWith, LeapSeconds, Time, Utc};
//!
//! let gps = Time::<Gps>::from_week_tow(
//!     2200,
//!     DurationParts {
//!         seconds: 0,
//!         nanos: 0,
//!     },
//! )
//! .unwrap();
//! let ls = LeapSeconds::builtin();
//! let utc: Time<Utc> = gps.into_scale_with(ls).unwrap();
//! ```
//!
//! ## Leap-second ambiguity
//!
//! During leap-second insertion, `GPS → UTC` conversion may map into a
//! one-second interval that cannot be represented as a single unambiguous
//! civil-time instant.
//!
//! Use [`IntoScaleWith::into_scale_with_checked`] to detect ambiguity.
//!
//! ```rust
//! use gnss_time::{ConvertResult, Gps, IntoScaleWith, LeapSeconds, Time, Utc};
//!
//! let ls = LeapSeconds::builtin();
//! let gps = Time::<Gps>::from_seconds(1_167_264_018);
//!
//! let result: Result<ConvertResult<Time<Utc>>, _> = gps.into_scale_with_checked(ls);
//!
//! assert!(matches!(result, Ok(ConvertResult::AmbiguousLeapSecond(_))));
//! ```

use crate::{
    beidou_to_glonass, beidou_to_utc, galileo_to_glonass, galileo_to_utc, glonass_to_beidou,
    glonass_to_galileo, glonass_to_gps, glonass_to_utc, gps_to_glonass, gps_to_utc, utc_to_beidou,
    utc_to_galileo, utc_to_glonass, utc_to_gps, Beidou, Galileo, Glonass, GnssTimeError, Gps,
    LeapSecondsProvider, Tai, Time, TimeScale, Utc,
};

/// Fixed-offset conversion between time scales.
///
/// This trait is implemented for conversions where the relationship between
/// time scales is constant and independent of leap seconds.
#[must_use = "conversion result must be used; ignoring it discards the converted time"]
pub trait IntoScale<Target: TimeScale>: Sized {
    /// Converts the value into the target time scale.
    ///
    /// # Errors
    ///
    /// Returns [`GnssTimeError::Overflow`] if the result cannot be represented
    /// in the target scale.
    fn into_scale(self) -> Result<Time<Target>, GnssTimeError>;
}

/// Leap-second-aware conversion between time scales.
///
/// Required for conversions involving UTC or any scale derived from UTC.
///
/// This trait uses an external [`LeapSecondsProvider`] to resolve
/// discontinuities introduced by leap seconds.
#[must_use = "conversion result must be used; ignoring it discards the converted time"]
pub trait IntoScaleWith<Target: TimeScale>: Sized {
    /// Converts using leap-second data.
    fn into_scale_with<P: LeapSecondsProvider>(
        self,
        ls: P,
    ) -> Result<Time<Target>, GnssTimeError>;

    /// Converts and reports whether the result is ambiguous due to a
    /// leap-second insertion.
    fn into_scale_with_checked<P: LeapSecondsProvider>(
        self,
        ls: P,
    ) -> Result<ConvertResult<Time<Target>>, GnssTimeError>;
}

/// Result of a leap-second-aware conversion.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[must_use = "ConvertResult contains ambiguity information; call .into_inner() or match explicitly"]
pub enum ConvertResult<T> {
    /// Unambiguous conversion result.
    Exact(T),

    /// Conversion falls inside a leap-second insertion window.
    ///
    /// The value represents the closest representable instant.
    AmbiguousLeapSecond(T),
}

impl<T> ConvertResult<T> {
    /// Returns the inner value.
    #[inline]
    #[must_use]
    pub fn into_inner(self) -> T {
        match self {
            Self::Exact(t) | Self::AmbiguousLeapSecond(t) => t,
        }
    }

    /// Returns `true` if the result is unambiguous.
    #[inline]
    #[must_use]
    pub fn is_exact(&self) -> bool {
        matches!(self, Self::Exact(_))
    }

    /// Returns `true` if the result is ambiguous due to a leap second.
    #[inline]
    #[must_use]
    pub fn is_ambiguous(&self) -> bool {
        matches!(self, Self::AmbiguousLeapSecond(_))
    }
}

////////////////////////////////////////////////////////////////////////////////
// GLONASS for Gps, Galileo, Beidou, UTC
////////////////////////////////////////////////////////////////////////////////

impl IntoScale<Glonass> for Time<Utc> {
    /// UTC -> GLONASS: постоянный сдвиг эпохи.
    ///
    /// # Errors
    ///
    /// [`GnssTimeError::Overflow`] если UTC раньше эпохи GLONASS
    /// (1995-12-31 21:00:00 UTC).
    #[inline]
    fn into_scale(self) -> Result<Time<Glonass>, GnssTimeError> {
        utc_to_glonass(self)
    }
}

impl IntoScaleWith<Glonass> for Time<Gps> {
    fn into_scale_with<P: LeapSecondsProvider>(
        self,
        ls: P,
    ) -> Result<Time<Glonass>, GnssTimeError> {
        gps_to_glonass(self, &ls)
    }

    fn into_scale_with_checked<P: LeapSecondsProvider>(
        self,
        ls: P,
    ) -> Result<ConvertResult<Time<Glonass>>, GnssTimeError> {
        Ok(ConvertResult::Exact(gps_to_glonass(self, &ls)?))
    }
}

impl IntoScaleWith<Glonass> for Time<Galileo> {
    fn into_scale_with<P: LeapSecondsProvider>(
        self,
        ls: P,
    ) -> Result<Time<Glonass>, GnssTimeError> {
        galileo_to_glonass(self, &ls)
    }

    fn into_scale_with_checked<P: LeapSecondsProvider>(
        self,
        ls: P,
    ) -> Result<ConvertResult<Time<Glonass>>, GnssTimeError> {
        Ok(ConvertResult::Exact(galileo_to_glonass(self, &ls)?))
    }
}

impl IntoScaleWith<Glonass> for Time<Beidou> {
    fn into_scale_with<P: LeapSecondsProvider>(
        self,
        ls: P,
    ) -> Result<Time<Glonass>, GnssTimeError> {
        beidou_to_glonass(self, &ls)
    }

    fn into_scale_with_checked<P: LeapSecondsProvider>(
        self,
        ls: P,
    ) -> Result<ConvertResult<Time<Glonass>>, GnssTimeError> {
        Ok(ConvertResult::Exact(beidou_to_glonass(self, &ls)?))
    }
}

////////////////////////////////////////////////////////////////////////////////
// Gps for Glonass, Galileo, Beidou, Tai, Utc
////////////////////////////////////////////////////////////////////////////////

impl IntoScale<Gps> for Time<Galileo> {
    #[inline]
    fn into_scale(self) -> Result<Time<Gps>, GnssTimeError> {
        self.try_convert::<Gps>()
    }
}

impl IntoScale<Gps> for Time<Beidou> {
    /// BeiDou -> GPS: `GPS = BDT + 14s`.
    ///
    /// ```rust
    /// use gnss_time::{Beidou, Gps, IntoScale, Time};
    ///
    /// let bdt = Time::<Beidou>::from_seconds(86);
    /// let gps: Time<Gps> = bdt.into_scale().unwrap();
    ///
    /// assert_eq!(gps.as_seconds(), 100); // 86 - 19 + 33 = 100
    /// ```
    #[inline]
    fn into_scale(self) -> Result<Time<Gps>, GnssTimeError> {
        self.try_convert::<Gps>()
    }
}

impl IntoScale<Gps> for Time<Tai> {
    /// TAI -> GPS: subtract 19 seconds.
    ///
    /// ```rust
    /// use gnss_time::{Gps, IntoScale, Tai, Time};
    ///
    /// let tai = Time::<Tai>::from_seconds(119);
    /// let gps: Time<Gps> = tai.into_scale().unwrap();
    ///
    /// assert_eq!(gps.as_seconds(), 100);
    /// ```
    #[inline]
    fn into_scale(self) -> Result<Time<Gps>, GnssTimeError> {
        Time::<Gps>::from_tai(self)
    }
}

impl IntoScaleWith<Gps> for Time<Glonass> {
    /// GLONASS -> GPS via UTC.
    fn into_scale_with<P: LeapSecondsProvider>(
        self,
        ls: P,
    ) -> Result<Time<Gps>, GnssTimeError> {
        glonass_to_gps(self, &ls)
    }

    fn into_scale_with_checked<P: LeapSecondsProvider>(
        self,
        ls: P,
    ) -> Result<ConvertResult<Time<Gps>>, GnssTimeError> {
        Ok(ConvertResult::Exact(glonass_to_gps(self, &ls)?))
    }
}

impl IntoScaleWith<Gps> for Time<Utc> {
    /// UTC -> GPS with leap-second context.
    ///
    /// ```rust
    /// use gnss_time::{DurationParts, Gps, IntoScale, IntoScaleWith, LeapSeconds, Time, Utc};
    ///
    /// let ls = LeapSeconds::builtin();
    /// let gps_orig = Time::<Gps>::from_week_tow(
    ///     2086,
    ///     DurationParts {
    ///         seconds: 0,
    ///         nanos: 0,
    ///     },
    /// )
    /// .unwrap();
    /// let utc: Time<Utc> = gps_orig.into_scale_with(ls).unwrap();
    /// let gps_back: Time<Gps> = utc.into_scale_with(ls).unwrap();
    ///
    /// assert_eq!(gps_orig, gps_back);
    /// ```
    fn into_scale_with<P: LeapSecondsProvider>(
        self,
        ls: P,
    ) -> Result<Time<Gps>, GnssTimeError> {
        utc_to_gps(self, &ls)
    }

    fn into_scale_with_checked<P: LeapSecondsProvider>(
        self,
        ls: P,
    ) -> Result<ConvertResult<Time<Gps>>, GnssTimeError> {
        // UTC -> GPS is unambiguous: each UTC nanosecond corresponds to
        // exactly one GPS nanosecond (GPS has no skipped or repeated seconds).
        Ok(ConvertResult::Exact(utc_to_gps(self, &ls)?))
    }
}

////////////////////////////////////////////////////////////////////////////////
// Galileo for Glonass, Gps, Beidou, Utc
////////////////////////////////////////////////////////////////////////////////

impl IntoScale<Galileo> for Time<Gps> {
    /// GPS -> Galileo: identical at nanosecond level (both use `TAI − 19s`).
    ///
    /// GPS and Galileo timestamps with identical nanoseconds represent
    /// the same physical instant.
    ///
    /// ```rust
    /// use gnss_time::{Galileo, Gps, IntoScale, Time};
    ///
    /// let gps = Time::<Gps>::from_seconds(12_345);
    /// let gal: Time<Galileo> = gps.into_scale().unwrap();
    ///
    /// assert_eq!(gps.as_nanos(), gal.as_nanos());
    /// ```
    #[inline]
    fn into_scale(self) -> Result<Time<Galileo>, GnssTimeError> {
        // GPS and Galileo use the same offset relative to TAI (19 s)
        // → converting via TAI preserves nanoseconds exactly
        self.try_convert::<Galileo>()
    }
}

impl IntoScale<Galileo> for Time<Beidou> {
    /// BeiDou -> Galileo via TAI.
    #[inline]
    fn into_scale(self) -> Result<Time<Galileo>, GnssTimeError> {
        self.try_convert::<Galileo>()
    }
}

impl IntoScaleWith<Galileo> for Time<Glonass> {
    /// GLONASS -> Galileo via UTC.
    fn into_scale_with<P: LeapSecondsProvider>(
        self,
        ls: P,
    ) -> Result<Time<Galileo>, GnssTimeError> {
        glonass_to_galileo(self, &ls)
    }

    fn into_scale_with_checked<P: LeapSecondsProvider>(
        self,
        ls: P,
    ) -> Result<ConvertResult<Time<Galileo>>, GnssTimeError> {
        Ok(ConvertResult::Exact(glonass_to_galileo(self, &ls)?))
    }
}

impl IntoScaleWith<Galileo> for Time<Utc> {
    /// UTC -> Galileo via GPS.
    fn into_scale_with<P: LeapSecondsProvider>(
        self,
        ls: P,
    ) -> Result<Time<Galileo>, GnssTimeError> {
        utc_to_galileo(self, &ls)
    }

    fn into_scale_with_checked<P: LeapSecondsProvider>(
        self,
        ls: P,
    ) -> Result<ConvertResult<Time<Galileo>>, GnssTimeError> {
        Ok(ConvertResult::Exact(utc_to_galileo(self, &ls)?))
    }
}

////////////////////////////////////////////////////////////////////////////////
// Beidou for Glonass, Gps, Galileo, Utc
////////////////////////////////////////////////////////////////////////////////

impl IntoScale<Beidou> for Time<Gps> {
    /// GPS -> BeiDou: `BDT = GPS - 14s`.
    ///
    /// ```rust
    /// use gnss_time::{Beidou, Gps, IntoScale, Time};
    ///
    /// let gps = Time::<Gps>::from_seconds(100);
    /// let bdt: Time<Beidou> = gps.into_scale().unwrap();
    ///
    /// assert_eq!(bdt.as_seconds(), 86); // 100 - 14 = 86
    /// ```
    #[inline]
    fn into_scale(self) -> Result<Time<Beidou>, GnssTimeError> {
        self.try_convert::<Beidou>()
    }
}

impl IntoScale<Beidou> for Time<Galileo> {
    /// Galileo -> BeiDou via TAI.
    #[inline]
    fn into_scale(self) -> Result<Time<Beidou>, GnssTimeError> {
        self.try_convert::<Beidou>()
    }
}

impl IntoScaleWith<Beidou> for Time<Utc> {
    /// UTC → BeiDou via GPS.
    fn into_scale_with<P: LeapSecondsProvider>(
        self,
        ls: P,
    ) -> Result<Time<Beidou>, GnssTimeError> {
        utc_to_beidou(self, &ls)
    }
    fn into_scale_with_checked<P: LeapSecondsProvider>(
        self,
        ls: P,
    ) -> Result<ConvertResult<Time<Beidou>>, GnssTimeError> {
        Ok(ConvertResult::Exact(utc_to_beidou(self, &ls)?))
    }
}

impl IntoScaleWith<Beidou> for Time<Glonass> {
    /// GLONASS -> BeiDou via UTC.
    fn into_scale_with<P: LeapSecondsProvider>(
        self,
        ls: P,
    ) -> Result<Time<Beidou>, GnssTimeError> {
        glonass_to_beidou(self, &ls)
    }

    fn into_scale_with_checked<P: LeapSecondsProvider>(
        self,
        ls: P,
    ) -> Result<ConvertResult<Time<Beidou>>, GnssTimeError> {
        Ok(ConvertResult::Exact(glonass_to_beidou(self, &ls)?))
    }
}

////////////////////////////////////////////////////////////////////////////////
// Utc for Glonass, Gps, Galileo, Beidou
////////////////////////////////////////////////////////////////////////////////

impl IntoScale<Utc> for Time<Glonass> {
    /// GLONASS -> UTC: fixed epoch shift.
    ///
    /// GLONASS uses UTC(SU), a time scale offset from UTC by +3 hours and
    /// including leap seconds.
    ///
    /// ```rust
    /// use gnss_time::{DurationParts, Glonass, IntoScale, Time, Utc};
    ///
    /// let glo = Time::<Glonass>::from_day_tod(
    ///     0,
    ///     DurationParts {
    ///         seconds: 0,
    ///         nanos: 0,
    ///     },
    /// )
    /// .unwrap(); // GLONASS epoch
    /// let utc: Time<Utc> = glo.into_scale().unwrap();
    ///
    /// // UTC at the GLONASS epoch:
    /// // 1995-12-31 21:00:00 UTC = 757_371_600 s from 1972
    /// assert_eq!(utc.as_nanos(), 757_371_600_000_000_000);
    /// ```
    #[inline]
    fn into_scale(self) -> Result<Time<Utc>, GnssTimeError> {
        glonass_to_utc(self)
    }
}

impl IntoScaleWith<Utc> for Time<Gps> {
    /// GPS -> UTC with leap-second context.
    ///
    /// Round-trip consistency: `GPS -> UTC -> GPS` is exact (< 1 ns) for all
    /// moments except the one-second leap-second insertion window.
    ///
    /// ```rust
    /// use gnss_time::{Gps, IntoScaleWith, LeapSeconds, Time, Utc};
    ///
    /// let ls = LeapSeconds::builtin();
    /// let gps = Time::<Gps>::from_seconds(1_167_264_018); // 2017-01-01 GPS
    /// let utc: Time<Utc> = gps.into_scale_with(ls).unwrap();
    ///
    /// let delta = gps.as_seconds() as i64 - utc.as_seconds() as i64 + 252_892_800_i64;
    ///
    /// // GPS leads UTC by 18 s → UTC is 18 s earlier
    /// assert_eq!(delta, 18);
    /// ```
    #[inline]
    fn into_scale_with<P: LeapSecondsProvider>(
        self,
        ls: P,
    ) -> Result<Time<Utc>, GnssTimeError> {
        gps_to_utc(self, &ls)
    }

    fn into_scale_with_checked<P: LeapSecondsProvider>(
        self,
        ls: P,
    ) -> Result<ConvertResult<Time<Utc>>, GnssTimeError> {
        let utc = gps_to_utc(self, &ls)?;

        // Detect leap-second window: compute TAI at this GPS timestamp
        // and compare leap-second offsets before and after.
        // If values differ — we are inside (or adjacent to) a leap-second boundary.
        let tai = self.to_tai()?;
        let n_at = ls.tai_minus_utc_at(tai);

        // Check 1 second back to detect entry into leap second
        let tai_prev = if tai.as_nanos() >= 1_000_000_000 {
            Time::<Tai>::from_nanos(tai.as_nanos() - 1_000_000_000)
        } else {
            tai
        };
        let n_before = ls.tai_minus_utc_at(tai_prev);

        if n_at != n_before {
            // We crossed a leap-second boundary within the last second.
            // The GPS second corresponding to the old offset is ambiguous.
            Ok(ConvertResult::AmbiguousLeapSecond(utc))
        } else {
            Ok(ConvertResult::Exact(utc))
        }
    }
}

impl IntoScaleWith<Utc> for Time<Galileo> {
    /// Galileo -> UTC via GPS (both share the same TAI offset of 19s).
    fn into_scale_with<P: LeapSecondsProvider>(
        self,
        ls: P,
    ) -> Result<Time<Utc>, GnssTimeError> {
        galileo_to_utc(self, &ls)
    }

    fn into_scale_with_checked<P: LeapSecondsProvider>(
        self,
        ls: P,
    ) -> Result<ConvertResult<Time<Utc>>, GnssTimeError> {
        Ok(ConvertResult::Exact(galileo_to_utc(self, &ls)?))
    }
}

impl IntoScaleWith<Utc> for Time<Beidou> {
    /// BeiDou -> UTC via GPS.
    fn into_scale_with<P: LeapSecondsProvider>(
        self,
        ls: P,
    ) -> Result<Time<Utc>, GnssTimeError> {
        beidou_to_utc(self, &ls)
    }

    fn into_scale_with_checked<P: LeapSecondsProvider>(
        self,
        ls: P,
    ) -> Result<ConvertResult<Time<Utc>>, GnssTimeError> {
        Ok(ConvertResult::Exact(beidou_to_utc(self, &ls)?))
    }
}

////////////////////////////////////////////////////////////////////////////////
// Tai for Gps
////////////////////////////////////////////////////////////////////////////////

impl IntoScale<Tai> for Time<Gps> {
    /// GPS -> TAI: add 19 seconds (constant, no leap seconds).
    ///
    /// ```rust
    /// use gnss_time::{Gps, IntoScale, Tai, Time};
    ///
    /// let gps = Time::<Gps>::from_seconds(100);
    /// let tai: Time<Tai> = gps.into_scale().unwrap();
    ///
    /// assert_eq!(tai.as_seconds(), 119);
    /// ```
    #[inline]
    fn into_scale(self) -> Result<Time<Tai>, GnssTimeError> {
        self.to_tai()
    }
}

////////////////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////////////////

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{DurationParts, LeapSeconds};

    #[test]
    fn test_gps_to_tai_adds_19_seconds() {
        let gps = Time::<Gps>::from_seconds(100);
        let tai: Time<Tai> = gps.into_scale().unwrap();

        // 100 + 19
        assert_eq!(tai.as_seconds(), 119);
    }

    #[test]
    fn test_tai_to_gps_subtracts_19_seconds() {
        let tai = Time::<Tai>::from_seconds(119);
        let gps: Time<Gps> = tai.into_scale().unwrap();

        // 119 - 19 = 100
        assert_eq!(gps.as_seconds(), 100);
    }

    #[test]
    fn test_gps_tai_gps_roundtrip() {
        let gps = Time::<Gps>::from_week_tow(
            2345,
            DurationParts {
                seconds: 432_000,
                nanos: 0,
            },
        )
        .unwrap();
        let tai: Time<Tai> = gps.into_scale().unwrap();
        let back: Time<Gps> = tai.into_scale().unwrap();

        assert_eq!(gps, back);
    }

    #[test]
    fn test_tai_to_gps_underflow_at_tai_zero() {
        // TAI(0) − 19 s → negative GPS time → overflow
        let tai = Time::<Tai>::EPOCH;
        let result: Result<Time<Gps>, _> = tai.into_scale();

        assert!(matches!(result, Err(GnssTimeError::Overflow)));
    }

    #[test]
    fn test_gps_to_galileo_preserves_nanos() {
        let gps = Time::<Gps>::from_seconds(12_345_678);
        let gal: Time<Galileo> = gps.into_scale().unwrap();

        assert_eq!(gps.as_nanos(), gal.as_nanos());
    }

    #[test]
    fn test_galileo_to_gps_preserves_nanos() {
        let gal = Time::<Galileo>::from_seconds(99_999_999);
        let gps: Time<Gps> = gal.into_scale().unwrap();

        assert_eq!(gal.as_nanos(), gps.as_nanos());
    }

    #[test]
    fn test_gps_galileo_gps_roundtrip() {
        let gps = Time::<Gps>::from_week_tow(
            2000,
            DurationParts {
                seconds: 123_456,
                nanos: 789_000_000,
            },
        )
        .unwrap();
        let gal: Time<Galileo> = gps.into_scale().unwrap();
        let back: Time<Gps> = gal.into_scale().unwrap();

        assert_eq!(gps, back);
    }

    #[test]
    fn test_gps_to_beidou_subtracts_14_seconds() {
        // GPS + 19 s = TAI; BDT + 33 s = TAI → BDT = GPS + 19 - 33 = GPS - 14
        let gps = Time::<Gps>::from_seconds(100);
        let bdt: Time<Beidou> = gps.into_scale().unwrap();

        assert_eq!(bdt.as_seconds(), 86); // 100 - 14 = 86
    }

    #[test]
    fn test_beidou_to_gps_adds_14_seconds() {
        let bdt = Time::<Beidou>::from_seconds(86);
        let gps: Time<Gps> = bdt.into_scale().unwrap();

        assert_eq!(gps.as_seconds(), 100);
    }

    #[test]
    fn test_gps_beidou_gps_roundtrip() {
        let gps = Time::<Gps>::from_week_tow(
            2100,
            DurationParts {
                seconds: 86_400,
                nanos: 0,
            },
        )
        .unwrap();
        let bdt: Time<Beidou> = gps.into_scale().unwrap();
        let back: Time<Gps> = bdt.into_scale().unwrap();

        assert_eq!(gps, back);
    }

    #[test]
    fn test_galileo_beidou_roundtrip() {
        let gal = Time::<Galileo>::from_seconds(1_000_000_000);
        let bdt: Time<Beidou> = gal.into_scale().unwrap();
        let back: Time<Galileo> = bdt.into_scale().unwrap();

        assert_eq!(gal, back);
    }

    #[test]
    fn test_glonass_epoch_to_utc_nanos() {
        let glo = Time::<Glonass>::EPOCH;
        let utc: Time<Utc> = glo.into_scale().unwrap();

        // GLONASS epoch = 1995-12-31 21:00:00 UTC = 757_371_600 seconds from 1972
        assert_eq!(utc.as_nanos(), 757_371_600_000_000_000);
    }

    #[test]
    fn test_utc_at_glonass_epoch_gives_zero() {
        let utc = Time::<Utc>::from_nanos(757_371_600_000_000_000);
        let glo: Time<Glonass> = utc.into_scale().unwrap();

        assert_eq!(glo, Time::<Glonass>::EPOCH);
    }

    #[test]
    fn test_glonass_utc_glonass_roundtrip() {
        let glo = Time::<Glonass>::from_day_tod(
            10_000,
            DurationParts {
                seconds: 36_000,
                nanos: 0,
            },
        )
        .unwrap();
        let utc: Time<Utc> = glo.into_scale().unwrap();
        let back: Time<Glonass> = utc.into_scale().unwrap();

        assert_eq!(glo, back);
    }

    #[test]
    fn test_utc_before_glonass_epoch_is_error() {
        let utc = Time::<Utc>::EPOCH;
        let result: Result<Time<Glonass>, _> = utc.into_scale();

        assert!(matches!(result, Err(GnssTimeError::Overflow)));
    }

    #[test]
    fn test_gps_utc_gps_roundtrip_at_gps_epoch() {
        let ls = LeapSeconds::builtin();
        let gps = Time::<Gps>::EPOCH;
        let utc: Time<Utc> = gps.into_scale_with(ls).unwrap();
        let back: Time<Gps> = utc.into_scale_with(ls).unwrap();

        assert_eq!(gps, back);
    }

    #[test]
    fn test_gps_utc_gps_roundtrip_at_2020() {
        let ls = LeapSeconds::builtin();
        let gps = Time::<Gps>::from_week_tow(
            2086,
            DurationParts {
                seconds: 0,
                nanos: 0,
            },
        )
        .unwrap();
        let utc: Time<Utc> = gps.into_scale_with(ls).unwrap();
        let back: Time<Gps> = utc.into_scale_with(ls).unwrap();

        assert_eq!(gps, back);
    }

    #[test]
    fn test_gps_utc_roundtrip_exact_at_nanosecond_level() {
        let ls = LeapSeconds::builtin();
        // Use a timestamp with a non-zero nanosecond component
        let gps = Time::<Gps>::from_nanos(1_167_264_100_123_456_789);
        let utc: Time<Utc> = gps.into_scale_with(ls).unwrap();
        let back: Time<Gps> = utc.into_scale_with(ls).unwrap();

        assert_eq!(gps, back); // exact, no rounding
    }

    #[test]
    fn test_gps_leads_utc_by_18s_at_2017_01_01() {
        let ls = LeapSeconds::builtin();
        // 2017-01-01 UTC: 16,437 days * 86,400 s from 1972-01-01
        let expected_utc_s: u64 = 16_437 * 86_400;
        // GPS seconds for this UTC moment:
        // GPS = UTC - epoch_offset + (n - 19)
        // where n = 37, epoch_offset = 252,892,800 s
        let gps_s: u64 = 1_167_264_000 + 18; // pre-verified
        let gps = Time::<Gps>::from_seconds(gps_s);
        let utc: Time<Utc> = gps.into_scale_with(ls).unwrap();

        assert_eq!(utc.as_seconds(), expected_utc_s);
    }

    #[test]
    fn test_gps_leads_utc_by_13s_at_1999_01_01() {
        let ls = LeapSeconds::builtin();
        let gps = Time::<Gps>::from_seconds(599_184_013);
        let utc: Time<Utc> = gps.into_scale_with(ls).unwrap();
        let expected_utc_s: u64 = 9_862 * 86_400; // days from 1972 to 1999

        assert_eq!(utc.as_seconds(), expected_utc_s);
    }

    #[test]
    fn test_gps_glonass_gps_roundtrip() {
        let ls = LeapSeconds::builtin();
        let gps = Time::<Gps>::from_week_tow(
            2100,
            DurationParts {
                seconds: 86_400,
                nanos: 0,
            },
        )
        .unwrap();
        let glo: Time<Glonass> = gps.into_scale_with(ls).unwrap();
        let back: Time<Gps> = glo.into_scale_with(ls).unwrap();

        assert_eq!(gps, back);
    }

    #[test]
    fn test_normal_gps_gives_exact_convert_result() {
        let ls = LeapSeconds::builtin();
        let gps = Time::<Gps>::from_week_tow(
            2086,
            DurationParts {
                seconds: 0,
                nanos: 0,
            },
        )
        .unwrap();
        let result: ConvertResult<Time<Utc>> = gps.into_scale_with_checked(ls).unwrap();

        assert!(result.is_exact());
    }

    #[test]
    fn test_utc_to_gps_always_exact() {
        let ls = LeapSeconds::builtin();
        let utc = Time::<Utc>::from_nanos(757_371_600_000_000_000 + 1_000_000_000);
        let result: ConvertResult<Time<Gps>> = utc.into_scale_with_checked(ls).unwrap();

        assert!(result.is_exact());
    }

    #[test]
    fn test_into_inner_returns_value() {
        let t = Time::<Gps>::from_seconds(100);
        let r = ConvertResult::Exact(t);

        assert_eq!(r.into_inner(), t);

        let t2 = Time::<Gps>::from_seconds(200);
        let r2 = ConvertResult::AmbiguousLeapSecond(t2);

        assert_eq!(r2.into_inner(), t2);
    }

    #[test]
    fn test_gps_to_tai_overflow_at_max() {
        let gps = Time::<Gps>::MAX;
        let result: Result<Time<Tai>, _> = gps.into_scale();

        assert!(matches!(result, Err(GnssTimeError::Overflow)));
    }

    #[test]
    fn test_into_scale_gps_tai_matches_to_tai() {
        let gps = Time::<Gps>::from_seconds(999_999);
        let via_trait: Time<Tai> = gps.into_scale().unwrap();
        let via_method = gps.to_tai().unwrap();

        assert_eq!(via_trait, via_method);
    }

    #[test]
    fn test_into_scale_with_gps_utc_matches_gps_to_utc() {
        use crate::leap::{gps_to_utc, LeapSeconds};
        let ls = LeapSeconds::builtin();
        let gps = Time::<Gps>::from_seconds(599_184_013);
        let via_trait: Time<Utc> = gps.into_scale_with(ls).unwrap();
        let via_fn = gps_to_utc(gps, ls).unwrap();

        assert_eq!(via_trait, via_fn);
    }

    #[test]
    fn test_gps_to_utc_detects_leap_second_ambiguity() {
        let ls = LeapSeconds::builtin();
        // GPS time прямо на leap second boundary (2017-01-01)
        let gps = Time::<Gps>::from_seconds(1_167_264_018);
        let result: ConvertResult<Time<Utc>> = gps.into_scale_with_checked(ls).unwrap();

        assert!(matches!(result, ConvertResult::AmbiguousLeapSecond(_)));
    }

    #[test]
    fn test_all_roundtrip_invariants() {
        let ls = LeapSeconds::builtin();

        let gps_values = [
            Time::<Gps>::from_week_tow(
                2086,
                DurationParts {
                    seconds: 0,
                    nanos: 0,
                },
            )
            .unwrap(),
            Time::<Gps>::from_week_tow(
                2100,
                DurationParts {
                    seconds: 86_400,
                    nanos: 0,
                },
            )
            .unwrap(),
            Time::<Gps>::from_nanos(1_167_264_100_123_456_789),
        ];

        for gps in gps_values {
            let utc: Time<Utc> = gps.into_scale_with(ls).unwrap();
            let back: Time<Gps> = utc.into_scale_with(ls).unwrap();
            assert_eq!(gps, back);

            let gal: Time<Galileo> = gps.into_scale().unwrap();
            let back: Time<Gps> = gal.into_scale().unwrap();
            assert_eq!(gps, back);

            let bdt: Time<Beidou> = gps.into_scale().unwrap();
            let back: Time<Gps> = bdt.into_scale().unwrap();
            assert_eq!(gps, back);
        }
    }

    #[test]
    fn test_gps_epoch_to_utc_is_exact() {
        let ls = LeapSeconds::builtin();

        let gps = Time::<Gps>::EPOCH;
        let utc: Time<Utc> = gps.into_scale_with(ls).unwrap();

        assert_eq!(utc.as_seconds(), 252_892_800);
    }

    #[test]
    fn test_gps_epoch_utc_roundtrip() {
        let ls = LeapSeconds::builtin();

        let gps = Time::<Gps>::EPOCH;
        let utc: Time<Utc> = gps.into_scale_with(ls).unwrap();
        let back: Time<Gps> = utc.into_scale_with(ls).unwrap();

        assert_eq!(gps, back);
    }

    #[test]
    fn test_glonass_roundtrip_invariants_supported_range() {
        let ls = LeapSeconds::builtin();

        let gps_values = [
            Time::<Gps>::from_week_tow(
                2086,
                DurationParts {
                    seconds: 0,
                    nanos: 0,
                },
            )
            .unwrap(),
            Time::<Gps>::from_week_tow(
                2100,
                DurationParts {
                    seconds: 86_400,
                    nanos: 0,
                },
            )
            .unwrap(),
            Time::<Gps>::from_nanos(1_167_264_100_123_456_789),
        ];

        for gps in gps_values {
            let glo: Time<Glonass> = gps.into_scale_with(ls).unwrap();
            let back: Time<Gps> = glo.into_scale_with(ls).unwrap();

            assert_eq!(gps, back);
        }
    }

    #[test]
    fn test_checked_variants_contract() {
        let ls = LeapSeconds::builtin();
        let gps = Time::<Gps>::from_week_tow(
            2000,
            DurationParts {
                seconds: 0,
                nanos: 0,
            },
        )
        .unwrap();
        let res: ConvertResult<Time<Utc>> = gps.into_scale_with_checked(ls).unwrap();

        match res {
            ConvertResult::Exact(_) => {}
            ConvertResult::AmbiguousLeapSecond(_) => panic!("unexpected ambiguity"),
        }
    }

    #[test]
    fn test_convert_result_consistency() {
        let t = Time::<Gps>::from_seconds(42);
        let exact = ConvertResult::Exact(t);

        assert!(exact.is_exact());
        assert!(!exact.is_ambiguous());

        let amb = ConvertResult::AmbiguousLeapSecond(t);

        assert!(!amb.is_exact());
        assert!(amb.is_ambiguous());
    }

    #[test]
    fn test_gps_to_tai_overflow_near_max() {
        let gps = Time::<Gps>::from_nanos(Time::<Gps>::MAX.as_nanos() - 1);
        let result: Result<Time<Tai>, _> = gps.into_scale();

        assert!(matches!(result, Err(GnssTimeError::Overflow)));
    }

    #[test]
    fn test_gps_to_tai_near_overflow_succeeds() {
        let gps = Time::<Gps>::from_nanos(Time::<Gps>::MAX.as_nanos() - 20_000_000_000);
        let tai: Time<Tai> = gps.into_scale().unwrap();

        assert!(tai.as_nanos() > gps.as_nanos());
    }

    #[test]
    fn test_glonass_utc_symmetry_random() {
        let utc = Time::<Utc>::from_nanos(800_000_000_000_000_000);
        let glo: Time<Glonass> = utc.into_scale().unwrap();
        let back: Time<Utc> = glo.into_scale().unwrap();

        assert_eq!(utc, back);
    }
}