sameplace 0.2.0

A SAME/EAS Message Parser
Documentation
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
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
//! SAME message ASCII encoding and decoding

mod eventcode;
mod originator;
mod phenomenon;
mod significance;

use std::convert::TryFrom;
use std::fmt;

#[cfg(feature = "chrono")]
use chrono::{DateTime, Datelike, Duration, NaiveDate, TimeZone, Utc};
use lazy_static::lazy_static;
use regex::Regex;
use thiserror::Error;

pub use eventcode::EventCode;
pub use originator::Originator;
pub use phenomenon::Phenomenon;
pub use significance::SignificanceLevel;

/// The result of parsing a message
pub type MessageResult = Result<Message, MessageDecodeErr>;

/// A fully-decoded SAME/EAS message
///
/// In order to automatically disseminate alerts, SAME/EAS wraps a
/// **voice message** in digital data. The digital data demarcates the
/// [`StartOfMessage`](Message::StartOfMessage) and the
/// [`EndOfMessage`](Message::EndOfMessage). Again, the digital data
/// is **not** the message. The "message" in EAS is the voice message
/// that is intended for a human listener.
///
/// With that said, the digital headers provide a good deal of
/// information about the message.
///
/// 1. The [`StartOfMessage`](Message::StartOfMessage) contains
///    digital codes and timestamps which summarize the audio
///    message to follow. Some messages are intended for either
///    silent or audible tests. Others report actual emergencies;
///    these either may or must interrupt normal broadcast
///    programming.
///
/// 2. The voice message immediately follows. The voice message may
///    be up to two minutes long and is intended for streaming
///    playback. This datatype does not represent the audio.
///
/// 3. The [`EndOfMessage`](Message::EndOfMessage) demarcates the
///    end of the audio message.
///
/// `Message` implements `Display` and efficient conversion to
/// `&str`. These methods output the wireline text representation,
/// such as "`ZCZC-...`" for `StartOfMessage` and `NNNN` for
/// `EndOfMessage`.
///
/// More information on the SAME/EAS standard may be found in,
/// * "NOAA Weather Radio (NWR) All Hazards Specific Area Message
///   Encoding (SAME)," NWSI 10-172, 3 Oct. 2011,
///   <https://www.nws.noaa.gov/directives/sym/pd01017012curr.pdf>
///
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Message {
    /// Indicates start of audio message
    ///
    /// A `StartOfMessage` indicates that a SAME/EAS audio
    /// message immediately follows. The message
    /// [header](MessageHeader) contains the event
    /// type, affected areas, time extents, and originator
    /// information.
    ///
    /// For broadcast stations, the in-band audio which immediately
    /// follows the `StartOfMessage` *may* break station
    /// programming and be aired directly to listeners.
    StartOfMessage(MessageHeader),

    /// Indicates end of audio message
    ///
    /// An `EndOfMessage` marks the conclusion of the SAME/EAS
    /// audio message. For broadcast stations, it is an
    /// indication that normal programming may resume.
    EndOfMessage,
}

/// Error decoding a `MessageHeader`
#[derive(Error, Clone, Debug, PartialEq, Eq, Hash)]
pub enum MessageDecodeErr {
    /// The starting prefix of the message was not recognized
    #[error("invalid SAME header: unrecognized prefix")]
    UnrecognizedPrefix,

    /// Header contains non-ASCII characters
    #[error("invalid SAME header: message contains non-ASCII characters")]
    NotAscii,

    /// Header does not match general format
    #[error("invalid SAME header: message text does not match required pattern")]
    Malformed,
}

impl Message {
    /// Wireline Text Representation
    ///
    /// Outputs UTF-8 string representation: i.e., `ZCZC-...`
    /// for start-of-message or `NNNN` for end-of-message.
    pub fn as_str(&self) -> &str {
        match self {
            Self::StartOfMessage(m) => m.as_str(),
            Self::EndOfMessage => PREFIX_MESSAGE_END,
        }
    }

    /// Count of parity errors
    ///
    /// The number of *bit errors* which were corrected by the
    /// 2-of-3 parity correction algorithm. High parity error
    /// counts indicate a high bit error rate in the receiving
    /// system.
    ///
    /// Parity errors are *not* tracked for the `EndOfMessage`
    /// variant. Parity errors are only tracked within sameold
    /// and aren't available for Messages constructed from
    /// string.
    pub fn parity_error_count(&self) -> usize {
        match self {
            Self::StartOfMessage(m) => m.parity_error_count(),
            Self::EndOfMessage => 0,
        }
    }

    /// Number of bytes which were bit-voted
    ///
    /// `voting_byte_count` is the total number of bytes which were
    /// checked via the "two of three" bitwise voting algorithm—i.e.,
    /// the total number of bytes for which all three SAME bursts were
    /// available.
    ///
    /// Voting counts are *not* tracked for the `EndOfMessage`
    /// variant. Voting counts are only tracked within sameold
    /// and aren't available for Messages constructed from string.
    pub fn voting_byte_count(&self) -> usize {
        match self {
            Self::StartOfMessage(m) => m.voting_byte_count(),
            Self::EndOfMessage => 0,
        }
    }
}

