satellite_datetime/
duration.rs1use crate::error::{Error, Result};
4use crate::NS_PER_SEC;
5
6#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
11pub struct Duration {
12 ns: i128,
13}
14
15impl Duration {
16 pub const ZERO: Self = Self { ns: 0 };
18 pub const SECOND: Self = Self { ns: NS_PER_SEC };
20 pub const MILLISECOND: Self = Self { ns: 1_000_000 };
22 pub const MICROSECOND: Self = Self { ns: 1_000 };
24 pub const NANOSECOND: Self = Self { ns: 1 };
26
27 pub const TT_MINUS_TAI: Self = Self { ns: 32_184_000_000 };
29
30 pub const fn from_nanos(ns: i128) -> Self {
32 Self { ns }
33 }
34
35 pub const fn from_seconds(sec: i64) -> Self {
37 Self {
38 ns: sec as i128 * NS_PER_SEC,
39 }
40 }
41
42 pub const fn from_millis(ms: i64) -> Self {
44 Self {
45 ns: ms as i128 * 1_000_000,
46 }
47 }
48
49 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 pub const fn as_nanos(self) -> i128 {
65 self.ns
66 }
67
68 pub const fn as_seconds(self) -> i128 {
70 self.ns / NS_PER_SEC
71 }
72
73 pub fn as_seconds_f64(self) -> f64 {
75 self.ns as f64 / 1_000_000_000.0
76 }
77
78 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 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 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 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}