Skip to main content

ntpsec_rs_core/
parse.rs

1// ──── parse.rs ──────────────────────────────────────────────────────────────
2// Forensic reconstruction of include/parse.h, libparse/parse.c,
3// libparse/parse_conf.c
4//
5// Reference clock timecode parsing engine.
6//
7// ## Supported timecode formats
8//
9// 1. Fixed-width numeric formats: YYMMDDHHMMSS, YYYYMMDDHHMMSS, HHMMSS, etc.
10// 2. NMEA 0183 sentences: $GPGGA, $GPRMC, $GPZDA (and with any talker ID).
11//
12// =============================================================================
13
14use crate::ntp_types::{LeapIndicator, NtpTs64};
15
16// ──── Error Type ────────────────────────────────────────────────────────────
17
18/// Error returned when a timecode string cannot be parsed.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub enum ParseError {
21    /// The sentence type is unknown / not supported.
22    UnknownSentenceType(String),
23    /// The checksum (if applicable) is missing or incorrect.
24    ChecksumError,
25    /// A required field is missing or invalid.
26    MissingField(String),
27    /// A field value is out of the valid range.
28    InvalidValue(String),
29    /// The string does not match any configured format.
30    FormatMismatch(String),
31}
32
33impl std::fmt::Display for ParseError {
34    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35        match self {
36            Self::UnknownSentenceType(s) => write!(f, "unknown sentence type: {s}"),
37            Self::ChecksumError => write!(f, "checksum error"),
38            Self::MissingField(s) => write!(f, "missing field: {s}"),
39            Self::InvalidValue(s) => write!(f, "invalid value: {s}"),
40            Self::FormatMismatch(s) => write!(f, "format mismatch: {s}"),
41        }
42    }
43}
44
45impl std::error::Error for ParseError {}
46
47// ──── Parsed Timecode ───────────────────────────────────────────────────────
48
49/// A parsed timecode result.
50///
51/// This represents the fully decomposed date/time components extracted from
52/// a serial reference-clock timecode string (NMEA, IRIG, WWVB, etc.).
53#[derive(Debug, Clone, PartialEq)]
54pub struct ParsedTimecode {
55    /// Year (e.g. 2024).
56    pub year: i32,
57    /// Month (1–12).
58    pub month: u8,
59    /// Day (1–31).
60    pub day: u8,
61    /// Hour (0–23).
62    pub hour: u8,
63    /// Minute (0–59).
64    pub minute: u8,
65    /// Second (0–60 — may be 60 during a leap second).
66    pub second: u8,
67    /// Sub-second nanoseconds (0..999_999_999).
68    pub subsecond_ns: u32,
69    /// UTC offset in hours (e.g. +5 = UTC+5).
70    pub utc_offset: i32,
71    /// Whether daylight saving time is active.
72    pub dst: bool,
73    /// Whether this second is a leap second event.
74    pub leap_second: bool,
75}
76
77impl Default for ParsedTimecode {
78    fn default() -> Self {
79        Self {
80            year: 0,
81            month: 1,
82            day: 1,
83            hour: 0,
84            minute: 0,
85            second: 0,
86            subsecond_ns: 0,
87            utc_offset: 0,
88            dst: false,
89            leap_second: false,
90        }
91    }
92}
93
94// ──── Leap Indicator ────────────────────────────────────────────────────────
95
96/// The parsed timecode with an associated NTP leap indicator.
97///
98/// Leap indicators are computed from the timecode content (e.g. leap-second
99/// markers in NMEA $GPZDA, or special day-of-year values).
100#[derive(Debug, Clone, PartialEq)]
101pub struct ParsedTimecodeWithLeap {
102    /// The parsed time components.
103    pub timecode: ParsedTimecode,
104    /// The leap indicator derived from the timecode.
105    pub leap: LeapIndicator,
106}
107
108impl ParsedTimecodeWithLeap {
109    /// Create a new timecode result with NoWarning leap.
110    pub fn new(tc: ParsedTimecode) -> Self {
111        Self {
112            leap: LeapIndicator::NoWarning,
113            timecode: tc,
114        }
115    }
116
117    /// Create a timecode result with an explicit leap indicator.
118    pub fn with_leap(tc: ParsedTimecode, leap: LeapIndicator) -> Self {
119        Self { timecode: tc, leap }
120    }
121}
122
123// ──── Timecode Source ───────────────────────────────────────────────────────
124
125/// Metadata identifying the source format of a parsed timecode.
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127pub enum TimecodeSource {
128    /// NMEA GGA sentence.
129    NmeaGga,
130    /// NMEA RMC sentence.
131    NmeaRmc,
132    /// NMEA ZDA sentence (UTC time + date with local zone).
133    NmeaZda,
134    /// Fixed-width numeric format (e.g. YYMMDDHHMMSS).
135    FixedWidth,
136    /// Unrecognised format.
137    Unknown,
138}
139
140// ──── TimecodeParser Trait ──────────────────────────────────────────────────
141
142/// A parser that converts a raw timecode string from a reference clock into
143/// an NTP timestamp and leap-indicator pair.
144///
145/// Implementations handle specific timecode formats (NMEA, IRIG, WWVB, etc.)
146pub trait TimecodeParser {
147    /// Parse a raw timecode string into a parsed timecode.
148    ///
149    /// Returns the parsed components on success, or a `ParseError` describing
150    /// the failure.
151    fn parse(&self, line: &str) -> Result<ParsedTimecodeWithLeap, ParseError>;
152
153    /// Parse a raw timecode string into an NTP timestamp directly.
154    ///
155    /// The default implementation calls `parse()` and converts the result
156    /// into an `NtpTs64` using the timecode's date-time components.
157    ///
158    /// # Errors
159    ///
160    /// Delegates to `parse()`.
161    fn parse_to_ntp(&self, line: &str) -> Result<(NtpTs64, LeapIndicator), ParseError> {
162        let parsed = self.parse(line)?;
163        let ntp = datetime_to_ntp(&parsed.timecode).ok_or_else(|| {
164            ParseError::InvalidValue("cannot convert date to NTP timestamp".into())
165        })?;
166        Ok((ntp, parsed.leap))
167    }
168
169    /// Return the source format identifier for this parser.
170    fn source(&self) -> TimecodeSource;
171}
172
173// ──── Default Parser: Fixed-Width Numeric Formats ──────────────────────────
174
175/// A parser for fixed-width numeric timecode strings.
176///
177/// Supports formats like `YYMMDDHHMMSS`, `YYYYMMDDHHMMSS`, `HHMMSS`, etc.
178/// The format string uses:
179///   * `Y` — 4-digit year
180///   * `y` — 2-digit year (70-99→19xx, 00-69→20xx)
181///   * `M` — 2-digit month (01-12)
182///   * `D` — 2-digit day (01-31)
183///   * `h` — 2-digit hour (00-23)
184///   * `m` — 2-digit minute (00-59)
185///   * `s` — 2-digit second (00-60)
186pub struct FixedWidthParser<'a> {
187    /// List of format strings to try, in order.
188    pub formats: &'a [&'a str],
189}
190
191impl<'a> FixedWidthParser<'a> {
192    /// Create a new parser with the given format strings.
193    pub fn new(formats: &'a [&'a str]) -> Self {
194        Self { formats }
195    }
196}
197
198impl TimecodeParser for FixedWidthParser<'_> {
199    fn parse(&self, line: &str) -> Result<ParsedTimecodeWithLeap, ParseError> {
200        let tc = parse_fixed_width_timecode(line, self.formats).ok_or_else(|| {
201            ParseError::FormatMismatch(format!(
202                "line '{}' does not match any format in {:?}",
203                line, self.formats
204            ))
205        })?;
206        Ok(ParsedTimecodeWithLeap::new(tc))
207    }
208
209    fn source(&self) -> TimecodeSource {
210        TimecodeSource::FixedWidth
211    }
212}
213
214// ──── NMEA Parser ───────────────────────────────────────────────────────────
215
216/// A parser for NMEA 0183 timecode sentences: `$GPGGA`, `$GPRMC`, `$GPZDA`
217/// (and with any talker ID, e.g. `$GNGGA`, `$GNRMC`, `$GNZDA`).
218pub struct NmeaParser;
219
220impl NmeaParser {
221    pub fn new() -> Self {
222        Self
223    }
224}
225
226impl Default for NmeaParser {
227    fn default() -> Self {
228        Self::new()
229    }
230}
231
232impl TimecodeParser for NmeaParser {
233    fn parse(&self, line: &str) -> Result<ParsedTimecodeWithLeap, ParseError> {
234        parse_nmea_timecode(line)
235    }
236
237    fn source(&self) -> TimecodeSource {
238        TimecodeSource::Unknown // determined per-sentence
239    }
240}
241
242// ──── Composite Parser ──────────────────────────────────────────────────────
243
244/// A composite parser that tries multiple parsers in order.
245///
246/// The first parser to succeed wins.  Useful for refclock drivers that accept
247/// multiple timecode formats (e.g. NMEA + fixed-width fallback).
248pub struct CompositeParser<'a> {
249    parsers: Vec<Box<dyn TimecodeParser + 'a>>,
250}
251
252#[allow(clippy::new_without_default)]
253impl<'a> CompositeParser<'a> {
254    pub fn new() -> Self {
255        Self {
256            parsers: Vec::new(),
257        }
258    }
259
260    /// Add a parser
261    /// Add a parser to the end of the try-order.
262    pub fn add<P: TimecodeParser + 'a>(&mut self, parser: P) {
263        self.parsers.push(Box::new(parser));
264    }
265
266    /// Create a CompositeParser from an iterator of parsers.
267    pub fn from_parsers<I>(iter: I) -> Self
268    where
269        I: IntoIterator<Item = Box<dyn TimecodeParser + 'a>>,
270    {
271        Self {
272            parsers: iter.into_iter().collect(),
273        }
274    }
275}
276
277impl TimecodeParser for CompositeParser<'_> {
278    fn parse(&self, line: &str) -> Result<ParsedTimecodeWithLeap, ParseError> {
279        let mut last_err = ParseError::FormatMismatch("no parsers configured".into());
280        for parser in &self.parsers {
281            match parser.parse(line) {
282                Ok(result) => return Ok(result),
283                Err(e) => last_err = e,
284            }
285        }
286        Err(last_err)
287    }
288
289    fn source(&self) -> TimecodeSource {
290        // Return the source of the first parser, or Unknown.
291        self.parsers
292            .first()
293            .map(|p| p.source())
294            .unwrap_or(TimecodeSource::Unknown)
295    }
296}
297
298// ──── Fixed-Width Timecode Parsing ──────────────────────────────────────────
299
300/// Parse a numeric-only timecode string (fixed-width fields).
301///
302/// Supports formats like: YYMMDDHHMMSS, YYYYMMDDHHMMSS, HHMMSS, etc.
303///
304/// Each format string uses single-letter field specifiers:
305///   * `Y` — exactly 4 digit positions (year)
306///   * `y` — exactly 2 digit positions (year, ambiguous century)
307///   * `M` — exactly 2 digit positions (month)
308///   * `D` — exactly 2 digit positions (day)
309///   * `h` — exactly 2 digit positions (hour)
310///   * `m` — exactly 2 digit positions (minute)
311///   * `s` — exactly 2 digit positions (second)
312///
313/// Unknown format characters cause the format to be skipped.
314pub fn parse_fixed_width_timecode(s: &str, formats: &[&str]) -> Option<ParsedTimecode> {
315    for fmt in formats {
316        let chars = fmt.chars().filter(|c| *c != ' ').collect::<Vec<_>>();
317        if s.len() < chars.len() {
318            continue;
319        }
320        // Try to extract fields based on format specifiers
321        let mut tc = ParsedTimecode::default();
322        let mut pos = 0;
323        let mut matched = true;
324        let mut i = 0;
325        while i < chars.len() {
326            if pos >= s.len() {
327                matched = false;
328                break;
329            }
330            let c = chars[i];
331            // Count consecutive identical format chars as one field
332            let mut count = 0;
333            for &c2 in &chars[i..] {
334                if c2 == c {
335                    count += 1;
336                } else {
337                    break;
338                }
339            }
340            match c {
341                'Y' => {
342                    /* 4-digit year */
343                    if pos + 4 <= s.len() {
344                        tc.year = s[pos..pos + 4].parse().ok()?;
345                        pos += 4;
346                    } else {
347                        matched = false;
348                        break;
349                    }
350                }
351                'y' => {
352                    /* 2-digit year */
353                    if pos + 2 <= s.len() {
354                        let yy: i32 = s[pos..pos + 2].parse().ok()?;
355                        tc.year = if yy >= 70 { 1900 + yy } else { 2000 + yy };
356                        pos += 2;
357                    } else {
358                        matched = false;
359                        break;
360                    }
361                }
362                'M' if pos + 2 <= s.len() => {
363                    /* 2-digit month */
364                    tc.month = s[pos..pos + 2].parse().ok()?;
365                    pos += 2;
366                }
367                'D' if pos + 2 <= s.len() => {
368                    /* 2-digit day */
369                    tc.day = s[pos..pos + 2].parse().ok()?;
370                    pos += 2;
371                }
372                'h' if pos + 2 <= s.len() => {
373                    tc.hour = s[pos..pos + 2].parse().ok()?;
374                    pos += 2;
375                }
376                'm' if pos + 2 <= s.len() => {
377                    tc.minute = s[pos..pos + 2].parse().ok()?;
378                    pos += 2;
379                }
380                's' if pos + 2 <= s.len() => {
381                    tc.second = s[pos..pos + 2].parse().ok()?;
382                    pos += 2;
383                }
384                _ => {
385                    matched = false;
386                    break;
387                } // Unknown format char
388            }
389            // Skip past consecutive identical format characters
390            i += count;
391        }
392        if matched
393            && tc.month >= 1
394            && tc.month <= 12
395            && tc.day >= 1
396            && tc.day <= 31
397            && tc.hour <= 23
398            && tc.minute <= 59
399            && tc.second <= 60
400        {
401            return Some(tc);
402        }
403    }
404    None
405}
406
407// ──── NMEA Timecode Parsing ─────────────────────────────────────────────────
408
409/// Parse an NMEA 0183 timecode sentence and return the parsed components
410/// together with a leap indicator.
411///
412/// Supported sentences:
413///   * `$GPGGA` / `$GNGGA` — UTC time only (no date), leap = NoWarning
414///   * `$GPRMC` / `$GNRMC` — UTC time + date, leap = NoWarning
415///   * `$GPZDA` / `$GNZDA` — UTC time + date + local zone, leap = NoWarning
416///
417/// When only time (no date) is available, the date fields remain at their
418/// defaults (year=0, month=1, day=1) — the caller is expected to fill in
419/// the date from context.
420pub fn parse_nmea_timecode(line: &str) -> Result<ParsedTimecodeWithLeap, ParseError> {
421    let trimmed = line.trim();
422    if trimmed.is_empty() {
423        return Err(ParseError::MissingField("empty line".into()));
424    }
425    if !trimmed.starts_with('$') && !trimmed.starts_with('!') {
426        return Err(ParseError::UnknownSentenceType(format!(
427            "line does not start with $ or !: {trimmed}"
428        )));
429    }
430
431    // Verify the NMEA checksum.
432    if !nmea_checksum_ok(trimmed) {
433        return Err(ParseError::ChecksumError);
434    }
435
436    // Split on '*', take the body before the checksum.
437    let body = trimmed.split('*').next().ok_or(ParseError::ChecksumError)?;
438
439    let fields: Vec<&str> = body.split(',').collect();
440    if fields.is_empty() {
441        return Err(ParseError::MissingField("no fields".into()));
442    }
443
444    // Strip leading '$' or '!' from field 0.
445    let field0 = if fields[0].starts_with('$') || fields[0].starts_with('!') {
446        &fields[0][1..]
447    } else {
448        fields[0]
449    };
450
451    let sid = sentence_id(field0);
452
453    match sid {
454        "GGA" => parse_nmea_gga_timecode(&fields),
455        "RMC" => parse_nmea_rmc_timecode(&fields),
456        "ZDA" => parse_nmea_zda_timecode(&fields),
457        _ => Err(ParseError::UnknownSentenceType(format!(
458            "unsupported NMEA sentence: {sid}"
459        ))),
460    }
461}
462
463/// Extract the 3-character sentence formatter from a talker+sentence field.
464///
465/// NMEA 0183 field 0 is either `ttsss` (talker ID + formatter, 5 chars) or
466/// `sss` (formatter only, 3 chars). Returns just the 3-char formatter.
467fn sentence_id(field0: &str) -> &str {
468    if field0.len() >= 5 {
469        &field0[2..] // strip 2-char talker ID
470    } else {
471        field0
472    }
473}
474
475/// Verify the NMEA 0183 checksum.
476fn nmea_checksum_ok(line: &str) -> bool {
477    let line = line.trim();
478    let star = match line.rfind('*') {
479        Some(pos) => pos,
480        None => return false,
481    };
482
483    let checksum_str = &line[star + 1..];
484    let cs_trimmed = checksum_str.trim();
485    if cs_trimmed.len() != 2 {
486        return false;
487    }
488
489    let expected = match u8::from_str_radix(cs_trimmed, 16) {
490        Ok(v) => v,
491        Err(_) => return false,
492    };
493
494    let start = if line.starts_with('$') || line.starts_with('!') {
495        1
496    } else {
497        0
498    };
499
500    let mut computed = 0u8;
501    for &b in &line.as_bytes()[start..star] {
502        computed ^= b;
503    }
504
505    computed == expected
506}
507
508/// Parse an NMEA time field in HHMMSS[.sss] format.
509fn parse_nmea_time(raw: &str) -> Option<(u8, u8, u8, u32)> {
510    if raw.len() < 6 {
511        return None;
512    }
513    let hh: u8 = raw[..2].parse().ok()?;
514    let mm: u8 = raw[2..4].parse().ok()?;
515    let ss: u8 = raw[4..6].parse().ok()?;
516    if hh > 23 || mm > 59 || ss > 59 {
517        return None;
518    }
519
520    let nanos = if raw.len() > 6 && raw.as_bytes().get(6) == Some(&b'.') {
521        let frac_str = &raw[7..];
522        let mut val: u32 = 0;
523        let mut digits = 0u32;
524        for c in frac_str.chars() {
525            if let Some(d) = c.to_digit(10) {
526                if digits < 9 {
527                    val = val * 10 + d;
528                    digits += 1;
529                }
530            } else {
531                break;
532            }
533        }
534        for _ in digits..9 {
535            val *= 10;
536        }
537        val
538    } else {
539        0
540    };
541
542    Some((hh, mm, ss, nanos))
543}
544
545/// Parse an NMEA date field in DDMMYY format.
546fn parse_nmea_date(raw: &str) -> Option<(u8, u8, u8)> {
547    if raw.len() < 6 {
548        return None;
549    }
550    let dd: u8 = raw[..2].parse().ok()?;
551    let mm: u8 = raw[2..4].parse().ok()?;
552    let yy: u8 = raw[4..6].parse().ok()?;
553    if !(1..=31).contains(&dd) || !(1..=12).contains(&mm) {
554        return None;
555    }
556    Some((dd, mm, yy))
557}
558
559/// Parse a $GPGGA / $GNGGA sentence into a ParsedTimecode.
560///
561/// GGA provides UTC time but no date.  The date fields remain at their
562/// defaults.
563///
564/// Fields: talker+GGA, time, lat, NS, lon, EW, quality, numSats, HDOP,
565///         alt, altUnit, geoidSep, geoidUnit, age, refStation
566fn parse_nmea_gga_timecode(fields: &[&str]) -> Result<ParsedTimecodeWithLeap, ParseError> {
567    // Need at least 6 fields for the time; full GGA has 15.
568    if fields.len() < 6 {
569        return Err(ParseError::MissingField(format!(
570            "GGA requires at least 6 fields, got {}",
571            fields.len()
572        )));
573    }
574
575    let time_str = fields
576        .get(1)
577        .ok_or(ParseError::MissingField("GGA time".into()))?;
578    if time_str.is_empty() {
579        return Err(ParseError::MissingField("GGA time is empty".into()));
580    }
581
582    let (hh, mm, ss, nanos) = parse_nmea_time(time_str).ok_or(ParseError::InvalidValue(
583        format!("GGA invalid time: {time_str}"),
584    ))?;
585
586    Ok(ParsedTimecodeWithLeap::new(ParsedTimecode {
587        hour: hh,
588        minute: mm,
589        second: ss,
590        subsecond_ns: nanos,
591        ..ParsedTimecode::default()
592    }))
593}
594
595/// Parse a $GPRMC / $GNRMC sentence into a ParsedTimecode.
596///
597/// RMC provides UTC time + date.
598///
599/// Fields: talker+RMC, time, status, lat, NS, lon, EW, speed, course, date,
600///         magVar, magVarDir, mode
601fn parse_nmea_rmc_timecode(fields: &[&str]) -> Result<ParsedTimecodeWithLeap, ParseError> {
602    if fields.len() < 10 {
603        return Err(ParseError::MissingField(format!(
604            "RMC requires at least 10 fields, got {}",
605            fields.len()
606        )));
607    }
608
609    let time_str = fields
610        .get(1)
611        .ok_or(ParseError::MissingField("RMC time".into()))?;
612    if time_str.is_empty() {
613        return Err(ParseError::MissingField("RMC time is empty".into()));
614    }
615    let (hh, mm, ss, nanos) = parse_nmea_time(time_str).ok_or(ParseError::InvalidValue(
616        format!("RMC invalid time: {time_str}"),
617    ))?;
618
619    // Status field: 'A' = active/valid, 'V' = void/invalid.
620    let status: &str = fields
621        .get(2)
622        .copied()
623        .ok_or(ParseError::MissingField("RMC status".into()))?;
624    if status != "A" {
625        return Err(ParseError::InvalidValue(format!(
626            "RMC status is '{status}', expected 'A' (active)"
627        )));
628    }
629
630    let date_str = fields
631        .get(9)
632        .ok_or(ParseError::MissingField("RMC date".into()))?;
633    if date_str.is_empty() {
634        return Err(ParseError::MissingField("RMC date is empty".into()));
635    }
636    let (dd, mm_date, yy) = parse_nmea_date(date_str).ok_or(ParseError::InvalidValue(format!(
637        "RMC invalid date: {date_str}"
638    )))?;
639
640    // Convert 2-digit year to full year.
641    let year = if yy >= 80 {
642        1900 + yy as i32
643    } else {
644        2000 + yy as i32
645    };
646
647    Ok(ParsedTimecodeWithLeap::new(ParsedTimecode {
648        year,
649        month: mm_date,
650        day: dd,
651        hour: hh,
652        minute: mm,
653        second: ss,
654        subsecond_ns: nanos,
655        ..ParsedTimecode::default()
656    }))
657}
658
659/// Parse a $GPZDA / $GNZDA sentence into a ParsedTimecode.
660///
661/// ZDA provides UTC time + date + local zone offset.
662///
663/// Fields: talker+ZDA, time, day, month, year, localZoneHours,
664///         localZoneMinutes
665fn parse_nmea_zda_timecode(fields: &[&str]) -> Result<ParsedTimecodeWithLeap, ParseError> {
666    if fields.len() < 7 {
667        return Err(ParseError::MissingField(format!(
668            "ZDA requires at least 7 fields, got {}",
669            fields.len()
670        )));
671    }
672
673    let time_str = fields
674        .get(1)
675        .ok_or(ParseError::MissingField("ZDA time".into()))?;
676    if time_str.is_empty() {
677        return Err(ParseError::MissingField("ZDA time is empty".into()));
678    }
679    let (hh, mm, ss, nanos) = parse_nmea_time(time_str).ok_or(ParseError::InvalidValue(
680        format!("ZDA invalid time: {time_str}"),
681    ))?;
682
683    let day_str = fields
684        .get(2)
685        .ok_or(ParseError::MissingField("ZDA day".into()))?;
686    let day: u8 = day_str
687        .parse()
688        .map_err(|_| ParseError::InvalidValue(format!("ZDA invalid day: {day_str}")))?;
689
690    let month_str = fields
691        .get(3)
692        .ok_or(ParseError::MissingField("ZDA month".into()))?;
693    let month: u8 = month_str
694        .parse()
695        .map_err(|_| ParseError::InvalidValue(format!("ZDA invalid month: {month_str}")))?;
696
697    let year_str = fields
698        .get(4)
699        .ok_or(ParseError::MissingField("ZDA year".into()))?;
700    let year: i32 = year_str
701        .parse()
702        .map_err(|_| ParseError::InvalidValue(format!("ZDA invalid year: {year_str}")))?;
703
704    let zone_hours_str = fields
705        .get(5)
706        .ok_or(ParseError::MissingField("ZDA zone hours".into()))?;
707    let zone_hours: i32 = if zone_hours_str.is_empty() {
708        0
709    } else {
710        zone_hours_str.parse().map_err(|_| {
711            ParseError::InvalidValue(format!("ZDA invalid zone hours: {zone_hours_str}"))
712        })?
713    };
714
715    let zone_minutes_str = fields
716        .get(6)
717        .ok_or(ParseError::MissingField("ZDA zone minutes".into()))?;
718    let zone_minutes: i32 = if zone_minutes_str.is_empty() {
719        0
720    } else {
721        zone_minutes_str.parse().map_err(|_| {
722            ParseError::InvalidValue(format!("ZDA invalid zone minutes: {zone_minutes_str}"))
723        })?
724    };
725
726    if !(1..=31).contains(&day) || !(1..=12).contains(&month) {
727        return Err(ParseError::InvalidValue(format!(
728            "ZDA invalid date: {year:04}-{month:02}-{day:02}"
729        )));
730    }
731
732    // UTC offset in hours (zone_hours + zone_minutes/60).
733    let utc_offset = zone_hours + if zone_hours >= 0 { 1 } else { -1 } * zone_minutes / 60;
734
735    Ok(ParsedTimecodeWithLeap::new(ParsedTimecode {
736        year,
737        month,
738        day,
739        hour: hh,
740        minute: mm,
741        second: ss,
742        subsecond_ns: nanos,
743        utc_offset,
744        ..ParsedTimecode::default()
745    }))
746}
747
748// ──── Date/Time to NTP Timestamp Conversion ─────────────────────────────────
749
750/// Convert a ParsedTimecode into an NTP 64-bit timestamp.
751///
752/// The civil date is converted to Unix seconds using a days-from-civil
753/// algorithm, then shifted to the NTP epoch.
754fn datetime_to_ntp(tc: &ParsedTimecode) -> Option<NtpTs64> {
755    if tc.year == 0 {
756        // No year available (e.g. GGA-only data) — cannot convert.
757        return None;
758    }
759    if tc.month < 1 || tc.month > 12 || tc.day < 1 || tc.day > 31 {
760        return None;
761    }
762    if tc.hour > 23 || tc.minute > 59 || tc.second > 60 {
763        return None;
764    }
765
766    let unix_secs = civil_to_unix(tc.year as i64, tc.month as u32, tc.day as u32)
767        + (tc.hour as i64) * 3600
768        + (tc.minute as i64) * 60
769        + (tc.second as i64);
770
771    let ntp_secs = unix_secs + crate::ntp_fp::NTP_TO_UNIX_OFFSET as i64;
772
773    // Convert sub-second nanoseconds to NTP fraction.
774    let frac = ((tc.subsecond_ns as u64) << 32) / 1_000_000_000;
775
776    Some(NtpTs64 {
777        seconds: ntp_secs,
778        fraction: frac as u32,
779    })
780}
781
782/// Compute Unix epoch seconds for a civil date.
783fn civil_to_unix(year: i64, month: u32, day: u32) -> i64 {
784    let days = days_from_civil(year, month, day);
785    let unix_epoch_days = days_from_civil(1970, 1, 1);
786    (days - unix_epoch_days) * 86_400
787}
788
789/// Days from civil date using Howard Hinnant's algorithm.
790///
791/// Returns the number of days since the proleptic Gregorian epoch (0000-03-01).
792fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
793    let y = if m <= 2 { y - 1 } else { y };
794    let era = if y >= 0 { y / 400 } else { (y - 399) / 400 };
795    let yoe = (y - era * 400) as u32; // [0, 399]
796    let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1;
797    let doe = (yoe * 365 + yoe / 4 - yoe / 100) as i64 + doy as i64;
798    era * 146_097 + doe - 719_468 // 719468 = days from 0000-03-01 to 1970-01-01
799}
800
801// ──── Tests ─────────────────────────────────────────────────────────────────
802
803#[cfg(test)]
804mod tests {
805    use super::*;
806
807    // ─── Fixed-width parser tests ───────────────────────────────────────
808
809    #[test]
810    fn test_parse_yyyymmddhhmmss() {
811        let tc = parse_fixed_width_timecode("20241225143015", &["YYYYMMDDhhmmss"]).unwrap();
812        assert_eq!(tc.year, 2024);
813        assert_eq!(tc.month, 12);
814        assert_eq!(tc.day, 25);
815        assert_eq!(tc.hour, 14);
816        assert_eq!(tc.minute, 30);
817        assert_eq!(tc.second, 15);
818    }
819
820    #[test]
821    fn test_parse_yymmddhhmmss() {
822        let tc = parse_fixed_width_timecode("241225143015", &["yyMMDDhhmmss"]).unwrap();
823        assert_eq!(tc.year, 2024);
824        assert_eq!(tc.month, 12);
825        assert_eq!(tc.day, 25);
826    }
827
828    #[test]
829    fn test_parse_yy_before_70() {
830        let tc = parse_fixed_width_timecode("691225143015", &["yyMMDDhhmmss"]).unwrap();
831        assert_eq!(tc.year, 2069);
832    }
833
834    #[test]
835    fn test_parse_short_string() {
836        assert!(parse_fixed_width_timecode("2412", &["yyMMDDhhmmss"]).is_none());
837    }
838
839    #[test]
840    fn test_parse_invalid_chars() {
841        assert!(parse_fixed_width_timecode("abcdefghijkl", &["yyMMDDhhmmss"]).is_none());
842    }
843
844    #[test]
845    fn test_parse_out_of_range_month() {
846        assert!(parse_fixed_width_timecode("241300000000", &["yyMMDDhhmmss"]).is_none());
847    }
848
849    #[test]
850    fn test_parse_out_of_range_day() {
851        assert!(parse_fixed_width_timecode("240132000000", &["yyMMDDhhmmss"]).is_none());
852    }
853
854    #[test]
855    fn test_parse_out_of_range_hour() {
856        assert!(parse_fixed_width_timecode("240101240000", &["yyMMDDhhmmss"]).is_none());
857    }
858
859    #[test]
860    fn test_parse_leap_second() {
861        let tc = parse_fixed_width_timecode("240101235960", &["yyMMDDhhmmss"]).unwrap();
862        assert_eq!(tc.second, 60);
863    }
864
865    // ─── NMEA checksum tests ────────────────────────────────────────────
866
867    #[test]
868    fn test_nmea_checksum_valid() {
869        assert!(nmea_checksum_ok(
870            "$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47"
871        ));
872    }
873
874    #[test]
875    fn test_nmea_checksum_invalid() {
876        assert!(!nmea_checksum_ok(
877            "$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*00"
878        ));
879    }
880
881    #[test]
882    fn test_nmea_checksum_missing_star() {
883        assert!(!nmea_checksum_ok("$GPGGA,123519"));
884    }
885
886    #[test]
887    fn test_nmea_checksum_rmc() {
888        assert!(nmea_checksum_ok(
889            "$GPRMC,123519,A,4807.038,N,01131.000,E,022.4,084.4,230394,003.1,W*6A"
890        ));
891    }
892
893    // ─── NMEA time parsing tests ────────────────────────────────────────
894
895    #[test]
896    fn test_parse_nmea_time_basic() {
897        let (hh, mm, ss, ns) = parse_nmea_time("123519").unwrap();
898        assert_eq!(hh, 12);
899        assert_eq!(mm, 35);
900        assert_eq!(ss, 19);
901        assert_eq!(ns, 0);
902    }
903
904    #[test]
905    fn test_parse_nmea_time_with_fraction() {
906        let (hh, mm, ss, ns) = parse_nmea_time("123519.500").unwrap();
907        assert_eq!(hh, 12);
908        assert_eq!(mm, 35);
909        assert_eq!(ss, 19);
910        assert_eq!(ns, 500_000_000);
911    }
912
913    #[test]
914    fn test_parse_nmea_time_with_microsecond() {
915        let (_hh, _mm, _ss, ns) = parse_nmea_time("123519.005").unwrap();
916        assert_eq!(ns, 5_000_000);
917    }
918
919    #[test]
920    fn test_parse_nmea_time_invalid() {
921        assert!(parse_nmea_time("").is_none());
922        assert!(parse_nmea_time("12345").is_none());
923        assert!(parse_nmea_time("256000").is_none()); // hour > 23
924    }
925
926    #[test]
927    fn test_parse_nmea_date_basic() {
928        let (dd, mm, yy) = parse_nmea_date("250324").unwrap();
929        assert_eq!(dd, 25);
930        assert_eq!(mm, 3);
931        assert_eq!(yy, 24);
932    }
933
934    #[test]
935    fn test_parse_nmea_date_invalid() {
936        assert!(parse_nmea_date("000101").is_none()); // day=0
937        assert!(parse_nmea_date("320101").is_none()); // day=32
938        assert!(parse_nmea_date("011301").is_none()); // month=13
939    }
940
941    // ─── GGA parser tests ───────────────────────────────────────────────
942
943    #[test]
944    fn test_parse_nmea_gga_timecode_valid() {
945        let line = "$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47";
946        let result = parse_nmea_timecode(line).unwrap();
947        assert_eq!(result.leap, LeapIndicator::NoWarning);
948        assert_eq!(result.timecode.hour, 12);
949        assert_eq!(result.timecode.minute, 35);
950        assert_eq!(result.timecode.second, 19);
951        assert_eq!(result.timecode.subsecond_ns, 0);
952        // GGA has no date, so year remains 0.
953        assert_eq!(result.timecode.year, 0);
954    }
955
956    #[test]
957    fn test_parse_nmea_gga_timecode_with_fraction() {
958        let line = "$GPGGA,123519.500,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*5C";
959        let result = parse_nmea_timecode(line).unwrap();
960        assert_eq!(result.timecode.hour, 12);
961        assert_eq!(result.timecode.minute, 35);
962        assert_eq!(result.timecode.second, 19);
963        assert_eq!(result.timecode.subsecond_ns, 500_000_000);
964    }
965
966    #[test]
967    fn test_parse_nmea_gga_bad_checksum() {
968        let line = "$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*00";
969        let result = parse_nmea_timecode(line);
970        assert_eq!(result.unwrap_err(), ParseError::ChecksumError);
971    }
972
973    // ─── RMC parser tests ───────────────────────────────────────────────
974
975    #[test]
976    fn test_parse_nmea_rmc_timecode_valid() {
977        let line = "$GPRMC,123519,A,4807.038,N,01131.000,E,022.4,084.4,230394,003.1,W*6A";
978        let result = parse_nmea_timecode(line).unwrap();
979        assert_eq!(result.timecode.year, 1994);
980        assert_eq!(result.timecode.month, 3);
981        assert_eq!(result.timecode.day, 23);
982        assert_eq!(result.timecode.hour, 12);
983        assert_eq!(result.timecode.minute, 35);
984        assert_eq!(result.timecode.second, 19);
985    }
986
987    #[test]
988    fn test_parse_nmea_rmc_timecode_modern() {
989        let line = "$GPRMC,083559,A,1234.567,N,01234.567,E,000.0,360.0,251224,000.0,E*73";
990        let result = parse_nmea_timecode(line).unwrap();
991        assert_eq!(result.timecode.year, 2024);
992        assert_eq!(result.timecode.month, 12);
993        assert_eq!(result.timecode.day, 25);
994        assert_eq!(result.timecode.hour, 8);
995        assert_eq!(result.timecode.minute, 35);
996        assert_eq!(result.timecode.second, 59);
997    }
998
999    #[test]
1000    fn test_parse_nmea_rmc_inactive() {
1001        // Status 'V' (void) should produce an error.
1002        let line = "$GPRMC,123519,V,4807.038,N,01131.000,E,022.4,084.4,230394,003.1,W*7D";
1003        let result = parse_nmea_timecode(line);
1004        assert!(result.is_err());
1005        match result.unwrap_err() {
1006            ParseError::InvalidValue(s) => assert!(s.contains("status")),
1007            _ => panic!("expected InvalidValue"),
1008        }
1009    }
1010
1011    #[test]
1012    fn test_parse_nmea_rmc_missing_time() {
1013        let line = "$GPRMC,,A,4807.038,N,01131.000,E,022.4,084.4,230394,003.1,W*5D";
1014        let result = parse_nmea_timecode(line);
1015        assert!(result.is_err());
1016    }
1017
1018    // ─── ZDA parser tests ───────────────────────────────────────────────
1019
1020    #[test]
1021    fn test_parse_nmea_zda_timecode_valid() {
1022        let line = "$GPZDA,083559,25,12,2024,00,00*4A";
1023        let result = parse_nmea_timecode(line).unwrap();
1024        assert_eq!(result.timecode.year, 2024);
1025        assert_eq!(result.timecode.month, 12);
1026        assert_eq!(result.timecode.day, 25);
1027        assert_eq!(result.timecode.hour, 8);
1028        assert_eq!(result.timecode.minute, 35);
1029        assert_eq!(result.timecode.second, 59);
1030        assert_eq!(result.timecode.utc_offset, 0);
1031    }
1032
1033    #[test]
1034    fn test_parse_nmea_zda_with_zone_offset() {
1035        let line = "$GPZDA,083559,25,12,2024,+05,30*67";
1036        let result = parse_nmea_timecode(line).unwrap();
1037        assert_eq!(result.timecode.year, 2024);
1038        assert_eq!(result.timecode.month, 12);
1039        assert_eq!(result.timecode.day, 25);
1040        assert_eq!(result.timecode.hour, 8);
1041        assert_eq!(result.timecode.minute, 35);
1042        assert_eq!(result.timecode.second, 59);
1043        assert_eq!(result.timecode.utc_offset, 5);
1044    }
1045
1046    #[test]
1047    fn test_parse_nmea_zda_negative_zone() {
1048        let line = "$GPZDA,083559,25,12,2024,-05,00*62";
1049        let result = parse_nmea_timecode(line).unwrap();
1050        assert_eq!(result.timecode.utc_offset, -5);
1051    }
1052
1053    #[test]
1054    fn test_parse_nmea_zda_gnss_talker() {
1055        let line = "$GNZDA,083559,25,12,2024,00,00*54";
1056        let result = parse_nmea_timecode(line).unwrap();
1057        assert_eq!(result.timecode.year, 2024);
1058        assert_eq!(result.timecode.month, 12);
1059        assert_eq!(result.timecode.day, 25);
1060    }
1061
1062    #[test]
1063    fn test_parse_nmea_zda_missing_field() {
1064        // Too few fields.
1065        let line = "$GPZDA,083559,25,12*53";
1066        let result = parse_nmea_timecode(line);
1067        assert!(result.is_err());
1068    }
1069
1070    // ─── Unknown sentence test ──────────────────────────────────────────
1071
1072    #[test]
1073    fn test_parse_unknown_sentence() {
1074        let line = "$GPGLL,4916.45,N,12311.12,W,225444,A*31";
1075        let result = parse_nmea_timecode(line);
1076        assert!(result.is_err());
1077        match result.unwrap_err() {
1078            ParseError::UnknownSentenceType(s) => assert!(s.contains("GLL")),
1079            _ => panic!("expected UnknownSentenceType"),
1080        }
1081    }
1082
1083    // ─── TimecodeParser trait tests ─────────────────────────────────────
1084
1085    #[test]
1086    fn test_fixed_width_parser_trait() {
1087        let parser = FixedWidthParser::new(&["yyMMDDhhmmss"]);
1088        let result = parser.parse("241225143015").unwrap();
1089        assert_eq!(result.timecode.year, 2024);
1090        assert_eq!(result.timecode.month, 12);
1091        assert_eq!(result.timecode.day, 25);
1092        assert_eq!(parser.source(), TimecodeSource::FixedWidth);
1093    }
1094
1095    #[test]
1096    fn test_fixed_width_parser_format_mismatch() {
1097        let parser = FixedWidthParser::new(&["YYMMDDhhmmss"]);
1098        let result = parser.parse("short");
1099        assert!(result.is_err());
1100    }
1101
1102    #[test]
1103    fn test_nmea_parser_trait_gga() {
1104        let parser = NmeaParser;
1105        let line = "$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47";
1106        let result = parser.parse(line).unwrap();
1107        assert_eq!(result.timecode.hour, 12);
1108    }
1109
1110    #[test]
1111    fn test_nmea_parser_trait_rmc() {
1112        let parser = NmeaParser;
1113        let line = "$GPRMC,083559,A,1234.567,N,01234.567,E,000.0,360.0,251224,000.0,E*73";
1114        let result = parser.parse(line).unwrap();
1115        assert_eq!(result.timecode.year, 2024);
1116    }
1117
1118    #[test]
1119    fn test_nmea_parser_trait_zda() {
1120        let parser = NmeaParser;
1121        let line = "$GPZDA,083559,25,12,2024,00,00*4A";
1122        let result = parser.parse(line).unwrap();
1123        assert_eq!(result.timecode.year, 2024);
1124    }
1125
1126    #[test]
1127    fn test_nmea_parser_trait_bad_checksum() {
1128        let parser = NmeaParser;
1129        let line = "$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*00";
1130        let result = parser.parse(line);
1131        assert_eq!(result.unwrap_err(), ParseError::ChecksumError);
1132    }
1133
1134    // ─── Composite parser tests ─────────────────────────────────────────
1135
1136    #[test]
1137    fn test_composite_parser_first_wins() {
1138        let mut composite = CompositeParser::new();
1139        composite.add(NmeaParser);
1140        composite.add(FixedWidthParser::new(&["yyMMDDhhmmss"]));
1141
1142        // NMEA sentence should be parsed by the NMEA parser.
1143        let result = composite
1144            .parse("$GPRMC,083559,A,1234.567,N,01234.567,E,000.0,360.0,251224,000.0,E*73")
1145            .unwrap();
1146        assert_eq!(result.timecode.year, 2024);
1147        assert_eq!(composite.source(), TimecodeSource::Unknown); // from NmeaParser
1148
1149        // Fixed-width sentence should fall through to the fixed-width parser.
1150        let result = composite.parse("241225143015").unwrap();
1151        assert_eq!(result.timecode.year, 2024);
1152    }
1153
1154    #[test]
1155    fn test_composite_parser_empty() {
1156        let composite = CompositeParser::<'_>::new();
1157        let result = composite.parse("anything");
1158        assert!(result.is_err());
1159        assert_eq!(
1160            result.unwrap_err(),
1161            ParseError::FormatMismatch("no parsers configured".into())
1162        );
1163    }
1164
1165    #[test]
1166    fn test_composite_parser_all_fail() {
1167        let mut composite = CompositeParser::new();
1168        composite.add(FixedWidthParser::new(&["YYYYMMDDhhmmss"]));
1169        let result = composite.parse("short");
1170        assert!(result.is_err());
1171    }
1172
1173    // ─── parse_to_ntp tests ─────────────────────────────────────────────
1174
1175    #[test]
1176    fn test_parse_to_ntp_rmc() {
1177        let parser = NmeaParser;
1178        let line = "$GPRMC,083559,A,1234.567,N,01234.567,E,000.0,360.0,251224,000.0,E*73";
1179        let (ntp, leap) = parser.parse_to_ntp(line).unwrap();
1180        assert_eq!(leap, LeapIndicator::NoWarning);
1181        // 2024-12-25 08:35:59 UTC in NTP seconds.
1182        // Unix: 1735115759. NTP: 1735115759 + 2208988800 = 3944104559
1183        assert_eq!(ntp.seconds, 3_944_104_559);
1184    }
1185
1186    #[test]
1187    fn test_parse_to_ntp_gga_no_date() {
1188        let parser = NmeaParser;
1189        let line = "$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47";
1190        // GGA has no date, so parse_to_ntp should fail.
1191        let result = parser.parse_to_ntp(line);
1192        assert!(result.is_err());
1193    }
1194
1195    #[test]
1196    fn test_parse_to_ntp_fixed_width() {
1197        let parser = FixedWidthParser::new(&["yyMMDDhhmmss"]);
1198        let (ntp, leap) = parser.parse_to_ntp("241225143015").unwrap();
1199        assert_eq!(leap, LeapIndicator::NoWarning);
1200        // 2024-12-25 14:30:15 UTC in NTP seconds.
1201        assert_eq!(ntp.seconds, 3_944_125_815);
1202    }
1203
1204    // ─── ParsedTimecodeWithLeap tests ───────────────────────────────────
1205
1206    #[test]
1207    fn test_parsed_timecode_with_leap_new() {
1208        let tc = ParsedTimecode::default();
1209        let parsed = ParsedTimecodeWithLeap::new(tc);
1210        assert_eq!(parsed.leap, LeapIndicator::NoWarning);
1211    }
1212
1213    #[test]
1214    fn test_parsed_timecode_with_leap_explicit() {
1215        let tc = ParsedTimecode::default();
1216        let parsed = ParsedTimecodeWithLeap::with_leap(tc, LeapIndicator::Alarm);
1217        assert_eq!(parsed.leap, LeapIndicator::Alarm);
1218    }
1219
1220    // ─── ParseError tests ───────────────────────────────────────────────
1221
1222    #[test]
1223    fn test_parse_error_display() {
1224        assert_eq!(format!("{}", ParseError::ChecksumError), "checksum error");
1225        assert_eq!(
1226            format!("{}", ParseError::UnknownSentenceType("GLL".into())),
1227            "unknown sentence type: GLL"
1228        );
1229        assert_eq!(
1230            format!("{}", ParseError::MissingField("time".into())),
1231            "missing field: time"
1232        );
1233    }
1234
1235    // ─── Test RMC with GNRMC (GNSS talker) ──────────────────────────────
1236
1237    #[test]
1238    fn test_parse_gnrmc_timecode() {
1239        let line = "$GNRMC,083559,A,1234.567,N,01234.567,E,000.0,360.0,251224,000.0,E*6D";
1240        let result = parse_nmea_timecode(line).unwrap();
1241        assert_eq!(result.timecode.year, 2024);
1242        assert_eq!(result.timecode.month, 12);
1243        assert_eq!(result.timecode.day, 25);
1244    }
1245
1246    // ─── Test with GNZDA (GNSS talker) ──────────────────────────────────
1247
1248    #[test]
1249    fn test_parse_gnzda_timecode() {
1250        let line = "$GNZDA,083559,25,12,2024,00,00*54";
1251        let result = parse_nmea_timecode(line).unwrap();
1252        assert_eq!(result.timecode.year, 2024);
1253    }
1254
1255    // ─── datetime_to_ntp tests ─────────────────────────────────────────
1256
1257    #[test]
1258    fn test_datetime_to_ntp_no_year() {
1259        let tc = ParsedTimecode {
1260            year: 0,
1261            hour: 12,
1262            minute: 0,
1263            second: 0,
1264            ..ParsedTimecode::default()
1265        };
1266        assert!(datetime_to_ntp(&tc).is_none());
1267    }
1268
1269    #[test]
1270    fn test_datetime_to_ntp_out_of_range() {
1271        let tc = ParsedTimecode {
1272            year: 2024,
1273            month: 13,
1274            ..ParsedTimecode::default()
1275        };
1276        assert!(datetime_to_ntp(&tc).is_none());
1277    }
1278
1279    // ─── Sentence ID extraction tests ───────────────────────────────────
1280
1281    #[test]
1282    fn test_sentence_id_with_talker() {
1283        assert_eq!(sentence_id("GPGGA"), "GGA");
1284        assert_eq!(sentence_id("GNRMC"), "RMC");
1285        assert_eq!(sentence_id("GNZDA"), "ZDA");
1286        assert_eq!(sentence_id("GGA"), "GGA");
1287    }
1288}