Skip to main content

deep_time/dt/
constructors.rs

1use crate::{
2    ATTOS_PER_FS, ATTOS_PER_MS, ATTOS_PER_NS, ATTOS_PER_PS, ATTOS_PER_SEC_I128, ATTOS_PER_US, Dt,
3    Real, SEC_PER_DAYI64, SEC_PER_DAYI128, SEC_PER_WEEK, Scale,
4    TAI_SECS_1970_MIDNIGHT_TO_2000_NOON,
5};
6
7impl Dt {
8    /// The library’s internal reference epoch: exactly **2000-01-01 12:00:00 TAI**.
9    ///
10    /// [`Dt::new(0)`].
11    pub const ZERO: Self = Self::new(0, Scale::TAI, Scale::TAI);
12
13    /// NTP epoch.
14    /// - 1900-01-01 00:00:00 UTC.
15    /// - Stored here on the **TAI** timescale as an offset from [`Self::ZERO`].
16    /// - -3_155_716_800_000_000_000_000_000_000 attoseconds
17    /// - The library's epoch for time scales during conversions is 2000-01-01 12:00:00.
18    pub const NTP_EPOCH: Self =
19        Self::new(-3155716800000000000000000000i128, Scale::TAI, Scale::TAI);
20
21    /// UNIX epoch.
22    /// - 1970-01-01 00:00:00 TAI.
23    /// - Stored here on the **TAI** timescale as an offset from [`Self::ZERO`].
24    /// - -946_728_000_000_000_000_000_000_000 attoseconds
25    /// - Does not take into account historical UTC offsets from the "rubber time" era.
26    /// - The library's epoch for time scales during conversions is 2000-01-01 12:00:00.
27    pub const UNIX_EPOCH: Self = Self::new(
28        -(TAI_SECS_1970_MIDNIGHT_TO_2000_NOON as i128) * ATTOS_PER_SEC_I128,
29        Scale::TAI,
30        Scale::UTC,
31    );
32
33    /// TT/TCG/TCB/TDB epoch.
34    /// - 1977-01-01 00:00:00 TAI.
35    /// - Stored here on the **TAI** timescale as an offset from [`Self::ZERO`].
36    /// - -725_803_200_000_000_000_000_000_000 attoseconds
37    /// - The library's epoch for time scales during conversions is 2000-01-01 12:00:00.
38    pub const TAI_1977_EPOCH: Self =
39        Self::new(-725803200000000000000000000i128, Scale::TAI, Scale::TAI);
40
41    /// Chandra X-ray Center (CXC) Time epoch.
42    /// - 1998-01-01 00:00:00 TT.
43    /// - Stored here on the **TAI** timescale as an offset from [`Self::ZERO`].
44    /// - -63_115_232_184_000_000_000_000_000_000 attoseconds
45    /// - The library's epoch for time scales during conversions is 2000-01-01 12:00:00.
46    pub const CXC_EPOCH: Self = Self::new(-63115232184000000000000000i128, Scale::TAI, Scale::TT);
47
48    /// GPS/Galileo Experiment (GALEX) Time epoch.
49    /// - 1980-01-06 00:00:00 UTC.
50    /// - Stored here on the **TAI** timescale as an offset from [`Self::ZERO`].
51    /// - -630_763_181_000_000_000_000_000_000 attoseconds
52    /// - The library's epoch for time scales during conversions is 2000-01-01 12:00:00.
53    pub const GPS_EPOCH: Self = Self::new(-630763181000000000000000000i128, Scale::TAI, Scale::GPS);
54
55    /// Galileo System Time (GST) epoch.
56    /// - 1999-08-22 00:00:00 GST.
57    /// - Stored here on the **TAI** timescale as an offset from [`Self::ZERO`].
58    /// - -11_447_981_000_000_000_000_000_000 attoseconds
59    /// - The library's epoch for time scales during conversions is 2000-01-01 12:00:00.
60    pub const GALILEO_EPOCH: Self =
61        Self::new(-11447981000000000000000000i128, Scale::TAI, Scale::GST);
62
63    /// BeiDou Time (BDT) epoch.
64    /// - 2006-01-01 00:00:00 UTC.
65    /// - Stored here on the **TAI** timescale as an offset from [`Self::ZERO`].
66    /// - 189_345_633_000_000_000_000_000_000 attoseconds
67    /// - The library's epoch for time scales during conversions is 2000-01-01 12:00:00.
68    pub const BDT_EPOCH: Self = Self::new(189345633000000000000000000i128, Scale::TAI, Scale::BDT);
69
70    /// Maximum representable duration.
71    pub const MAX: Self = Self::new(i128::MAX, Scale::TAI, Scale::TAI);
72
73    /// Minimum (most negative) representable duration.
74    pub const MIN: Self = Self::new(i128::MIN, Scale::TAI, Scale::TAI);
75
76    pub const SEC_19: Self = Self::new(19i128 * ATTOS_PER_SEC_I128, Scale::TAI, Scale::TAI);
77    pub const SEC_33: Self = Self::new(33i128 * ATTOS_PER_SEC_I128, Scale::TAI, Scale::TAI);
78    pub const SEC_37: Self = Self::new(37i128 * ATTOS_PER_SEC_I128, Scale::TAI, Scale::TAI);
79    pub const ONE_DAY: Self = Self::new(
80        (SEC_PER_DAYI64 as i128) * ATTOS_PER_SEC_I128,
81        Scale::TAI,
82        Scale::TAI,
83    );
84
85    /// Creates a new `Dt` from a total number of attoseconds (signed i128).
86    #[inline(always)]
87    pub const fn new(attos: i128, scale: Scale, target: Scale) -> Dt {
88        Self {
89            attos,
90            scale,
91            target,
92        }
93    }
94
95    /// Creates a new [`Dt`] from a total number of attoseconds (signed i128) without
96    /// performing any time scale conversions.
97    ///
98    /// This is an easy way to create a duration.
99    #[inline(always)]
100    pub const fn span(attos: i128) -> Dt {
101        Dt::new(attos, Scale::TAI, Scale::TAI)
102    }
103
104    /// Creates a [`Dt`] from a floating-point number of seconds without performing
105    /// any time scale conversions.
106    ///
107    /// This is an easy way to create a duration.
108    #[inline(always)]
109    pub const fn span_f(sec_f: Real) -> Dt {
110        Self::from_sec_f_on(sec_f, Scale::TAI)
111    }
112
113    /// Returns a [`Dt`] on the TAI time scale, after having been converted to TAI from
114    /// the given `scale`.
115    ///
116    /// - Requires a seconds and attoseconds count such that would be returned from the
117    ///   functions [`Dt::to_sec64`](../struct.Dt.html#method.to_sec64) and
118    ///   [`Dt::to_sec_ufrac`](../struct.Dt.html#method.to_sec_ufrac).
119    /// - The returned object's `scale` field is set to TAI and its `target` field is set to
120    ///   the given `scale` arg.
121    /// - The `sec` should be from the epoch TAI 2000-01-01 12:00:00.
122    #[inline(always)]
123    pub(crate) fn from_sec_and_attos(sec: i64, attos: u64, scale: Scale) -> Dt {
124        if attos == 0 {
125            Dt::from_attos((sec as i128) * ATTOS_PER_SEC_I128, scale)
126        } else {
127            Dt::from_attos((sec as i128) * ATTOS_PER_SEC_I128 + (attos as i128), scale)
128        }
129    }
130
131    /// Returns a [`Dt`] on the TAI time scale, after having been converted to TAI from
132    /// the given `scale`.
133    ///
134    /// - Requires a total attoseconds value.
135    /// - The value should be from the epoch TAI 2000-01-01 12:00:00.
136    /// - The returned object's `scale` field is set to TAI and its `target` field is set to
137    ///   the given `scale` arg.
138    #[inline(always)]
139    pub const fn from_attos(attos: i128, current: Scale) -> Dt {
140        Dt::new(attos, current, current).to_tai()
141    }
142
143    /// Creates a new [`Dt`] from a total number of seconds (signed i128) without
144    /// performing any time scale conversions.
145    #[inline(always)]
146    pub const fn from_tai_sec(sec: i128) -> Dt {
147        Self::from_attos(sec.saturating_mul(ATTOS_PER_SEC_I128), Scale::TAI)
148    }
149
150    /// Returns a [`Dt`] on the TAI time scale, after having been converted to TAI from
151    /// the given `scale`.
152    ///
153    /// - Requires a total seconds value.
154    /// - The value should be from the epoch TAI 2000-01-01 12:00:00.
155    /// - The returned object's `scale` field is set to TAI and its `target` field is set to
156    ///   the given `scale` arg.
157    #[inline(always)]
158    pub const fn from_sec(sec: i128, scale: Scale) -> Dt {
159        Self::from_attos(sec.saturating_mul(ATTOS_PER_SEC_I128), scale)
160    }
161
162    /// Returns a [`Dt`] on the TAI time scale, after having been converted to TAI from
163    /// the given `scale`.
164    ///
165    /// - Requires a total milliseconds value.
166    /// - The value should be from the epoch TAI 2000-01-01 12:00:00.
167    /// - The returned object's `scale` field is set to TAI and its `target` field is set to
168    ///   the given `scale` arg.
169    #[inline(always)]
170    pub const fn from_ms(ms: i128, scale: Scale) -> Dt {
171        let attos = ms.saturating_mul(ATTOS_PER_MS as i128);
172        Self::from_attos(attos, scale)
173    }
174
175    /// Returns a [`Dt`] on the TAI time scale, after having been converted to TAI from
176    /// the given `scale`.
177    ///
178    /// - Requires a total microseconds value.
179    /// - The value should be from the epoch TAI 2000-01-01 12:00:00.
180    /// - The returned object's `scale` field is set to TAI and its `target` field is set to
181    ///   the given `scale` arg.
182    #[inline(always)]
183    pub const fn from_us(us: i128, scale: Scale) -> Dt {
184        let attos = us.saturating_mul(ATTOS_PER_US as i128);
185        Self::from_attos(attos, scale)
186    }
187
188    /// Returns a [`Dt`] on the TAI time scale, after having been converted to TAI from
189    /// the given `scale`.
190    ///
191    /// - Requires a total nanoseconds value.
192    /// - The value should be from the epoch TAI 2000-01-01 12:00:00.
193    /// - The returned object's `scale` field is set to TAI and its `target` field is set to
194    ///   the given `scale` arg.
195    #[inline(always)]
196    pub const fn from_ns(ns: i128, scale: Scale) -> Dt {
197        let attos = ns.saturating_mul(ATTOS_PER_NS as i128);
198        Self::from_attos(attos, scale)
199    }
200
201    /// Returns a [`Dt`] on the TAI time scale, after having been converted to TAI from
202    /// the given `scale`.
203    ///
204    /// - Requires a total picoseconds value.
205    /// - The value should be from the epoch TAI 2000-01-01 12:00:00.
206    /// - The returned object's `scale` field is set to TAI and its `target` field is set to
207    ///   the given `scale` arg.
208    #[inline(always)]
209    pub const fn from_ps(ps: i128, scale: Scale) -> Dt {
210        let attos = ps.saturating_mul(ATTOS_PER_PS as i128);
211        Self::from_attos(attos, scale)
212    }
213
214    /// Returns a [`Dt`] on the TAI time scale, after having been converted to TAI from
215    /// the given `scale`.
216    ///
217    /// - Requires a total femtoseconds value.
218    /// - The value should be from the epoch TAI 2000-01-01 12:00:00.
219    /// - The returned object's `scale` field is set to TAI and its `target` field is set to
220    ///   the given `scale` arg.
221    #[inline(always)]
222    pub const fn from_fs(fs: i128, scale: Scale) -> Dt {
223        let attos = fs.saturating_mul(ATTOS_PER_FS as i128);
224        Self::from_attos(attos, scale)
225    }
226
227    /// Returns a [`Dt`] on the TAI time scale, after having been converted to TAI from
228    /// the given `scale`.
229    ///
230    /// Convenience wrapper around
231    /// [`Dt::from_sec`](../struct.Dt.html#method.from_sec).
232    #[inline(always)]
233    pub const fn from_min(m: i64, scale: Scale) -> Dt {
234        Self::from_sec((m as i128) * 60, scale)
235    }
236
237    /// Returns a [`Dt`] on the TAI time scale, after having been converted to TAI from
238    /// the given `scale`.
239    ///
240    /// Convenience wrapper around
241    /// [`Dt::from_sec`](../struct.Dt.html#method.from_sec).
242    #[inline(always)]
243    pub const fn from_hr(h: i64, scale: Scale) -> Dt {
244        Self::from_sec((h as i128) * 3600, scale)
245    }
246
247    /// Returns a [`Dt`] on the TAI time scale, after having been converted to TAI from
248    /// the given `scale`.
249    ///
250    /// - Params are hours, minutes, seconds, milliseconds, microseconds, and nanoseconds.
251    /// - All values are essentially optional (you can use 0 for ones you want to leave out).
252    /// - Negative values are handled.
253    /// - Uses saturating arithmetic.
254    pub const fn from_hms(
255        hr: i64,
256        min: i64,
257        sec: i64,
258        ms: i128,
259        us: i128,
260        ns: i128,
261        scale: Scale,
262    ) -> Dt {
263        // Combine hours/minutes/seconds with saturating arithmetic
264        let total_sec: i128 = (hr as i128)
265            .saturating_mul(3600)
266            .saturating_add((min as i128).saturating_mul(60))
267            .saturating_add(sec as i128);
268
269        // Combine sub-second parts (nanoseconds) with saturating arithmetic
270        let sub_ns: i128 = ms
271            .saturating_mul(1_000_000)
272            .saturating_add(us.saturating_mul(1_000))
273            .saturating_add(ns);
274
275        if sub_ns == 0 {
276            return Self::from_sec(total_sec, scale);
277        }
278
279        // Handle carry/borrow from sub-second component
280        let abs_ns: u128 = sub_ns.unsigned_abs();
281        let extra_sec: i128 = (abs_ns / 1_000_000_000) as i128;
282        let rem_ns: u64 = (abs_ns % 1_000_000_000) as u64;
283        let frac_attos: u128 = (rem_ns as u128) * (ATTOS_PER_NS as u128);
284
285        let attos = if sub_ns >= 0 {
286            total_sec
287                .saturating_add(extra_sec)
288                .saturating_mul(ATTOS_PER_SEC_I128)
289                .saturating_add(frac_attos as i128)
290        } else if frac_attos == 0 {
291            total_sec
292                .saturating_sub(extra_sec)
293                .saturating_mul(ATTOS_PER_SEC_I128)
294        } else {
295            total_sec
296                .saturating_sub(extra_sec)
297                .saturating_sub(1)
298                .saturating_mul(ATTOS_PER_SEC_I128)
299                .saturating_add(ATTOS_PER_SEC_I128 - frac_attos as i128)
300        };
301
302        Self::from_attos(attos, scale)
303    }
304
305    /// Returns a [`Dt`] on the TAI time scale, after having been converted to TAI from
306    /// the given `scale`.
307    ///
308    /// - Convenience wrapper around
309    ///   [`Dt::from_sec`](../struct.Dt.html#method.from_sec).
310    /// - Uses `86400` seconds per day in the calculation.
311    #[inline(always)]
312    pub const fn from_days(d: i64, scale: Scale) -> Dt {
313        Self::from_sec((d as i128).saturating_mul(SEC_PER_DAYI128), scale)
314    }
315
316    /// Returns a [`Dt`] on the TAI time scale, after having been converted to TAI from
317    /// the given `scale`.
318    ///
319    /// - Convenience wrapper around
320    ///   [`Dt::from_sec`](../struct.Dt.html#method.from_sec).
321    /// - Uses `604800` seconds per week in the calculation.
322    #[inline(always)]
323    pub const fn from_wk(wk: i64, scale: Scale) -> Dt {
324        Dt::from_sec((wk as i128).saturating_mul(SEC_PER_WEEK as i128), scale)
325    }
326
327    /// Returns a [`Dt`] on the TAI time scale, after having been converted to TAI from
328    /// the given `scale`.
329    ///
330    /// - Convenience wrapper around
331    ///   [`Dt::from_sec`](../struct.Dt.html#method.from_sec).
332    /// - Uses `31_557_600` in the calculation.
333    #[inline(always)]
334    pub const fn from_yr(yr: i64, scale: Scale) -> Dt {
335        Dt::from_sec((yr as i128).saturating_mul(31_557_600), scale)
336    }
337
338    /// Returns a [`Dt`] that is this duration ago from the given scale.
339    #[inline(always)]
340    pub const fn ago(self, scale: Scale) -> Dt {
341        Dt::from_attos(0, scale).sub(self)
342    }
343
344    /// Returns a [`Dt`] that is this duration from now in the given scale.
345    #[inline(always)]
346    pub const fn from_now(self, scale: Scale) -> Dt {
347        Dt::from_attos(0, scale).add(self)
348    }
349
350    /// Returns the negation of this [`Dt`].
351    #[inline(always)]
352    pub const fn neg(self) -> Dt {
353        Dt::new(-self.attos, self.scale, self.target)
354    }
355
356    /// Returns the positive of this [`Dt`].
357    #[inline(always)]
358    pub const fn abs(self) -> Dt {
359        Dt::new(self.attos.saturating_abs(), self.scale, self.target)
360    }
361
362    /// Creates a [`Dt`] from a floating-point number of seconds.
363    #[inline(always)]
364    pub const fn from_sec_f(sec_f: Real, scale: Scale) -> Dt {
365        Self::from_sec_f_on(sec_f, scale)
366    }
367
368    /// High-precision conversion from [`Real`] seconds to total attoseconds (i128).
369    /// Uses IEEE 754 bit extraction + exact integer multiplication by 5^18.
370    /// Returns the correctly rounded integer (round-to-nearest, ties away from zero).
371    pub const fn sec_f_to_total_attos(sec_f: Real) -> i128 {
372        if sec_f == 0.0 {
373            return 0;
374        }
375
376        let bits = sec_f.to_bits();
377        let is_negative = (bits >> 63) != 0;
378        let biased_exp = ((bits >> 52) & 0x7ff) as i32;
379        let mantissa = bits & 0x000f_ffff_ffff_ffff;
380
381        let (sig, exp) = if biased_exp == 0 {
382            if mantissa == 0 {
383                return 0;
384            }
385            (mantissa as u128, -1022i32 - 52)
386        } else {
387            let sig = ((1u64 << 52) | mantissa) as u128;
388            (sig, biased_exp - 1023 - 52)
389        };
390
391        const FIVE_POW_18: u128 = 3_814_697_265_625; // 5^18 exactly
392        let product = sig * FIVE_POW_18;
393        let total_exp = exp + 18;
394
395        // Safe saturation / underflow guards (prevents invalid shifts >= 128)
396        if total_exp > 120 {
397            return if is_negative { i128::MIN } else { i128::MAX };
398        }
399        if total_exp < -97 {
400            return 0;
401        }
402
403        let abs_total = if total_exp >= 0 {
404            let shift = total_exp as u32;
405            if product > (u128::MAX >> shift) {
406                if is_negative { i128::MIN } else { i128::MAX }
407            } else {
408                let shifted = product << shift;
409                if shifted > i128::MAX as u128 {
410                    if is_negative { i128::MIN } else { i128::MAX }
411                } else {
412                    shifted as i128
413                }
414            }
415        } else {
416            let shift = (-total_exp) as u32;
417            let int_part = (product >> shift) as i128;
418
419            // Round to nearest, half away from zero (on the absolute value)
420            let mask = (1u128 << shift) - 1;
421            let rem = product & mask;
422            if rem > (mask >> 1) {
423                int_part + 1
424            } else {
425                int_part
426            }
427        };
428
429        if is_negative { -abs_total } else { abs_total }
430    }
431
432    /// Creates a [`Dt`] from a floating-point number of seconds.
433    /// - Assumes the value is on the given scale.
434    /// - Converts the values **to TAI**, the returned [`Dt`] is on
435    ///   the TAI time scale.
436    pub const fn from_sec_f_on(sec_f: Real, s: Scale) -> Dt {
437        if sec_f.is_nan() {
438            return Self::ZERO;
439        } else if sec_f.is_infinite() {
440            return if sec_f.is_sign_positive() {
441                Self::MAX
442            } else {
443                Self::MIN
444            };
445        }
446
447        let total_attos = Self::sec_f_to_total_attos(sec_f);
448
449        Self::from_attos(total_attos, s)
450    }
451
452    /// Returns the current system time as TAI from 2000-01-01 12:00:00.
453    ///
454    /// This method is only available when the `std` feature is enabled and the target
455    /// is not WASM with the `js` feature.
456    #[cfg(all(feature = "std", not(all(target_arch = "wasm32", feature = "js"))))]
457    pub fn now() -> Dt {
458        let now = std::time::SystemTime::now();
459
460        let (secs, nanos): (i64, i64) = match now.duration_since(std::time::UNIX_EPOCH) {
461            Ok(dur) => (dur.as_secs() as i64, dur.subsec_nanos() as i64),
462            Err(e) => {
463                let dur = e.duration();
464                (-(dur.as_secs() as i64), -(dur.subsec_nanos() as i64))
465            }
466        };
467
468        Dt::from_diff_and_scale(
469            Dt::new(Dt::sec_to_attos(secs as i128), Scale::TAI, Scale::UTC),
470            Dt::UNIX_EPOCH,
471            false,
472        )
473        .add(Dt::from_ns(nanos as i128, Scale::TAI))
474    }
475
476    /// Returns the current system time as TAI from 2000-01-01 12:00:00.
477    /// (browser WASM version using JavaScript’s `Date.now()`).
478    #[cfg(all(target_arch = "wasm32", feature = "js"))]
479    pub fn now() -> Dt {
480        let ms: f64 = js_sys::Date::now();
481        let secs = (ms / 1000.0).floor() as i128;
482        let nanos = ((ms % 1000.0) * 1_000_000.0) as i128;
483        Dt::from_diff_and_scale(
484            Dt::new(Dt::sec_to_attos(secs), Scale::TAI, Scale::UTC),
485            Dt::UNIX_EPOCH,
486            false,
487        )
488        .add(Dt::from_ns(nanos as i128, Scale::TAI))
489    }
490}