protoflight 0.1.4

Protoflight flight controller.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
/*
An NMEA 0183 sentence always follows a strict pattern:
1. Starts with a `$` character.
2. Contains payload bytes (characters like letters, numbers, commas).
3. Optional (but highly recommended): A `*` character indicating the end of data and start of a 2-hex-digit checksum.
4. Concludes with a `\r\n`
*/

#[allow(unused)]
#[derive(Clone, Copy, Debug, PartialEq)]
enum NmeaEvent {
    NoEvent,
    Start,
    PayloadByte(u8),
    Complete,
}

/// `NmeaState` knows about:
/// 1. $
/// 2. payload
/// 3. *
/// 4. checksum digits
/// 5. CR/LF
/// 6. checksum calculation
#[allow(unused)]
#[derive(Clone, Copy, Debug, Default, PartialEq)]
enum NmeaState {
    #[default]
    WaitingForStart,
    InPayload {
        calculated_checksum: u8,
    },
    WaitingForChecksum1 {
        calculated_checksum: u8,
    },
    WaitingForChecksum2 {
        calculated_checksum: u8,
        received_checksum_high: u8,
    },
    WaitingForCr,
    WaitingForLf,
}

#[allow(unused)]
impl NmeaState {
    fn on_data_received(&mut self, data: u8) -> NmeaEvent {
        // '$' always starts a new NMEA sentence, regardless of the
        // current parser state.
        if data == b'$' {
            *self = Self::InPayload { calculated_checksum: 0 };

            return NmeaEvent::Start;
        }

        match *self {
            Self::WaitingForStart => {
                if data == b'$' {
                    *self = Self::InPayload { calculated_checksum: 0 };

                    NmeaEvent::Start
                } else {
                    NmeaEvent::NoEvent
                }
            }

            Self::InPayload { mut calculated_checksum } => {
                if data == b'*' {
                    *self = Self::WaitingForChecksum1 { calculated_checksum };

                    NmeaEvent::NoEvent
                } else if data.is_ascii_graphic() || data == b' ' {
                    calculated_checksum ^= data;

                    *self = Self::InPayload { calculated_checksum };

                    NmeaEvent::PayloadByte(data)
                } else {
                    *self = Self::WaitingForStart;
                    NmeaEvent::NoEvent
                }
            }

            Self::WaitingForChecksum1 { calculated_checksum } => {
                if let Some(val) = Self::parse_hex_digit(data) {
                    *self = Self::WaitingForChecksum2 { calculated_checksum, received_checksum_high: val };
                } else {
                    *self = Self::WaitingForStart;
                }

                NmeaEvent::NoEvent
            }

            Self::WaitingForChecksum2 { calculated_checksum, received_checksum_high } => {
                if let Some(val) = Self::parse_hex_digit(data) {
                    let received_checksum = (received_checksum_high << 4) | val;

                    if calculated_checksum == received_checksum {
                        *self = Self::WaitingForCr;
                    } else {
                        *self = Self::WaitingForStart;
                    }
                } else {
                    *self = Self::WaitingForStart;
                }

                NmeaEvent::NoEvent
            }

            Self::WaitingForCr => {
                if data == b'\r' {
                    *self = Self::WaitingForLf;
                } else {
                    *self = Self::WaitingForStart;
                }

                NmeaEvent::NoEvent
            }

            Self::WaitingForLf => {
                if data == b'\n' {
                    *self = Self::WaitingForStart;
                    NmeaEvent::Complete
                } else {
                    *self = Self::WaitingForStart;
                    NmeaEvent::NoEvent
                }
            }
        }
    }

    const fn parse_hex_digit(byte: u8) -> Option<u8> {
        match byte {
            b'0'..=b'9' => Some(byte - b'0'),
            b'A'..=b'F' => Some(byte - b'A' + 10),
            b'a'..=b'f' => Some(byte - b'a' + 10),
            _ => None,
        }
    }
}

