Skip to main content

stkcraft_time/
kernel_date.rs

1//! N0067 date literals from SPICE text kernels.
2//!
3//! A text kernel may give an epoch as a date literal that begins with `@`,
4//! for example `EPOCH = @2000-JAN-01-12:00:00`. NAIF resolves such a
5//! literal with `TPARSE` into **seconds past J2000**. That value is a bare
6//! kernel constant: no UTC, TT or TDB conversion is implied, and no
7//! leap-second kernel is consulted.
8//!
9//! [`parse_kernel_date`] implements the documented kernel-literal grammar.
10//! It never falls back to a missing value or to a default epoch:
11//! a literal it cannot resolve returns [`TimeError::KernelDateUnsupported`].
12//! This distinction matters because a downstream reader must be able to
13//! tell an unsupported literal apart from a variable the kernel omitted.
14//!
15//! # Supported forms
16//!
17//! * Named/numeric calendar dates, mixed dash/slash delimiters and native
18//!   month-name prefixes. Year selection follows TPARTV token categories.
19//! * Short years use N0067's default 1969--2068 expansion interval.
20//! * Time is `HH[:MM[:SS]]`, with a decimal permitted only in its final
21//!   component. Integer tokens at least 1000 are classified as years.
22//! * Month, day and clock overflow follow native normalization and the
23//!   original Muller-Wimberly integer expression.
24//! * Julian dates marked with `JD`, numeric ISO calendar/ordinal forms,
25//!   and year/day forms with a slash or explicit day-of-year marker.
26//!
27//! Standalone `@2000-060`, unrecognized text and unsupported grammar return
28//! an explicit error. Era/zone modifiers and a configurable TSETYR context
29//! are outside this resolver. Full TPARSE grammar conformance is not claimed.
30
31use alloc::vec::Vec;
32
33use crate::calendar::{self, J2000_JDN};
34use crate::error::TimeError;
35use crate::naif;
36
37/// A resolved kernel date literal.
38#[derive(Clone, Copy, Debug, PartialEq)]
39pub struct KernelDate {
40    /// Seconds past J2000 (`2000-01-01T12:00:00`) as a bare kernel
41    /// constant, matching the value a SPICE text kernel assigns.
42    pub seconds_past_j2000: f64,
43    /// Normalized proleptic-Gregorian year.
44    pub year: i32,
45    /// Normalized month, `1..=12`.
46    pub month: u8,
47    /// Normalized day of month.
48    pub day: u8,
49    /// Hour of day, `0..=23`.
50    pub hour: u8,
51    /// Minute of hour, `0..=59`.
52    pub minute: u8,
53    /// Second of minute, `0.0 .. 60.0`.
54    pub second: f64,
55}
56
57/// Resolves a kernel date literal such as `@2000-JAN-01-12:00:00`.
58///
59/// The leading `@` is required. The result is the exact N0067/TPARSE
60/// value: proleptic-Gregorian calendar arithmetic expressed as seconds
61/// past J2000, with no leap-second or time-scale conversion.
62///
63/// ```rust
64/// use stkcraft_time::kernel_date::parse_kernel_date;
65///
66/// let epoch = parse_kernel_date("@2001-FEB-29")?;
67/// assert_eq!(epoch.seconds_past_j2000, 36_676_800.0);
68/// assert_eq!((epoch.year, epoch.month, epoch.day), (2001, 3, 1));
69/// # Ok::<(), stkcraft_time::TimeError>(())
70/// ```
71///
72/// # Errors
73///
74/// Returns [`TimeError::KernelDateUnsupported`] when the literal is not a
75/// supported form. It never returns a missing-kernel error, because a date
76/// literal is present data, not an absent variable.
77pub fn parse_kernel_date(text: &str) -> Result<KernelDate, TimeError> {
78    let body = text
79        .strip_prefix('@')
80        .ok_or(TimeError::KernelDateUnsupported)?;
81    if body.is_empty() || !body.is_ascii() || body.bytes().any(|x| x.is_ascii_whitespace()) {
82        return Err(TimeError::KernelDateUnsupported);
83    }
84    let upper = body.to_ascii_uppercase();
85    if let Some(number) = upper
86        .strip_prefix("JD")
87        .or_else(|| upper.strip_suffix("JD"))
88    {
89        let unsigned = number.strip_prefix('-').unwrap_or(number);
90        decimal(unsigned)?;
91        let jd = naif::parse_f64(number).ok_or(TimeError::KernelDateUnsupported)?;
92        let seconds = (jd - 2451545.0) * 86400.0;
93        return calendar_result(seconds, 0, [0.0, 0.0, 0.0], true);
94    }
95
96    if let Some((date, time)) = upper
97        .split_once('T')
98        .filter(|(date, _)| date.bytes().all(|c| c.is_ascii_digit() || c == b'-'))
99    {
100        let fields: Vec<_> = date.split('-').collect();
101        if fields
102            .iter()
103            .skip(1)
104            .any(|field| integer(field).is_ok_and(|value| value >= 1000))
105        {
106            return Err(TimeError::KernelDateUnsupported);
107        }
108        let clock = clock(time)?;
109        let (year, month, day) = match fields.as_slice() {
110            [year, day] => (integer(year)?, 1, integer(day)?),
111            [year, month, day] => (integer(year)?, integer(month)?, integer(day)?),
112            _ => return Err(TimeError::KernelDateUnsupported),
113        };
114        return from_calendar(expand_year(year), month, day, clock);
115    }
116
117    for marker in ["//", "::"] {
118        if let Some((date, time)) = body.split_once(marker) {
119            let fields: Vec<_> = date.split(['-', '/']).collect();
120            if let [year, day] = fields.as_slice() {
121                return from_calendar(expand_year(integer(year)?), 1, integer(day)?, clock(time)?);
122            }
123            return Err(TimeError::KernelDateUnsupported);
124        }
125    }
126    let fields: Vec<_> = body.split(['-', '/']).collect();
127    if fields.iter().any(|field| field.is_empty()) {
128        return Err(TimeError::KernelDateUnsupported);
129    }
130    if fields.len() == 3 && fields[2].contains(':') {
131        // TPARTV's year/day/time slash production is distinct from a
132        // three-component calendar date and from a standalone YYYY-DDD.
133        let delimiter = body.rfind('/').ok_or(TimeError::KernelDateUnsupported)?;
134        if &body[delimiter + 1..] != fields[2] {
135            return Err(TimeError::KernelDateUnsupported);
136        }
137        return from_calendar(
138            expand_year(integer(fields[0])?),
139            1,
140            integer(fields[1])?,
141            clock(fields[2])?,
142        );
143    }
144    let (date, clock) = match fields.as_slice() {
145        [a, b, c] => ([*a, *b, *c], [0.0, 0.0, 0.0]),
146        [a, b, c, time] => ([*a, *b, *c], clock(time)?),
147        _ => return Err(TimeError::KernelDateUnsupported),
148    };
149    // TPARTV permits a decimal only in the final numeric component.
150    if date[..2].iter().any(|field| field.contains('.'))
151        || (fields.len() == 4 && date[2].contains('.'))
152    {
153        return Err(TimeError::KernelDateUnsupported);
154    }
155    let named = date
156        .iter()
157        .enumerate()
158        .find_map(|(index, field)| month(field).map(|month| (index, month)));
159    let years: Vec<_> = date
160        .iter()
161        .enumerate()
162        .filter_map(|(index, field)| {
163            integer(field)
164                .ok()
165                .filter(|value| *value >= 1000)
166                .map(|value| (index, value))
167        })
168        .collect();
169    let year_index = match years.as_slice() {
170        [(index, _)] => *index,
171        [] => match named {
172            Some((0, _)) => 2,
173            Some(_) => 0,
174            None if fields.len() == 3 && body.contains('/') => 2,
175            None => return Err(TimeError::KernelDateUnsupported),
176        },
177        _ => return Err(TimeError::KernelDateUnsupported),
178    };
179    let month_index = match named {
180        Some((index, _)) => index,
181        None if year_index == 0 => 1,
182        None if year_index == 2 => 0,
183        None => return Err(TimeError::KernelDateUnsupported),
184    };
185    if year_index == month_index {
186        return Err(TimeError::KernelDateUnsupported);
187    }
188    let day_index = 3 - year_index - month_index;
189    let year = expand_year(integer(date[year_index])?);
190    let month = match named {
191        Some((_, month)) => month,
192        None => integer(date[month_index])?,
193    };
194    let day = libm::round(decimal(date[day_index])?);
195    if day > i32::MAX as f64 {
196        return Err(TimeError::KernelDateUnsupported);
197    }
198    from_calendar(year, month, day as i64, clock)
199}
200
201fn decimal(token: &str) -> Result<f64, TimeError> {
202    if !token.as_bytes().first().is_some_and(u8::is_ascii_digit)
203        || token.bytes().any(|c| !c.is_ascii_digit() && c != b'.')
204        || token.bytes().filter(|c| *c == b'.').count() > 1
205    {
206        return Err(TimeError::KernelDateUnsupported);
207    }
208    let value = naif::parse_f64(token).ok_or(TimeError::KernelDateUnsupported)?;
209    if !value.is_finite() {
210        return Err(TimeError::KernelDateUnsupported);
211    }
212    Ok(value)
213}
214
215fn integer(token: &str) -> Result<i64, TimeError> {
216    if token.is_empty() || !token.bytes().all(|c| c.is_ascii_digit()) {
217        return Err(TimeError::KernelDateUnsupported);
218    }
219    let value = token
220        .parse::<i64>()
221        .map_err(|_| TimeError::KernelDateUnsupported)?;
222    if value > i32::MAX as i64 {
223        return Err(TimeError::KernelDateUnsupported);
224    }
225    Ok(value)
226}
227
228fn expand_year(year: i64) -> i64 {
229    if year < 69 {
230        2000 + year
231    } else if year < 100 {
232        1900 + year
233    } else {
234        year
235    }
236}
237
238fn month(token: &str) -> Option<i64> {
239    if token.len() < 3 {
240        return None;
241    }
242    let token = token.to_ascii_uppercase();
243    [
244        "JANUARY",
245        "FEBRUARY",
246        "MARCH",
247        "APRIL",
248        "MAY",
249        "JUNE",
250        "JULY",
251        "AUGUST",
252        "SEPTEMBER",
253        "OCTOBER",
254        "NOVEMBER",
255        "DECEMBER",
256    ]
257    .iter()
258    .position(|name| name.starts_with(&token))
259    .map(|index| index as i64 + 1)
260}
261
262fn clock(token: &str) -> Result<[f64; 3], TimeError> {
263    let fields: Vec<_> = token.split(':').collect();
264    if fields.is_empty() || fields.len() > 3 {
265        return Err(TimeError::KernelDateUnsupported);
266    }
267    let mut result = [0.0; 3];
268    for (index, field) in fields.iter().enumerate() {
269        if index + 1 != fields.len() && field.contains('.') {
270            return Err(TimeError::KernelDateUnsupported);
271        }
272        // TPARTV promotes integer tokens >= 1000 to year tokens before
273        // resolving clocks. A decimal token remains a separate category.
274        if integer(field).is_ok_and(|value| value >= 1000) {
275            return Err(TimeError::KernelDateUnsupported);
276        }
277        result[index] = decimal(field)?;
278    }
279    Ok(result)
280}
281
282fn from_calendar(
283    year: i64,
284    month: i64,
285    day: i64,
286    clock: [f64; 3],
287) -> Result<KernelDate, TimeError> {
288    // N0067 TPARSE's Muller-Wimberly integer expression uses truncating
289    // division. Preserve it even for out-of-range month/day fields.
290    let days = year * 367
291        - (year + (month + 9) / 12) * 7 / 4
292        - ((year + (month - 9) / 7) / 100 + 1) * 3 / 4
293        + month * 275 / 9
294        + day
295        - 730516;
296    if days < i32::MIN as i64 || days > i32::MAX as i64 {
297        return Err(TimeError::KernelDateUnsupported);
298    }
299    let seconds = (days as f64 - 0.5) * 86400.0 + clock[0] * 3600.0 + clock[1] * 60.0 + clock[2];
300    calendar_result(seconds, days, clock, false)
301}
302
303fn calendar_result(
304    seconds: f64,
305    days: i64,
306    clock: [f64; 3],
307    julian: bool,
308) -> Result<KernelDate, TimeError> {
309    if !seconds.is_finite() {
310        return Err(TimeError::KernelDateUnsupported);
311    }
312    let (days, hour, minute, second) = if julian {
313        let midnight = seconds + 43200.0;
314        let days = libm::floor(midnight / 86400.0);
315        if days < i32::MIN as f64 || days > i32::MAX as f64 {
316            return Err(TimeError::KernelDateUnsupported);
317        }
318        let remainder = midnight - days * 86400.0;
319        let hour = libm::floor(remainder / 3600.0);
320        let minute = libm::floor((remainder - hour * 3600.0) / 60.0);
321        (
322            days as i64,
323            hour as u8,
324            minute as u8,
325            remainder - hour * 3600.0 - minute * 60.0,
326        )
327    } else {
328        let hours = libm::floor(clock[0]);
329        let minutes = clock[1] + (clock[0] - hours) * 60.0;
330        let whole_minutes = libm::floor(minutes);
331        let raw_seconds = clock[2] + (minutes - whole_minutes) * 60.0;
332        let second_carry = libm::floor(raw_seconds / 60.0);
333        let second = raw_seconds - second_carry * 60.0;
334        let minutes = whole_minutes + second_carry;
335        let hour_carry = libm::floor(minutes / 60.0);
336        let minute = minutes - hour_carry * 60.0;
337        let hours = hours + hour_carry;
338        let day_carry = libm::floor(hours / 24.0);
339        if day_carry > i32::MAX as f64 {
340            return Err(TimeError::KernelDateUnsupported);
341        }
342        (
343            days + day_carry as i64,
344            (hours - day_carry * 24.0) as u8,
345            minute as u8,
346            second,
347        )
348    };
349    let (year, month, day) = calendar::jdn_to_gregorian(J2000_JDN + days);
350    Ok(KernelDate {
351        seconds_past_j2000: seconds,
352        year,
353        month,
354        day,
355        hour,
356        minute,
357        second,
358    })
359}
360
361#[cfg(test)]
362mod tests {
363    use super::parse_kernel_date;
364
365    #[test]
366    fn single_digit_lsk_day_is_not_a_year() {
367        let date = parse_kernel_date("@1972-JAN-1").unwrap();
368        assert_eq!(date.seconds_past_j2000, -883_656_000.0);
369    }
370
371    #[test]
372    fn numeric_month_positions_are_unambiguous() {
373        let year_first = parse_kernel_date("@1990-01-02").unwrap();
374        let year_last = parse_kernel_date("@01/02/1990").unwrap();
375
376        assert_eq!(
377            (year_first.year, year_first.month, year_first.day),
378            (1990, 1, 2)
379        );
380        assert_eq!(
381            (year_last.year, year_last.month, year_last.day),
382            (1990, 1, 2)
383        );
384    }
385
386    #[test]
387    fn free_text_and_duplicate_date_markers_are_rejected() {
388        for text in ["@NOT_A_DATE", "@@2000-JAN-01"] {
389            assert!(parse_kernel_date(text).is_err(), "{text}");
390        }
391    }
392}