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
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
//! NMEA 0183 parser
//!
//! Use nmea::Nmea::parse and nmea::Nmea::parse_for_fix to preserve
//! state between recieving new nmea sentence, and nmea::parse
//! to parse sentences without state
//!
//! Units that used every where: degrees, knots, meters for altitude
// Copyright (C) 2016 Felix Obenhuber
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

mod parse;
mod sentences;

pub use crate::parse::{
    parse, BwcData, GgaData, GllData, GsaData, GsvData, NmeaError, ParseResult, RmcData,
    RmcStatusOfFix, TxtData, VtgData, SENTENCE_MAX_LEN,
};
use chrono::{NaiveDate, NaiveTime};
use core::{fmt, mem, ops::BitOr};
use std::{collections::VecDeque, convert::TryInto};

/// NMEA parser
/// This struct parses NMEA sentences, including checksum checks and sentence
/// validation.
///
/// # Examples
///
/// ```
/// use nmea::Nmea;
///
/// let mut nmea= Nmea::default();
/// let gga = "$GPGGA,092750.000,5321.6802,N,00630.3372,W,1,8,1.03,61.7,M,55.2,M,,*76";
/// nmea.parse(gga).unwrap();
/// println!("{}", nmea);
/// ```
#[derive(Debug, Clone, Default)]
pub struct Nmea {
    pub fix_time: Option<NaiveTime>,
    pub fix_date: Option<NaiveDate>,
    pub fix_type: Option<FixType>,
    pub latitude: Option<f64>,
    pub longitude: Option<f64>,
    /// MSL Altitude in meters
    pub altitude: Option<f32>,
    pub speed_over_ground: Option<f32>,
    pub true_course: Option<f32>,
    pub num_of_fix_satellites: Option<u32>,
    pub hdop: Option<f32>,
    pub vdop: Option<f32>,
    pub pdop: Option<f32>,
    /// Geoid separation in meters
    pub geoid_separation: Option<f32>,
    pub fix_satellites_prns: Option<Vec<u32>>,
    satellites_scan: [SatsPack; GnssType::COUNT],
    required_sentences_for_nav: SentenceMask,
    last_fix_time: Option<NaiveTime>,
    last_txt: Option<TxtData>,
    sentences_for_this_time: SentenceMask,
}

#[derive(Debug, Clone, Default)]
struct SatsPack {
    data: VecDeque<[Option<Satellite>; 4]>,
    max_len: usize,
}

