Skip to main content

deep_time/dt/
mod.rs

1mod arithmetic;
2mod constructors;
3mod conversions;
4mod epoch;
5mod from_ccsds;
6mod from_gps;
7mod from_str;
8mod gregorian;
9mod julian_date;
10mod ops;
11mod to_ccsds_bin;
12mod to_gps;
13mod to_str;
14mod trajectory;
15
16#[cfg(feature = "alloc")]
17mod formatting;
18#[cfg(feature = "alloc")]
19mod to_ccsds_str;
20
21#[cfg(feature = "hifitime")]
22mod from_hifitime;
23#[cfg(feature = "hifitime")]
24mod to_hifitime;
25
26#[cfg(feature = "chrono")]
27mod from_chrono;
28#[cfg(feature = "chrono")]
29mod to_chrono;
30
31#[cfg(feature = "jiff")]
32mod from_jiff;
33#[cfg(feature = "jiff")]
34mod to_jiff;
35
36use crate::ATTOS_PER_SEC;
37use core::fmt;
38
39/// Dt, and the library, is in the process of being switched from the sec
40/// and subsec fields being related to the scale, TO the sec and subsec fields
41/// always being TAI Epoch 2000-01-01 noon.
42/// Much of the documentation is outdated and should be ignored. But this docstring
43/// will hopefully help you understand Grok. Thanks.
44#[derive(Clone, Copy)]
45#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
46#[cfg_attr(feature = "js", derive(tsify::Tsify))]
47pub struct Dt {
48    pub(crate) sec: i64,
49    pub(crate) attos: u64,
50}
51
52impl Dt {
53    /// Seconds field getter.
54    #[inline]
55    pub const fn sec(&self) -> i64 {
56        self.sec
57    }
58
59    /// Subseconds field getter (attoseconds).
60    #[inline]
61    pub const fn attos(&self) -> u64 {
62        self.attos
63    }
64
65    /// Normalizes the representation so that the attosecond part lies in the range `[0, ATTOS_PER_SEC)`.
66    #[inline]
67    pub const fn carry_over(&mut self) -> &mut Self {
68        if self.attos >= ATTOS_PER_SEC {
69            self.sec += (self.attos / ATTOS_PER_SEC) as i64;
70            self.attos %= ATTOS_PER_SEC;
71        }
72        self
73    }
74}
75
76impl Default for Dt {
77    fn default() -> Self {
78        Self::ZERO
79    }
80}
81
82impl fmt::Display for Dt {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        let sec = self.sec();
85        let attos = self.attos();
86
87        // Default to nanosecond precision (9 digits) — most useful for everyday use
88        let precision = f.precision().unwrap_or(9);
89
90        // Respect the `+` sign when the user writes {:+}
91        if f.sign_plus() && sec >= 0 {
92            write!(f, "+")?;
93        }
94
95        write!(f, "{}", sec)?;
96
97        if precision > 0 {
98            let prec = precision.min(18);
99            let scale = 10u64.pow(18 - prec as u32);
100            let value = attos / scale;
101            write!(f, ".{:0>width$}", value, width = prec)?;
102        }
103
104        Ok(())
105    }
106}
107
108impl fmt::Debug for Dt {
109    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110        let approx_sec = self.sec() as f64 + (self.attos() as f64 / 1_000_000_000_000_000_000.0);
111
112        f.debug_struct("Dt")
113            .field("sec", &self.sec())
114            .field("attos", &self.attos())
115            .field("approx_sec", &approx_sec)
116            .finish()
117    }
118}
119
120#[cfg(feature = "wire")]
121impl Dt {
122    /// Current wire format version.
123    pub const WIRE_VERSION: u8 = 1;
124
125    /// Size of the canonical wire representation in bytes (17 bytes).
126    pub const WIRE_SIZE: usize = 17;
127
128    /// Serializes this `Dt` into a fixed 17-byte little-endian buffer.
129    ///
130    /// # Wire Format
131    ///
132    /// - Byte `0`: Version (`WIRE_VERSION`)
133    /// - Bytes `[1..9]`: `sec` as little-endian `i64`
134    /// - Bytes `[9..17]`: `subsec` as little-endian `u64`
135    ///
136    /// This format is stable, portable, and suitable for network transmission,
137    /// file storage, or FFI. The internal representation is always TAI.
138    pub fn to_wire_bytes(&self) -> [u8; Self::WIRE_SIZE] {
139        let mut buf = [0u8; Self::WIRE_SIZE];
140        buf[0] = Self::WIRE_VERSION;
141        buf[1..9].copy_from_slice(&self.sec.to_le_bytes());
142        buf[9..17].copy_from_slice(&self.attos.to_le_bytes());
143        buf
144    }
145
146    /// Deserializes a `Dt` from exactly 17 bytes of wire data.
147    ///
148    /// Returns `None` if the version byte is unknown.
149    /// Any `subsec` value ≥ 10¹⁸ is automatically normalized using
150    /// [`carry_over`](Self::carry_over) so the resulting `Dt`
151    /// is always in canonical form.
152    ///
153    /// ## Security
154    ///
155    /// Safe to call with completely untrusted input. Fixed-size format,
156    /// no allocation, no `unsafe`, and no possibility of code execution.
157    /// Malicious data simply produces a normalized (but still valid) `Dt`.
158    pub fn from_wire_bytes(bytes: &[u8]) -> Option<Self> {
159        if bytes.len() != Self::WIRE_SIZE {
160            return None;
161        }
162
163        if bytes[0] != Self::WIRE_VERSION {
164            return None;
165        }
166
167        let sec = i64::from_le_bytes([
168            bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], bytes[8],
169        ]);
170        let subsec = u64::from_le_bytes([
171            bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15], bytes[16],
172        ]);
173
174        Some(Self::new(sec, subsec))
175    }
176}