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
//! # Conversion matrix: the full graph of supported transformations
//!
//! This module documents and validates the **complete matrix** of allowed
//! conversions between time scales, and also provides
//! [`crate::matrix::ConversionMatrix`],
//! a runtime type for checking scale compatibility.
//!
//! ## Offset table (sources: ICD-GLONASS, IS-GPS-200, OS-SIS-ICD Galileo, BDS-SIS-ICD)
//!
//! | From \ To  | GLONASS     | GPS        | Galileo    | BeiDou     | TAI        | UTC         |
//! |------------|-------------|------------|------------|------------|------------|-------------|
//! | **GLONASS**| —           | via UTC+LS | via UTC+LS | via UTC+LS | no (ctx)   | +757371600c |
//! | **GPS**    | via UTC+LS  | —          | identity   | −14c       | +19c       | via LS      |
//! | **Galileo**| via UTC+LS  | identity   | —          | −14c       | +19c       | via LS      |
//! | **BeiDou** | via UTC+LS  | +14c       | +14c       | —          | +33c       | via LS      |
//! | **TAI**    | no (ctx)    | −19c       | −19c       | −33c       | —          | via LS      |
//! | **UTC**    | +757371600s | via LS     | via LS     | via LS     | via LS     | —           |

use crate::{
    Beidou, Glonass, GnssTimeError, Gps, IntoScale, IntoScaleWith, LeapSecondsProvider, Tai, Time,
    Utc,
};

/// GPS offset relative to TAI in nanoseconds (GPS = TAI - 19 s).
pub const TAI_OFFSET_GPS_NS: i64 = 19 * 1_000_000_000;

/// Galileo offset relative to TAI in nanoseconds (GAL = TAI - 19 s).
pub const TAI_OFFSET_GALILEO_NS: i64 = 19 * 1_000_000_000;

/// BeiDou offset relative to TAI in nanoseconds (BDT = TAI - 33 s).
pub const TAI_OFFSET_BEIDOU_NS: i64 = 33 * 1_000_000_000;

/// TAI offset relative to itself (0 nanoseconds).
pub const TAI_OFFSET_TAI_NS: i64 = 0;

/// Constant epoch shift between GLONASS and UTC in nanoseconds.
///
/// GLONASS epoch (1996-01-01 00:00:00 UTC(SU)) is 757_371_600 seconds ahead
/// of the UTC epoch (1972-01-01).
pub const GLONASS_UTC_EPOCH_SHIFT_NS: i64 = 757_371_600 * 1_000_000_000;

/// Conversion kind between two time scales.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ConversionKind {
    /// Fixed offset — no context required.
    Fixed,

    /// Identity mapping (GPS <-> Galileo: same nanoseconds).
    Identity,

    /// Constant epoch shift without leap-second context (GLONASS <-> UTC).
    EpochShift,

    /// Requires [`LeapSecondsProvider`].
    Contextual,

    /// Same scale (no conversion needed).
    SameScale,
}

/// Runtime time-scale identifier.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ScaleId {
    /// GLONASS time scale.
    Glonass,

    /// GPS time scale.
    Gps,

    /// Galileo time scale.
    Galileo,

    /// BeiDou time scale.
    Beidou,

    /// International Atomic Time.
    Tai,

    /// Coordinated Universal Time.
    Utc,
}

/// Conversion matrix: documents and validates all allowed routes between the
/// supported time scales.
///
/// # Example
///
/// ```rust
/// use gnss_time::{ConversionMatrix, ScaleId};
///
/// // Check that GPS <-> Galileo is a fixed conversion
/// assert!(ScaleId::Gps.is_fixed(ScaleId::Galileo));
///
/// // Check that GPS <-> UTC requires leap seconds
/// assert!(ScaleId::Gps.needs_leap_seconds(ScaleId::Utc));
///
/// // Full 6x6 matrix
/// let matrix = ConversionMatrix::new();
///
/// assert_eq!(matrix.path_count(false), 14); // fixed paths
/// assert_eq!(matrix.path_count(true), 16); // contextual paths
/// ```
pub struct ConversionMatrix;