/// `NmeaParser` knows about:
/// 1. the payload buffer
/// 2. the payload index
/// 3. buffer overflow
/// 4. whether a complete sentence is available.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct NmeaParser {
    state: NmeaState,
    payload_buf: [u8; Self::BUFFER_SIZE],
    payload_index: usize,
    complete: bool,
}

impl Default for NmeaParser {
    fn default() -> Self {
        Self::new()
    }
}

impl NmeaParser {
    // Maximum NMEA sentence length is 82 bytes including '$' and CR/LF.
    // This buffer contains only the payload between '$' and '*'.
    // `BUFFER_SIZE` is rounded up to 80 which is larger than the payload permitted by the NMEA 0183 sentence length limit.
    const BUFFER_SIZE: usize = 80;

    pub const fn new() -> Self {
        Self {
            state: NmeaState::WaitingForStart,
            payload_buf: [0u8; Self::BUFFER_SIZE],
            payload_index: 0,
            complete: false,
        }
    }

    pub fn on_data_received(&mut self, data: u8) -> bool {
        // A new byte means that the previously completed sentence
        // has been consumed/expired.
        self.complete = false;

        match self.state.on_data_received(data) {
            NmeaEvent::NoEvent => {}

            NmeaEvent::Start => {
                self.payload_index = 0;
            }
            NmeaEvent::PayloadByte(byte) => {
                if self.payload_index >= self.payload_buf.len() {
                    // Payload is too long. Discard the sentence.
                    self.state = NmeaState::WaitingForStart;
                    self.payload_index = 0;
                } else {
                    self.payload_buf[self.payload_index] = byte;
                    self.payload_index += 1;
                }
            }
            NmeaEvent::Complete => {
                self.complete = true;
            }
        }
        self.complete
    }

