Skip to main content

satellite_datetime/
duration.rs

1//! SI durations. Never a calendar day, never a leap second.
2
3use crate::error::{Error, Result};
4use crate::NS_PER_SEC;
5
6/// A signed span of SI seconds, stored as nanoseconds.
7///
8/// This is the only duration type in the core. Calendar days, sols, and UTC
9/// days that contain leap seconds are *not* durations; convert them explicitly.
10#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
11pub struct Duration {
12    ns: i128,
13}
14
15impl Duration {
16    /// Zero length.
17    pub const ZERO: Self = Self { ns: 0 };
18    /// One SI second.
19    pub const SECOND: Self = Self { ns: NS_PER_SEC };
20    /// One SI millisecond.
21    pub const MILLISECOND: Self = Self { ns: 1_000_000 };
22    /// One SI microsecond.
23    pub const MICROSECOND: Self = Self { ns: 1_000 };
24    /// One SI nanosecond.
25    pub const NANOSECOND: Self = Self { ns: 1 };
26
27    /// Exact TT − TAI offset (IAU): 32.184 SI seconds.
28    pub const TT_MINUS_TAI: Self = Self { ns: 32_184_000_000 };
29
30    /// Construct from SI nanoseconds.
31    pub const fn from_nanos(ns: i128) -> Self {
32        Self { ns }
33    }
34
35    /// Construct from whole SI seconds.
36    pub const fn from_seconds(sec: i64) -> Self {
37        Self {
38            ns: sec as i128 * NS_PER_SEC,
39        }
40    }
41
42    /// Construct from whole milliseconds.
43    pub const fn from_millis(ms: i64) -> Self {
44        Self {
45            ns: ms as i128 * 1_000_000,
46        }
47    }
48
49    /// Construct from a floating SI second count. Rounds to nearest nanosecond.
50    ///
51    /// Prefer integer constructors for flight code.
52    pub fn from_seconds_f64(sec: f64) -> Result<Self> {
53        if !sec.is_finite() {
54            return Err(Error::Overflow);
55        }
56        let ns = libm::round(sec * 1_000_000_000.0);
57        if ns < i128::MIN as f64 || ns > i128::MAX as f64 {
58            return Err(Error::Overflow);
59        }
60        Ok(Self { ns: ns as i128 })
61    }
62
63    /// SI nanoseconds.
64    pub const fn as_nanos(self) -> i128 {
65        self.ns
66    }
67
68    /// Truncated whole SI seconds toward zero.
69    pub const fn as_seconds(self) -> i128 {
70        self.ns / NS_PER_SEC
71    }
72
73    /// SI seconds as `f64` (sub-nanosecond rounding at large magnitudes).
74    pub fn as_seconds_f64(self) -> f64 {
75        self.ns as f64 / 1_000_000_000.0
76    }
77
78    /// Checked addition.
79    pub const fn checked_add(self, other: Self) -> Result<Self> {
80        match self.ns.checked_add(other.ns) {
81            Some(ns) => Ok(Self { ns }),
82            None => Err(Error::Overflow),
83        }
84    }
85
86    /// Checked subtraction.
87    pub const fn checked_sub(self, other: Self) -> Result<Self> {
88        match self.ns.checked_sub(other.ns) {
89            Some(ns) => Ok(Self { ns }),
90            None => Err(Error::Overflow),
91        }
92    }
93
94    /// Checked negation.
95    pub const fn checked_neg(self) -> Result<Self> {
96        match self.ns.checked_neg() {
97            Some(ns) => Ok(Self { ns }),
98            None => Err(Error::Overflow),
99        }
100    }
101
102    /// Multiply by a signed integer.
103    pub const fn checked_mul(self, rhs: i128) -> Result<Self> {
104        match self.ns.checked_mul(rhs) {
105            Some(ns) => Ok(Self { ns }),
106            None => Err(Error::Overflow),
107        }
108    }
109}
110
111impl core::ops::Neg for Duration {
112    type Output = Result<Self>;
113    fn neg(self) -> Self::Output {
114        self.checked_neg()
115    }
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121
122    #[test]
123    fn tt_offset_is_exact() {
124        assert_eq!(Duration::TT_MINUS_TAI.as_nanos(), 32_184_000_000);
125        assert!((Duration::TT_MINUS_TAI.as_seconds_f64() - 32.184).abs() < 1e-15);
126    }
127
128    #[test]
129    fn overflow() {
130        assert_eq!(
131            Duration::from_nanos(i128::MAX).checked_add(Duration::NANOSECOND),
132            Err(Error::Overflow)
133        );
134    }
135}