Skip to main content

deep_time/dt/
jiff.rs

1use crate::{Dt, DtErr, DtErrKind, Scale, an_err};
2use core::convert::{From, TryFrom};
3use jiff::{SignedDuration, Span, Timestamp};
4
5impl Dt {
6    /// Converts this [`Dt`] to a [`jiff::Timestamp`].
7    ///
8    /// ## Time scale
9    ///
10    /// [`jiff::Timestamp`] is a **Unix / POSIX** instant: nanoseconds since
11    /// `1970-01-01 00:00:00Z`. Jiff documents this as “the Unix timescale with a
12    /// UTC offset of zero” and **does not support leap seconds** (it behaves as if
13    /// they do not exist in the numeric count). Conversion therefore goes through
14    /// [`Scale::UTC`](../enum.Scale.html#variant.UTC) and the Unix epoch so deep-time's
15    /// leap-second tables are applied on the way out of TAI storage.
16    ///
17    /// This is **not** a TAI timestamp. A [`Dt`] stored on TAI (or any other scale)
18    /// is converted to the equivalent UTC civil instant before the Unix count is
19    /// taken.
20    ///
21    /// ## Precision and range
22    ///
23    /// - Sub-nanosecond attoseconds are truncated toward zero.
24    /// - Saturates at [`Timestamp::MIN`] / [`Timestamp::MAX`] if out of range
25    ///   (jiff's supported range is roughly years −9999…9999).
26    pub fn to_jiff_timestamp(&self) -> Timestamp {
27        let mut nanos = self.target(Scale::UTC).to_unix().to_ns().0;
28        // required to due jiff panic in v0.2.33
29        if nanos > Timestamp::MAX.as_nanosecond() {
30            nanos = Timestamp::MAX.as_nanosecond();
31        } else if nanos < Timestamp::MIN.as_nanosecond() {
32            nanos = Timestamp::MIN.as_nanosecond();
33        }
34        match Timestamp::from_nanosecond(nanos) {
35            Ok(ts) => ts,
36            Err(_) => {
37                if nanos >= 0 {
38                    Timestamp::MAX
39                } else {
40                    Timestamp::MIN
41                }
42            }
43        }
44    }
45
46    /// Creates a TAI [`Dt`] from a [`jiff::Timestamp`].
47    ///
48    /// Inverse of [`Dt::to_jiff_timestamp`]. The Unix nanosecond count is treated
49    /// as a POSIX/UTC elapsed time since the Unix epoch (not TAI, and not as a
50    /// count since J2000), then converted into deep-time's TAI storage via
51    /// [`Dt::from_unix`].
52    #[inline]
53    pub fn from_jiff_timestamp(ts: Timestamp) -> Dt {
54        Dt::from_unix_ns(ts.as_nanosecond())
55    }
56
57    /// Converts this [`Dt`] to a [`jiff::Span`] (seconds + nanoseconds only).
58    ///
59    /// ## Time scale
60    ///
61    /// A [`Span`] built this way is a pure elapsed span of SI nanoseconds taken
62    /// from this [`Dt`]'s raw attosecond count. It is **not** tied to UTC leap
63    /// seconds or calendar units (years/months/days are left at zero).
64    ///
65    /// ## Precision and range
66    ///
67    /// - Sub-nanosecond attoseconds are truncated toward zero.
68    /// - Saturates at jiff's `Span` second/nanosecond limits
69    ///   (`±631_107_417_600` s and `±999_999_999` ns) if out of range.
70    pub fn to_jiff_span(&self) -> Span {
71        let (total_nanos, _) = self.to_ns();
72        let seconds = Dt::to_i64(total_nanos / 1_000_000_000);
73        let nanoseconds = Dt::to_i64(total_nanos % 1_000_000_000);
74
75        if let Ok(base) = Span::new().try_seconds(seconds)
76            && let Ok(span) = base.try_nanoseconds(nanoseconds)
77        {
78            return span;
79        }
80        // Saturate to Jiff's Span limits
81        if total_nanos >= 0 {
82            Span::new()
83                .seconds(631_107_417_600i64)
84                .nanoseconds(999_999_999i64)
85        } else {
86            Span::new()
87                .seconds(-631_107_417_600i64)
88                .nanoseconds(-999_999_999i64)
89        }
90    }
91
92    /// Converts this [`Dt`] to a [`jiff::SignedDuration`] (nanosecond precision).
93    ///
94    /// ## Time scale
95    ///
96    /// A [`SignedDuration`] is a pure elapsed span (SI seconds + nanoseconds). It
97    /// is **not** tied to UTC, TAI, or any other time scale. The conversion uses
98    /// this [`Dt`]'s raw attosecond count (same convention as chrono/`time` duration
99    /// interop).
100    ///
101    /// ## Precision and range
102    ///
103    /// - Sub-nanosecond attoseconds are **truncated toward zero**.
104    /// - Supports the **entire** range of [`Dt`]'s nanosecond projection
105    ///   (`SignedDuration::from_nanos_i128`; never saturates here).
106    #[inline]
107    pub fn to_jiff_signed_duration(&self) -> SignedDuration {
108        SignedDuration::from_nanos_i128(self.to_ns().0)
109    }
110
111    /// Creates a [`Dt`] from a [`jiff::SignedDuration`] (nanosecond precision).
112    ///
113    /// Inverse of [`Dt::to_jiff_signed_duration`]. The result is a span stored on
114    /// TAI (no leap-second adjustment of the duration itself), matching
115    /// chrono/`time` duration interop.
116    #[inline]
117    pub fn from_jiff_signed_duration(dur: SignedDuration) -> Dt {
118        Self::from_ns(dur.as_nanos(), 0, Scale::TAI, Scale::TAI)
119    }
120
121    /// Creates a [`Dt`] from a [`jiff::Span`] (nanosecond precision).
122    ///
123    /// Inverse of [`Dt::to_jiff_span`]. Converts the span to a
124    /// [`SignedDuration`] (seconds + nanoseconds only; calendar units must already
125    /// be zero or convertible without a relative datetime) and then uses
126    /// [`Dt::from_jiff_signed_duration`].
127    pub fn from_jiff_span(span: Span) -> Result<Self, DtErr> {
128        let dur = SignedDuration::try_from(span)
129            .map_err(|e| an_err!(DtErrKind::InvalidInput, "{}", e))?;
130        Ok(Self::from_jiff_signed_duration(dur))
131    }
132}
133
134impl From<Timestamp> for Dt {
135    #[inline]
136    fn from(ts: Timestamp) -> Self {
137        Self::from_jiff_timestamp(ts)
138    }
139}
140
141impl From<Dt> for Timestamp {
142    #[inline]
143    fn from(dt: Dt) -> Self {
144        dt.to_jiff_timestamp()
145    }
146}
147
148impl From<SignedDuration> for Dt {
149    #[inline]
150    fn from(dur: SignedDuration) -> Self {
151        Self::from_jiff_signed_duration(dur)
152    }
153}
154
155impl From<Dt> for SignedDuration {
156    #[inline]
157    fn from(dt: Dt) -> Self {
158        dt.to_jiff_signed_duration()
159    }
160}
161
162impl TryFrom<Span> for Dt {
163    type Error = DtErr;
164
165    fn try_from(span: Span) -> Result<Self, Self::Error> {
166        Self::from_jiff_span(span)
167    }
168}