    pub fn payload(&self) -> Option<&[u8]> {
        if self.complete { Some(&self.payload_buf[..self.payload_index]) } else { None }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NmeaRecordType {
    Gga,
    Rmc,
    Gsa,
    /*Gll,
    Gsv,
    Vtg,*/
}

#[allow(unused)]
impl NmeaRecordType {
    pub fn from_record(record: &[u8]) -> Option<Self> {
        if record.len() < 6 {
            return None;
        }
        match &record[2..5] {
            b"GGA" => Some(Self::Gga),
            b"RMC" => Some(Self::Rmc),
            b"GSA" => Some(Self::Gsa),
            _ => None,
        }
    }
}

pub struct Parse;

#[allow(unused)]
impl Parse {
    /// Parses a byte slice into an integer.
    pub fn int(bytes: &[u8]) -> Option<u32> {
        if bytes.is_empty() {
            return None;
        }
        let mut val = 0u32;
        for &b in bytes {
            if !b.is_ascii_digit() {
                return None;
            }
            val = val.checked_mul(10)?.checked_add(u32::from(b - b'0'))?;
        }
        Some(val)
    }

    /// Parses a decimal fixed-point value without allocation.
    ///
    /// `scale` specifies the number of units per whole number, and must be a
    /// positive power of ten. For example:
    ///
    /// - `scale = 10`   -> one decimal place
    /// - `scale = 100`  -> two decimal places
    /// - `scale = 1000` -> three decimal places
    ///
    /// Excess fractional digits are truncated.
    ///
    /// Examples:
    /// - `12.34` with scale 100 -> 1234
    /// - `12.3`  with scale 100 -> 1230
    /// - `12`    with scale 100 -> 1200
    pub fn fixed_point(bytes: &[u8], scale: u32) -> Option<i32> {
        if bytes.is_empty() || scale == 0 {
            return None;
        }
        let mut index = 0;
        let negative = bytes[0] == b'-';
        if negative {
            index = 1;
            // "-" by itself isn't a number.
            if index == bytes.len() {
                return None;
            }
        }
        let mut integer_part = 0i32;
        let mut saw_integer_digit = false;
        // Parse integer part.
        while index < bytes.len() {
            let byte = bytes[index];
            if byte == b'.' {
                break;
            }
            let digit = byte.checked_sub(b'0')?;
            if digit > 9 {
                return None;
            }
            saw_integer_digit = true;
            integer_part = integer_part.checked_mul(10)?.checked_add(i32::from(digit))?;
            index += 1;
        }
        // Don't accept ".5".
        if !saw_integer_digit {
            return None;
        }
        let scale_i32 = i32::try_from(scale).ok()?;
        let mut result = integer_part.checked_mul(scale_i32)?;
        // Parse fractional part, if present.
        if index < bytes.len() {
            // Skip '.'.
            index += 1;
            let mut fractional_scale = scale;
            while index < bytes.len() {
                let byte = bytes[index];
                let digit = byte.checked_sub(b'0')?;
                if digit > 9 {
                    return None;
                }
                // Once the requested precision has been reached, continue
                // validating digits but stop adding them to the result.
                fractional_scale /= 10;
                if fractional_scale != 0 {
                    let fractional_scale_i32 = i32::try_from(fractional_scale).ok()?;
                    let contribution = i32::from(digit).checked_mul(fractional_scale_i32)?;
                    result = result.checked_add(contribution)?;
                }
                index += 1;
            }
        }
        if negative { result.checked_neg() } else { Some(result) }
    }

    /// Parses an NMEA latitude/longitude coordinate.
    ///
    /// NMEA coordinates are represented as:
    ///
    /// - latitude:  `ddmm.mmmm`
    /// - longitude: `dddmm.mmmm`
    ///
    /// `direction` must be `N`, `S`, `E`, or `W`.
    ///
    /// The result is returned as degrees × 1e7, rounded to the nearest unit.
    pub fn nmea_coordinate(value: &[u8], direction: u8) -> Option<i32> {
        if value.is_empty() {
            return None;
        }

        let negative = match direction {
            b'N' | b'E' => false,
            b'S' | b'W' => true,
            _ => return None,
        };

        // Find the decimal point separating degrees/minutes from the
        // fractional part.
        let decimal_pos = value.iter().position(|&b| b == b'.')?;

        // There must be either:
        //   ddmm.mmmm   -> 4 digits before '.'
        //   dddmm.mmmm  -> 5 digits before '.'
        if decimal_pos != 4 && decimal_pos != 5 {
            return None;
        }

        // The two digits immediately before the decimal point are the
        // integer portion of the minutes.
        let minute_start = decimal_pos - 2;

        // Parse degrees.
        let mut degrees = 0u32;

        for &byte in &value[..minute_start] {
            let digit = byte.checked_sub(b'0')?;

            if digit > 9 {
                return None;
            }

            degrees = degrees.checked_mul(10)?.checked_add(u32::from(digit))?;
        }

        // Parse integer minutes.
        let minute_tens = value[minute_start].checked_sub(b'0')?;

        let minute_units = value[minute_start + 1].checked_sub(b'0')?;

        if minute_tens > 9 || minute_units > 9 {
            return None;
        }

        let minutes = u32::from(minute_tens) * 10 + u32::from(minute_units);

        // Minutes must be in [0, 60).
        if minutes >= 60 {
            return None;
        }

        // Parse fractional minutes, normalizing to 1/10000 minute.
        //
        // NMEA normally provides four decimal places, but accepting fewer
        // is harmless. Additional digits are deliberately truncated.
        let mut fractional = 0u32;
        let mut fractional_digits = 0;

        for &byte in &value[decimal_pos + 1..] {
            let digit = byte.checked_sub(b'0')?;

            if digit > 9 {
                return None;
            }

            if fractional_digits < 4 {
                fractional = fractional * 10 + u32::from(digit);
                fractional_digits += 1;
            }
        }

        // Scale fractional minutes to 1/10000 minute.
        while fractional_digits < 4 {
            fractional *= 10;
            fractional_digits += 1;
        }

        let minutes_x1e4 = minutes.checked_mul(10_000)?.checked_add(fractional)?;

        // Convert minutes to degrees × 1e7:
        //
        // minutes_x1e4 * 1e7 / (60 * 1e4)
        // = minutes_x1e4 * 500 / 3
        //
        // Add 1 before division to round to nearest integer.
        let minute_degrees_x1e7 = minutes_x1e4.checked_mul(50)?.checked_add(1)? / 3;

        let result = degrees.checked_mul(10_000_000)?.checked_add(minute_degrees_x1e7)?;

        let result = i32::try_from(result).ok()?;

        if negative { result.checked_neg() } else { Some(result) }
    }

    /// Parses an NMEA UTC time (`hhmmss` or `hhmmss.ss`) into milliseconds
    /// since midnight.
    ///
    /// Fractional seconds beyond millisecond precision are truncated.
    pub fn nmea_time(bytes: &[u8]) -> Option<u32> {
        if bytes.len() < 6 {
            return None;
        }
        // hhmmss
        let hour = Self::two_digits(&bytes[0..2])?;
        let minute = Self::two_digits(&bytes[2..4])?;
        let second = Self::two_digits(&bytes[4..6])?;
        if hour >= 24 || minute >= 60 || second >= 60 {
            return None;
        }
        let mut milliseconds = u32::from(hour) * 3_600_000 + u32::from(minute) * 60_000 + u32::from(second) * 1_000;

        // Optional fractional seconds.
        if bytes.len() > 6 {
            if bytes[6] != b'.' {
                return None;
            }
            let mut fraction_ms = 0u32;
            for (index, &byte) in bytes[7..].iter().enumerate() {
                let digit = byte.checked_sub(b'0')?;
                if digit > 9 {
                    return None;
                }
                match index {
                    0 => fraction_ms += u32::from(digit) * 100,
                    1 => fraction_ms += u32::from(digit) * 10,
                    2 => fraction_ms += u32::from(digit),
                    _ => {}
                }
            }
            milliseconds = milliseconds.checked_add(fraction_ms)?;
        }
        Some(milliseconds)
    }

    /// Helper function to parse 2 digits.
    fn two_digits(bytes: &[u8]) -> Option<u8> {
        if bytes.len() != 2 {
            return None;
        }
        let tens = bytes[0].checked_sub(b'0')?;
        let units = bytes[1].checked_sub(b'0')?;
        if tens > 9 || units > 9 {
            return None;
        }
        Some(tens * 10 + units)
    }
}

pub struct NmeaFields<'a> {
    remainder: Option<&'a [u8]>,
}

impl<'a> NmeaFields<'a> {
    pub const fn new(payload: &'a [u8]) -> Self {
        Self { remainder: Some(payload) }
    }
}

impl<'a> Iterator for NmeaFields<'a> {
    type Item = &'a [u8];