/// Result of the end-to-end conversion BeiDou -> GPS -> GLONASS -> UTC -> TAI.
#[derive(Debug)]
pub struct ConversionChain {
    /// GLONASS time.
    pub glonass: Time<Glonass>,

    /// GPS time.
    pub gps: Time<Gps>,

    /// UTC time.
    pub utc: Time<Utc>,

    /// TAI time.
    pub tai: Time<Tai>,
}

impl ScaleId {
    /// All supported scales.
    pub const ALL: [ScaleId; 6] = [
        ScaleId::Glonass,
        ScaleId::Gps,
        ScaleId::Galileo,
        ScaleId::Beidou,
        ScaleId::Tai,
        ScaleId::Utc,
    ];

    /// Returns the ASCII name of the scale.
    #[inline]
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            ScaleId::Glonass => "GLO",
            ScaleId::Gps => "GPS",
            ScaleId::Galileo => "GAL",
            ScaleId::Beidou => "BDT",
            ScaleId::Tai => "TAI",
            ScaleId::Utc => "UTC",
        }
    }

    /// Determines the conversion kind between the current scale and a target
    /// scale.
    ///
    /// # Parameters
    /// - `target` — target time scale
    ///
    /// # Returns
    /// The conversion kind: fixed, identity, epoch shift, contextual, or same
    /// scale.
    #[inline]
    #[must_use]
    pub const fn conversion_kind(
        self,
        target: ScaleId,
    ) -> ConversionKind {
        use ConversionKind::*;
        use ScaleId::*;
        match (self, target) {
            // Same scale → no conversion needed
            (a, b) if a as u8 == b as u8 => SameScale,
            // GPS <-> TAI
            (Gps, Tai) | (Tai, Gps) => Fixed,
            // GPS <-> Galileo: identical TAI offset (19 s)
            (Gps, Galileo) | (Galileo, Gps) => Identity,
            // GPS <-> BeiDou: fixed ±14 seconds offset
            (Gps, Beidou) | (Beidou, Gps) => Fixed,
            // Galileo <-> BeiDou: same fixed relationship via TAI
            (Galileo, Beidou) | (Beidou, Galileo) => Fixed,
            // Galileo <-> TAI, BeiDou <-> TAI
            (Galileo, Tai) | (Tai, Galileo) => Fixed,
            (Beidou, Tai) | (Tai, Beidou) => Fixed,
            // GLONASS <-> UTC: epoch shift, no leap-second handling
            (Glonass, Utc) | (Utc, Glonass) => EpochShift,
            // All conversions involving UTC require leap-second context
            (Gps, Utc) | (Utc, Gps) => Contextual,
            (Gps, Glonass) | (Glonass, Gps) => Contextual,
            (Galileo, Utc) | (Utc, Galileo) => Contextual,
            (Galileo, Glonass) | (Glonass, Galileo) => Contextual,
            (Beidou, Utc) | (Utc, Beidou) => Contextual,
            (Beidou, Glonass) | (Glonass, Beidou) => Contextual,
            // TAI <-> UTC and TAI <-> GLONASS: context-dependent (leap seconds / epoch)
            (Tai, Utc) | (Utc, Tai) => Contextual,
            (Tai, Glonass) | (Glonass, Tai) => Contextual,
            // Default for future or unknown scales
            _ => Contextual,
        }
    }

    /// Returns `true` if the conversion `self -> target` does not require leap
    /// second context.
    #[inline]
    #[must_use]
    pub const fn is_fixed(
        self,
        target: ScaleId,
    ) -> bool {
        matches!(
            self.conversion_kind(target),
            ConversionKind::Fixed | ConversionKind::Identity | ConversionKind::EpochShift
        )
    }

    /// Returns `true` if the conversion requires a [`LeapSecondsProvider`].
    #[inline]
    #[must_use]
    pub const fn needs_leap_seconds(
        self,
        target: ScaleId,
    ) -> bool {
        matches!(self.conversion_kind(target), ConversionKind::Contextual)
    }
}