impl<'a> Nmea {
    /// Constructs a new `Nmea` for navigation purposes.
    ///
    /// # Examples
    ///
    /// ```
    /// use nmea::{Nmea, SentenceType};
    ///
    /// let mut nmea = Nmea::create_for_navigation(&[SentenceType::RMC,
    /// SentenceType::GGA]).unwrap();
    /// let gga = "$GPGGA,092750.000,5321.6802,N,00630.3372,W,1,8,1.03,61.7,M,55.2,M,,*76";
    /// nmea.parse(gga).unwrap();
    /// println!("{}", nmea);
    /// ```
    pub fn create_for_navigation(
        required_sentences_for_nav: &[SentenceType],
    ) -> Result<Nmea, NmeaError<'a>> {
        if required_sentences_for_nav.is_empty() {
            return Err(NmeaError::EmptyNavConfig);
        }
        let mut n = Self::default();
        for sentence in required_sentences_for_nav.iter() {
            n.required_sentences_for_nav.insert(*sentence);
        }
        Ok(n)
    }

    /// Returns fix type
    pub fn fix_timestamp(&self) -> Option<NaiveTime> {
        self.fix_time
    }

    /// Returns fix type
    pub fn fix_type(&self) -> Option<FixType> {
        self.fix_type
    }

    /// Returns last fixed latitude in degress. None if not fixed.
    pub fn latitude(&self) -> Option<f64> {
        self.latitude
    }

    /// Returns last fixed longitude in degress. None if not fixed.
    pub fn longitude(&self) -> Option<f64> {
        self.longitude
    }

    /// Returns altitude above WGS-84 ellipsoid, meters.
    pub fn altitude(&self) -> Option<f32> {
        self.altitude
    }

    /// Returns the number of satellites use for fix.
    pub fn fix_satellites(&self) -> Option<u32> {
        self.num_of_fix_satellites
    }

    /// Returns the number fix HDOP
    pub fn hdop(&self) -> Option<f32> {
        self.hdop
    }

    /// Returns the altitude above MSL (geoid), meters.
    pub fn geoid_altitude(&self) -> Option<f32> {
        match (self.altitude, self.geoid_separation) {
            (Some(alt), Some(geoid_diff)) => Some(alt + geoid_diff),
            _ => None,
        }
    }

    /// Returns used sattelites
    pub fn satellites(&self) -> Vec<Satellite> {
        let mut ret = Vec::with_capacity(20);
        let sat_key = |sat: &Satellite| (sat.gnss_type() as u8, sat.prn());
        for sns in &self.satellites_scan {
            for sat_pack in sns.data.iter().rev() {
                for sat in sat_pack.iter().flatten() {
                    match ret.binary_search_by_key(&sat_key(sat), sat_key) {
                        Ok(_pos) => {} //already setted
                        Err(pos) => ret.insert(pos, sat.clone()),
                    }
                }
            }
        }
        ret
    }

    fn merge_gga_data(&mut self, gga_data: GgaData) {
        self.fix_time = gga_data.fix_time;
        self.latitude = gga_data.latitude;
        self.longitude = gga_data.longitude;
        self.fix_type = gga_data.fix_type;
        self.num_of_fix_satellites = gga_data.fix_satellites;
        self.hdop = gga_data.hdop;
        self.altitude = gga_data.altitude;
        self.geoid_separation = gga_data.geoid_separation;
    }

    fn merge_gsv_data(&mut self, data: GsvData) -> Result<(), NmeaError<'a>> {
        {
            let d = &mut self.satellites_scan[data.gnss_type as usize];
            let full_pack_size: usize = data
                .sentence_num
                .try_into()
                .map_err(|_| NmeaError::InvalidGsvSentenceNum)?;
            d.max_len = full_pack_size.max(d.max_len);

            d.data.push_back(data.sats_info);
            if d.data.len() > d.max_len {
                d.data.pop_front();
            }
        }

        Ok(())
    }

    fn merge_rmc_data(&mut self, rmc_data: RmcData) {
        self.fix_time = rmc_data.fix_time;
        self.fix_date = rmc_data.fix_date;
        self.fix_type = Some(match rmc_data.status_of_fix {
            RmcStatusOfFix::Autonomous => FixType::Gps,
            RmcStatusOfFix::Differential => FixType::DGps,
            RmcStatusOfFix::Invalid => FixType::Invalid,
        });
        self.latitude = rmc_data.lat;
        self.longitude = rmc_data.lon;
        self.speed_over_ground = rmc_data.speed_over_ground;
        self.true_course = rmc_data.true_course;
    }

    fn merge_gns_data(&mut self, gns_data: parse::GnsData) {
        self.fix_time = gns_data.fix_time;
        self.fix_type = Some(gns_data.faa_modes.into());
        self.latitude = gns_data.lat;
        self.longitude = gns_data.lon;
        self.altitude = gns_data.alt;
        self.hdop = gns_data.hdop;
        self.geoid_separation = gns_data.geoid_separation;
    }

    fn merge_gsa_data(&mut self, gsa: GsaData) {
        self.fix_satellites_prns = Some(gsa.fix_sats_prn);
        self.hdop = gsa.hdop;
        self.vdop = gsa.vdop;
        self.pdop = gsa.pdop;
    }

    fn merge_vtg_data(&mut self, vtg: VtgData) {
        self.speed_over_ground = vtg.speed_over_ground;
        self.true_course = vtg.true_course;
    }

    fn merge_gll_data(&mut self, gll: GllData) {
        self.latitude = gll.latitude;
        self.longitude = gll.longitude;
        self.fix_time = Some(gll.fix_time);
        if let Some(faa_mode) = gll.faa_mode {
            self.fix_type = Some(faa_mode.into());
        } else {
            self.fix_type = Some(if gll.valid {
                FixType::Gps
            } else {
                FixType::Invalid
            });
        }
    }

    fn merge_txt_data(&mut self, txt: TxtData) {
        self.last_txt = Some(txt);
    }

    /// Parse any NMEA sentence and stores the result. The type of sentence
    /// is returnd if implemented and valid.
    pub fn parse(&mut self, s: &'a str) -> Result<SentenceType, NmeaError<'a>> {
        match parse(s.as_bytes())? {
            ParseResult::VTG(vtg) => {
                self.merge_vtg_data(vtg);
                Ok(SentenceType::VTG)
            }
            ParseResult::GGA(gga) => {
                self.merge_gga_data(gga);
                Ok(SentenceType::GGA)
            }
            ParseResult::GSV(gsv) => {
                self.merge_gsv_data(gsv)?;
                Ok(SentenceType::GSV)
            }
            ParseResult::RMC(rmc) => {
                self.merge_rmc_data(rmc);
                Ok(SentenceType::RMC)
            }
            ParseResult::GNS(gns) => {
                self.merge_gns_data(gns);
                Ok(SentenceType::GNS)
            }
            ParseResult::GSA(gsa) => {
                self.merge_gsa_data(gsa);
                Ok(SentenceType::GSA)
            }
            ParseResult::GLL(gll) => {
                self.merge_gll_data(gll);
                Ok(SentenceType::GLL)
            }
            ParseResult::TXT(txt) => {
                self.merge_txt_data(txt);
                Ok(SentenceType::TXT)
            }
            ParseResult::BWC(_) => Err(NmeaError::Unsupported(SentenceType::BWC)),
            ParseResult::Unsupported(sentence_type) => Err(NmeaError::Unsupported(sentence_type)),
        }
    }

    fn new_tick(&mut self) {
        let old = mem::take(self);
        self.satellites_scan = old.satellites_scan;
        self.required_sentences_for_nav = old.required_sentences_for_nav;
        self.last_fix_time = old.last_fix_time;
    }

    fn clear_position_info(&mut self) {
        self.last_fix_time = None;
        self.new_tick();
    }

    pub fn parse_for_fix(&mut self, xs: &'a [u8]) -> Result<FixType, NmeaError<'a>> {
        match parse(xs)? {
            ParseResult::GSA(gsa) => {
                self.merge_gsa_data(gsa);
                return Ok(FixType::Invalid);
            }
            ParseResult::GSV(gsv_data) => {
                self.merge_gsv_data(gsv_data)?;
                return Ok(FixType::Invalid);
            }
            ParseResult::VTG(vtg) => {
                //have no time field, so only if user explicity mention it
                if self.required_sentences_for_nav.contains(&SentenceType::VTG) {
                    if vtg.true_course.is_none() || vtg.speed_over_ground.is_none() {
                        self.clear_position_info();
                        return Ok(FixType::Invalid);
                    }
                    self.merge_vtg_data(vtg);
                    self.sentences_for_this_time.insert(SentenceType::VTG);
                } else {
                    return Ok(FixType::Invalid);
                }
            }
            ParseResult::RMC(rmc_data) => {
                if rmc_data.status_of_fix == RmcStatusOfFix::Invalid {
                    self.clear_position_info();
                    return Ok(FixType::Invalid);
                }
                if !self.update_fix_time(rmc_data.fix_time) {
                    return Ok(FixType::Invalid);
                }
                self.merge_rmc_data(rmc_data);
                self.sentences_for_this_time.insert(SentenceType::RMC);
            }
            ParseResult::GNS(gns_data) => {
                let fix_type: FixType = gns_data.faa_modes.into();
                if !fix_type.is_valid() {
                    self.clear_position_info();
                    return Ok(FixType::Invalid);
                }
                if !self.update_fix_time(gns_data.fix_time) {
                    return Ok(FixType::Invalid);
                }
                self.merge_gns_data(gns_data);
                self.sentences_for_this_time.insert(SentenceType::GNS);
            }
            ParseResult::GGA(gga_data) => {
                match gga_data.fix_type {
                    Some(FixType::Invalid) | None => {
                        self.clear_position_info();
                        return Ok(FixType::Invalid);
                    }
                    _ => { /*nothing*/ }
                }
                if !self.update_fix_time(gga_data.fix_time) {
                    return Ok(FixType::Invalid);
                }
                self.merge_gga_data(gga_data);
                self.sentences_for_this_time.insert(SentenceType::GGA);
            }
            ParseResult::GLL(gll_data) => {
                if !self.update_fix_time(Some(gll_data.fix_time)) {
                    return Ok(FixType::Invalid);
                }
                self.merge_gll_data(gll_data);
                return Ok(FixType::Invalid);
            }
            ParseResult::TXT(txt_data) => {
                self.merge_txt_data(txt_data);
                return Ok(FixType::Invalid);
            }
            ParseResult::BWC(_) => return Ok(FixType::Invalid),
            ParseResult::Unsupported(_) => {
                return Ok(FixType::Invalid);
            }
        }
        match self.fix_type {
            Some(FixType::Invalid) | None => Ok(FixType::Invalid),
            Some(ref fix_type)
                if self
                    .required_sentences_for_nav
                    .is_subset(&self.sentences_for_this_time) =>
            {
                Ok(*fix_type)
            }
            _ => Ok(FixType::Invalid),
        }
    }

    pub fn last_txt(&self) -> Option<&TxtData> {
        self.last_txt.as_ref()
    }

    fn update_fix_time(&mut self, fix_time: Option<NaiveTime>) -> bool {
        match (self.last_fix_time, fix_time) {
            (Some(ref last_fix_time), Some(ref new_fix_time)) => {
                if *last_fix_time != *new_fix_time {
                    self.new_tick();
                    self.last_fix_time = Some(*new_fix_time);
                }
            }
            (None, Some(ref new_fix_time)) => self.last_fix_time = Some(*new_fix_time),
            (Some(_), None) | (None, None) => {
                self.clear_position_info();
                return false;
            }
        }
        true
    }
}

impl fmt::Display for Nmea {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{}: lat: {} lon: {} alt: {} {:?}",
            self.fix_time
                .map(|l| format!("{:?}", l))
                .unwrap_or_else(|| "None".to_owned()),
            self.latitude
                .map(|l| format!("{:3.8}", l))
                .unwrap_or_else(|| "None".to_owned()),
            self.longitude
                .map(|l| format!("{:3.8}", l))
                .unwrap_or_else(|| "None".to_owned()),
            self.altitude
                .map(|l| format!("{:.3}", l))
                .unwrap_or_else(|| "None".to_owned()),
            self.satellites()
        )
    }
}

