Skip to main content

satellite_datetime/earth/
utc_day.rs

1//! Cached UTC calendar day for hot `Instant` → [`CivilUtc`] without the search loop.
2//!
3//! Build a [`UtcDay`] once per UTC date, then call [`UtcDay::civil_from_instant`] on every
4//! sample that falls on that day. Use [`UtcContext`] when the day is not known in advance.
5
6use crate::constants::{NS_PER_DAY, NS_PER_SEC, TAI_EPOCH_UNIX_DAYS};
7use crate::duration::Duration;
8use crate::error::{Error, Result};
9use crate::instant::Instant;
10use crate::julian::unix_days_from_civil;
11
12use super::{civil_from_since, tai_minus_utc, CivilUtc};
13
14/// Leap-second-aware bounds for one proleptic Gregorian UTC date.
15///
16/// Stores midnight TAI and day length so [`Self::civil_from_instant`] is O(1) arithmetic
17/// (no ±2-day search). Build once per day in a hot loop; refresh when [`UtcContext`] misses.
18#[derive(Clone, Copy, Debug, Eq, PartialEq)]
19pub struct UtcDay {
20    year: i32,
21    month: u8,
22    day: u8,
23    midnight_tai: i128,
24    day_len_ns: i128,
25    leap_at_end: i8,
26}
27
28impl UtcDay {
29    /// Pin one UTC civil date (0h–24h, including a positive leap second at the end if any).
30    pub fn new(year: i32, month: u8, day: u8) -> Result<Self> {
31        if year < 1960 {
32            return Err(Error::UtcUndefined);
33        }
34        let leap = tai_minus_utc(year, month, day, 0.0)?;
35        let unix_days = unix_days_from_civil(year, month, day);
36        let idx = (unix_days - TAI_EPOCH_UNIX_DAYS) as i128;
37        let dat_ns = Duration::from_seconds_f64(leap.tai_minus_utc)?.as_nanos();
38        let midnight_tai = idx
39            .checked_mul(NS_PER_DAY)
40            .and_then(|v| v.checked_add(dat_ns))
41            .ok_or(Error::Overflow)?;
42        let day_len_ns = NS_PER_DAY + i128::from(leap.leap_at_end) * NS_PER_SEC;
43        Ok(Self {
44            year,
45            month,
46            day,
47            midnight_tai,
48            day_len_ns,
49            leap_at_end: leap.leap_at_end,
50        })
51    }
52
53    /// Civil year of this pinned day.
54    pub const fn year(self) -> i32 {
55        self.year
56    }
57
58    /// Civil month `1..=12`.
59    pub const fn month(self) -> u8 {
60        self.month
61    }
62
63    /// Civil day `1..=31`.
64    pub const fn day(self) -> u8 {
65        self.day
66    }
67
68    /// TAI nanoseconds at 0h UTC on this day.
69    pub const fn midnight_tai(self) -> i128 {
70        self.midnight_tai
71    }
72
73    /// Whether `instant` falls in this UTC day (including `23:59:60` when applicable).
74    pub fn contains(self, instant: Instant) -> bool {
75        let tai_ns = instant.as_tai_nanos();
76        let since = tai_ns - self.midnight_tai;
77        since >= 0 && since < self.day_len_ns
78    }
79
80    /// Map `instant` to civil UTC when it lies on this pinned day.
81    ///
82    /// Returns [`Error::InvalidTime`] if `instant` is outside this day.
83    pub fn civil_from_instant(self, instant: Instant) -> Result<CivilUtc> {
84        let tai_ns = instant.as_tai_nanos();
85        let since = tai_ns
86            .checked_sub(self.midnight_tai)
87            .ok_or(Error::InvalidTime)?;
88        if since < 0 || since >= self.day_len_ns {
89            return Err(Error::InvalidTime);
90        }
91        civil_from_since(self.year, self.month, self.day, since, self.leap_at_end)
92    }
93}
94
95/// Streaming decoder: fast same-day path, slow [`Instant::to_utc`] only on day change.
96#[derive(Clone, Copy, Debug, Eq, PartialEq)]
97pub struct UtcContext {
98    day: UtcDay,
99}
100
101impl UtcContext {
102    /// Start with a pinned UTC day (typically from the first sample or schedule).
103    pub fn new(day: UtcDay) -> Self {
104        Self { day }
105    }
106
107    /// Current pinned day.
108    pub const fn day(self) -> UtcDay {
109        self.day
110    }
111
112    /// Resolve civil UTC, re-pinning the day when the instant crosses midnight (or a leap).
113    pub fn civil_from_instant(&mut self, instant: Instant) -> Result<CivilUtc> {
114        if self.day.contains(instant) {
115            return self.day.civil_from_instant(instant);
116        }
117        let utc = instant.to_utc()?;
118        self.day = UtcDay::new(utc.year, utc.month, utc.day)?;
119        Ok(utc)
120    }
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126    #[test]
127    fn same_day_matches_to_utc() {
128        let day = UtcDay::new(2010, 7, 24).unwrap();
129        let civil = CivilUtc::new(2010, 7, 24, 11, 18, 7, 318_000_000).unwrap();
130        let inst = civil.to_instant().unwrap();
131        assert!(day.contains(inst));
132        assert_eq!(day.civil_from_instant(inst).unwrap(), civil);
133        assert_eq!(inst.to_utc().unwrap(), civil);
134    }
135
136    #[test]
137    fn leap_second_day() {
138        let day = UtcDay::new(2016, 12, 31).unwrap();
139        let leap = CivilUtc::new(2016, 12, 31, 23, 59, 60, 0).unwrap();
140        let inst = leap.to_instant().unwrap();
141        assert!(day.contains(inst));
142        assert_eq!(day.civil_from_instant(inst).unwrap(), leap);
143    }
144
145    #[test]
146    fn outside_day_errors() {
147        let day = UtcDay::new(2017, 1, 1).unwrap();
148        let prev = CivilUtc::new(2016, 12, 31, 23, 59, 59, 0)
149            .unwrap()
150            .to_instant()
151            .unwrap();
152        assert!(!day.contains(prev));
153        assert_eq!(day.civil_from_instant(prev), Err(Error::InvalidTime));
154    }
155
156    #[test]
157    fn context_repins_on_crossing() {
158        let day0 = UtcDay::new(2016, 12, 31).unwrap();
159        let mut ctx = UtcContext::new(day0);
160        let leap = CivilUtc::new(2016, 12, 31, 23, 59, 60, 0)
161            .unwrap()
162            .to_instant()
163            .unwrap();
164        assert_eq!(ctx.civil_from_instant(leap).unwrap().second, 60);
165        let next = CivilUtc::new(2017, 1, 1, 0, 0, 0, 0)
166            .unwrap()
167            .to_instant()
168            .unwrap();
169        let c = ctx.civil_from_instant(next).unwrap();
170        assert_eq!(c.year, 2017);
171        assert_eq!(ctx.day().year(), 2017);
172    }
173
174    #[test]
175    fn many_samples_same_day() {
176        let day = UtcDay::new(2010, 7, 24).unwrap();
177        let base = day.midnight_tai();
178        for sod in [0, 3600, 86_399] {
179            let inst = Instant::from_tai_nanos(base + sod as i128 * NS_PER_SEC);
180            let fast = day.civil_from_instant(inst).unwrap();
181            let slow = inst.to_utc().unwrap();
182            assert_eq!(fast, slow);
183        }
184    }
185}