impl ConversionMatrix {
    /// Creates a new conversion matrix.
    #[inline]
    #[must_use]
    pub fn new() -> Self {
        ConversionMatrix
    }

    /// Returns the number of paths of the requested type (fixed or contextual).
    #[must_use]
    pub fn path_count(
        &self,
        contextual: bool,
    ) -> usize {
        let mut count = 0;

        for &from in &ScaleId::ALL {
            for &to in &ScaleId::ALL {
                if from != to {
                    let kind = from.conversion_kind(to);
                    let is_ctx = matches!(kind, ConversionKind::Contextual);

                    if contextual == is_ctx {
                        count += 1;
                    }
                }
            }
        }

        count
    }

    /// Returns the conversion kind for `from -> to`.
    #[inline]
    #[must_use]
    pub fn kind(
        &self,
        from: ScaleId,
        to: ScaleId,
    ) -> ConversionKind {
        from.conversion_kind(to)
    }
}

impl Default for ConversionMatrix {
    fn default() -> Self {
        ConversionMatrix::new()
    }
}

/// Performs the conversion GPS -> BeiDou -> GLONASS -> UTC -> TAI in one call.
pub fn beidou_via_gps_to_glonass_via_utc<P: LeapSecondsProvider>(
    bdt: Time<Beidou>,
    ls: &P,
) -> Result<ConversionChain, GnssTimeError> {
    let gps: Time<Gps> = bdt.into_scale()?;
    let glo: Time<Glonass> = gps.into_scale_with(ls)?;
    let utc: Time<Utc> = glo.into_scale()?;
    let tai: Time<Tai> = gps.into_scale()?;

    Ok(ConversionChain {
        gps,
        glonass: glo,
        utc,
        tai,
    })
}

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

#[cfg(test)]
mod tests {
    #[allow(unused_imports)]
    use std::vec;

    use super::*;

    #[test]
    fn test_scale_id_names_are_correct() {
        assert_eq!(ScaleId::Glonass.name(), "GLO");
        assert_eq!(ScaleId::Gps.name(), "GPS");
        assert_eq!(ScaleId::Galileo.name(), "GAL");
        assert_eq!(ScaleId::Beidou.name(), "BDT");
        assert_eq!(ScaleId::Tai.name(), "TAI");
        assert_eq!(ScaleId::Utc.name(), "UTC");
    }

    #[test]
    fn test_same_scale_is_same_scale() {
        for &s in &ScaleId::ALL {
            assert_eq!(s.conversion_kind(s), ConversionKind::SameScale);
        }
    }

    #[test]
    fn test_gps_galileo_is_identity() {
        // Error
        assert_eq!(
            ScaleId::Gps.conversion_kind(ScaleId::Galileo),
            ConversionKind::Identity
        );
        assert_eq!(
            ScaleId::Galileo.conversion_kind(ScaleId::Gps),
            ConversionKind::Identity
        );
    }

    #[test]
    fn test_gps_tai_is_fixed() {
        assert_eq!(
            ScaleId::Gps.conversion_kind(ScaleId::Tai),
            ConversionKind::Fixed
        );
        assert_eq!(
            ScaleId::Tai.conversion_kind(ScaleId::Gps),
            ConversionKind::Fixed
        );
    }

    #[test]
    fn test_gps_beidou_is_fixed() {
        assert_eq!(
            ScaleId::Gps.conversion_kind(ScaleId::Beidou),
            ConversionKind::Fixed
        );
        assert_eq!(
            ScaleId::Beidou.conversion_kind(ScaleId::Gps),
            ConversionKind::Fixed
        );
    }

    #[test]
    fn test_glonass_utc_is_epoch_shift() {
        assert_eq!(
            ScaleId::Glonass.conversion_kind(ScaleId::Utc),
            ConversionKind::EpochShift
        );
        assert_eq!(
            ScaleId::Utc.conversion_kind(ScaleId::Glonass),
            ConversionKind::EpochShift
        );
    }