#[derive(Clone, PartialEq)]
/// Satellite information
pub struct Satellite {
    gnss_type: GnssType,
    prn: u32,
    elevation: Option<f32>,
    azimuth: Option<f32>,
    snr: Option<f32>,
}

impl Satellite {
    #[inline]
    pub fn gnss_type(&self) -> GnssType {
        self.gnss_type
    }
    #[inline]
    pub fn prn(&self) -> u32 {
        self.prn
    }
    #[inline]
    pub fn elevation(&self) -> Option<f32> {
        self.elevation
    }
    #[inline]
    pub fn azimuth(&self) -> Option<f32> {
        self.azimuth
    }
    #[inline]
    pub fn snr(&self) -> Option<f32> {
        self.snr
    }
}

impl fmt::Display for Satellite {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{}: {} elv: {} ath: {} snr: {}",
            self.gnss_type,
            self.prn,
            self.elevation
                .map(|e| format!("{}", e))
                .unwrap_or_else(|| "--".to_owned()),
            self.azimuth
                .map(|e| format!("{}", e))
                .unwrap_or_else(|| "--".to_owned()),
            self.snr
                .map(|e| format!("{}", e))
                .unwrap_or_else(|| "--".to_owned())
        )
    }
}

impl fmt::Debug for Satellite {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "[{:?},{:?},{:?},{:?},{:?}]",
            self.gnss_type, self.prn, self.elevation, self.azimuth, self.snr
        )
    }
}