/// An invalid issuance time
#[derive(Error, Clone, Debug, PartialEq, Eq, Hash)]
#[error("message issuance time not valid for its receive time")]
pub struct InvalidDateErr {}

/// Event, area, time, and originator information
///
/// The message header is the decoded *digital header* which precedes
/// the analog SAME message. See
/// [crate documentation](./index.html#interpreting-messages)
/// for an example.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct MessageHeader {
    // message content, including the leading `ZCZC-`
    message: String,

    // where does the time field begin?
    // includes the leading plus character (`+`)
    offset_time: usize,

    // parity errors
    parity_error_count: usize,

    // number of message bytes which could be bit-voted
    // (i.e., because three bursts were available)
    voting_byte_count: usize,
}

impl MessageHeader {
    /// Try to construct a SAME header from `String`
    ///
    /// The `message` string must match the general format of
    /// a SAME header. If it does not, an error is returned.
    pub fn new<S>(message: S) -> Result<Self, MessageDecodeErr>
    where
        S: Into<String>,
    {
        let mut message: String = message.into();
        if !message.is_ascii() {
            return Err(MessageDecodeErr::NotAscii);
        }

        let (offset_time, hdr_length) = check_header(&message)?;
        message.truncate(hdr_length);

        Ok(Self {
            message,
            offset_time,
            parity_error_count: 0,
            voting_byte_count: 0,
        })
    }

    /// Try to construct a SAME header from `String`, with error counts
    ///
    /// The `message` string must match the general format of
    /// a SAME header. If it does not, an error is returned.
    ///
    /// The `error_counts` slice counts the number of bit errors
    /// corrected in byte of `message`. The slice must have the
    /// same length as `message`.
    pub fn new_with_errors<S>(message: S, error_counts: &[u8]) -> Result<Self, MessageDecodeErr>
    where
        S: Into<String>,
    {
        let mut out = Self::new(message)?;
        let mut parity_error_count = 0;
        for (&e, _m) in error_counts.iter().zip(out.message().as_bytes().iter()) {
            parity_error_count += e as usize;
        }

        out.parity_error_count = parity_error_count;
        Ok(out)
    }

    /// Try to construct a SAME header from `String`, with error details
    ///
    /// The `message` string must match the general format of
    /// a SAME header. If it does not, an error is returned.
    ///
    /// The `error_counts` slice counts the number of bit errors
    /// corrected in byte of `message`. The slice must have the
    /// same byte count as `message`.
    ///
    /// `burst_counts` is the total number of SAME bursts which were
    /// used to estimate each message byte. This slice must have
    /// the same byte count as `message`.
    pub fn new_with_error_info<S>(
        message: S,
        error_counts: &[u8],
        burst_counts: &[u8],
    ) -> Result<Self, MessageDecodeErr>
    where
        S: Into<String>,
    {
        const MIN_BURSTS_FOR_VOTING: u8 = 3;

        let mut out = Self::new_with_errors(message, error_counts)?;
        let mut voting_byte_count = 0;
        for (&e, _m) in burst_counts.iter().zip(out.message().as_bytes().iter()) {
            voting_byte_count += (e >= MIN_BURSTS_FOR_VOTING) as usize;
        }
        out.voting_byte_count = voting_byte_count;
        Ok(out)
    }

    /// Wireline Text Representation
    ///
    /// Returns UTF-8 string representation of a SAME/EAS
    /// start-of-message: i.e., `ZCZC-...`
    ///
    /// Use [`release()`](MessageHeader::release()) to obtain
    /// an owned `String` instead.
    pub fn message(&self) -> &str {
        &self.message
    }

    /// Wireline Text Representation
    ///
    /// Returns UTF-8 string representation of a SAME/EAS
    /// start-of-message: i.e., `ZCZC-...`
    ///
    /// Use [`release()`](MessageHeader::release()) to obtain
    /// an owned `String` instead.
    pub fn as_str(&self) -> &str {
        &self.message
    }

    /// Originator code
    ///
    /// The ultimate source of the message, such as
    /// [`Originator::NationalWeatherService`] for the
    /// National Weather Service
    pub fn originator(&self) -> Originator {
        Originator::from_org_and_call(self.originator_str(), self.callsign())
    }

    /// Originator code (as string)
    ///
    /// A three-character string that is usually one of the
    /// following:
    ///
    /// - `PEP`: Primary Entry Point Station. Generally only
    ///   used for national activations, which are very rare.
    ///
    /// - `CIV`: Civil authorities (usu. state and local government)
    ///
    /// - `WXR`: National Weather Service or Environment Canada
    ///
    /// - `EAS`: EAS Participant. Usually a broadcast station.
    ///
    /// The originator code returned is three characters but is
    /// not guaranteed to be one of the above.
    pub fn originator_str(&self) -> &str {
        &self.message[Self::OFFSET_ORG..Self::OFFSET_ORG + 3]
    }