    fn next(&mut self) -> Option<Self::Item> {
        let remainder = self.remainder.take()?;

        if let Some(comma_pos) = remainder.iter().position(|&b| b == b',') {
            let field = &remainder[..comma_pos];
            self.remainder = Some(&remainder[comma_pos + 1..]);
            Some(field)
        } else {
            // This is the final field. Setting remainder to None means
            // that even an empty final field is returned once.
            Some(remainder)
        }
    }
}

#[cfg(test)]
mod tests_record_type {
    #![allow(clippy::expect_used)]
    use super::*;
    #[test]
    fn identifies_gga_record() {
        assert_eq!(NmeaRecordType::from_record(b"GPGGA,123519,..."), Some(NmeaRecordType::Gga));
    }
    #[test]
    fn identifies_rmc_record() {
        assert_eq!(NmeaRecordType::from_record(b"GPRMC,123519,..."), Some(NmeaRecordType::Rmc));
    }
    #[test]
    fn identifies_gsa_record() {
        assert_eq!(NmeaRecordType::from_record(b"GPGSA,A,3,..."), Some(NmeaRecordType::Gsa));
    }
    #[test]
    fn unknown_record_type_is_rejected() {
        assert_eq!(NmeaRecordType::from_record(b"GPXXX,123,..."), None);
    }
    #[test]
    fn short_record_is_rejected() {
        assert_eq!(NmeaRecordType::from_record(b"GP"), None);
    }
    #[test]
    fn record_type_does_not_depend_on_talker() {
        assert_eq!(NmeaRecordType::from_record(b"GNGGA,123519,..."), Some(NmeaRecordType::Gga));

        assert_eq!(NmeaRecordType::from_record(b"GNRMC,123519,..."), Some(NmeaRecordType::Rmc));
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::expect_used)]
    use super::*;

