Skip to main content

deep_time/dt/
constructors.rs

1use crate::{
2    ATTOS_PER_DAY, ATTOS_PER_FS_I128, ATTOS_PER_HOUR, ATTOS_PER_MIN, ATTOS_PER_MS_I128,
3    ATTOS_PER_NS_I128, ATTOS_PER_PS_I128, ATTOS_PER_SEC_I128, ATTOS_PER_US_I128, Dt, Real,
4    SEC_PER_DAY_F, SEC_PER_DAY_I64, SEC_PER_WEEK, Scale, TAI_SEC_1970_MIDNIGHT_TO_2000_NOON,
5};
6
7impl Dt {
8    /// The library’s internal reference epoch.
9    ///
10    /// - **2000-01-01 12:00:00 TAI**.
11    /// - 0 attoseconds
12    /// - The vast majority of conversion functions in the library expect the given
13    ///   [`Dt`] to be an attoseconds count since this epoch.
14    pub const ZERO: Self = Self::new(0, Scale::TAI, Scale::TAI);
15
16    /// UNIX epoch.
17    ///
18    /// - 1970-01-01 00:00:00 TAI.
19    /// - Stored here on the **TAI** timescale as an offset from [`Dt::ZERO`](#associatedconstant.ZERO).
20    /// - -946_728_000_000_000_000_000_000_000 attoseconds
21    /// - Does not take into account historical UTC offsets from the "rubber time" era.
22    /// - The library's epoch for time scales during conversions is 2000-01-01 12:00:00.
23    pub const UNIX_EPOCH: Self = Self::new(
24        -(TAI_SEC_1970_MIDNIGHT_TO_2000_NOON as i128) * ATTOS_PER_SEC_I128,
25        Scale::TAI,
26        Scale::UTC,
27    );
28
29    /// NTP epoch.
30    ///
31    /// - 1900-01-01 00:00:00 UTC.
32    /// - Stored here on the **TAI** timescale as an offset from [`Dt::ZERO`](#associatedconstant.ZERO).
33    /// - -3_155_716_800_000_000_000_000_000_000 attoseconds
34    /// - The library's epoch for time scales during conversions is 2000-01-01 12:00:00.
35    pub const NTP_EPOCH: Self = Self::new(
36        -3_155_716_800_000_000_000_000_000_000i128,
37        Scale::TAI,
38        Scale::TAI,
39    );
40
41    /// TT/TCG/TCB/TDB epoch.
42    ///
43    /// - 1977-01-01 00:00:00 TAI.
44    /// - Stored here on the **TAI** timescale as an offset from [`Dt::ZERO`](#associatedconstant.ZERO).
45    /// - -725_803_200_000_000_000_000_000_000 attoseconds
46    /// - The library's epoch for time scales during conversions is 2000-01-01 12:00:00.
47    pub const TAI_1977_EPOCH: Self = Self::new(
48        -725_803_200_000_000_000_000_000_000i128,
49        Scale::TAI,
50        Scale::TAI,
51    );
52
53    /// Chandra X-ray Center (CXC) Time epoch.
54    ///
55    /// - 1998-01-01 00:00:00 TT.
56    /// - Stored here on the **TAI** timescale as an offset from [`Dt::ZERO`](#associatedconstant.ZERO).
57    /// - -63_115_232_184_000_000_000_000_000_000 attoseconds
58    /// - The library's epoch for time scales during conversions is 2000-01-01 12:00:00.
59    pub const CXC_EPOCH: Self = Self::new(
60        -63_115_232_184_000_000_000_000_000i128,
61        Scale::TAI,
62        Scale::TT,
63    );
64
65    /// GPS/Galileo Experiment (GALEX) Time epoch.
66    ///
67    /// - 1980-01-06 00:00:00 UTC.
68    /// - Stored here on the **TAI** timescale as an offset from [`Dt::ZERO`](#associatedconstant.ZERO).
69    /// - -630_763_181_000_000_000_000_000_000 attoseconds
70    /// - The library's epoch for time scales during conversions is 2000-01-01 12:00:00.
71    pub const GPS_EPOCH: Self = Self::new(
72        -630_763_181_000_000_000_000_000_000i128,
73        Scale::TAI,
74        Scale::GPS,
75    );
76
77    /// Galileo System Time (GST) epoch.
78    ///
79    /// - 1999-08-22 00:00:00 GST.
80    /// - Stored here on the **TAI** timescale as an offset from [`Dt::ZERO`](#associatedconstant.ZERO).
81    /// - -11_447_981_000_000_000_000_000_000 attoseconds
82    /// - The library's epoch for time scales during conversions is 2000-01-01 12:00:00.
83    pub const GALILEO_EPOCH: Self = Self::new(
84        -11_447_981_000_000_000_000_000_000i128,
85        Scale::TAI,
86        Scale::GST,
87    );
88
89    /// BeiDou Time (BDT) epoch.
90    ///
91    /// - 2006-01-01 00:00:00 UTC.
92    /// - Stored here on the **TAI** timescale as an offset from [`Dt::ZERO`](#associatedconstant.ZERO).
93    /// - 189_345_633_000_000_000_000_000_000 attoseconds
94    /// - The library's epoch for time scales during conversions is 2000-01-01 12:00:00.
95    pub const BDT_EPOCH: Self = Self::new(
96        189_345_633_000_000_000_000_000_000i128,
97        Scale::TAI,
98        Scale::BDT,
99    );
100
101    /// CCSDS epoch (used in CCSDS time codes such as CUC).
102    ///
103    /// - 1958-01-01 00:00:00 TAI.
104    /// - Stored here on the **TAI** timescale as an offset from [`Dt::ZERO`](#associatedconstant.ZERO).
105    /// - -1_325_419_200_000_000_000_000_000_000 attoseconds
106    /// - The library's epoch for time scales during conversions is 2000-01-01 12:00:00.
107    pub const CCSDS_EPOCH: Self = Self::new(
108        -1_325_419_200_000_000_000_000_000_000i128,
109        Scale::TAI,
110        Scale::TAI,
111    );
112
113    /// JD epoch (JD 0.0).
114    ///
115    /// - -4713-11-24 12:00:00
116    /// - Stored here on the **TAI** timescale as an offset from [`Dt::ZERO`](#associatedconstant.ZERO).
117    /// - -211_813_488_000_000_000_000_000_000 attoseconds
118    /// - The library's epoch for time scales during conversions is 2000-01-01 12:00:00.
119    pub const JD_EPOCH: Self = Self::new(
120        -211_813_488_000_000_000_000_000_000_000i128,
121        Scale::TAI,
122        Scale::TAI,
123    );
124
125    /// MJD epoch (MJD 0.0)
126    ///
127    /// - 1858-11-17 00:00:00
128    /// - Stored here on the **TAI** timescale as an offset from [`Dt::ZERO`](#associatedconstant.ZERO).
129    /// - -4_453_444_800_000_000_000_000_000_000 attoseconds
130    /// - The library's epoch for time scales during conversions is 2000-01-01 12:00:00.
131    pub const MJD_EPOCH: Self = Self::new(
132        -4_453_444_800_000_000_000_000_000_000i128,
133        Scale::TAI,
134        Scale::TAI,
135    );
136
137    /// Maximum representable duration.
138    pub const MAX: Self = Self::new(i128::MAX, Scale::TAI, Scale::TAI);
139
140    /// Minimum (most negative) representable duration.
141    pub const MIN: Self = Self::new(i128::MIN, Scale::TAI, Scale::TAI);
142
143    /// 19 seconds.
144    pub const SEC_19: Self = Self::new(19i128 * ATTOS_PER_SEC_I128, Scale::TAI, Scale::TAI);
145
146    /// 33 seconds.
147    pub const SEC_33: Self = Self::new(33i128 * ATTOS_PER_SEC_I128, Scale::TAI, Scale::TAI);
148
149    /// 37 seconds.
150    pub const SEC_37: Self = Self::new(37i128 * ATTOS_PER_SEC_I128, Scale::TAI, Scale::TAI);
151
152    /// One days worth of attoseconds.
153    pub const ONE_DAY: Self = Self::new(
154        (SEC_PER_DAY_I64 as i128) * ATTOS_PER_SEC_I128,
155        Scale::TAI,
156        Scale::TAI,
157    );
158
159    /// Creates a new [`Dt`] from a total number of attoseconds since the librarys
160    /// epoch **2000-01-01 12:00:00 TAI**.
161    ///
162    /// Does **not** perform any time scale conversions.
163    ///
164    /// ## Examples
165    ///
166    /// ```rust
167    /// use deep_time::{Dt, Scale};
168    ///
169    /// // current scale TAI, target scale UTC
170    /// let a = Dt::new(0, Scale::TAI, Scale::UTC);
171    ///
172    /// // equivalent to direct construction
173    /// let b = Dt { attos: 0, scale: Scale::TAI, target: Scale::UTC };
174    ///
175    /// assert_eq!(a, b);
176    /// ```
177    ///
178    /// ## See also
179    ///
180    /// - [`dt!`](../macro.dt.html)
181    /// - [`ns!`](../macro.ns.html)
182    #[inline(always)]
183    pub const fn new(attos: i128, scale: Scale, target: Scale) -> Dt {
184        Dt {
185            attos,
186            scale,
187            target,
188        }
189    }
190
191    /// Low level constructor from total attoseconds since a given epoch.
192    ///
193    /// Simply adds the total attoseconds to the epoch. Does not perform
194    /// any time scale conversions.
195    ///
196    /// The returned [`Dt`] copies the epoch's `scale` and `target` fields.
197    ///
198    /// ## Examples
199    ///
200    /// ```rust
201    /// use deep_time::{Dt, Scale};
202    ///
203    /// // A leap second from the middle of the table (36 leap seconds accumulated)
204    /// let original = Dt::from_ymd(2015, 6, 30, Scale::UTC, 23, 59, 60, 123_456_789_000_000_000);
205    ///
206    /// // Round-trip through canonical attoseconds
207    /// let canon = original.to_diff_raw(Dt::UNIX_EPOCH).to_attos();
208    /// let roundtrip1 = Dt::from_diff_raw(canon, Dt::UNIX_EPOCH);
209    ///
210    /// assert_eq!(original, roundtrip1, "Canonical round-trip failed");
211    /// ```
212    ///
213    /// ## See also
214    ///
215    /// - [`Dt::to_diff_raw`](../struct.Dt.html#method.to_diff_raw)
216    /// - [`Dt::to_diff_raw_f`](../struct.Dt.html#method.to_diff_raw_f)
217    #[inline(always)]
218    pub const fn from_diff_raw(attos: i128, epoch: Dt) -> Dt {
219        epoch.add(Dt::new(attos, epoch.scale, epoch.target))
220    }
221
222    /// Builds a [`Dt`] holding the given whole seconds and sub-second remainder.
223    ///
224    /// The remainder is in **attoseconds**, not seconds. Pairs with
225    /// [`Dt::to_sec64`](#method.to_sec64) + [`Dt::to_sec_frac`](#method.to_sec_frac).
226    ///
227    /// Does **not** perform any time scale conversions.
228    ///
229    /// ## Parameters
230    ///
231    /// - `sec` — whole seconds (truncating / signed-remainder split).
232    /// - `attos` — fractional part of that split, in attoseconds.
233    ///   Prefer helpers such as [`Dt::ms_to_attos`](#method.ms_to_attos) /
234    ///   [`Dt::ns_to_attos`](#method.ns_to_attos) or the [`ms!`](../macro.ms.html) /
235    ///   [`ns!`](../macro.ns.html) macros instead of hand-counting zeros:
236    ///   - `1.3` s → `sec = 1`, `attos = Dt::ms_to_attos(300)`
237    ///   - `-1.3` s → `sec = -1`, `attos = Dt::ms_to_attos(-300)`
238    ///   - `-0.5` s → `sec = 0`, `attos = Dt::ms_to_attos(-500)`
239    /// - `on` — value stored in the returned [`Dt`]'s `scale` field.
240    /// - `target` — value stored in the returned [`Dt`]'s `target` field.
241    ///
242    /// ## Examples
243    ///
244    /// ```rust
245    /// use deep_time::{Dt, Scale};
246    /// use deep_time::macros::{dt, ms};
247    ///
248    /// // 1.3 s — convert 300 ms of remainder to attoseconds
249    /// let a = Dt::from_sec_and_frac(1, ms!(300), Scale::TAI, Scale::TAI);
250    /// assert_eq!(a, dt!(1_300_000_000_000_000_000));
251    ///
252    /// // -1.3 s (signed remainder)
253    /// assert_eq!(
254    ///     Dt::from_sec_and_frac(-1, Dt::ms_to_attos(-300), Scale::TAI, Scale::TAI),
255    ///     dt!(-1_300_000_000_000_000_000),
256    /// );
257    ///
258    /// // -0.5 s
259    /// assert_eq!(
260    ///     Dt::from_sec_and_frac(0, Dt::ms_to_attos(-500), Scale::TAI, Scale::TAI),
261    ///     dt!(-500_000_000_000_000_000),
262    /// );
263    /// ```
264    #[inline(always)]
265    pub const fn from_sec_and_frac(sec: i128, attos: i128, on: Scale, target: Scale) -> Dt {
266        Dt::new(
267            sec.saturating_mul(ATTOS_PER_SEC_I128).saturating_add(attos),
268            on,
269            target,
270        )
271    }
272
273    /// Builds a [`Dt`] holding the given whole seconds.
274    ///
275    /// Does **not** perform any time scale conversions. The `sec` count is stored
276    /// as-is (converted only from seconds to attoseconds); its meaning depends on
277    /// how you use the value afterward (for example as a library-epoch offset, a
278    /// Unix offset passed to [`Dt::from_unix`](#method.from_unix), a duration, etc.).
279    ///
280    /// ## Parameters
281    ///
282    /// - `sec` — whole seconds count to store.
283    /// - `on` — value stored in the returned [`Dt`]'s `scale` field.
284    /// - `target` — value stored in the returned [`Dt`]'s `target` field.
285    #[inline(always)]
286    pub const fn from_sec(sec: i128, on: Scale, target: Scale) -> Dt {
287        Dt::new(sec.saturating_mul(ATTOS_PER_SEC_I128), on, target)
288    }
289
290    /// Builds a [`Dt`] holding the given whole milliseconds and sub-millisecond remainder.
291    ///
292    /// The remainder is in **attoseconds**, not milliseconds. Pairs with
293    /// [`to_ms`](../struct.Dt.html#method.to_ms).
294    ///
295    /// Does **not** perform any time scale conversions.
296    ///
297    /// ## Parameters
298    ///
299    /// - `ms` — whole milliseconds (truncating / signed-remainder split).
300    /// - `frac_attos` — fractional part of that split, in attoseconds.
301    ///   Use a smaller-unit converter rather than counting zeros by hand:
302    ///   - `1.3` ms → `ms = 1`, `frac_attos = Dt::us_to_attos(300)` (0.3 ms = 300 µs)
303    ///   - `-1.3` ms → `ms = -1`, `frac_attos = Dt::us_to_attos(-300)`
304    /// - `on` — value stored in the returned [`Dt`]'s `scale` field.
305    /// - `target` — value stored in the returned [`Dt`]'s `target` field.
306    ///
307    /// ## Examples
308    ///
309    /// ```rust
310    /// use deep_time::{Dt, Scale};
311    /// use deep_time::macros::us;
312    ///
313    /// // 1.3 ms
314    /// let a = Dt::from_ms(1, us!(300), Scale::TAI, Scale::TAI);
315    /// assert_eq!(a.to_attos(), 1_300_000_000_000_000);
316    ///
317    /// // -1.3 ms
318    /// let neg = Dt::from_ms(-1, us!(-300), Scale::TAI, Scale::TAI);
319    /// assert_eq!(neg.to_attos(), -1_300_000_000_000_000);
320    ///
321    /// // or as floored -1.3 ms
322    /// let neg = Dt::from_ms(-2, us!(700), Scale::TAI, Scale::TAI);
323    /// assert_eq!(neg.to_attos(), -1_300_000_000_000_000);
324    /// ```
325    ///
326    /// ## See also
327    ///
328    /// - [`from_ms!`](../macros/macro.from_ms.html)
329    /// - [`us!`](../macros/macro.us.html)
330    #[inline(always)]
331    pub const fn from_ms(ms: i128, attos: i128, on: Scale, target: Scale) -> Dt {
332        let attos = Dt::unit_to_total_attos(ms, attos, ATTOS_PER_MS_I128);
333        Dt::new(attos, on, target)
334    }
335
336    /// Builds a [`Dt`] holding the given whole microseconds and sub-microsecond remainder.
337    ///
338    /// The remainder is in **attoseconds**, not microseconds. Pairs with
339    /// [`to_us`](../struct.Dt.html#method.to_us).
340    ///
341    /// Does **not** perform any time scale conversions.
342    ///
343    /// ## Parameters
344    ///
345    /// - `us` — whole microseconds (truncating / signed-remainder split).
346    /// - `frac_attos` — fractional part of that split, in attoseconds.
347    ///   Use a smaller-unit converter rather than counting zeros by hand:
348    ///   - `1.3` µs → `us = 1`, `frac_attos = Dt::ns_to_attos(300)` (0.3 µs = 300 ns)
349    ///   - `-1.3` µs → `us = -1`, `frac_attos = Dt::ns_to_attos(-300)`
350    /// - `on` — value stored in the returned [`Dt`]'s `scale` field.
351    /// - `target` — value stored in the returned [`Dt`]'s `target` field.
352    ///
353    /// ## Examples
354    ///
355    /// ```rust
356    /// use deep_time::{Dt, Scale};
357    /// use deep_time::macros::ns;
358    ///
359    /// // 1.3 µs
360    /// let a = Dt::from_us(1, ns!(300), Scale::TAI, Scale::TAI);
361    /// assert_eq!(a.to_attos(), 1_300_000_000_000);
362    ///
363    /// // -1.3 µs
364    /// let neg = Dt::from_us(-1, ns!(-300), Scale::TAI, Scale::TAI);
365    /// assert_eq!(neg.to_attos(), -1_300_000_000_000);
366    ///
367    /// // or as floored -1.3 µs
368    /// let neg = Dt::from_us(-2, ns!(700), Scale::TAI, Scale::TAI);
369    /// assert_eq!(neg.to_attos(), -1_300_000_000_000);
370    /// ```
371    ///
372    /// ## See also
373    ///
374    /// - [`from_us!`](../macros/macro.from_us.html)
375    /// - [`ns!`](../macro.ns.html)
376    #[inline(always)]
377    pub const fn from_us(us: i128, attos: i128, on: Scale, target: Scale) -> Dt {
378        let attos = Dt::unit_to_total_attos(us, attos, ATTOS_PER_US_I128);
379        Dt::new(attos, on, target)
380    }
381
382    /// Builds a [`Dt`] holding the given whole nanoseconds and sub-nanosecond remainder.
383    ///
384    /// The remainder is in **attoseconds**, not nanoseconds. Pairs with
385    /// [`to_ns`](../struct.Dt.html#method.to_ns).
386    ///
387    /// Does **not** perform any time scale conversions.
388    ///
389    /// ## Parameters
390    ///
391    /// - `ns` — whole nanoseconds (truncating / signed-remainder split).
392    /// - `frac_attos` — fractional part of that split, in attoseconds.
393    ///   Use a smaller-unit converter rather than counting zeros by hand:
394    ///   - `1.3` ns → `ns = 1`, `frac_attos = Dt::ps_to_attos(300)` (0.3 ns = 300 ps)
395    ///   - `-1.3` ns → `ns = -1`, `frac_attos = Dt::ps_to_attos(-300)`
396    /// - `on` — value stored in the returned [`Dt`]'s `scale` field.
397    /// - `target` — value stored in the returned [`Dt`]'s `target` field.
398    ///
399    /// ## Examples
400    ///
401    /// ```rust
402    /// use deep_time::{Dt, Scale};
403    /// use deep_time::macros::ps;
404    ///
405    /// // 1.3 ns → whole nanoseconds + 300 ps remainder
406    /// let a = Dt::from_ns(1, ps!(300), Scale::TAI, Scale::TAI);
407    /// assert_eq!(a.to_attos(), 1_300_000_000);
408    ///
409    /// // -1.3 ns
410    /// let neg = Dt::from_ns(-1, Dt::ps_to_attos(-300), Scale::TAI, Scale::TAI);
411    /// assert_eq!(neg.to_attos(), -1_300_000_000);
412    /// ```
413    #[inline(always)]
414    pub const fn from_ns(ns: i128, attos: i128, on: Scale, target: Scale) -> Dt {
415        let attos = Dt::unit_to_total_attos(ns, attos, ATTOS_PER_NS_I128);
416        Dt::new(attos, on, target)
417    }
418
419    /// Builds a [`Dt`] holding the given whole picoseconds and sub-picosecond remainder.
420    ///
421    /// The remainder is in **attoseconds**, not picoseconds. Pairs with
422    /// [`to_ps`](../struct.Dt.html#method.to_ps).
423    ///
424    /// Does **not** perform any time scale conversions.
425    ///
426    /// ## Parameters
427    ///
428    /// - `ps` — whole picoseconds (truncating / signed-remainder split).
429    /// - `frac_attos` — fractional part of that split, in attoseconds.
430    ///   Use a smaller-unit converter rather than counting zeros by hand:
431    ///   - `1.3` ps → `ps = 1`, `frac_attos = Dt::fs_to_attos(300)` (0.3 ps = 300 fs)
432    ///   - `-1.3` ps → `ps = -1`, `frac_attos = Dt::fs_to_attos(-300)`
433    /// - `on` — value stored in the returned [`Dt`]'s `scale` field.
434    /// - `target` — value stored in the returned [`Dt`]'s `target` field.
435    ///
436    /// ## Examples
437    ///
438    /// ```rust
439    /// use deep_time::{Dt, Scale};
440    /// use deep_time::macros::fs;
441    ///
442    /// // 1.3 ps
443    /// let a = Dt::from_ps(1, fs!(300), Scale::TAI, Scale::TAI);
444    /// assert_eq!(a.to_attos(), 1_300_000);
445    ///
446    /// // -1.3 ps
447    /// let neg = Dt::from_ps(-1, Dt::fs_to_attos(-300), Scale::TAI, Scale::TAI);
448    /// assert_eq!(neg.to_attos(), -1_300_000);
449    /// ```
450    #[inline(always)]
451    pub const fn from_ps(ps: i128, attos: i128, on: Scale, target: Scale) -> Dt {
452        let attos = Dt::unit_to_total_attos(ps, attos, ATTOS_PER_PS_I128);
453        Dt::new(attos, on, target)
454    }
455
456    /// Builds a [`Dt`] holding the given whole femtoseconds and sub-femtosecond remainder.
457    ///
458    /// The remainder is in **attoseconds**, not femtoseconds. Pairs with
459    /// [`to_fs`](../struct.Dt.html#method.to_fs).
460    ///
461    /// Does **not** perform any time scale conversions.
462    ///
463    /// ## Parameters
464    ///
465    /// - `fs` — whole femtoseconds (truncating / signed-remainder split).
466    /// - `frac_attos` — fractional part of that split, in attoseconds.
467    ///   One femtosecond is 1000 attoseconds, so a fractional remainder is already
468    ///   a small integer: `1.3` fs → `fs = 1`, `frac_attos = 300`.
469    ///   For `-1.3` fs: `fs = -1`, `frac_attos = -300`.
470    /// - `on` — value stored in the returned [`Dt`]'s `scale` field.
471    /// - `target` — value stored in the returned [`Dt`]'s `target` field.
472    ///
473    /// ## Examples
474    ///
475    /// ```rust
476    /// use deep_time::{Dt, Scale};
477    ///
478    /// // 1.3 fs — sub-fs remainder is already in attoseconds (×10³)
479    /// let a = Dt::from_fs(1, 300, Scale::TAI, Scale::TAI);
480    /// assert_eq!(a.to_attos(), 1_300);
481    ///
482    /// // whole fs only — still fine to use the converter for the whole part
483    /// // if you are building total attos by hand:
484    /// assert_eq!(Dt::fs_to_attos(1), 1_000);
485    ///
486    /// // -1.3 fs
487    /// let neg = Dt::from_fs(-1, -300, Scale::TAI, Scale::TAI);
488    /// assert_eq!(neg.to_attos(), -1_300);
489    /// ```
490    #[inline(always)]
491    pub const fn from_fs(fs: i128, attos: i128, on: Scale, target: Scale) -> Dt {
492        let attos = Dt::unit_to_total_attos(fs, attos, ATTOS_PER_FS_I128);
493        Dt::new(attos, on, target)
494    }
495
496    /// Builds a [`Dt`] holding the given whole minutes and sub-minute remainder.
497    ///
498    /// The remainder is in **attoseconds**, not minutes.
499    ///
500    /// Does **not** perform any time scale conversions.
501    ///
502    /// ## Parameters
503    ///
504    /// - `n` — whole minutes (truncating / signed-remainder split).
505    /// - `frac_attos` — fractional part of that split, in attoseconds.
506    ///   Use a time-unit converter rather than counting zeros by hand:
507    ///   - `1.5` min → `n = 1`, `frac_attos = Dt::sec_to_attos(30)` (0.5 min = 30 s)
508    ///   - `-1.5` min → `n = -1`, `frac_attos = Dt::sec_to_attos(-30)`
509    /// - `on` — value stored in the returned [`Dt`]'s `scale` field.
510    /// - `target` — value stored in the returned [`Dt`]'s `target` field.
511    ///
512    /// ## Examples
513    ///
514    /// ```rust
515    /// use deep_time::{Dt, Scale};
516    /// use deep_time::macros::sec;
517    ///
518    /// // 1.5 min
519    /// let a = Dt::from_mins(1, sec!(30), Scale::TAI, Scale::TAI);
520    /// assert_eq!(a.to_sec(), 90);
521    ///
522    /// // -1.5 min
523    /// let neg = Dt::from_mins(-1, Dt::sec_to_attos(-30), Scale::TAI, Scale::TAI);
524    /// assert_eq!(neg.to_sec(), -90);
525    /// ```
526    #[inline(always)]
527    pub const fn from_mins(n: i128, attos: i128, on: Scale, target: Scale) -> Dt {
528        let attos = Dt::unit_to_total_attos(n, attos, ATTOS_PER_MIN);
529        Dt::new(attos, on, target)
530    }
531
532    /// Builds a [`Dt`] holding the given whole hours and sub-hour remainder.
533    ///
534    /// The remainder is in **attoseconds**, not hours.
535    ///
536    /// Does **not** perform any time scale conversions.
537    ///
538    /// ## Parameters
539    ///
540    /// - `n` — whole hours (truncating / signed-remainder split).
541    /// - `frac_attos` — fractional part of that split, in attoseconds.
542    ///   Use a time-unit converter rather than counting zeros by hand:
543    ///   - `1.5` h → `n = 1`, `frac_attos = Dt::mins_to_attos(30)` (0.5 h = 30 min)
544    ///   - `-1.5` h → `n = -1`, `frac_attos = Dt::mins_to_attos(-30)`
545    /// - `on` — value stored in the returned [`Dt`]'s `scale` field.
546    /// - `target` — value stored in the returned [`Dt`]'s `target` field.
547    ///
548    /// ## Examples
549    ///
550    /// ```rust
551    /// use deep_time::{Dt, Scale};
552    /// use deep_time::macros::mins;
553    ///
554    /// // 1.5 h
555    /// let a = Dt::from_hours(1, mins!(30), Scale::TAI, Scale::TAI);
556    /// assert_eq!(a.to_sec(), 5400);
557    ///
558    /// // -1.5 h
559    /// let neg = Dt::from_hours(-1, Dt::mins_to_attos(-30), Scale::TAI, Scale::TAI);
560    /// assert_eq!(neg.to_sec(), -5400);
561    /// ```
562    #[inline(always)]
563    pub const fn from_hours(n: i128, attos: i128, on: Scale, target: Scale) -> Dt {
564        let attos = Dt::unit_to_total_attos(n, attos, ATTOS_PER_HOUR);
565        Dt::new(attos, on, target)
566    }
567
568    /// Builds a [`Dt`] holding the given whole days and sub-day remainder.
569    ///
570    /// The remainder is in **attoseconds**, not days. Uses `86400` seconds per day.
571    ///
572    /// Does **not** perform any time scale conversions.
573    ///
574    /// ## Parameters
575    ///
576    /// - `d` — whole days (truncating / signed-remainder split).
577    /// - `frac` — fractional part in attoseconds (`frac.attos` only).
578    ///   - `1.25` d → `d = 1`, `frac = dt!(Dt::hours_to_attos(6))` (0.25 d = 6 h)
579    ///   - `-1.25` d → `d = -1`, `frac = dt!(Dt::hours_to_attos(-6))`
580    /// - `on` — value stored in the returned [`Dt`]'s `scale` field.
581    /// - `target` — value stored in the returned [`Dt`]'s `target` field.
582    ///
583    /// ## Examples
584    ///
585    /// ```rust
586    /// use deep_time::{Dt, Scale};
587    /// use deep_time::macros::{dt, hours};
588    ///
589    /// // 1.25 d
590    /// let a = Dt::from_days(1, dt!(hours!(6)), Scale::TAI, Scale::TAI);
591    /// assert_eq!(a.to_sec(), 108_000); // 1.25 * 86400
592    ///
593    /// // -1.25 d
594    /// let neg = Dt::from_days(-1, dt!(Dt::hours_to_attos(-6)), Scale::TAI, Scale::TAI);
595    /// assert_eq!(neg.to_sec(), -108_000);
596    /// ```
597    #[inline(always)]
598    pub const fn from_days(d: i128, frac: Dt, on: Scale, target: Scale) -> Dt {
599        let attos = Dt::unit_to_total_attos(d, frac.attos, ATTOS_PER_DAY);
600        Dt::new(attos, on, target)
601    }
602
603    /// Builds a [`Dt`] from a floating-point day count since the library epoch
604    /// (2000-01-01 12:00:00 TAI).
605    ///
606    /// This is the inverse of [`Dt::to_days_f`](../struct.Dt.html#method.to_days_f).
607    ///
608    /// Does **not** perform any time scale conversions.
609    ///
610    /// ## Parameters
611    ///
612    /// - `days` — day count to store (converted to attoseconds).
613    /// - `on` — value stored in the returned [`Dt`]'s `scale` field.
614    /// - `target` — value stored in the returned [`Dt`]'s `target` field.
615    ///
616    /// ## Examples
617    ///
618    /// ```rust
619    /// use deep_time::{Dt, Scale};
620    ///
621    /// let dt = Dt::from_days_f(1.25, Scale::TAI, Scale::TAI);
622    /// assert_eq!(dt.to_days_f(), 1.25);
623    ///
624    /// let neg = Dt::from_days_f(-1.25, Scale::TAI, Scale::TAI);
625    /// assert_eq!(neg.to_days_f(), -1.25);
626    /// ```
627    ///
628    /// ## See also
629    ///
630    /// - [`Dt::from_days`](../struct.Dt.html#method.from_days)
631    /// - [`Dt::to_days_f`](../struct.Dt.html#method.to_days_f)
632    #[inline]
633    pub const fn from_days_f(days: Real, on: Scale, target: Scale) -> Dt {
634        Self::from_sec_f(days * SEC_PER_DAY_F, on, target)
635    }
636
637    /// Builds a [`Dt`] holding the given number of weeks (`604800` seconds each).
638    ///
639    /// Does **not** perform any time scale conversions.
640    ///
641    /// ## Parameters
642    ///
643    /// - `n` — whole weeks.
644    /// - `on` — value stored in the returned [`Dt`]'s `scale` field.
645    /// - `target` — value stored in the returned [`Dt`]'s `target` field.
646    #[inline(always)]
647    pub const fn from_weeks(n: i128, on: Scale, target: Scale) -> Dt {
648        Dt::new(
649            n.saturating_mul(SEC_PER_WEEK as i128)
650                .saturating_mul(ATTOS_PER_SEC_I128),
651            on,
652            target,
653        )
654    }
655
656    /// Builds a [`Dt`] holding the given number of Julian years (`31_557_600` seconds each).
657    ///
658    /// Does **not** perform any time scale conversions.
659    ///
660    /// ## Parameters
661    ///
662    /// - `n` — whole years.
663    /// - `on` — value stored in the returned [`Dt`]'s `scale` field.
664    /// - `target` — value stored in the returned [`Dt`]'s `target` field.
665    #[inline(always)]
666    pub const fn from_years(n: i128, on: Scale, target: Scale) -> Dt {
667        Dt::new(
668            n.saturating_mul(31_557_600)
669                .saturating_mul(ATTOS_PER_SEC_I128),
670            on,
671            target,
672        )
673    }
674
675    /// Returns an instant that is this duration **before** zero attoseconds on `scale`.
676    ///
677    /// Zero attoseconds is the library epoch **2000-01-01 12:00:00** (see
678    /// [`Dt::ZERO`](../struct.Dt.html#associatedconstant.ZERO)).
679    ///
680    /// This method does **not** read the system clock.
681    ///
682    /// For wall-clock “N units ago”, use [`Dt::ago`](../struct.Dt.html#method.ago)
683    /// (requires `std`, or WASM with `js`).
684    ///
685    /// ## Examples
686    ///
687    /// ```rust
688    /// use deep_time::{Dt, Scale, TraitsTime};
689    ///
690    /// let t = 5.sec().before_zero(Scale::TAI);
691    /// assert_eq!(t, Dt::ZERO.sub(5.sec()));
692    /// assert_eq!(t.to_sec(), -5);
693    /// ```
694    ///
695    /// ## See also
696    ///
697    /// - [`Dt::ago`](../struct.Dt.html#method.ago)
698    #[inline(always)]
699    pub const fn before_zero(self, scale: Scale) -> Dt {
700        Dt::new(0, scale, scale).to_tai().sub(self)
701    }
702
703    /// Returns the saturating negation of this [`Dt`].
704    #[inline(always)]
705    pub const fn neg(self) -> Dt {
706        Dt::new(self.attos.saturating_neg(), self.scale, self.target)
707    }
708
709    /// Returns the saturating positive of this [`Dt`].
710    #[inline(always)]
711    pub const fn abs(self) -> Dt {
712        Dt::new(self.attos.saturating_abs(), self.scale, self.target)
713    }
714
715    /// Builds a [`Dt`] holding the given floating-point seconds count.
716    ///
717    /// Does **not** perform any time scale conversions. The `sec` value is
718    /// stored as attoseconds only; its meaning depends on how you use the
719    /// result afterward.
720    ///
721    /// ## Parameters
722    ///
723    /// - `sec` — seconds count to store (`NaN` → zero attoseconds;
724    ///   `±∞` → [`i128::MAX`] / [`i128::MIN`]).
725    /// - `on` — value stored in the returned [`Dt`]'s `scale` field.
726    /// - `target` — value stored in the returned [`Dt`]'s `target` field.
727    ///
728    /// ## Examples
729    ///
730    /// ```rust
731    /// use deep_time::{Dt, Scale};
732    ///
733    /// let seconds = 5.5;
734    /// let duration = Dt::from_sec_f(seconds, Scale::TAI, Scale::TAI);
735    ///
736    /// assert_eq!(duration.to_sec_f(), seconds);
737    /// ```
738    pub const fn from_sec_f(sec: Real, on: Scale, target: Scale) -> Dt {
739        if sec.is_nan() {
740            return Self::new(0, on, target);
741        } else if sec.is_infinite() {
742            return if sec.is_sign_positive() {
743                Self::new(i128::MAX, on, target)
744            } else {
745                Self::new(i128::MIN, on, target)
746            };
747        }
748        Dt::new(Self::sec_f_to_attos(sec), on, target)
749    }
750
751    /// High-precision conversion from [`Real`] seconds to total attoseconds (i128).
752    ///
753    /// - Uses IEEE 754 bit extraction + exact integer multiplication by 5^18.
754    /// - Returns the rounded integer (round-to-nearest, ties away from zero).
755    pub const fn sec_f_to_attos(sec: Real) -> i128 {
756        if sec == 0.0 {
757            return 0;
758        }
759
760        let bits = sec.to_bits();
761        let is_negative = (bits >> 63) != 0;
762        let biased_exp = ((bits >> 52) & 0x7ff) as i32;
763        let mantissa = bits & 0x000f_ffff_ffff_ffff;
764
765        let (sig, exp) = if biased_exp == 0 {
766            if mantissa == 0 {
767                return 0;
768            }
769            (mantissa as u128, -1022i32 - 52)
770        } else {
771            let sig = ((1u64 << 52) | mantissa) as u128;
772            (sig, biased_exp - 1023 - 52)
773        };
774
775        const FIVE_POW_18: u128 = 3_814_697_265_625; // 5^18 exactly
776        let product = sig * FIVE_POW_18;
777        let total_exp = exp + 18;
778
779        // Safe saturation / underflow guards (prevents invalid shifts >= 128)
780        if total_exp > 120 {
781            return if is_negative { i128::MIN } else { i128::MAX };
782        }
783        if total_exp < -97 {
784            return 0;
785        }
786
787        // Keep abs_total as a magnitude only (>= 0). If the value cannot fit in
788        // i128 attoseconds, return MIN or MAX here. Putting MIN into abs_total and
789        // later doing `-abs_total` for a negative input overflows.
790        let abs_total = if total_exp >= 0 {
791            let shift = total_exp as u32;
792            if product > (u128::MAX >> shift) {
793                return if is_negative { i128::MIN } else { i128::MAX };
794            }
795            let shifted = product << shift;
796            if shifted > i128::MAX as u128 {
797                return if is_negative { i128::MIN } else { i128::MAX };
798            }
799            shifted as i128
800        } else {
801            let shift = (-total_exp) as u32;
802            let int_part = (product >> shift) as i128;
803
804            // Round to nearest, half away from zero (on the absolute value)
805            let mask = (1u128 << shift) - 1;
806            let rem = product & mask;
807            if rem > (mask >> 1) {
808                int_part + 1
809            } else {
810                int_part
811            }
812        };
813
814        // abs_total ∈ [0, i128::MAX] — plain negate is safe
815        if is_negative { -abs_total } else { abs_total }
816    }
817
818    /// Returns the current **UTC** system time as TAI from 2000-01-01 12:00:00.
819    ///
820    /// This method is only available when the `std` feature is enabled and the target
821    /// is not WASM with the `js` feature.
822    #[cfg(all(feature = "std", not(all(target_arch = "wasm32", feature = "js"))))]
823    pub fn now() -> Dt {
824        use crate::macros::{from_sec, ns};
825
826        let now = std::time::SystemTime::now();
827
828        let (sec, nanos) = match now.duration_since(std::time::UNIX_EPOCH) {
829            Ok(dur) => (dur.as_secs() as i128, dur.subsec_nanos() as i128),
830            Err(e) => {
831                let dur = e.duration();
832                (-(dur.as_secs() as i128), -(dur.subsec_nanos() as i128))
833            }
834        };
835        Dt::from_diff_and_scale(
836            from_sec!(sec, ns!(nanos), on = Scale::UTC),
837            Dt::UNIX_EPOCH,
838            false,
839        )
840    }
841
842    /// Returns the current **UTC** system time as TAI from 2000-01-01 12:00:00.
843    /// (browser WASM version using JavaScript’s `Date.now()`).
844    #[cfg(all(target_arch = "wasm32", feature = "js"))]
845    pub fn now() -> Dt {
846        use crate::macros::{from_sec, ns};
847
848        let ms: f64 = js_sys::Date::now();
849        let sec = (ms / 1000.0).floor() as i128;
850        let nanos = ((ms % 1000.0) * 1_000_000.0) as i128;
851        Dt::from_diff_and_scale(
852            from_sec!(sec as i128, ns!(nanos as i128), on = Scale::UTC),
853            Dt::UNIX_EPOCH,
854            false,
855        )
856    }
857
858    /// Returns an instant that is this duration **before** the current system time.
859    ///
860    /// Subtracts `self` from [`Dt::now`](../struct.Dt.html#method.now). Available under
861    /// the same conditions as that method: the `std` feature (non-WASM-js), or WASM with
862    /// the `js` feature.
863    ///
864    /// For a `const` offset from the library epoch (no system clock), use
865    /// [`Dt::before_zero`](../struct.Dt.html#method.before_zero).
866    ///
867    /// ## Examples
868    ///
869    /// ```rust
870    /// # #[cfg(feature = "std")]
871    /// # {
872    /// use deep_time::{Dt, TraitsTime};
873    ///
874    /// // ~3 days in the past relative to the system clock
875    /// let past = 3.days().ago();
876    /// assert!(past < Dt::now());
877    /// # }
878    /// ```
879    ///
880    /// ## See also
881    ///
882    /// - [`Dt::from_now`](../struct.Dt.html#method.from_now)
883    /// - [`Dt::before_zero`](../struct.Dt.html#method.before_zero)
884    /// - [`Dt::now`](../struct.Dt.html#method.now)
885    #[cfg(any(
886        all(feature = "std", not(all(target_arch = "wasm32", feature = "js"))),
887        all(target_arch = "wasm32", feature = "js"),
888    ))]
889    #[inline(always)]
890    pub fn ago(self) -> Dt {
891        Dt::now().sub(self)
892    }
893
894    /// Returns an instant that is this duration **after** the current system time.
895    ///
896    /// Adds `self` to [`Dt::now`](../struct.Dt.html#method.now). Available under the same
897    /// conditions as that method: the `std` feature (non-WASM-js), or WASM with the `js`
898    /// feature.
899    ///
900    /// ## Examples
901    ///
902    /// ```rust
903    /// # #[cfg(feature = "std")]
904    /// # {
905    /// use deep_time::{Dt, TraitsTime};
906    ///
907    /// // ~3 days in the future relative to the system clock
908    /// let future = 3.days().from_now();
909    /// assert!(future > Dt::now());
910    /// # }
911    /// ```
912    ///
913    /// ## See also
914    ///
915    /// - [`Dt::ago`](../struct.Dt.html#method.ago)
916    /// - [`Dt::now`](../struct.Dt.html#method.now)
917    #[cfg(any(
918        all(feature = "std", not(all(target_arch = "wasm32", feature = "js"))),
919        all(target_arch = "wasm32", feature = "js"),
920    ))]
921    #[inline(always)]
922    pub fn from_now(self) -> Dt {
923        Dt::now().add(self)
924    }
925}