macro_rules! define_sentence_type_enum {
    (
        $(#[$outer:meta])*
        enum $Name:ident { $($Variant:ident),* $(,)* }
    ) => {
        $(#[$outer])*
        #[derive(PartialEq, Debug, Hash, Eq, Clone, Copy)]
        #[repr(C)]
        pub enum $Name {
            $($Variant),*,
            None
        }

        impl<'a> From<&'a str> for $Name {
            fn from(s: &str) -> Self {
                match s {
                    $(stringify!($Variant) => $Name::$Variant,)*
                    _ => $Name::None,
                }
            }
        }

        impl $Name {
            fn from_slice(s: &[u8]) -> Self {
                $(
                    #[allow(nonstandard_style)]
                    const $Variant: &[u8] = stringify!($Variant).as_bytes();
                )*
                match s {
                    $($Variant => $Name::$Variant,)*
                    _ => $Name::None,
                }
            }

            fn to_mask_value(&self) -> u128 {
                1 << *self as u32
            }
        }
    }
}

define_sentence_type_enum!(
    /// NMEA sentence type
    /// General: OSD |
    /// Autopilot: APA | APB | ASD |
    /// Decca: DCN |
    /// D-GPS: MSK
    /// Echo: DBK | DBS | DBT |
    /// Radio: FSI | SFI | TLL
    /// Speed: VBW | VHW | VLW |
    /// GPS: ALM | GBS | GGA | GNS | GSA | GSV |
    /// Course: DPT | HDG | HDM | HDT | HSC | ROT | VDR |
    /// Loran-C: GLC | LCD |
    /// Machine: RPM |
    /// Navigation: RMA | RMB | RMC |
    /// Omega: OLN |
    /// Position: GLL | DTM
    /// Radar: RSD | TLL | TTM |
    /// Rudder: RSA |
    /// Temperature: MTW |
    /// Transit: GXA | RTF |
    /// Waypoints and tacks: AAM | BEC | BOD | BWC | BWR | BWW | ROO | RTE |
    ///                      VTG | WCV | WNC | WPL | XDR | XTE | XTR |
    /// Wind: MWV | VPW | VWR |
    /// Date and Time: GDT | ZDA | ZFO | ZTG |
    enum SentenceType {
        AAM,
        ABK,
        ACA,
        ACK,
        ACS,
        AIR,
        ALM,
        ALR,
        APA,
        APB,
        ASD,
        BEC,
        BOD,
        BWC,
        BWR,
        BWW,
        CUR,
        DBK,
        DBS,
        DBT,
        DCN,
        DPT,
        DSC,
        DSE,
        DSI,
        DSR,
        DTM,
        FSI,
        GBS,
        GGA,
        GLC,
        GLL,
        GMP,
        GNS,
        GRS,
        GSA,
        GST,
        GSV,
        GTD,
        GXA,
        HDG,
        HDM,
        HDT,
        HMR,
        HMS,
        HSC,
        HTC,
        HTD,
        LCD,
        LRF,
        LRI,
        LR1,
        LR2,
        LR3,
        MLA,
        MSK,
        MSS,
        MWD,
        MTW,
        MWV,
        OLN,
        OSD,
        ROO,
        RMA,
        RMB,
        RMC,
        ROT,
        RPM,
        RSA,
        RSD,
        RTE,
        SFI,
        SSD,
        STN,
        TLB,
        TLL,
        TRF,
        TTM,
        TUT,
        TXT,
        VBW,
        VDM,
        VDO,
        VDR,
        VHW,
        VLW,
        VPW,
        VSD,
        VTG,
        VWR,
        WCV,
        WNC,
        WPL,
        XDR,
        XTE,
        XTR,
        ZDA,
        ZDL,
        ZFO,
        ZTG,
    }
);

#[derive(Copy, Clone, PartialEq, Debug, Default)]
pub struct SentenceMask {
    mask: u128,
}

impl SentenceMask {
    fn contains(&self, sentence_type: &SentenceType) -> bool {
        sentence_type.to_mask_value() & self.mask != 0
    }

    fn is_subset(&self, mask: &Self) -> bool {
        (mask.mask | self.mask) == mask.mask
    }

    fn insert(&mut self, sentence_type: SentenceType) {
        self.mask |= sentence_type.to_mask_value()
    }
}

impl BitOr for SentenceType {
    type Output = SentenceMask;
    fn bitor(self, rhs: Self) -> Self::Output {
        SentenceMask {
            mask: self.to_mask_value() | rhs.to_mask_value(),
        }
    }
}

impl BitOr<SentenceType> for SentenceMask {
    type Output = Self;
    fn bitor(self, rhs: SentenceType) -> Self {
        SentenceMask {
            mask: self.mask | rhs.to_mask_value(),
        }
    }
}

/// Fix type
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum FixType {
    Invalid,
    Gps,
    DGps,
    /// Precise Position Service
    Pps,
    Rtk,
    FloatRtk,
    Estimated,
    Manual,
    Simulation,
}

impl FixType {
    #[inline]
    pub fn is_valid(self) -> bool {
        match self {
            FixType::Simulation | FixType::Manual | FixType::Estimated | FixType::Invalid => false,
            FixType::DGps | FixType::Gps | FixType::Rtk | FixType::FloatRtk | FixType::Pps => true,
        }
    }
}

macro_rules! count_tts {
    () => {0usize};
    ($_head:tt , $($tail:tt)*) => {1usize + count_tts!($($tail)*)};
    ($item:tt) => {1usize};
}

macro_rules! define_enum_with_count {
    (
        $(#[$outer:meta])*
        enum $Name:ident { $($Variant:ident),* $(,)* }
    ) => {
        $(#[$outer])*
        #[derive(PartialEq, Debug, Hash, Eq, Clone, Copy)]
        #[repr(u8)]
        pub enum $Name {
            $($Variant),*
        }
        impl $Name {
            const COUNT: usize = count_tts!($($Variant),*);
        }
    };
}

define_enum_with_count!(
    /// GNSS type
    enum GnssType {
        Beidou,
        Galileo,
        Gps,
        Glonass,
    }
);

impl fmt::Display for GnssType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            GnssType::Beidou => write!(f, "Beidou"),
            GnssType::Galileo => write!(f, "Galileo"),
            GnssType::Gps => write!(f, "GPS"),
            GnssType::Glonass => write!(f, "GLONASS"),
        }
    }
}

impl From<char> for FixType {
    fn from(x: char) -> Self {
        match x {
            '0' => FixType::Invalid,
            '1' => FixType::Gps,
            '2' => FixType::DGps,
            '3' => FixType::Pps,
            '4' => FixType::Rtk,
            '5' => FixType::FloatRtk,
            '6' => FixType::Estimated,
            '7' => FixType::Manual,
            '8' => FixType::Simulation,
            _ => FixType::Invalid,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::parse::checksum;
    use super::*;
    use quickcheck::{QuickCheck, TestResult};

    fn check_parsing_lat_lon_in_gga(lat: f64, lon: f64) -> TestResult {
        fn scale(val: f64, max: f64) -> f64 {
            val % max
        }
        if !lat.is_finite() || !lon.is_finite() {
            return TestResult::discard();
        }
        let lat = scale(lat, 90.0);
        let lon = scale(lon, 180.0);
        let lat_min = (lat.abs() * 60.0) % 60.0;
        let lon_min = (lon.abs() * 60.0) % 60.0;
        let mut nmea = Nmea::default();
        let mut s = format!(
            "$GPGGA,092750.000,{lat_deg:02}{lat_min:09.6},{lat_dir},\
             {lon_deg:03}{lon_min:09.6},{lon_dir},1,8,1.03,61.7,M,55.2,M,,*",
            lat_deg = lat.abs().floor() as u8,
            lon_deg = lon.abs().floor() as u8,
            lat_min = lat_min,
            lon_min = lon_min,
            lat_dir = if lat.is_sign_positive() { 'N' } else { 'S' },
            lon_dir = if lon.is_sign_positive() { 'E' } else { 'W' },
        );
        let cs = checksum(s.as_bytes()[1..s.len() - 1].iter());
        s.push_str(&format!("{:02X}", cs));
        nmea.parse(&s).unwrap();
        let (new_lat, new_lon) = (nmea.latitude.unwrap(), nmea.longitude.unwrap());
        const MAX_COOR_DIFF: f64 = 1e-7;
        TestResult::from_bool(
            (new_lat - lat).abs() < MAX_COOR_DIFF && (new_lon - lon).abs() < MAX_COOR_DIFF,
        )
    }

    #[test]
    fn test_fix_type() {
        assert_eq!(FixType::from('A'), FixType::Invalid);
        assert_eq!(FixType::from('0'), FixType::Invalid);
        assert_eq!(FixType::from('1'), FixType::Gps);
        assert_eq!(FixType::from('2'), FixType::DGps);
        assert_eq!(FixType::from('3'), FixType::Pps);
        assert_eq!(FixType::from('4'), FixType::Rtk);
        assert_eq!(FixType::from('5'), FixType::FloatRtk);
        assert_eq!(FixType::from('6'), FixType::Estimated);
        assert_eq!(FixType::from('7'), FixType::Manual);
        assert_eq!(FixType::from('8'), FixType::Simulation);
    }

    #[test]
    fn test_checksum() {
        use crate::parse::checksum;
        let valid = "$GNGSA,A,1,,,,,,,,,,,,,99.99,99.99,99.99*2E";
        let invalid = "$GNZDA,165118.00,13,05,2016,00,00*71";
        assert_eq!(
            checksum((&valid[1..valid.len() - 3]).as_bytes().iter()),
            0x2E
        );
        assert_ne!(
            checksum((&invalid[1..invalid.len() - 3]).as_bytes().iter()),
            0x71
        );
    }

    #[test]
    fn test_message_type() {
        assert_eq!(SentenceType::from_slice(b"GGA"), SentenceType::GGA);
        assert_eq!(SentenceType::from_slice(b"XXX"), SentenceType::None);
    }

    #[test]
    fn test_parsing_lat_lon_in_gga() {
        // regressions found by quickcheck,
        // explicit because of quickcheck use random gen
        assert!(!check_parsing_lat_lon_in_gga(0., 57.89528).is_failure());
        assert!(!check_parsing_lat_lon_in_gga(0., -43.33031).is_failure());
        QuickCheck::new()
            .tests(10_000_000_000)
            .quickcheck(check_parsing_lat_lon_in_gga as fn(f64, f64) -> TestResult);
    }

    #[test]
    fn test_sentence_type_enum() {
        // So we don't trip over the max value of u128 when shifting it with
        // SentenceType as u32
        assert!((SentenceType::None as u32) < 127);
    }
}