    /// Event code
    ///
    /// Decodes the SAME event code (like `RWT`) into an
    /// [`EventCode`], which is a combination of:
    ///
    /// * [`phenomenon()`](Phenomenon), which describes what
    ///   is occurring; and
    ///
    /// * [`significance()`](SignificanceLevel), which indicates the
    ///   overall severity and/or how "noisy" or intrusive the alert
    ///   should be.
    ///
    /// `EventCode` Display as a human-readable string which describes
    /// the SAME code. For example, "`TOR`" displays as "Tornado Warning."
    ///
    /// ```
    /// # use std::fmt;
    /// use sameplace::{MessageHeader, Phenomenon, SignificanceLevel};
    ///
    /// let msg = MessageHeader::new("ZCZC-WXR-RWT-012345+0351-3662322-NOCALL  -").unwrap();
    /// let evt = msg.event();
    ///
    /// assert_eq!(evt.phenomenon(), Phenomenon::RequiredWeeklyTest);
    /// assert_eq!(evt.significance(), SignificanceLevel::Test);
    /// assert_eq!(format!("{}", evt), "Required Weekly Test");
    /// ```
    ///
    /// The decoder will make every effort to interpret SAME codes it
    /// does not explicitly know. The `EventCode` might contain only a
    /// valid significance level—or perhaps not even that.
    ///
    /// ```
    /// # use std::fmt;
    /// # use sameplace::{MessageHeader, SignificanceLevel};
    /// let msg = MessageHeader::new("ZCZC-WXR-OMG-012345+0351-3662322-NOCALL  -").unwrap();
    /// assert_eq!(msg.event_str(), "OMG");
    /// assert_eq!(msg.event().to_string(), "Unrecognized Warning");
    /// assert_eq!(msg.event().significance(), SignificanceLevel::Unknown);
    /// assert!(msg.event().is_unrecognized());
    /// ```
    ///
    /// Unrecognized messages are still valid, and clients are encouraged
    /// to treat them at their [significance](EventCode::significance) level.
    /// Messages where even the significance level cannot be decoded should
    /// be treated as Warnings.
    ///
    /// [`eventcodes`](crate::eventcodes) contains the complete list of SAME
    /// codes that are interpreted by `sameplace`. See also: [`EventCode`].
    pub fn event(&self) -> EventCode {
        EventCode::from(self.event_str())
    }

    /// Event code
    ///
    /// A three-character code like "`RWT`" which describes the phenomenon
    /// and/or the severity level of the message. Use the
    /// [`event()`](MessageHeader::event) method to parse this
    /// code into its components for further processing or for
    /// a human-readable display.
    ///
    /// See [`eventcodes`](crate::eventcodes) for the complete list
    /// of SAME codes that are interpreted by `sameplace`. The string value
    /// is not guaranteed to be one of these codes.
    pub fn event_str(&self) -> &str {
        &self.message[Self::OFFSET_EVT..Self::OFFSET_EVT + 3]
    }