    #[test]
    fn test_contextual_conversions_require_leap_seconds() {
        let contextual_pairs = [
            (ScaleId::Gps, ScaleId::Utc),
            (ScaleId::Gps, ScaleId::Glonass),
            (ScaleId::Galileo, ScaleId::Utc),
            (ScaleId::Galileo, ScaleId::Glonass),
            (ScaleId::Beidou, ScaleId::Utc),
            (ScaleId::Beidou, ScaleId::Glonass),
        ];
        for (from, to) in contextual_pairs {
            assert!(
                from.needs_leap_seconds(to),
                "{:?} → {:?} should be contextual",
                from,
                to
            );
            assert!(
                to.needs_leap_seconds(from),
                "{:?} → {:?} should be contextual",
                to,
                from
            );
        }
    }

    #[test]
    fn test_fixed_conversions_dont_need_leap_seconds() {
        let fixed_pairs = [
            (ScaleId::Gps, ScaleId::Tai),
            (ScaleId::Gps, ScaleId::Galileo),
            (ScaleId::Gps, ScaleId::Beidou),
            (ScaleId::Galileo, ScaleId::Beidou),
            (ScaleId::Glonass, ScaleId::Utc),
        ];
        for (from, to) in fixed_pairs {
            assert!(from.is_fixed(to), "{:?} → {:?} should be fixed", from, to);
            assert!(to.is_fixed(from), "{:?} → {:?} should be fixed", to, from);
        }
    }

    #[test]
    fn test_tai_offset_constants_are_correct() {
        assert_eq!(TAI_OFFSET_GPS_NS, 19_000_000_000);
        assert_eq!(TAI_OFFSET_GALILEO_NS, 19_000_000_000);
        assert_eq!(TAI_OFFSET_BEIDOU_NS, 33_000_000_000);
        assert_eq!(TAI_OFFSET_TAI_NS, 0);
        assert_eq!(GLONASS_UTC_EPOCH_SHIFT_NS, 757_371_600_000_000_000);
    }

    #[test]
    fn test_matrix_counts_are_correct() {
        let m = ConversionMatrix::new();
        // 6×6 matrix → 6 diagonal elements → 30 off-diagonal cells
        //
        // Fixed/Identity/EpochShift paths are symmetric pairs:
        // GPS↔TAI(2) + GPS↔GAL(2) + GPS↔BDT(2)
        // GAL↔BDT(2) + GAL↔TAI(2) + BDT↔TAI(2)
        // GLO↔UTC(2) = 14 total fixed paths
        assert_eq!(m.path_count(false), 14, "14 fixed paths");
        // Remaining 30 − 14 = 16 are contextual conversions
        assert_eq!(m.path_count(true), 16, "16 contextual paths");
    }

    #[test]
    fn test_all_off_diagonal_cells_are_classified() {
        // Check that every off-diagonal conversion is properly classified
        // as Fixed / Identity / EpochShift / Contextual (never SameScale).
        for &from in &ScaleId::ALL {
            for &to in &ScaleId::ALL {
                if from != to {
                    let kind = from.conversion_kind(to);
                    assert_ne!(
                        kind,
                        ConversionKind::SameScale,
                        "{:?}→{:?} should not be SameScale",
                        from,
                        to
                    );
                }
            }
        }
    }

    #[test]
    fn test_matrix_is_symmetric_in_kind_category() {
        // For every pair, the "fixed vs contextual" classification must be symmetric.
        for &from in &ScaleId::ALL {
            for &to in &ScaleId::ALL {
                if from != to {
                    let fwd_fixed = from.is_fixed(to);
                    let rev_fixed = to.is_fixed(from);
                    assert_eq!(
                        fwd_fixed, rev_fixed,
                        "{:?}↔{:?}: fixed classification must be symmetric",
                        from, to
                    );
                }
            }
        }
    }
}