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

//! Strongly-typed raw time coordinates.
//!
//! [`Coord<S, F>`] is an affine *point* in time on scale `S` (TT, TAI, UTC,
//! …) in format `F` (JD, MJD, J2000 seconds, Unix, GPS, …). [`Offset<S, F>`]
//! is its associated displacement vector.
//!
//! Together, these two types let the crate name *and type-check* values that
//! used to circulate as bare `qtty::Day` / `qtty::Second`. For example,
//! `Coord<TT, JD>` is statically distinct from `Coord<UTC, JD>`, so the
//! compiler now rejects mistakes like reusing a UTC-axis Julian Date as a TT
//! one.
//!
//! The type parameter order `<S, F>` (Scale first, Format second) mirrors
//! [`EncodedTime<S, F>`](crate::EncodedTime) for consistency.
//!
//! # Affine semantics
//!
//! - `Coord - Coord -> Offset`
//! - `Coord + Offset -> Coord`
//! - `Coord - Offset -> Coord`
//! - `Offset + Offset -> Offset`
//! - `Offset - Offset -> Offset`
//! - `-Offset -> Offset`
//!
//! Adding two coordinates is intentionally not modeled — averaging or summing
//! instants in the same coordinate system is not a primitive operation here.
//!
//! # Interop with [`EncodedTime`]
//!
//! `Coord<S, F>` and [`EncodedTime<S, F>`](crate::EncodedTime) carry the
//! same information (a typed quantity, a scale, and a format). Conversion in
//! both directions is zero-cost via [`From`] / [`Into`]. Use `Coord` for raw
//! coordinate arithmetic and constants; use `EncodedTime` for the high-level
//! `to_time*` / `to::<Target>()` conversion machinery.

use core::fmt;
use core::marker::PhantomData;
use core::ops::{Add, Neg, Sub};

use crate::error::ConversionError;
use crate::format::{EncodedTime, TimeFormat};
use crate::scale::Scale;
use qtty::Quantity;

/// A typed time coordinate on scale `S` in format `F`.
///
/// `Coord<S, F>` is an affine point. To shift it, add an [`Offset<S, F>`].
/// To take the directed distance between two coordinates, subtract them.
///
/// `Coord` mirrors [`EncodedTime`] but is intentionally smaller in scope: it
/// only exposes raw-quantity access and affine arithmetic. The
/// `EncodedTime` API (`to_time`, `to::<Target>()`, …) is reachable through
/// the `From`/`Into` conversion below.
pub struct Coord<S: Scale, F: TimeFormat> {
    raw: Quantity<F::Unit>,
    _marker: PhantomData<fn() -> S>,
}

/// A typed displacement between two [`Coord<S, F>`] values.
pub struct Offset<S: Scale, F: TimeFormat> {
    raw: Quantity<F::Unit>,
    _marker: PhantomData<fn() -> S>,
}

// ── Common ZST plumbing (Copy/Clone/PartialEq/PartialOrd/Hash/Debug) ─────

macro_rules! impl_zst_plumbing {
    ($ty:ident, $kind:literal) => {
        impl<S: Scale, F: TimeFormat> Copy for $ty<S, F> {}

        impl<S: Scale, F: TimeFormat> Clone for $ty<S, F> {
            #[inline]
            fn clone(&self) -> Self {
                *self
            }
        }

        impl<S: Scale, F: TimeFormat> PartialEq for $ty<S, F> {
            #[inline]
            fn eq(&self, other: &Self) -> bool {
                self.raw == other.raw
            }
        }

        impl<S: Scale, F: TimeFormat> PartialOrd for $ty<S, F> {
            #[inline]
            fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
                self.raw.partial_cmp(&other.raw)
            }
        }

        impl<S: Scale, F: TimeFormat> fmt::Debug for $ty<S, F> {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.debug_struct($kind)
                    .field("scale", &S::NAME)
                    .field("format", &F::NAME)
                    .field("raw", &self.raw)
                    .finish()
            }
        }

        impl<S: Scale, F: TimeFormat> fmt::Display for $ty<S, F>
        where
            qtty::Quantity<F::Unit>: fmt::Display,
        {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                fmt::Display::fmt(&self.raw, f)
            }
        }

        impl<S: Scale, F: TimeFormat> fmt::LowerExp for $ty<S, F>
        where
            qtty::Quantity<F::Unit>: fmt::LowerExp,
        {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                fmt::LowerExp::fmt(&self.raw, f)
            }
        }

        impl<S: Scale, F: TimeFormat> fmt::UpperExp for $ty<S, F>
        where
            qtty::Quantity<F::Unit>: fmt::UpperExp,
        {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                fmt::UpperExp::fmt(&self.raw, f)
            }
        }

        impl<S: Scale, F: TimeFormat> $ty<S, F> {
            /// Wrap a raw quantity without checking finiteness.
            ///
            /// Provided for `const` contexts such as crate-level constants.
            /// The caller is responsible for passing a finite value.
            #[inline]
            pub const fn from_raw_unchecked(raw: Quantity<F::Unit>) -> Self {
                Self {
                    raw,
                    _marker: PhantomData,
                }
            }

            /// Return the underlying typed quantity.
            #[inline]
            pub const fn raw(self) -> Quantity<F::Unit> {
                self.raw
            }

            /// Alias for [`Self::raw`].
            #[inline]
            pub const fn quantity(self) -> Quantity<F::Unit> {
                self.raw
            }
        }
    };
}