    #[test]
    fn valid_sentence_is_accepted() {
        let sentence = b"$GPGSV,3,1,11,10,63,137,17,07,61,098,15,05,59,290,20,08,54,157,30*70\r\n";
        let mut parser = NmeaParser::new();
        let mut complete = false;
        for &byte in sentence {
            complete = parser.on_data_received(byte);
        }
        assert!(complete);
        assert_eq!(
            parser.payload(),
            Some(b"GPGSV,3,1,11,10,63,137,17,07,61,098,15,05,59,290,20,08,54,157,30".as_slice())
        );
    }
    #[test]
    fn invalid_checksum_is_rejected() {
        let sentence = b"$GPGSV,3,1,11,10,63,137,17,07,61,098,15,05,59,290,20,08,54,157,30*71\r\n";
        let mut parser = NmeaParser::new();
        for &byte in sentence {
            assert!(!parser.on_data_received(byte));
        }
        assert_eq!(parser.payload(), None);
    }
    #[test]
    fn invalid_checksum_character_is_rejected() {
        let sentence = b"$GPGSV,3,1,11,10,63,137,17,07,61,098,15,05,59,290,20,08,54,157,30*7G\r\n";
        let mut parser = NmeaParser::new();
        for &byte in sentence {
            assert!(!parser.on_data_received(byte));
        }
        assert_eq!(parser.payload(), None);
    }
    #[test]
    fn missing_lf_is_rejected() {
        let sentence = b"$GPGSV,3,1,11,10,63,137,17,07,61,098,15,05,59,290,20,08,54,157,30*70\r";
        let mut parser = NmeaParser::new();
        for &byte in sentence {
            assert!(!parser.on_data_received(byte));
        }
        assert_eq!(parser.payload(), None);
    }
    #[test]
    fn missing_cr_is_rejected() {
        let sentence = b"$GPGSV,3,1,11,10,63,137,17,07,61,098,15,05,59,290,20,08,54,157,30*70\n";
        let mut parser = NmeaParser::new();
        for &byte in sentence {
            assert!(!parser.on_data_received(byte));
        }
        assert_eq!(parser.payload(), None);
    }
    #[test]
    fn back_to_back_sentences_are_parsed() {
        let sentence1 = b"$GPGSV,3,1,11,10,63,137,17,07,61,098,15,05,59,290,20,08,54,157,30*70\r\n";
        let sentence2 = b"$GPGSV,3,1,11,10,63,137,17,07,61,098,15,05,59,290,20,08,54,157,30*70\r\n";
        let mut parser = NmeaParser::new();
        let mut complete_count = 0;
        for &byte in sentence1.iter().chain(sentence2) {
            if parser.on_data_received(byte) {
                complete_count += 1;
                assert_eq!(
                    parser.payload(),
                    Some(b"GPGSV,3,1,11,10,63,137,17,07,61,098,15,05,59,290,20,08,54,157,30".as_slice())
                );
            }
        }
        assert_eq!(complete_count, 2);
    }
    #[test]
    fn garbage_before_sentence_is_ignored() {
        let garbage = b"hello123";
        let sentence = b"$GPGSV,3,1,11,10,63,137,17,07,61,098,15,05,59,290,20,08,54,157,30*70\r\n";
        let mut parser = NmeaParser::new();
        for &byte in garbage.iter().chain(sentence) {
            _ = parser.on_data_received(byte);
        }
        assert_eq!(
            parser.payload(),
            Some(b"GPGSV,3,1,11,10,63,137,17,07,61,098,15,05,59,290,20,08,54,157,30".as_slice())
        );
    }
    #[test]
    fn recovers_after_invalid_sentence() {
        let invalid = b"$GPGSV,3,1,11,10,63,137,17,07,61,098,15,05,59,290,20,08,54,157,30*71\r\n";
        let valid = b"$GPGSV,3,1,11,10,63,137,17,07,61,098,15,05,59,290,20,08,54,157,30*70\r\n";
        let mut parser = NmeaParser::new();
        for &byte in invalid.iter().chain(valid) {
            _ = parser.on_data_received(byte);
        }
        assert_eq!(
            parser.payload(),
            Some(b"GPGSV,3,1,11,10,63,137,17,07,61,098,15,05,59,290,20,08,54,157,30".as_slice())
        );
    }
    #[test]
    fn resynchronises_on_new_dollar() {
        let valid = b"$GPGSV,3,1,11,10,63,137,17,07,61,098,15,05,59,290,20,08,54,157,30*70\r\n";

        // The first sentence is corrupt/incomplete. A new '$' appears
        // before the corrupt sentence has terminated.
        let corrupt_prefix = b"$GPGSV,3,1,11,10,63,137,17,07$";

        let mut parser = NmeaParser::new();

        let mut complete_count = 0;

        for &byte in corrupt_prefix.iter().chain(valid) {
            if parser.on_data_received(byte) {
                complete_count += 1;
            }
        }

        assert_eq!(complete_count, 1);

        assert_eq!(
            parser.payload(),
            Some(b"GPGSV,3,1,11,10,63,137,17,07,61,098,15,05,59,290,20,08,54,157,30".as_slice())
        );
    }
    #[test]
    fn payload_overflow_is_rejected() {
        let mut parser = NmeaParser::new();
        // Start a sentence.
        assert!(!parser.on_data_received(b'$'));
        // Fill the payload buffer exactly.
        for _ in 0..NmeaParser::BUFFER_SIZE {
            assert!(!parser.on_data_received(b'A'));
        }
        // One more payload byte must cause the sentence to be rejected.
        assert!(!parser.on_data_received(b'B'));
        assert_eq!(parser.payload(), None);
    }
    #[test]
    fn recovers_after_payload_overflow() {
        let valid = b"$GPGSV,3,1,11,10,63,137,17,07,61,098,15,05,59,290,20,08,54,157,30*70\r\n";
        let mut parser = NmeaParser::new();
        // Start a sentence and deliberately overflow the payload buffer.
        assert!(!parser.on_data_received(b'$'));
        for _ in 0..NmeaParser::BUFFER_SIZE {
            assert!(!parser.on_data_received(b'A'));
        }
        assert!(!parser.on_data_received(b'B'));
        // A new '$' should allow the parser to recover.
        let mut complete = false;
        for &byte in valid {
            complete = parser.on_data_received(byte);
        }
        assert!(complete);
        assert_eq!(
            parser.payload(),
            Some(b"GPGSV,3,1,11,10,63,137,17,07,61,098,15,05,59,290,20,08,54,157,30".as_slice())
        );
    }
    #[test]
    fn fixed_point_basic() {
        assert_eq!(Parse::fixed_point(b"12.34", 100), Some(1234));
        assert_eq!(Parse::fixed_point(b"12.3", 100), Some(1230));
        assert_eq!(Parse::fixed_point(b"12", 100), Some(1200));
    }
    #[test]
    fn fixed_point_negative() {
        assert_eq!(Parse::fixed_point(b"-12.34", 100), Some(-1234));
        assert_eq!(Parse::fixed_point(b"-12.3", 100), Some(-1230));
    }
    #[test]
    fn fixed_point_truncates_extra_precision() {
        assert_eq!(Parse::fixed_point(b"12.345", 100), Some(1234));
    }
    #[test]
    fn fixed_point_rejects_invalid_input() {
        assert_eq!(Parse::fixed_point(b"", 100), None);
        assert_eq!(Parse::fixed_point(b"-", 100), None);
        assert_eq!(Parse::fixed_point(b"12.x", 100), None);
        assert_eq!(Parse::fixed_point(b"12.3.4", 100), None);
        assert_eq!(Parse::fixed_point(b"abc", 100), None);
    }
    #[test]
    fn fixed_point_rejects_overflow() {
        assert_eq!(Parse::fixed_point(b"999999999999999999", 100), None);
    }
    #[test]
    fn parse_nmea_coordinate_north() {
        assert_eq!(Parse::nmea_coordinate(b"4916.45", b'N'), Some(492_741_667));
    }
    #[test]
    fn parse_nmea_coordinate_south() {
        assert_eq!(Parse::nmea_coordinate(b"4916.45", b'S'), Some(-492_741_667));
    }
    #[test]
    fn parse_nmea_coordinate_east() {
        assert_eq!(Parse::nmea_coordinate(b"12311.12", b'E'), Some(1_231_853_333));
    }
    #[test]
    fn parse_nmea_coordinate_west() {
        assert_eq!(Parse::nmea_coordinate(b"12311.12", b'W'), Some(-1_231_853_333));
    }
    #[test]
    fn parse_nmea_coordinate_rejects_invalid_direction() {
        assert_eq!(Parse::nmea_coordinate(b"4916.45", b'X'), None);
    }
    #[test]
    fn parse_nmea_coordinate_rejects_invalid_minutes() {
        assert_eq!(Parse::nmea_coordinate(b"4960.00", b'N'), None);
    }
    #[test]
    fn parse_nmea_coordinate_rejects_missing_decimal() {
        assert_eq!(Parse::nmea_coordinate(b"491645", b'N'), None);
    }
    #[test]
    fn parse_nmea_coordinate_rejects_bad_digit() {
        assert_eq!(Parse::nmea_coordinate(b"49x6.45", b'N'), None);
    }
    #[test]
    fn parse_nmea_coordinate_rejects_empty() {
        assert_eq!(Parse::nmea_coordinate(b"", b'N'), None);
    }
    #[test]
    fn parse_nmea_coordinate_zero() {
        assert_eq!(Parse::nmea_coordinate(b"0000.00", b'N'), Some(0));
    }
    #[test]
    fn parse_nmea_coordinate_exact_degree() {
        assert_eq!(Parse::nmea_coordinate(b"4900.00", b'N'), Some(490_000_000));
    }
    #[test]
    fn parse_nmea_coordinate_near_sixty_minutes() {
        assert_eq!(Parse::nmea_coordinate(b"4959.9999", b'N'), Some(499_999_983));
    }
    #[test]
    fn parse_nmea_time_basic() {
        assert_eq!(Parse::nmea_time(b"123519"), Some(45_319_000));
    }
    #[test]
    fn parse_nmea_time_with_fraction() {
        assert_eq!(Parse::nmea_time(b"123519.500"), Some(45_319_500));
    }
    #[test]
    fn parse_nmea_time_truncates_excess_precision() {
        assert_eq!(Parse::nmea_time(b"123519.5009"), Some(45_319_500));
    }
    #[test]
    fn parse_nmea_time_midnight() {
        assert_eq!(Parse::nmea_time(b"000000"), Some(0));
    }
    #[test]
    fn parse_nmea_time_end_of_day() {
        assert_eq!(Parse::nmea_time(b"235959.999"), Some(86_399_999));
    }
    #[test]
    fn parse_nmea_time_rejects_invalid_hour() {
        assert_eq!(Parse::nmea_time(b"240000"), None);
    }
    #[test]
    fn parse_nmea_time_rejects_invalid_minute() {
        assert_eq!(Parse::nmea_time(b"126000"), None);
    }
    #[test]
    fn parse_nmea_time_rejects_invalid_second() {
        assert_eq!(Parse::nmea_time(b"125960"), None);
    }
    #[test]
    fn parse_nmea_time_rejects_bad_digit() {
        assert_eq!(Parse::nmea_time(b"1235X9"), None);
    }
    #[test]
    fn parse_nmea_time_rejects_bad_separator() {
        assert_eq!(Parse::nmea_time(b"123519X500"), None);
    }
}