    /// Iterator over location codes
    ///
    /// Returns an iterator over the location codes in the
    /// message. Location codes are six-digit strings of
    /// the form `PSSCCC`:
    ///
    /// - `P`: part of county, or zero for entire county
    /// - `SS`: FIPS State code
    /// - `CCC`: FIPS County code
    ///
    /// Locations are returned in the order listed in the
    /// message. Iterator values are guaranteed to be
    /// six-digit strings.
    ///
    /// Per the SAME standard, a message can have up to 31
    /// location codes.
    pub fn location_str_iter<'m>(&'m self) -> std::str::Split<'m, char> {
        self.location_str().split('-')
    }

    /// Message validity duration (`Duration`)
    ///
    /// Returns the message validity duration or "purge time."
    /// The duration specifies how long, relative to the
    /// [issue time](MessageHeader::issue_datetime), that the
    /// message is valid.
    ///
    /// The Duration is typically:
    ///
    /// * increments of **15 minutes** for Durations of
    ///   **1 hour** or less
    ///
    /// * increments of **30 minutes** for Durations longer
    ///   than **1 hour**
    ///
    /// * no longer than
    ///   [99.5 hours](https://www.weather.gov/nwr/samealertduration)
    ///
    /// but sameplace does not enforce any of these restrictions.
    ///
    /// This field represents the validity duration of the *message*
    /// and not the expected duration of the severe condition.
    /// **An expired message may still refer to an ongoing hazard** or
    /// event. Expiration merely indicates that the *message* is no
    /// longer valid. Clients are encouraged to retain a history of
    /// alerts and voice message contents.
    ///
    /// The valid duration is relative to the
    /// [`issue_datetime()`](MessageHeader::issue_datetime) and
    /// *not* the current time.
    ///
    /// Requires `chrono`.
    #[cfg(feature = "chrono")]
    pub fn valid_duration(&self) -> Duration {
        let (hrs, mins) = self.valid_duration_fields();
        Duration::hours(hrs as i64) + Duration::minutes(mins as i64)
    }

    /// Message validity duration
    ///
    /// Returns the message validity duration or "purge time."
    /// This is a tuple of (`hours`, `minutes`).
    /// The duration specifies how long, relative to the
    /// [issue time](MessageHeader::issue_datetime), that the
    /// message is valid.
    ///
    /// The duration is typically:
    ///
    /// * increments of **15 minutes** for durations of
    ///   **1 hour** or less
    ///
    /// * increments of **30 minutes** for durations longer
    ///   than **1 hour**
    ///
    /// * no longer than
    ///   [99.5 hours](https://www.weather.gov/nwr/samealertduration)
    ///
    /// but sameplace does not enforce any of these restrictions.
    ///
    /// This field represents the validity duration of the *message*
    /// and not the expected duration of the severe condition.
    /// **An expired message may still refer to an ongoing hazard** or
    /// event. Expiration merely indicates that the *message* is no
    /// longer valid. Clients are encouraged to retain a history of
    /// alerts and voice message contents.
    ///
    /// The valid duration is relative to the
    /// [`issue_datetime()`](MessageHeader::issue_datetime) and
    /// *not* the current time.
    pub fn valid_duration_fields(&self) -> (u8, u8) {
        let dur_str = &self.message[self.offset_time + Self::OFFSET_FROMPLUS_VALIDTIME
            ..self.offset_time + Self::OFFSET_FROMPLUS_VALIDTIME + 4];
        (
            dur_str[0..2].parse().expect(Self::PANIC_MSG),
            dur_str[2..4].parse().expect(Self::PANIC_MSG),
        )
    }

    /// Estimated message issuance datetime (UTC)
    ///
    /// Computes the datetime that the SAME message was *issued*
    /// from the time that the message was `received`, which
    /// must be provided.
    ///
    /// SAME headers do not include the year of issuance. This makes
    /// it impossible to calculate the full datetime of issuance
    /// without a rough idea of the message's true UTC time. It is
    /// *unnecessary* for the `received` time to be a precision
    /// timestamp. As long as the provided value is within ±90 days
    /// of true UTC, the output time will be correct.
    ///
    /// An error is returned if we are unable to calculate
    /// a valid timestamp. This can happen, for example, if we
    /// project a message sent on Julian/Ordinal Day 366 into a
    /// year that is not a leap year.
    ///
    /// The returned datetime is always in one minute increments
    /// with the seconds field set to zero.
    ///
    /// Requires `chrono`.
    #[cfg(feature = "chrono")]
    pub fn issue_datetime(
        &self,
        received: &DateTime<Utc>,
    ) -> Result<DateTime<Utc>, InvalidDateErr> {
        calculate_issue_time(
            self.issue_daytime_fields(),
            (received.year(), received.ordinal()),
        )
    }

    /// Message purge/expiration datetime (UTC)
    ///
    /// Compute the datetime that the SAME message should be
    /// *purged* or discarded. The caller must provide the time
    /// that the message was `received`.
    ///
    /// The returned timestamp is rounded per NWSI 10-1712:
    ///
    /// * For [valid durations](MessageHeader::valid_duration) ≤01h00m,
    ///   the timestamp is rounded to the nearest 15 minutes
    ///
    /// * For valid durations greater than an hour, the timestamp is
    ///   rounded to the nearest 30 minutes
    ///
    /// An error is returned if we are unable to calculate
    /// a valid timestamp. This can happen, for example, if we
    /// project a message sent on Julian/Ordinal Day 366 into a
    /// year that is not a leap year.
    ///
    /// SAME headers do not include the year of issuance. This makes
    /// it impossible to calculate the full datetime of issuance—or
    /// purge, for that matter—without a rough idea of the message's
    /// true UTC time. It is *unnecessary* for the `received` time
    /// to be a precision timestamp. As long as the provided value
    /// is within ±90 days of true UTC, the output time will be
    /// correct.
    ///
    /// This field represents the expiration time of the *message*
    /// and not the expected duration of the severe condition.
    /// **An expired message may still refer to an ongoing hazard** or
    /// event. Expiration merely indicates that the *message* is no
    /// longer valid. Clients are encouraged to retain a history of
    /// alerts and voice message contents.
    ///
    /// Requires `chrono`.
    #[cfg(feature = "chrono")]
    pub fn purge_datetime(
        &self,
        received: &DateTime<Utc>,
    ) -> Result<DateTime<Utc>, InvalidDateErr> {
        calculate_expire_time(&self.issue_datetime(received)?, &self.valid_duration())
    }

    /// Is the message expired?
    ///
    /// Given the current time, determine if this message has
    /// expired. It is assumed that `now` is within ±90 days of
    /// the message's [issuance time](MessageHeader::issue_datetime).
    /// The [maximum duration](https://www.weather.gov/nwr/samealertduration)
    /// of a SAME message is 99.5 hours.
    ///
    /// **An expired message may still refer to an ongoing hazard** or
    /// event. Expiration merely indicates that the *message* is no
    /// longer valid. Clients are encouraged to retain a history of
    /// alerts and voice message contents.
    ///
    /// Requires `chrono`.
    #[cfg(feature = "chrono")]
    pub fn is_expired_at(&self, now: &DateTime<Utc>) -> bool {
        if let Ok(purge) = self.purge_datetime(&now) {
            purge < *now
        } else {
            false
        }
    }

    /// Message issuance day/time (fields)
    ///
    /// Returns the message issue day and time, as the string
    /// `JJJHHMM`,
    ///
    /// - `JJJ`: Ordinal day of the year. `001` represents 1 Jan.,
    ///   and `365` represents 31 Dec. in non leap-years. During
    ///   leap-years, `366` represents 31 Dec. `000` is not used.
    ///   It is up to the receiving station to have some notion
    ///   of what the current year is and to detect calendar
    ///   rollovers.
    ///
    /// - `HHMM`: UTC time of day, using a 24-hour time scale.
    ///   Times are UTC and are **NOT** local times.
    pub fn issue_daytime_fields(&self) -> (u16, u8, u8) {
        let issue = &self.message[self.offset_time + Self::OFFSET_FROMPLUS_ISSUETIME
            ..self.offset_time + Self::OFFSET_FROMPLUS_ISSUETIME + 7];
        (
            issue[0..3].parse().expect(Self::PANIC_MSG),
            issue[3..5].parse().expect(Self::PANIC_MSG),
            issue[5..7].parse().expect(Self::PANIC_MSG),
        )
    }

    /// Sending station callsign
    ///
    /// The FCC or other regulatory body-assigned callsign
    /// of the sending station. Minus signs (`-`) in the
    /// callsign are replaced with slashes (`/`).
    pub fn callsign(&self) -> &str {
        let end = self.message.len();
        &self.message[self.offset_time + Self::OFFSET_FROMPLUS_CALLSIGN
            ..end - Self::OFFSET_FROMEND_CALLSIGN_END]
    }

    /// Count of parity errors
    ///
    /// The number of *bit errors* which were corrected by the
    /// 2-of-3 parity correction algorithm. High parity error
    /// counts indicate a high bit error rate in the receiving
    /// system.
    pub fn parity_error_count(&self) -> usize {
        self.parity_error_count
    }

    /// Number of bytes which were bit-voted
    ///
    /// `voting_byte_count` is the total number of bytes which were
    /// checked via the "two of three" bitwise voting algorithm—i.e.,
    /// the total number of bytes for which all three SAME bursts were
    /// available.
    pub fn voting_byte_count(&self) -> usize {
        self.voting_byte_count
    }

    /// True if the message is a national activation
    ///
    /// Returns true if:
    ///
    /// - the location code in the SAME message indicates
    ///   national applicability; and
    ///
    /// - the event code is reserved for national use
    ///
    /// The message may either be a test or an actual emergency.
    /// Consult the [`event()`](MessageHeader::event) for details.
    ///
    /// Clients are **strongly encouraged** to always play
    /// national-level messages and to never provide the option to
    /// suppress them.
    pub fn is_national(&self) -> bool {
        self.location_str() == Self::LOCATION_NATIONAL && self.event().phenomenon().is_national()
    }

    /// Obtain the owned message String
    ///
    /// Destroys this object and releases the message
    /// contained within
    pub fn release(self) -> String {
        self.message
    }

    /// The location portion of the message string
    fn location_str(&self) -> &str {
        &self.message[Self::OFFSET_AREA_START..self.offset_time]
    }

    const OFFSET_ORG: usize = 5;
    const OFFSET_EVT: usize = 9;
    const OFFSET_AREA_START: usize = 13;
    const OFFSET_FROMPLUS_VALIDTIME: usize = 1;
    const OFFSET_FROMPLUS_ISSUETIME: usize = 6;
    const OFFSET_FROMPLUS_CALLSIGN: usize = 14;
    const OFFSET_FROMEND_CALLSIGN_END: usize = 1;
    const PANIC_MSG: &'static str = "MessageHeader validity check admitted a malformed message";
    const LOCATION_NATIONAL: &'static str = "000000";
}

