Skip to main content

stkcraft_time/
sclk.rs

1//! Spacecraft clock (SCLK) kernels, type 1.
2//!
3//! A type-1 clock is a set of cascading integer counters. The SCLK kernel
4//! stores, for one spacecraft:
5//!
6//! * `SCLK01_N_FIELDS_<id>` — number of fields,
7//! * `SCLK01_MODULI_<id>` — modulus of each field,
8//! * `SCLK01_OFFSETS_<id>` — offset added to each field value,
9//! * `SCLK01_TIME_SYSTEM_<id>` — `1` for TDB/ET, `2` for TT (default 1),
10//! * `SCLK01_COEFFICIENTS_<id>` — triplets `(ticks, parallel_seconds,
11//!   rate)` describing the piecewise-linear map from encoded ticks to the
12//!   parallel time system,
13//! * `SCLK01_OUTPUT_DELIM_<id>` — delimiter used in formatted strings.
14//!
15//! The encoded tick count of a field vector is
16//!
17//! ```text
18//! ticks = (((f0 - o0) * m1 + (f1 - o1)) * m2 + (f2 - o2)) * ...
19//! ```
20//!
21//! The offsets give the value of the first count of each field. For
22//! Voyager, the third field starts at 1, so its offset is 1 and the
23//! encoded counter runs from 0 to 799.
24//!
25//! and the number of ticks in one count of the most significant field is
26//! `m1 * m2 * ...`. The spacing between successive coefficient samples is
27//! therefore `rate / ticks_per_msb` seconds per tick, which is the
28//! behaviour verified against CSPICE `sct2e`.
29//!
30//! # Scope
31//!
32//! Encoded-tick/time conversions enforce the cumulative duration of the
33//! declared partitions, rounding the accumulated raw durations as SCTE01.
34//! Native-style encoded string conversion is available separately from the
35//! legacy field API. Partitioned SclkClock strings use discrete SCET01 ticks;
36//! continuous tick conversion rejects values outside its own domain. A map
37//! without partition metadata has no declared upper bound.
38//!
39//! Only clock type 1 is supported. No SCLK kernel is embedded at runtime; load the
40//! mission kernel you need at deployment time.
41
42use alloc::format;
43use alloc::string::{String, ToString};
44use alloc::vec::Vec;
45
46use crate::convert::{tai_to_et, tai_to_tt};
47use crate::epoch::Epoch;
48use crate::error::TimeError;
49use crate::leap::LeapSecondTable;
50use crate::math;
51
52/// The parallel time system that SCLK coefficients map to.
53#[derive(Clone, Copy, Debug, PartialEq, Eq)]
54pub enum SclkTimeSystem {
55    /// Barycentric Dynamical Time: the coefficients give ET seconds past
56    /// J2000 directly.
57    Tdb,
58    /// Terrestrial Dynamical Time: the coefficients give TT seconds past
59    /// J2000, and the LSK is needed to reach ET.
60    Tdt,
61}
62
63/// One piecewise-linear segment of the tick-to-time map.
64#[derive(Clone, Copy, Debug, PartialEq)]
65pub struct SclkCoefficient {
66    /// Encoded tick count at the start of the segment.
67    pub ticks: f64,
68    /// Parallel-time value at the start of the segment, in seconds.
69    pub seconds: f64,
70    /// Parallel-time rate per most-significant-field count.
71    pub rate: f64,
72}
73
74/// Error symbol for partition-aware SCLK string conversion.
75#[derive(Clone, Copy, Debug, PartialEq, Eq)]
76pub struct SclkStringError(&'static str);
77
78impl SclkStringError {
79    /// Return the CSPICE short error symbol, or `STKCRAFT(NONFINITE)` for
80    /// the library's explicit non-finite input guard.
81    pub fn spice_short(self) -> &'static str {
82        self.0
83    }
84}
85
86impl core::fmt::Display for SclkStringError {
87    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
88        f.write_str(self.0)
89    }
90}
91
92#[cfg(feature = "std")]
93impl std::error::Error for SclkStringError {}
94
95/// State of NAIF's type-1 SCLK component parser across calls.
96///
97/// Keep one context for each independent native-style kernel-pool history.
98/// A failed numeric component can affect a later blank component until a
99/// numeric component is successfully parsed.
100#[derive(Clone, Debug, Default)]
101pub struct SclkStringContext {
102    component_error: bool,
103}
104
105/// A parsed type-1 SCLK kernel for one spacecraft clock.
106#[derive(Clone, Debug)]
107pub struct SclkKernel {
108    spacecraft_id: i32,
109    data_type: i32,
110    time_system: SclkTimeSystem,
111    n_fields: usize,
112    moduli: Vec<i64>,
113    offsets: Vec<i64>,
114    coefficients: Vec<SclkCoefficient>,
115    delimiter: char,
116    native_delimiter_code: Option<i64>,
117    partition_start: Vec<f64>,
118    partition_end: Vec<f64>,
119    max_encoded_ticks: Option<f64>,
120}
121
122impl SclkKernel {
123    /// Decode continuous encoded ticks to a partition-prefixed NAIF clock string.
124    pub fn decode_native_sclk(&self, ticks: f64) -> Result<String, SclkStringError> {
125        self.validate_native_string_metadata()?;
126        let totals = self.partition_totals(false)?;
127        if !ticks.is_finite() {
128            return Err(SclkStringError("STKCRAFT(NONFINITE)"));
129        }
130        let ticks = native_nint(ticks);
131        let last = *totals
132            .last()
133            .ok_or(SclkStringError("SPICE(KERNELVARNOTFOUND)"))?;
134        let part = if ticks == last {
135            totals.len() - 1
136        } else {
137            totals
138                .iter()
139                .position(|&end| ticks < end)
140                .ok_or(SclkStringError("SPICE(VALUEOUTOFRANGE)"))?
141        };
142        if ticks < 0.0 {
143            return Err(SclkStringError("SPICE(VALUEOUTOFRANGE)"));
144        }
145        let readout = if part == 0 {
146            ticks + self.partition_start[part]
147        } else {
148            ticks + self.partition_start[part] - totals[part - 1]
149        };
150        let mut factors = alloc::vec![1.0; self.n_fields];
151        for index in (0..self.n_fields - 1).rev() {
152            factors[index] = factors[index + 1] * self.moduli[index + 1] as f64;
153        }
154        let mut remaining = native_nint(readout);
155        if remaining < 0.0 || !remaining.is_finite() {
156            return Err(SclkStringError("SPICE(VALUEOUTOFRANGE)"));
157        }
158        let mut parts = Vec::with_capacity(self.n_fields);
159        for (index, &factor) in factors.iter().enumerate() {
160            let component = if index + 1 == self.n_fields {
161                remaining + self.offsets[index] as f64
162            } else {
163                let value = math::floor(remaining / factor) + self.offsets[index] as f64;
164                remaining %= factor;
165                value
166            };
167            let max_width = self.moduli[index] as f64 + self.offsets[index] as f64 - 1.0;
168            if max_width + 0.5 <= 0.0 || !component.is_finite() {
169                return Err(SclkStringError("SPICE(INVALIDSCLKSTRING)"));
170            }
171            let width = (native_log10(max_width + 0.5) as i32 + 1).max(0) as usize;
172            // SCFM01 removes DPSTRF's leading sign character, including
173            // for negative field values induced by a negative offset.
174            let component = native_clock_component(component);
175            let mut padded = String::new();
176            if component.len() > 28 {
177                // The 30-byte DPSTRF buffer cannot contain a sign, this
178                // integer, and a decimal point. SCFM01 then observes a
179                // missing decimal and pads the field width plus two zeros.
180                for _ in 0..width + 2 {
181                    padded.push('0');
182                }
183            } else {
184                for _ in component.len()..width {
185                    padded.push('0');
186                }
187                padded.push_str(&component);
188            }
189            parts.push(padded);
190        }
191        Ok(format!(
192            "{}/{}",
193            part + 1,
194            parts.join(&self.delimiter.to_string())
195        ))
196    }
197
198    /// Encode a clock string using a fresh NAIF component-parser context.
199    ///
200    /// Use [`Self::encode_native_sclk_with_context`] to reproduce the native
201    /// parser's state across successive calls.
202    pub fn encode_native_sclk(&self, text: &str) -> Result<f64, SclkStringError> {
203        self.encode_native_sclk_with_context(text, &mut SclkStringContext::default())
204    }
205
206    /// Encode a clock string while preserving native parser state across calls.
207    pub fn encode_native_sclk_with_context(
208        &self,
209        text: &str,
210        context: &mut SclkStringContext,
211    ) -> Result<f64, SclkStringError> {
212        let text = text.split('\0').next().unwrap_or("");
213        if text.is_empty() {
214            return Err(SclkStringError("SPICE(EMPTYSTRING)"));
215        }
216        let invalid = SclkStringError("SPICE(INVALIDSCLKSTRING)");
217        let bad_partition = SclkStringError("SPICE(BADPARTNUMBER)");
218        self.validate_native_string_metadata()?;
219        let totals = self.partition_totals(true)?;
220        let (partition, clock) = match text.find('/') {
221            Some(0) => return Err(bad_partition),
222            Some(index) if index + 1 == text.len() => return Err(invalid),
223            Some(index) => (Some(&text[..index]), &text[index + 1..]),
224            None => (None, text),
225        };
226        if clock.trim_matches(' ').is_empty() {
227            return Err(invalid);
228        }
229        let fields = native_clock_fields(clock);
230        if fields.len() > self.n_fields {
231            return Err(invalid);
232        }
233        let mut factors = alloc::vec![1.0; self.n_fields];
234        for index in (0..self.n_fields - 1).rev() {
235            factors[index] = factors[index + 1] * self.moduli[index + 1] as f64;
236        }
237        let mut ticks = 0.0;
238        for (index, field) in fields.iter().enumerate() {
239            let value = if field.is_empty() {
240                if context.component_error {
241                    return Err(invalid);
242                }
243                self.offsets[index] as f64
244            } else {
245                match core::str::from_utf8(field)
246                    .ok()
247                    .and_then(parse_native_clock_number)
248                {
249                    Some(value) => {
250                        context.component_error = false;
251                        value
252                    }
253                    None => {
254                        context.component_error = true;
255                        return Err(invalid);
256                    }
257                }
258            } - self.offsets[index] as f64;
259            if native_nint(value) < 0.0 {
260                return Err(invalid);
261            }
262            ticks += value * factors[index];
263        }
264        ticks = native_nint(ticks);
265        let starts: Vec<f64> = self
266            .partition_start
267            .iter()
268            .copied()
269            .map(native_nint)
270            .collect();
271        let ends: Vec<f64> = self
272            .partition_end
273            .iter()
274            .copied()
275            .map(native_nint)
276            .collect();
277        let part = if let Some(number) = partition {
278            let value = parse_native_clock_number(number).ok_or(bad_partition)?;
279            if value < 1.0 || value >= (starts.len() + 1) as f64 {
280                return Err(bad_partition);
281            }
282            let index = value as usize - 1;
283            if ticks < starts[index] || ticks > ends[index] {
284                return Err(SclkStringError("SPICE(NOTINPART)"));
285            }
286            index
287        } else {
288            starts
289                .iter()
290                .zip(&ends)
291                .position(|(&start, &end)| ticks >= start && ticks <= end)
292                .ok_or(SclkStringError("SPICE(NOPARTITION)"))?
293        };
294        Ok(if part == 0 {
295            ticks - starts[part]
296        } else {
297            ticks - starts[part] + totals[part - 1]
298        })
299    }
300
301    fn validate_native_string_metadata(&self) -> Result<(), SclkStringError> {
302        if self.n_fields > 10 {
303            return Err(SclkStringError("SPICE(VALUEOUTOFRANGE)"));
304        }
305        match self.native_delimiter_code {
306            None => Err(SclkStringError("SPICE(KERNELVARNOTFOUND)")),
307            Some(1..=5) => Ok(()),
308            Some(_) => Err(SclkStringError("SPICE(VALUEOUTOFRANGE)")),
309        }
310    }
311
312    // SCDECD's LSTLED search selects partition 2 for a NaN tick when at
313    // least two partitions exist. The exercised N0067 SCFM01 builds render
314    // NaN components as zero-filled fields. This path is used only for an
315    // indeterminate intermediate generated from finite ET, not for a
316    // caller-supplied non-finite tick.
317    fn decode_indeterminate_ticks(&self) -> Result<String, SclkStringError> {
318        self.validate_native_string_metadata()?;
319        let totals = self.partition_totals(false)?;
320        if totals.len() < 2 {
321            return Err(SclkStringError("SPICE(VALUEOUTOFRANGE)"));
322        }
323        let mut parts = Vec::with_capacity(self.n_fields);
324        for index in 0..self.n_fields {
325            let max_width = self.moduli[index] as f64 + self.offsets[index] as f64 - 1.0;
326            if max_width + 0.5 <= 0.0 {
327                return Err(SclkStringError("SPICE(INVALIDSCLKSTRING)"));
328            }
329            let width = (native_log10(max_width + 0.5) as i32 + 1).max(0) as usize;
330            let mut field = String::new();
331            for _ in 0..width {
332                field.push('0');
333            }
334            parts.push(field);
335        }
336        Ok(format!("2/{}", parts.join(&self.delimiter.to_string())))
337    }
338
339    fn partition_totals(&self, round_endpoints: bool) -> Result<Vec<f64>, SclkStringError> {
340        if self.partition_start.is_empty() {
341            return Err(SclkStringError("SPICE(KERNELVARNOTFOUND)"));
342        }
343        if self.partition_start.len() > 9999 {
344            return Err(SclkStringError("SPICE(TOOMANYPARTITIONS)"));
345        }
346        let mut totals = Vec::with_capacity(self.partition_start.len());
347        let mut total = 0.0;
348        for (&start, &end) in self.partition_start.iter().zip(&self.partition_end) {
349            let (start, end) = if round_endpoints {
350                (native_nint(start), native_nint(end))
351            } else {
352                (start, end)
353            };
354            total = native_nint(total + end - start);
355            totals.push(total);
356        }
357        Ok(totals)
358    }
359    /// Parses a `KPL/SCLK` text kernel for the given clock.
360    ///
361    /// `spacecraft_id` may be given with either sign; kernel variables are
362    /// looked up with the magnitude, matching NAIF kernels such as
363    /// `MRO_SCLKSCET` (variables `_74`, clock id `-74`).
364    pub fn parse(text: &str, spacecraft_id: i32) -> Result<Self, TimeError> {
365        let tokens = tokenize(&extract_data(text)?);
366
367        let n_fields_token = find_var(&tokens, "SCLK01_N_FIELDS", spacecraft_id)
368            .ok_or(TimeError::SclkMissing("SCLK01_N_FIELDS"))?;
369        let n_fields_values = parse_list(&tokens, n_fields_token)?;
370        let n_fields = parse_i64(first(n_fields_values)?)?;
371        if n_fields <= 0 || n_fields > 64 {
372            return Err(TimeError::SclkParse);
373        }
374        let n_fields = n_fields as usize;
375
376        let data_type = match find_var(&tokens, "SCLK_DATA_TYPE", spacecraft_id) {
377            Some(index) => i32::try_from(parse_i64(first(parse_list(&tokens, index)?)?)?)
378                .map_err(|_| TimeError::SclkParse)?,
379            None => 1,
380        };
381        if data_type != 1 {
382            return Err(TimeError::SclkUnsupported);
383        }
384
385        let time_system = match find_var(&tokens, "SCLK01_TIME_SYSTEM", spacecraft_id) {
386            Some(index) => match parse_i64(first(parse_list(&tokens, index)?)?)? {
387                1 => SclkTimeSystem::Tdb,
388                2 => SclkTimeSystem::Tdt,
389                _ => return Err(TimeError::SclkParse),
390            },
391            None => SclkTimeSystem::Tdb,
392        };
393
394        let moduli_index = find_var(&tokens, "SCLK01_MODULI", spacecraft_id)
395            .ok_or(TimeError::SclkMissing("SCLK01_MODULI"))?;
396        let moduli = parse_i64_list(&tokens, moduli_index)?;
397        if moduli.len() != n_fields || moduli.iter().any(|&value| value <= 0) {
398            return Err(TimeError::SclkParse);
399        }
400
401        let offsets = match find_var(&tokens, "SCLK01_OFFSETS", spacecraft_id) {
402            Some(index) => parse_i64_list(&tokens, index)?,
403            None => alloc::vec![0i64; n_fields],
404        };
405        if offsets.len() != n_fields {
406            return Err(TimeError::SclkParse);
407        }
408
409        let coefficients_index = find_var(&tokens, "SCLK01_COEFFICIENTS", spacecraft_id)
410            .ok_or(TimeError::SclkMissing("SCLK01_COEFFICIENTS"))?;
411        let coefficient_values = parse_list(&tokens, coefficients_index)?;
412        if coefficient_values.len() < 3 || coefficient_values.len() % 3 != 0 {
413            return Err(TimeError::SclkParse);
414        }
415        let mut coefficients = Vec::new();
416        let mut previous_ticks = f64::NEG_INFINITY;
417        let mut previous_seconds = f64::NEG_INFINITY;
418        for chunk in coefficient_values.chunks(3) {
419            let ticks = parse_f64(chunk[0])?;
420            let seconds = parse_f64(chunk[1])?;
421            let rate = parse_f64(chunk[2])?;
422            if ticks <= previous_ticks || seconds <= previous_seconds || rate <= 0.0 {
423                return Err(TimeError::SclkParse);
424            }
425            previous_ticks = ticks;
426            previous_seconds = seconds;
427            coefficients.push(SclkCoefficient {
428                ticks,
429                seconds,
430                rate,
431            });
432        }
433
434        let native_delimiter_code = match find_var(&tokens, "SCLK01_OUTPUT_DELIM", spacecraft_id) {
435            Some(index) => Some(parse_i64(first(parse_list(&tokens, index)?)?)?),
436            None => None,
437        };
438        let delimiter = native_delimiter_code
439            .map(delimiter_from_code)
440            .unwrap_or('.');
441
442        let partition_start = match find_var(&tokens, "SCLK_PARTITION_START", spacecraft_id) {
443            Some(index) => parse_f64_list(&tokens, index)?,
444            None => Vec::new(),
445        };
446        let partition_end = match find_var(&tokens, "SCLK_PARTITION_END", spacecraft_id) {
447            Some(index) => parse_f64_list(&tokens, index)?,
448            None => Vec::new(),
449        };
450
451        if partition_start.len() != partition_end.len() {
452            return Err(TimeError::SclkParse);
453        }
454        // Only per-partition consistency is required. NAIF lets a clock
455        // readout jump ahead or regress, which is exactly why partitions
456        // exist, so a later partition may start at a lower readout than
457        // the previous one ended. The encoded domain uses their durations.
458        for (start, end) in partition_start.iter().zip(partition_end.iter()) {
459            if !start.is_finite() || !end.is_finite() || start > end {
460                return Err(TimeError::SclkParse);
461            }
462        }
463        // SCTE01 and SCET01 round each accumulated raw partition duration.
464        // This differs from SCENCD, which rounds each endpoint separately.
465        let max_encoded_ticks = if partition_start.is_empty() {
466            None
467        } else {
468            let total = partition_start
469                .iter()
470                .zip(&partition_end)
471                .fold(0.0, |total, (&start, &end)| {
472                    native_nint((end - start) + total)
473                });
474            if !total.is_finite() || total < 0.0 {
475                return Err(TimeError::SclkParse);
476            }
477            Some(total)
478        };
479
480        Ok(Self {
481            spacecraft_id,
482            data_type,
483            time_system,
484            n_fields,
485            moduli,
486            offsets,
487            coefficients,
488            delimiter,
489            native_delimiter_code,
490            partition_start,
491            partition_end,
492            max_encoded_ticks,
493        })
494    }
495
496    /// The clock id this kernel was parsed for.
497    pub fn spacecraft_id(&self) -> i32 {
498        self.spacecraft_id
499    }
500
501    /// The clock type. Only type 1 is supported.
502    pub fn data_type(&self) -> i32 {
503        self.data_type
504    }
505
506    /// The parallel time system of the coefficients.
507    pub fn time_system(&self) -> SclkTimeSystem {
508        self.time_system
509    }
510
511    /// Number of fields in a formatted clock string.
512    pub fn n_fields(&self) -> usize {
513        self.n_fields
514    }
515
516    /// Field moduli.
517    pub fn moduli(&self) -> &[i64] {
518        &self.moduli
519    }
520
521    /// Field offsets.
522    pub fn offsets(&self) -> &[i64] {
523        &self.offsets
524    }
525
526    /// Piecewise-linear coefficients.
527    pub fn coefficients(&self) -> &[SclkCoefficient] {
528        &self.coefficients
529    }
530
531    /// Partition readouts used to bound the cumulative encoded domain.
532    pub fn partitions(&self) -> (&[f64], &[f64]) {
533        (&self.partition_start, &self.partition_end)
534    }
535
536    /// Number of ticks per count of the most significant field.
537    pub fn ticks_per_msb(&self) -> f64 {
538        let mut product = 1.0;
539        for &modulus in self.moduli[1..].iter().rev() {
540            product *= modulus as f64;
541        }
542        product
543    }
544
545    /// Encodes a field vector as a total tick count.
546    pub fn ticks_from_fields(&self, fields: &[i64]) -> Result<f64, TimeError> {
547        self.ensure_partitionless()?;
548        if fields.len() != self.n_fields {
549            return Err(TimeError::SclkParse);
550        }
551
552        let mut ticks: i64 = 0;
553        for (index, &field) in fields.iter().enumerate() {
554            let value = field
555                .checked_sub(self.offsets[index])
556                .ok_or(TimeError::SclkParse)?;
557            if value < 0 {
558                return Err(TimeError::SclkParse);
559            }
560            ticks = if index == 0 {
561                value
562            } else {
563                ticks
564                    .checked_mul(self.moduli[index])
565                    .and_then(|partial| partial.checked_add(value))
566                    .ok_or(TimeError::SclkParse)?
567            };
568        }
569
570        Ok(ticks as f64)
571    }
572
573    /// Decodes a total tick count into a field vector.
574    ///
575    /// Partition boundaries are not applied; the fields are those of the
576    /// continuous tick encoding.
577    pub fn fields_from_ticks(&self, ticks: f64) -> Result<Vec<i64>, TimeError> {
578        self.ensure_partitionless()?;
579        if !(ticks.is_finite() && ticks >= 0.0) {
580            return Err(TimeError::SclkParse);
581        }
582        let rounded = math::round(ticks);
583        if (ticks - rounded).abs() > 1e-6 {
584            return Err(TimeError::SclkParse);
585        }
586        let mut remainder = rounded as i64;
587
588        let mut fields = alloc::vec![0i64; self.n_fields];
589
590        for index in (1..self.n_fields).rev() {
591            let modulus = self.moduli[index];
592            fields[index] = remainder % modulus + self.offsets[index];
593            remainder /= modulus;
594        }
595
596        if remainder >= self.moduli[0] {
597            return Err(TimeError::SclkParse);
598        }
599        fields[0] = remainder + self.offsets[0];
600
601        Ok(fields)
602    }
603
604    /// Converts encoded ticks to the parallel time system, in seconds.
605    pub fn parallel_seconds(&self, ticks: f64) -> Result<f64, TimeError> {
606        if !ticks.is_finite() {
607            return Err(TimeError::SclkParse);
608        }
609        let segment = self.segment_for_ticks(ticks)?;
610        let rate = segment.rate / self.ticks_per_msb();
611        Ok(segment.seconds + rate * (ticks - segment.ticks))
612    }
613
614    /// Converts a parallel-time value in seconds to encoded ticks.
615    pub fn ticks_from_parallel(&self, seconds: f64) -> Result<f64, TimeError> {
616        if !seconds.is_finite() {
617            return Err(TimeError::SclkParse);
618        }
619        let segment = self.segment_for_seconds(seconds)?;
620        if segment.rate == 0.0 {
621            return Err(TimeError::SclkParse);
622        }
623        let rate = 1.0 / (segment.rate / self.ticks_per_msb());
624        let ticks = segment.ticks + rate * (seconds - segment.seconds);
625        self.validate_ticks(ticks)?;
626        Ok(ticks)
627    }
628
629    /// Converts encoded ticks to `ET` (TDB seconds past J2000).
630    pub fn ticks_to_et(&self, ticks: f64, lsk: &LeapSecondTable) -> Result<f64, TimeError> {
631        let parallel = self.parallel_seconds(ticks)?;
632        match self.time_system {
633            SclkTimeSystem::Tdb => Ok(parallel),
634            SclkTimeSystem::Tdt => Ok(crate::naif::tt_to_et(parallel, lsk)),
635        }
636    }
637
638    pub(crate) fn classify_native_ticks_error(
639        &self,
640        ticks: f64,
641        error: TimeError,
642    ) -> NativeSclkError {
643        if error == TimeError::SclkParse
644            && ticks.is_finite()
645            && (ticks < 0.0
646                || self.max_encoded_ticks.is_some_and(|max| ticks > max)
647                || self
648                    .coefficients
649                    .first()
650                    .is_some_and(|first| ticks < first.ticks))
651        {
652            NativeSclkError::Native(SclkStringError("SPICE(VALUEOUTOFRANGE)"))
653        } else {
654            NativeSclkError::Time(error)
655        }
656    }
657
658    /// Converts `ET` (TDB seconds past J2000) to encoded ticks.
659    pub fn et_to_ticks(&self, et: f64, lsk: &LeapSecondTable) -> Result<f64, TimeError> {
660        match self.time_system {
661            SclkTimeSystem::Tdb => self.ticks_from_parallel(et),
662            SclkTimeSystem::Tdt => self.ticks_from_parallel(crate::naif::et_to_tt(et, lsk)),
663        }
664    }
665
666    /// Converts encoded ticks to a TAI epoch.
667    ///
668    /// Returns [`TimeError::Overflow`] when the result cannot be represented
669    /// as a finite integer epoch.
670    pub fn ticks_to_tai(&self, ticks: f64, lsk: &LeapSecondTable) -> Result<Epoch, TimeError> {
671        let parallel = self.parallel_seconds(ticks)?;
672        let tai = match self.time_system {
673            SclkTimeSystem::Tdb => {
674                let mean_anomaly = lsk.m0 + lsk.m1 * parallel;
675                let eccentric_anomaly = mean_anomaly + lsk.eb * math::sin(mean_anomaly);
676                parallel - lsk.delta_t_a + 43_200.0 - lsk.k * math::sin(eccentric_anomaly)
677            }
678            SclkTimeSystem::Tdt => parallel - lsk.delta_t_a + 43_200.0,
679        };
680        Epoch::checked_from_tai_seconds(tai).ok_or(TimeError::Overflow)
681    }
682
683    // SCET01 rounds the interpolated ticks before checking the clock range.
684    pub(crate) fn et_to_discrete_ticks(
685        &self,
686        et: f64,
687        lsk: &LeapSecondTable,
688    ) -> Result<f64, TimeError> {
689        let parallel = match self.time_system {
690            SclkTimeSystem::Tdb => et,
691            SclkTimeSystem::Tdt => crate::naif::et_to_tt(et, lsk),
692        };
693        let segment = self.segment_for_seconds(parallel)?;
694        if segment.rate <= 0.0 {
695            return Err(TimeError::SclkParse);
696        }
697        let rate = 1.0 / (segment.rate / self.ticks_per_msb());
698        let ticks = native_nint(segment.ticks + rate * (parallel - segment.seconds));
699        if !ticks.is_finite()
700            || ticks < native_nint(self.coefficients[0].ticks)
701            || self.max_encoded_ticks.is_some_and(|max| ticks > max)
702        {
703            return Err(TimeError::SclkParse);
704        }
705        Ok(ticks)
706    }
707
708    /// Converts a TAI epoch to encoded ticks.
709    pub fn tai_to_ticks(&self, epoch: Epoch, lsk: &LeapSecondTable) -> Result<f64, TimeError> {
710        let parallel = match self.time_system {
711            SclkTimeSystem::Tdb => tai_to_et(epoch, lsk),
712            SclkTimeSystem::Tdt => tai_to_tt(epoch, lsk),
713        };
714        self.ticks_from_parallel(parallel)
715    }
716
717    /// Parses a formatted clock string into a field vector.
718    pub fn parse_string(&self, sclk: &str) -> Result<Vec<i64>, TimeError> {
719        self.ensure_partitionless()?;
720        let mut fields = Vec::new();
721        for part in sclk.split(self.delimiter) {
722            fields.push(
723                part.trim()
724                    .parse::<i64>()
725                    .map_err(|_| TimeError::SclkParse)?,
726            );
727        }
728        if fields.len() != self.n_fields {
729            return Err(TimeError::SclkParse);
730        }
731        Ok(fields)
732    }
733
734    /// Formats a field vector as a clock string.
735    pub fn format_string(&self, fields: &[i64]) -> Result<String, TimeError> {
736        self.ensure_partitionless()?;
737        if fields.len() != self.n_fields {
738            return Err(TimeError::SclkParse);
739        }
740        let delimiter = self.delimiter.to_string();
741        let parts: Vec<String> = fields.iter().map(|value| value.to_string()).collect();
742        Ok(parts.join(&delimiter))
743    }
744
745    /// Fields and strings are only defined without partition offsets in
746    /// this version; keep encoded ticks available for partition-aware
747    /// callers that apply the boundaries themselves.
748    fn ensure_partitionless(&self) -> Result<(), TimeError> {
749        if self.partition_start.is_empty() && self.partition_end.is_empty() {
750            return Ok(());
751        }
752        if self.partition_start.len() == 1 && self.partition_start[0] == 0.0 {
753            return Ok(());
754        }
755        Err(TimeError::SclkPartitionsUnsupported)
756    }
757
758    fn segment_for_ticks(&self, ticks: f64) -> Result<SclkCoefficient, TimeError> {
759        self.validate_ticks(ticks)?;
760        if self.coefficients.is_empty() {
761            return Err(TimeError::SclkMissing("SCLK01_COEFFICIENTS"));
762        }
763        let index = self
764            .coefficients
765            .partition_point(|segment| segment.ticks <= ticks);
766        let index = index.checked_sub(1).ok_or(TimeError::SclkParse)?;
767        Ok(self.coefficients[index])
768    }
769
770    fn validate_ticks(&self, ticks: f64) -> Result<(), TimeError> {
771        if !ticks.is_finite()
772            || ticks < 0.0
773            || self.max_encoded_ticks.is_some_and(|max| ticks > max)
774            || self
775                .coefficients
776                .first()
777                .is_some_and(|first| ticks < first.ticks)
778        {
779            return Err(TimeError::SclkParse);
780        }
781        Ok(())
782    }
783
784    fn segment_for_seconds(&self, seconds: f64) -> Result<SclkCoefficient, TimeError> {
785        if !seconds.is_finite() {
786            return Err(TimeError::SclkParse);
787        }
788        if self.coefficients.is_empty() {
789            return Err(TimeError::SclkMissing("SCLK01_COEFFICIENTS"));
790        }
791        let index = self
792            .coefficients
793            .partition_point(|segment| segment.seconds <= seconds);
794        let index = if index == 0 { 0 } else { index - 1 };
795        Ok(self.coefficients[index])
796    }
797}
798
799// f2c's d_lg10 uses this operation order instead of the platform log10.
800fn native_log10(value: f64) -> f64 {
801    core::f64::consts::LOG10_E * math::ln(value)
802}
803
804// CSPICE's f2c implementation evaluates the addition before floor.
805fn native_nint(value: f64) -> f64 {
806    if value >= 0.0 {
807        math::floor(value + 0.5)
808    } else {
809        -math::floor(0.5 - value)
810    }
811}
812
813// SCFM01 uses DPSTRF, whose DPSTR decimal conversion preserves at most
814// fourteen significant digits. Integer components below 10^14 are exact.
815fn native_clock_component(value: f64) -> String {
816    let value = math::abs(value);
817    if value < 1.0e14 {
818        return format!("{value:.0}");
819    }
820    const INVERSE_POWERS: [f64; 17] = [
821        1.0, 0.1, 0.01, 0.001, 1e-4, 1e-5, 1e-6, 1e-7, 1e-8, 1e-9, 1e-10, 1e-11, 1e-12, 1e-13,
822        1e-14, 1e-15, 1e-16,
823    ];
824    let mut exponent = native_log10(value) as usize;
825    let mut scaled = value;
826    let mut remaining = exponent;
827    while remaining > 16 {
828        scaled *= 1e-16;
829        remaining -= 16;
830    }
831    scaled *= INVERSE_POWERS[remaining];
832    scaled = (native_nint(scaled * 1e13) + 0.125) * 1e-13;
833    if scaled >= 10.0 {
834        scaled *= 0.1;
835        exponent += 1;
836    }
837    let mut output = String::new();
838    for _ in 0..14 {
839        let digit = scaled as u8;
840        output.push(char::from(b'0' + digit));
841        scaled = (scaled - f64::from(digit)) * 10.0;
842    }
843    for _ in 14..=exponent {
844        output.push('0');
845    }
846    output
847}
848
849// LPARSM treats repeated non-space delimiters as blank components, while
850// whitespace adjacent to another delimiter does not add a component.
851fn native_clock_fields(clock: &str) -> Vec<&[u8]> {
852    let bytes = clock.as_bytes();
853    let mut end = bytes.len();
854    while end > 0 && bytes[end - 1] == b' ' {
855        end -= 1;
856    }
857    let mut begin = 0;
858    let mut fields = Vec::new();
859    while begin < end && fields.len() < 10 {
860        while begin < end && bytes[begin] == b' ' {
861            begin += 1;
862        }
863        let mut next = begin;
864        while next < end && !b".:-, ".contains(&bytes[next]) {
865            next += 1;
866        }
867        if next < end && bytes[next] == b' ' {
868            while next < end && bytes[next] == b' ' {
869                next += 1;
870            }
871            if next < end && !b".:-, ".contains(&bytes[next]) {
872                next -= 1;
873            }
874        }
875        let stop = next.min(begin.saturating_add(30));
876        let mut field = &bytes[begin..stop];
877        while field.first() == Some(&b' ') {
878            field = &field[1..];
879        }
880        while field.last() == Some(&b' ') {
881            field = &field[..field.len() - 1];
882        }
883        fields.push(field);
884        begin = next + 1;
885    }
886    if end > 0 && b".:-,".contains(&bytes[end - 1]) && fields.len() < 10 {
887        fields.push(&[]);
888    }
889    fields
890}
891
892// NPARSD accepts PI, an implicit exponent mantissa, and exponent strings
893// whose digit accumulation stops on underflow. Preserve its operation order
894// through the existing NAIF numeric arithmetic after lexical normalization.
895fn parse_native_clock_number(token: &str) -> Option<f64> {
896    let text: String = token
897        .chars()
898        .filter(|c| *c != ' ' && *c != ',')
899        .map(|c| c.to_ascii_uppercase())
900        .collect();
901    let (sign, unsigned) = match text.as_bytes().first() {
902        Some(b'-') => ("-", &text[1..]),
903        Some(b'+') => ("+", &text[1..]),
904        _ => ("", text.as_str()),
905    };
906    if unsigned == "PI" {
907        return Some(if sign == "-" {
908            -core::f64::consts::PI
909        } else {
910            core::f64::consts::PI
911        });
912    }
913    let position = unsigned.find(['E', 'D']);
914    let Some(position) = position else {
915        return crate::naif::parse_f64(&text);
916    };
917    let mantissa = &unsigned[..position];
918    let mut integer = 0.0;
919    let mut fraction = 0.0;
920    let mut decimal = false;
921    let mut zero_integer = true;
922    let mut shift = 0_i64;
923    let mut digits_found = false;
924    for byte in mantissa.bytes() {
925        if byte == b'.' && !decimal {
926            decimal = true;
927            zero_integer = integer == 0.0;
928            continue;
929        }
930        if !byte.is_ascii_digit() {
931            return None;
932        }
933        digits_found = true;
934        let digit = f64::from(byte - b'0');
935        if !decimal {
936            if integer < 1e15 {
937                integer = integer * 10.0 + digit;
938            } else {
939                shift += 1;
940            }
941        } else if zero_integer && fraction < 1e15 {
942            fraction = fraction * 10.0 + digit;
943            shift -= 1;
944        }
945    }
946    let raw_exponent = &unsigned[position + 1..];
947    let (exp_sign, exponent) = if let Some(value) = raw_exponent.strip_prefix('-') {
948        (-1_i64, value)
949    } else {
950        (
951            1_i64,
952            raw_exponent.strip_prefix('+').unwrap_or(raw_exponent),
953        )
954    };
955    let mut power = 0_i64;
956    for digit in exponent.bytes() {
957        if !digit.is_ascii_digit() || power + shift > 308 {
958            return None;
959        }
960        if power + shift >= -309 {
961            power = power * 10 + exp_sign * i64::from(digit - b'0');
962        }
963    }
964    let mantissa = if digits_found { mantissa } else { "1" };
965    crate::naif::parse_f64(&format!("{sign}{mantissa}E{power}"))
966}
967
968/// A spacecraft clock bound to a leap-second kernel.
969///
970/// The [`SclkMap`] trait needs the LSK for the `TT -> ET` step of clocks
971/// whose coefficients are in TT.
972pub struct SclkClock<'a> {
973    /// Parsed SCLK kernel.
974    pub kernel: &'a SclkKernel,
975    /// Leap-second kernel used to relate TT and ET.
976    pub lsk: &'a LeapSecondTable,
977}
978
979/// Error from a native-style SCLK string/ET conversion.
980///
981/// String parsing errors retain their CSPICE short symbol. Errors from the
982/// existing time conversion path remain distinguishable and are not assigned
983/// a guessed CSPICE symbol.
984#[derive(Clone, Debug, PartialEq, Eq)]
985pub enum NativeSclkError {
986    /// Native clock string encoding or decoding failed.
987    String(SclkStringError),
988    /// A native tick/time range check failed with a CSPICE short symbol.
989    Native(SclkStringError),
990    /// The encoded ticks/ET conversion failed.
991    Time(TimeError),
992}
993
994impl core::fmt::Display for NativeSclkError {
995    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
996        match self {
997            Self::String(error) | Self::Native(error) => error.fmt(f),
998            Self::Time(error) => error.fmt(f),
999        }
1000    }
1001}
1002
1003#[cfg(feature = "std")]
1004impl std::error::Error for NativeSclkError {}
1005
1006impl SclkClock<'_> {
1007    /// Convert a partition-aware native clock string to ET.
1008    ///
1009    /// # Errors
1010    /// Preserves string errors separately from tick/time conversion errors.
1011    pub fn native_sclk_to_et(&self, clock: &str) -> Result<f64, NativeSclkError> {
1012        self.native_sclk_to_et_with_context(clock, &mut SclkStringContext::default())
1013    }
1014
1015    /// Convert a native clock string to ET while retaining parser state.
1016    ///
1017    /// # Errors
1018    /// Preserves string errors separately from tick/time conversion errors.
1019    pub fn native_sclk_to_et_with_context(
1020        &self,
1021        clock: &str,
1022        context: &mut SclkStringContext,
1023    ) -> Result<f64, NativeSclkError> {
1024        let ticks = self
1025            .kernel
1026            .encode_native_sclk_with_context(clock, context)
1027            .map_err(NativeSclkError::String)?;
1028        self.kernel
1029            .ticks_to_et(ticks, self.lsk)
1030            .map_err(|error| self.kernel.classify_native_ticks_error(ticks, error))
1031    }
1032
1033    /// Convert ET to a partition-aware native clock string.
1034    ///
1035    /// # Errors
1036    /// Preserves string errors separately from tick/time conversion errors.
1037    pub fn native_et_to_sclk(&self, et: f64) -> Result<String, NativeSclkError> {
1038        if et.is_finite() {
1039            let parallel = match self.kernel.time_system {
1040                SclkTimeSystem::Tdb => et,
1041                SclkTimeSystem::Tdt => crate::naif::et_to_tt(et, self.lsk),
1042            };
1043            if parallel.is_finite() {
1044                if let Ok(segment) = self.kernel.segment_for_seconds(parallel) {
1045                    let rate = 1.0 / (segment.rate / self.kernel.ticks_per_msb());
1046                    let ticks = native_nint(segment.ticks + rate * (parallel - segment.seconds));
1047                    if ticks.is_nan() {
1048                        return self
1049                            .kernel
1050                            .decode_indeterminate_ticks()
1051                            .map_err(NativeSclkError::Native);
1052                    }
1053                }
1054            }
1055        }
1056        let ticks = self
1057            .kernel
1058            .et_to_discrete_ticks(et, self.lsk)
1059            .map_err(|error| {
1060                if error == TimeError::SclkParse {
1061                    let parallel = match self.kernel.time_system {
1062                        SclkTimeSystem::Tdb => et,
1063                        SclkTimeSystem::Tdt => crate::naif::et_to_tt(et, self.lsk),
1064                    };
1065                    if let Ok(segment) = self.kernel.segment_for_seconds(parallel) {
1066                        let rate = 1.0 / (segment.rate / self.kernel.ticks_per_msb());
1067                        let ticks =
1068                            native_nint(segment.ticks + rate * (parallel - segment.seconds));
1069                        if et.is_finite()
1070                            && parallel.is_finite()
1071                            && !ticks.is_nan()
1072                            && (ticks < native_nint(self.kernel.coefficients[0].ticks)
1073                                || self.kernel.max_encoded_ticks.is_some_and(|max| ticks > max))
1074                        {
1075                            return NativeSclkError::Native(SclkStringError(
1076                                "SPICE(VALUEOUTOFRANGE)",
1077                            ));
1078                        }
1079                    }
1080                }
1081                NativeSclkError::Time(error)
1082            })?;
1083        self.kernel
1084            .decode_native_sclk(ticks)
1085            .map_err(NativeSclkError::String)
1086    }
1087}
1088
1089impl SclkMap for SclkClock<'_> {
1090    fn sclk_to_et(&self, sclk: &str) -> Result<f64, TimeError> {
1091        if !self.kernel.partition_start.is_empty()
1092            && (sclk.contains('/') || self.kernel.ensure_partitionless().is_err())
1093        {
1094            let ticks = self
1095                .kernel
1096                .encode_native_sclk(sclk)
1097                .map_err(|_| TimeError::SclkParse)?;
1098            return self.kernel.ticks_to_et(ticks, self.lsk);
1099        }
1100        let fields = self.kernel.parse_string(sclk)?;
1101        let ticks = self.kernel.ticks_from_fields(&fields)?;
1102        self.kernel.ticks_to_et(ticks, self.lsk)
1103    }
1104
1105    fn et_to_sclk(&self, et: f64) -> Result<String, TimeError> {
1106        if self.kernel.ensure_partitionless().is_err() {
1107            let ticks = self.kernel.et_to_discrete_ticks(et, self.lsk)?;
1108            return self
1109                .kernel
1110                .decode_native_sclk(ticks)
1111                .map_err(|_| TimeError::SclkParse);
1112        }
1113        let ticks = self.kernel.et_to_ticks(et, self.lsk)?;
1114        let fields = self.kernel.fields_from_ticks(ticks)?;
1115        self.kernel.format_string(&fields)
1116    }
1117}
1118
1119/// Converts between a spacecraft clock string and `ET` (TDB seconds past
1120/// J2000).
1121pub trait SclkMap {
1122    /// Converts an SCLK string to `ET`.
1123    fn sclk_to_et(&self, sclk: &str) -> Result<f64, TimeError>;
1124
1125    /// Converts `ET` to an SCLK string.
1126    fn et_to_sclk(&self, et: f64) -> Result<String, TimeError>;
1127}
1128
1129/// Extracts every `\begindata` ... `\begintext` block.
1130fn extract_data(text: &str) -> Result<String, TimeError> {
1131    const BEGIN: &str = "\\begindata";
1132    const END: &str = "\\begintext";
1133
1134    let mut data = String::new();
1135    let mut rest = text;
1136    let mut found = false;
1137
1138    while let Some(start) = rest.find(BEGIN) {
1139        found = true;
1140        let after = &rest[start + BEGIN.len()..];
1141        let end = after.find(END).unwrap_or(after.len());
1142        data.push_str(&after[..end]);
1143        data.push('\n');
1144        if end == after.len() {
1145            break;
1146        }
1147        rest = &after[end + END.len()..];
1148    }
1149
1150    if found {
1151        Ok(data)
1152    } else {
1153        Err(TimeError::SclkParse)
1154    }
1155}
1156
1157/// Splits on whitespace and the assignment punctuation.
1158fn tokenize(input: &str) -> Vec<String> {
1159    let mut tokens = Vec::new();
1160    let mut current = String::new();
1161
1162    for ch in input.chars() {
1163        match ch {
1164            '=' | '(' | ')' | ',' => {
1165                if !current.is_empty() {
1166                    tokens.push(core::mem::take(&mut current));
1167                }
1168                tokens.push(ch.to_string());
1169            }
1170            c if c.is_whitespace() => {
1171                if !current.is_empty() {
1172                    tokens.push(core::mem::take(&mut current));
1173                }
1174            }
1175            c => current.push(c),
1176        }
1177    }
1178
1179    if !current.is_empty() {
1180        tokens.push(current);
1181    }
1182
1183    tokens
1184}
1185
1186/// Finds the index of a kernel variable token, trying both id signs.
1187fn find_var(tokens: &[String], base: &str, spacecraft_id: i32) -> Option<usize> {
1188    let magnitude = i64::from(spacecraft_id).abs();
1189    let candidates = [
1190        format!("{base}_{spacecraft_id}"),
1191        format!("{base}_{magnitude}"),
1192        format!("{base}_-{magnitude}"),
1193    ];
1194    tokens
1195        .iter()
1196        .rposition(|token| candidates.iter().any(|candidate| candidate == token))
1197}
1198
1199/// Reads one scalar or the parenthesized list following `name =`.
1200fn parse_list(tokens: &[String], name_index: usize) -> Result<Vec<&str>, TimeError> {
1201    let mut index = name_index + 1;
1202    expect(tokens, index, "=")?;
1203    index += 1;
1204    let value = tokens.get(index).ok_or(TimeError::SclkParse)?;
1205    if value != "(" {
1206        if matches!(value.as_str(), "=" | ")" | ",")
1207            || tokens.get(index + 1).is_some_and(|token| token == "=")
1208        {
1209            return Err(TimeError::SclkParse);
1210        }
1211        return Ok(alloc::vec![value.as_str()]);
1212    }
1213    index += 1;
1214
1215    let mut values = Vec::new();
1216    while index < tokens.len() && tokens[index] != ")" {
1217        if matches!(tokens[index].as_str(), "(" | "=") {
1218            return Err(TimeError::SclkParse);
1219        }
1220        if tokens[index] != "," {
1221            values.push(tokens[index].as_str());
1222        }
1223        index += 1;
1224    }
1225    if index >= tokens.len() {
1226        return Err(TimeError::SclkParse);
1227    }
1228    Ok(values)
1229}
1230
1231fn expect(tokens: &[String], index: usize, expected: &str) -> Result<(), TimeError> {
1232    if tokens.get(index).map(String::as_str) == Some(expected) {
1233        Ok(())
1234    } else {
1235        Err(TimeError::SclkParse)
1236    }
1237}
1238
1239fn first(values: Vec<&str>) -> Result<&str, TimeError> {
1240    values.into_iter().next().ok_or(TimeError::SclkParse)
1241}
1242
1243fn parse_i64(token: &str) -> Result<i64, TimeError> {
1244    if let Ok(value) = token.parse::<i64>() {
1245        return Ok(value);
1246    }
1247    // Kernel-pool integer retrieval accepts numeric exponents and rounds
1248    // to the nearest integer (ties away from zero), as NAIF GIPOOL does.
1249    let value = math::round(parse_f64(token)?);
1250    if value < i64::MIN as f64 || value >= -(i64::MIN as f64) {
1251        return Err(TimeError::SclkParse);
1252    }
1253    Ok(value as i64)
1254}
1255
1256fn parse_f64(token: &str) -> Result<f64, TimeError> {
1257    crate::naif::parse_f64(token).ok_or(TimeError::SclkParse)
1258}
1259
1260fn parse_i64_list(tokens: &[String], name_index: usize) -> Result<Vec<i64>, TimeError> {
1261    parse_list(tokens, name_index)?
1262        .into_iter()
1263        .map(parse_i64)
1264        .collect()
1265}
1266
1267fn parse_f64_list(tokens: &[String], name_index: usize) -> Result<Vec<f64>, TimeError> {
1268    parse_list(tokens, name_index)?
1269        .into_iter()
1270        .map(parse_f64)
1271        .collect()
1272}
1273
1274fn delimiter_from_code(code: i64) -> char {
1275    match code {
1276        2 => ':',
1277        3 => '-',
1278        4 => ',',
1279        5 => ' ',
1280        _ => '.',
1281    }
1282}