impl_zst_plumbing!(Coord, "Coord");
impl_zst_plumbing!(Offset, "Offset");

// ── Checked constructors ─────────────────────────────────────────────────

impl<S: Scale, F: TimeFormat> Coord<S, F> {
    /// Build a coordinate from a typed quantity, validating finiteness.
    #[inline]
    pub fn try_new(raw: Quantity<F::Unit>) -> Result<Self, ConversionError> {
        if raw.is_finite() {
            Ok(Self::from_raw_unchecked(raw))
        } else {
            Err(ConversionError::NonFinite)
        }
    }
}

impl<S: Scale, F: TimeFormat> Offset<S, F> {
    /// Build an offset from a typed quantity, validating finiteness.
    #[inline]
    pub fn try_new(raw: Quantity<F::Unit>) -> Result<Self, ConversionError> {
        if raw.is_finite() {
            Ok(Self::from_raw_unchecked(raw))
        } else {
            Err(ConversionError::NonFinite)
        }
    }

    /// The zero offset on this `(scale, format)` pair.
    #[inline]
    pub fn zero() -> Self
    where
        Quantity<F::Unit>: Default,
    {
        Self::from_raw_unchecked(Quantity::<F::Unit>::default())
    }
}

// ── Affine arithmetic ────────────────────────────────────────────────────

impl<S: Scale, F: TimeFormat> Sub for Coord<S, F>
where
    Quantity<F::Unit>: Sub<Output = Quantity<F::Unit>>,
{
    type Output = Offset<S, F>;

    #[inline]
    fn sub(self, rhs: Self) -> Self::Output {
        Offset::from_raw_unchecked(self.raw - rhs.raw)
    }
}

impl<S: Scale, F: TimeFormat> Add<Offset<S, F>> for Coord<S, F>
where
    Quantity<F::Unit>: Add<Output = Quantity<F::Unit>>,
{
    type Output = Coord<S, F>;

    #[inline]
    fn add(self, rhs: Offset<S, F>) -> Self::Output {
        Coord::from_raw_unchecked(self.raw + rhs.raw)
    }
}

impl<S: Scale, F: TimeFormat> Sub<Offset<S, F>> for Coord<S, F>
where
    Quantity<F::Unit>: Sub<Output = Quantity<F::Unit>>,
{
    type Output = Coord<S, F>;

    #[inline]
    fn sub(self, rhs: Offset<S, F>) -> Self::Output {
        Coord::from_raw_unchecked(self.raw - rhs.raw)
    }
}

impl<S: Scale, F: TimeFormat> Add for Offset<S, F>
where
    Quantity<F::Unit>: Add<Output = Quantity<F::Unit>>,
{
    type Output = Self;

    #[inline]
    fn add(self, rhs: Self) -> Self::Output {
        Self::from_raw_unchecked(self.raw + rhs.raw)
    }
}

impl<S: Scale, F: TimeFormat> Sub for Offset<S, F>
where
    Quantity<F::Unit>: Sub<Output = Quantity<F::Unit>>,
{
    type Output = Self;

    #[inline]
    fn sub(self, rhs: Self) -> Self::Output {
        Self::from_raw_unchecked(self.raw - rhs.raw)
    }
}

impl<S: Scale, F: TimeFormat> Neg for Offset<S, F>
where
    Quantity<F::Unit>: Neg<Output = Quantity<F::Unit>>,
{
    type Output = Self;

    #[inline]
    fn neg(self) -> Self::Output {
        Self::from_raw_unchecked(-self.raw)
    }
}

// ── Interop with EncodedTime ────────────────────────────────────────────

impl<S: Scale, F: TimeFormat> From<Coord<S, F>> for EncodedTime<S, F> {
    #[inline]
    fn from(value: Coord<S, F>) -> Self {
        EncodedTime::<S, F>::from_raw_unchecked(value.raw)
    }
}