impl fmt::Display for Message {
    /// Wireline Text Representation
    ///
    /// Outputs UTF-8 string representation: i.e., `ZCZC-...`
    /// for start-of-message or `NNNN` for end-of-message.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.as_str().fmt(f)
    }
}

impl AsRef<str> for Message {
    /// Wireline Text Representation
    ///
    /// Outputs UTF-8 string representation: i.e., `ZCZC-...`
    /// for start-of-message or `NNNN` for end-of-message.
    #[inline]
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl TryFrom<String> for Message {
    type Error = MessageDecodeErr;

    #[inline]
    fn try_from(inp: String) -> Result<Self, Self::Error> {
        if inp.starts_with(PREFIX_MESSAGE_START) {
            Ok(Message::StartOfMessage(MessageHeader::try_from(inp)?))
        } else if inp.starts_with(&PREFIX_MESSAGE_END[0..2]) {
            Ok(Message::EndOfMessage)
        } else {
            Err(MessageDecodeErr::UnrecognizedPrefix)
        }
    }
}

impl TryFrom<(String, &[u8])> for Message {
    type Error = MessageDecodeErr;

    #[inline]
    fn try_from(inp: (String, &[u8])) -> Result<Self, Self::Error> {
        if inp.0.starts_with(PREFIX_MESSAGE_START) {
            Ok(Message::StartOfMessage(MessageHeader::try_from(inp)?))
        } else if inp.0.starts_with(&PREFIX_MESSAGE_END[0..2]) {
            Ok(Message::EndOfMessage)
        } else {
            Err(MessageDecodeErr::UnrecognizedPrefix)
        }
    }
}

impl TryFrom<(&[u8], &[u8], &[u8])> for Message {
    type Error = MessageDecodeErr;

    #[inline]
    fn try_from(inp: (&[u8], &[u8], &[u8])) -> Result<Self, Self::Error> {
        let instr = std::str::from_utf8(inp.0).map_err(|_e| MessageDecodeErr::NotAscii)?;
        if instr.starts_with(PREFIX_MESSAGE_START) {
            Ok(Message::StartOfMessage(MessageHeader::try_from((
                instr.to_owned(),
                inp.1,
                inp.2,
            ))?))
        } else if instr.starts_with(&PREFIX_MESSAGE_END[0..2]) {
            Ok(Message::EndOfMessage)
        } else {
            Err(MessageDecodeErr::UnrecognizedPrefix)
        }
    }
}

impl fmt::Display for MessageHeader {
    /// Wireline Text Representation
    ///
    /// Outputs UTF-8 string representation: i.e., `ZCZC-...`
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.message.fmt(f)
    }
}

impl AsRef<str> for MessageHeader {
    /// Wireline Text Representation
    ///
    /// Outputs UTF-8 string representation: i.e., `ZCZC-...`
    #[inline]
    fn as_ref(&self) -> &str {
        self.message()
    }
}

impl AsRef<[u8]> for MessageHeader {
    /// Wireline Text Representation
    ///
    /// Outputs UTF-8 string representation: i.e., `ZCZC-...`
    #[inline]
    fn as_ref(&self) -> &[u8] {
        self.message().as_bytes()
    }
}

impl From<MessageHeader> for String {
    #[inline]
    fn from(msg: MessageHeader) -> String {
        msg.release()
    }
}

impl TryFrom<String> for MessageHeader {
    type Error = MessageDecodeErr;

    #[inline]
    fn try_from(inp: String) -> Result<Self, Self::Error> {
        Self::new(inp)
    }
}

impl TryFrom<(String, &[u8])> for MessageHeader {
    type Error = MessageDecodeErr;

    #[inline]
    fn try_from(inp: (String, &[u8])) -> Result<Self, Self::Error> {
        Self::new_with_errors(inp.0, inp.1)
    }
}

impl TryFrom<(String, &[u8], &[u8])> for MessageHeader {
    type Error = MessageDecodeErr;

    #[inline]
    fn try_from(inp: (String, &[u8], &[u8])) -> Result<Self, Self::Error> {
        Self::new_with_error_info(inp.0, inp.1, inp.2)
    }
}

const PREFIX_MESSAGE_START: &str = "ZCZC-";
const PREFIX_MESSAGE_END: &str = "NNNN";

// Check message header for basic format compliance
//
// We validate that the message may be split into fields
// correctly, but we do *not* do much validation of the
// fields themselves. Returns tuple of
//
// 1. start position of the purge time field, following
//    the `+`.
// 2. total length of the header. The `hdr` may be longer.
fn check_header(hdr: &str) -> Result<(usize, usize), MessageDecodeErr> {
    lazy_static! {
        static ref RE: Regex = Regex::new(
            r"^ZCZC-[[:alpha:]]{3}-[[:alpha:]]{3}(-[0-9]{6})+(\+[0-9]{4}-[0-9]{7}-.{3,8}-)"
        )
        .expect("bad SAME regexp");
    }

    let mtc = RE
        .captures(hdr)
        .ok_or(MessageDecodeErr::Malformed)?
        .get(2)
        .ok_or(MessageDecodeErr::Malformed)?;

    Ok((mtc.start(), mtc.end()))
}

// Calculate message issuance time
//
// Calculate Utc datetime of message issuance from the
// fields encoded into the `message` and a local estimate
// of when the message was `received`.
#[cfg(feature = "chrono")]
fn calculate_issue_time(
    message: (u16, u8, u8),
    received: (i32, u32),
) -> Result<DateTime<Utc>, InvalidDateErr> {
    let (day_of_year, hour, minute) = message;
    let (rx_year, rx_day_of_year) = received;

    let daydiff = rx_day_of_year as i32 - day_of_year as i32;
    let msg_year = if daydiff >= 180 {
        // message is over 180 days from now, which is unlikely
        // what is more likely is that the UTC new year has
        // arrived and this message is from next year
        rx_year.saturating_add(1)
    } else if daydiff <= -180 {
        // message is over 180 days old, which is unlikely
        // what is more likely is that we have received
        // a message from last UTC year
        rx_year.saturating_sub(1)
    } else {
        // message was received in the current year
        rx_year
    };

    // construct a calendar date
    yo_hms_to_utc(msg_year, day_of_year as u32, hour as u32, minute as u32, 0)
        .ok_or(InvalidDateErr {})
}

/// Calculate message expiration time
#[cfg(feature = "chrono")]
fn calculate_expire_time(
    issued: &DateTime<Utc>,
    purge: &Duration,
) -> Result<DateTime<Utc>, InvalidDateErr> {
    use chrono::DurationRound;

    const FIFTEEN_MINUTES: Duration = Duration::minutes(15);
    const THIRTY_MINUTES: Duration = Duration::minutes(30);
    const ONE_HOUR: Duration = Duration::hours(1);

    issued
        .checked_add_signed(*purge)
        .and_then(|purge_unrounded| {
            if *purge <= ONE_HOUR {
                purge_unrounded.duration_round(FIFTEEN_MINUTES)
            } else {
                purge_unrounded.duration_round(THIRTY_MINUTES)
            }
            .ok()
        })
        .ok_or(InvalidDateErr {})
}