impl<S: Scale, F: TimeFormat> From<EncodedTime<S, F>> for Coord<S, F> {
    #[inline]
    fn from(value: EncodedTime<S, F>) -> Self {
        Coord::<S, F>::from_raw_unchecked(value.raw())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::format::{JD, MJD};
    use crate::scale::{TT, UTC};
    use qtty::Day;

    #[test]
    fn coord_round_trip_with_encoded_time() {
        let c = Coord::<TT, JD>::try_new(Day::new(2_451_545.5)).unwrap();
        let e: EncodedTime<TT, JD> = c.into();
        let back: Coord<TT, JD> = e.into();
        assert_eq!(c, back);
    }

    #[test]
    fn coord_minus_coord_yields_offset() {
        let a = Coord::<TT, JD>::from_raw_unchecked(Day::new(2_451_545.5));
        let b = Coord::<TT, JD>::from_raw_unchecked(Day::new(2_451_545.0));
        let v: Offset<TT, JD> = a - b;
        assert_eq!(v.raw(), Day::new(0.5));
    }

    #[test]
    fn coord_plus_offset_yields_coord() {
        let a = Coord::<TT, JD>::from_raw_unchecked(Day::new(2_451_545.0));
        let v = Offset::<TT, JD>::from_raw_unchecked(Day::new(1.5));
        let b = a + v;
        assert_eq!(b.raw(), Day::new(2_451_546.5));
    }

    #[test]
    fn offset_arithmetic() {
        let v = Offset::<TT, JD>::from_raw_unchecked(Day::new(1.0));
        let w = Offset::<TT, JD>::from_raw_unchecked(Day::new(0.25));
        assert_eq!((v + w).raw(), Day::new(1.25));
        assert_eq!((v - w).raw(), Day::new(0.75));
        assert_eq!((-v).raw(), Day::new(-1.0));
    }

    #[test]
    fn try_new_rejects_non_finite() {
        let nan = Coord::<TT, JD>::try_new(Day::new(f64::NAN));
        assert!(matches!(nan, Err(ConversionError::NonFinite)));
        let inf = Offset::<UTC, MJD>::try_new(Day::new(f64::INFINITY));
        assert!(matches!(inf, Err(ConversionError::NonFinite)));
    }

    #[test]
    fn debug_includes_scale_and_format() {
        let c = Coord::<TT, JD>::from_raw_unchecked(Day::new(2_451_545.0));
        let dbg = format!("{c:?}");
        assert!(dbg.contains("TT"));
        assert!(dbg.contains("JD"));
    }

    #[test]
    fn display_delegates_to_quantity() {
        let c = Coord::<TT, JD>::from_raw_unchecked(Day::new(2_451_545.5));
        assert_eq!(format!("{c:.1}"), "2451545.5 d");
    }

    #[test]
    fn coord_scale_phantom_prevents_mixing() {
        fn accept_tt_jd(c: Coord<TT, JD>) -> Day {
            c.raw()
        }
        fn accept_utc_jd(c: Coord<UTC, JD>) -> Day {
            c.raw()
        }

        let tt = Coord::<TT, JD>::from_raw_unchecked(Day::new(2_451_545.0));
        let utc = Coord::<UTC, JD>::from_raw_unchecked(Day::new(2_451_545.0));

        let _ = accept_tt_jd(tt);
        let _ = accept_utc_jd(utc);
    }

    #[test]
    fn coord_quantity_is_alias_for_raw() {
        let c = Coord::<TT, JD>::from_raw_unchecked(Day::new(2_451_545.5));
        assert_eq!(c.raw(), c.quantity());
    }

    #[test]
    fn offset_quantity_is_alias_for_raw() {
        let v = Offset::<TT, JD>::from_raw_unchecked(Day::new(0.5));
        assert_eq!(v.raw(), v.quantity());
    }

    #[test]
    fn coord_minus_offset_yields_coord() {
        let a = Coord::<TT, JD>::from_raw_unchecked(Day::new(2_451_546.0));
        let v = Offset::<TT, JD>::from_raw_unchecked(Day::new(1.0));
        let b = a - v;
        assert_eq!(b.raw(), Day::new(2_451_545.0));
    }

    #[test]
    fn coord_lower_exp_delegates_to_quantity() {
        let c = Coord::<TT, JD>::from_raw_unchecked(Day::new(2_451_545.5));
        assert_eq!(format!("{c:.2e}"), format!("{:.2e}", c.raw()));
    }

    #[test]
    fn coord_upper_exp_delegates_to_quantity() {
        let c = Coord::<TT, JD>::from_raw_unchecked(Day::new(2_451_545.5));
        assert_eq!(format!("{c:.2E}"), format!("{:.2E}", c.raw()));
    }

    #[test]
    fn offset_lower_exp_delegates_to_quantity() {
        let v = Offset::<TT, JD>::from_raw_unchecked(Day::new(1.5));
        assert_eq!(format!("{v:.2e}"), format!("{:.2e}", v.raw()));
    }

    #[test]
    fn offset_upper_exp_delegates_to_quantity() {
        let v = Offset::<TT, JD>::from_raw_unchecked(Day::new(1.5));
        assert_eq!(format!("{v:.2E}"), format!("{:.2E}", v.raw()));
    }

    #[test]
    fn offset_debug_includes_scale_and_format() {
        let v = Offset::<TT, JD>::from_raw_unchecked(Day::new(1.0));
        let dbg = format!("{v:?}");
        assert!(dbg.contains("TT"));
        assert!(dbg.contains("JD"));
    }
}