// Create the latest-possible Utc date from year, ordinal, and HMS
#[cfg(feature = "chrono")]
#[inline]
fn yo_hms_to_utc(
    year: i32,
    ordinal: u32,
    hour: u32,
    minute: u32,
    second: u32,
) -> Option<DateTime<Utc>> {
    Some(Utc.from_utc_datetime(
        &NaiveDate::from_yo_opt(year, ordinal)?.and_hms_opt(hour, minute, second)?,
    ))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg(feature = "chrono")]
    use chrono::{TimeZone, Utc};

    #[test]
    fn test_check_header() {
        const INVALID_SHORT: &str = "ZCZC-ORG-EEE-+0000-0001122-NOCALL00-";
        const VALID_ONE: &str = "ZCZC-ORG-EEE-012345+0000-0001122-NOCALL00-";
        const VALID_TWO: &str = "ZCZC-ORG-EEE-012345-567890+0000-0001122-NOCALL00-garbage";

        assert_eq!(
            Err(MessageDecodeErr::Malformed),
            check_header(INVALID_SHORT)
        );

        assert_eq!(Ok((19, 42)), check_header(VALID_ONE));
        assert_eq!(VALID_ONE.as_bytes()[19], '+' as u8);

        assert_eq!(Ok((26, 49)), check_header(VALID_TWO));
        assert_eq!(VALID_TWO.as_bytes()[26], '+' as u8);
    }

    #[test]
    #[cfg(feature = "chrono")]
    fn test_calculate_issue_time() {
        let d = calculate_issue_time((83, 2, 53), (2021, 1)).unwrap();
        assert_eq!(d, Utc.with_ymd_and_hms(2021, 3, 24, 2, 53, 0).unwrap());

        let d = calculate_issue_time((84, 23, 59), (2021, 1)).unwrap();
        assert_eq!(d, Utc.with_ymd_and_hms(2021, 3, 25, 23, 59, 0).unwrap());

        // close to the current year
        let d = calculate_issue_time((1, 10, 00), (2021, 1)).unwrap();
        assert_eq!(d, Utc.with_ymd_and_hms(2021, 1, 1, 10, 00, 0).unwrap());

        // bumps to next year
        let d = calculate_issue_time((1, 10, 00), (2021, 200)).unwrap();
        assert_eq!(d, Utc.with_ymd_and_hms(2022, 1, 1, 10, 00, 0).unwrap());

        // this too
        let d = calculate_issue_time((1, 10, 00), (2021, 365)).unwrap();
        assert_eq!(d, Utc.with_ymd_and_hms(2022, 1, 1, 10, 00, 0).unwrap());

        // reverts to previous year, with leap year support
        let d = calculate_issue_time((366, 10, 00), (2021, 1)).unwrap();
        assert_eq!(d, Utc.with_ymd_and_hms(2020, 12, 31, 10, 00, 0).unwrap());

        // but this doesn't work at all if the year we propagate into
        // is not a leap year
        calculate_issue_time((366, 10, 00), (1971, 364)).expect_err("should not succeed");

        // and ordinal day 0 is totally invalid
        calculate_issue_time((0, 10, 00), (1971, 364)).expect_err("should not succeed");

        // hours invalid
        calculate_issue_time((84, 25, 59), (2021, 84)).expect_err("should not succeed");
    }

    #[cfg(feature = "chrono")]
    #[test]
    fn test_calculate_expire_time_short() {
        const FIFTEEN_MINUTES: Duration = Duration::minutes(15);

        let issued = Utc.with_ymd_and_hms(2021, 3, 24, 2, 44, 0).unwrap();
        assert_eq!(
            Utc.with_ymd_and_hms(2021, 3, 24, 3, 0, 0).unwrap(),
            calculate_expire_time(&issued, &FIFTEEN_MINUTES).unwrap()
        );

        let issued = Utc.with_ymd_and_hms(2021, 3, 24, 2, 46, 0).unwrap();
        assert_eq!(
            Utc.with_ymd_and_hms(2021, 3, 24, 3, 0, 0).unwrap(),
            calculate_expire_time(&issued, &FIFTEEN_MINUTES).unwrap()
        );

        let issued = Utc.with_ymd_and_hms(2021, 3, 24, 2, 55, 0).unwrap();
        assert_eq!(
            Utc.with_ymd_and_hms(2021, 3, 24, 3, 15, 0).unwrap(),
            calculate_expire_time(&issued, &FIFTEEN_MINUTES).unwrap()
        );

        let issued = Utc.with_ymd_and_hms(2021, 3, 24, 3, 00, 0).unwrap();
        assert_eq!(
            Utc.with_ymd_and_hms(2021, 3, 24, 3, 15, 0).unwrap(),
            calculate_expire_time(&issued, &FIFTEEN_MINUTES).unwrap()
        );
    }

    #[cfg(feature = "chrono")]
    #[test]
    fn test_calculate_expire_time_long() {
        let issued = Utc.with_ymd_and_hms(2021, 3, 24, 2, 53, 0).unwrap();

        assert_eq!(
            Utc.with_ymd_and_hms(2021, 3, 24, 3, 15, 0).unwrap(),
            calculate_expire_time(&issued, &Duration::minutes(15)).unwrap()
        );

        assert_eq!(
            Utc.with_ymd_and_hms(2021, 3, 24, 3, 30, 0).unwrap(),
            calculate_expire_time(&issued, &Duration::minutes(30)).unwrap()
        );

        assert_eq!(
            Utc.with_ymd_and_hms(2021, 3, 24, 3, 45, 0).unwrap(),
            calculate_expire_time(&issued, &Duration::minutes(45)).unwrap()
        );

        assert_eq!(
            Utc.with_ymd_and_hms(2021, 3, 24, 4, 00, 0).unwrap(),
            calculate_expire_time(&issued, &Duration::minutes(60)).unwrap()
        );
    }

    #[test]
    fn test_message_header() {
        const THREE_LOCATIONS: &str = "ZCZC-WXR-RWT-012345-567890-888990+0330-3662322-NOCALL00-@@@";

        let mut errs = vec![0u8; THREE_LOCATIONS.len()];
        errs[0] = 1u8;
        errs[20] = 5u8;
        errs[THREE_LOCATIONS.len() - 1] = 8u8;

        let burst_count = vec![3u8; THREE_LOCATIONS.len()];

        let msg = MessageHeader::try_from((
            THREE_LOCATIONS.to_owned(),
            errs.as_slice(),
            burst_count.as_slice(),
        ))
        .expect("bad msg");

        assert_eq!(msg.originator_str(), "WXR");
        assert_eq!(Originator::NationalWeatherService, msg.originator());
        assert_eq!(msg.event_str(), "RWT");
        assert_eq!(msg.event().phenomenon(), Phenomenon::RequiredWeeklyTest);
        assert_eq!(msg.valid_duration_fields(), (3, 30));
        assert_eq!(msg.issue_daytime_fields(), (366, 23, 22));
        assert_eq!(msg.callsign(), "NOCALL00");
        assert_eq!(msg.parity_error_count(), 6);
        assert_eq!(msg.voting_byte_count(), msg.as_str().len());
        assert!(!msg.is_national());

        let loc: Vec<&str> = msg.location_str_iter().collect();
        assert_eq!(loc.as_slice(), &["012345", "567890", "888990"]);

        // time API checks
        #[cfg(feature = "chrono")]
        {
            // mock system time that the message was received
            let received = Utc.with_ymd_and_hms(2020, 12, 31, 11, 30, 34).unwrap();

            assert_eq!(
                Utc.with_ymd_and_hms(2020, 12, 31, 23, 22, 00).unwrap(),
                msg.issue_datetime(&received).unwrap()
            );
            assert_eq!(
                msg.valid_duration(),
                Duration::hours(3) + Duration::minutes(30)
            );
            assert_eq!(
                Utc.with_ymd_and_hms(2021, 1, 1, 3, 0, 00).unwrap(),
                msg.purge_datetime(&received).unwrap()
            );
            assert!(!msg.is_expired_at(&Utc.with_ymd_and_hms(2020, 12, 31, 23, 59, 0).unwrap()));
            assert!(!msg.is_expired_at(&Utc.with_ymd_and_hms(2021, 1, 1, 1, 20, 30).unwrap()));
            assert!(!msg.is_expired_at(&Utc.with_ymd_and_hms(2021, 1, 1, 2, 59, 59).unwrap()));
            assert!(msg.is_expired_at(&Utc.with_ymd_and_hms(2021, 1, 1, 3, 0, 01).unwrap()));
        }

        // try again via Message
        let msg = Message::try_from(THREE_LOCATIONS.to_owned()).expect("bad msg");
        match &msg {
            Message::StartOfMessage(m) => assert_eq!(m.issue_daytime_fields(), (366, 23, 22)),
            _ => unreachable!(),
        }
        assert_eq!(&THREE_LOCATIONS[0..56], &format!("{}", msg));
    }

    #[test]
    fn test_message() {
        let msg = Message::try_from("NNNN".to_owned()).expect("bad msg");
        assert_eq!(Message::EndOfMessage, msg);
        assert_eq!("NNNN", &format!("{}", msg));

        let msg = Message::try_from("NN".to_owned()).expect("bad msg");
        assert_eq!(Message::EndOfMessage, msg);
    }

    #[test]
    fn test_is_national() {
        let national = MessageHeader::new("ZCZC-PEP-NPT-000000+0030-2771820-TEST    -").unwrap();
        assert!(national.is_national());

        let national = MessageHeader::new("ZCZC-PEP-EAN-000000+0030-2771820-TEST    -").unwrap();
        assert!(national.is_national());

        let not_national =
            MessageHeader::new("ZCZC-PEP-NPT-000001+0030-2771820-TEST    -").unwrap();
        assert!(!not_national.is_national());

        let not_national =
            MessageHeader::new("ZCZC-PEP-NPT-000000-000001+0030-2771820-TEST    -").unwrap();
        assert!(!not_national.is_national());
    }
}