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
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
use chrono::{Datelike, Timelike};

#[cfg(feature = "alloc")]
use alloc::format;

#[cfg(feature = "alloc")]
use alloc::borrow::ToOwned;

#[cfg(not(feature = "std"))]
use num_traits::Float;

#[cfg(feature = "serde")]
use serde::de::Deserialize;

/// TLE error
#[derive(Debug, Clone)]
pub enum ErrorTleWhat {
    /// Incorrect line checksum
    BadChecksum,

    /// Incorrect line length
    BadLength,

    /// Incorrect first character
    BadFirstCharacter,

    /// Parsing a float field failed
    ExpectedFloat,

    /// Parsing a float field failed (special TLE float representation with assumed decimal point)
    ExpectedFloatWithAssumedDecimalPoint,

    /// Parsing an integer field failed
    ExpectedInteger,

    /// Found a non-space character between fields
    ExpectedSpace,

    /// Parsing a string field failed
    ExpectedString,

    /// Tried to parse a float (special TLE float representation with assumed decimal point)
    /// with more than 16 ASCII characters
    FloatWithAssumedDecimalPointTooLong,

    /// NORAD mismatch between TLE lines
    NoradIdMismatch,

    /// Unknown classification code
    UnknownClassification,
}

/// Input line where a parse error was found
#[derive(Debug, Clone)]
pub enum ErrorTleLine {
    /// First TLE line (without taking the title line into account)
    Line1,

    /// Second TLE line (without taking the title line into account)
    Line2,

    /// The error is the result of a mismatch between lines
    Both,
}

/// Represents an SGP4 error
///
/// Errors can result from corrupted TLEs or if one of the orbital elements diverges during propagation.
#[derive(Debug, Clone)]
pub enum Error {
    /// The epoch eccentricity is outside the range [0, 1[
    OutOfRangeEpochEccentricity {
        /// Eccentricity value (unitless)
        eccentricity: f64,
    },

    /// The propagated eccentricity is outside the range [0, 1[ (before adding third-body perturbations)
    OutOfRangeEccentricity {
        /// Eccentricity value (unitless)
        eccentricity: f64,

        /// Minutes since epoch
        t: f64,
    },

    /// The propagated eccentricity is outside the range [0, 1[ (after adding third-body perturbations)
    OutOfRangePerturbedEccentricity {
        /// Eccentricity value (unitless)
        eccentricity: f64,

        /// Minutes since epoch
        t: f64,
    },

    /// The Brouwer mean motion calculated from epoch elements is negative
    NegativeBrouwerMeanMotion,

    /// The Kozai mean motion calculated from epoch elements is negative
    NegativeKozaiMeanMotion,

    /// The propagated semi-latus rectum is negative
    NegativeSemiLatusRectum {
        /// Minutes since epoch
        t: f64,
    },

    /// TLE parse error
    Tle {
        /// TLE error type
        what: ErrorTleWhat,

        /// TLE error line
        line: ErrorTleLine,

        /// Start character position of the line slice that caused the error
        start: usize,

        /// End character position of the line slice that caused the error
        end: usize,
    },
}

/// The result type returned by SGP4 functions
pub type Result<T> = core::result::Result<T, Error>;

#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
impl From<Error> for anyhow::Error {
    fn from(error: Error) -> Self {
        anyhow::Error::msg(match error {
            Error::OutOfRangeEpochEccentricity{eccentricity} => format!(
                "the eccentricity ({}) is outside the range [0, 1[ at epoch",
                eccentricity
            ),
            Error::OutOfRangeEccentricity{eccentricity, t} => format!(
                "the eccentricity without third-body perturbations ({}) is outside the range [0, 1[ {} min after epoch",
                eccentricity,
                t,
            ),
            Error::OutOfRangePerturbedEccentricity{eccentricity, t} => format!(
                "the eccentricity with third-body perturbations ({}) is outside the range [0, 1[ {} min after epoch",
                eccentricity,
                t,
            ),
            Error::NegativeBrouwerMeanMotion => "the Brouwer mean motion is negative".to_owned(),
            Error::NegativeKozaiMeanMotion => "the Kozai mean motion is negative".to_owned(),
            Error::NegativeSemiLatusRectum {t} => format!("the semi-latus rectum is negative {} min after epoch", t),
            Error::Tle {what, line, start, end} => format!("{} ({}..{}): {}",
                match line {
                    ErrorTleLine::Line1 => "TLE line 1",
                    ErrorTleLine::Line2 => "TLE line 2",
                    ErrorTleLine::Both => "TLE lines mismatch",
                },
                start,
                end,
                match what {
                    ErrorTleWhat::BadChecksum => "bad checksum",
                    ErrorTleWhat::BadLength => "bad length",
                    ErrorTleWhat::BadFirstCharacter => "bad first character",
                    ErrorTleWhat::ExpectedFloat => "expected a float",
                    ErrorTleWhat::ExpectedFloatWithAssumedDecimalPoint  => "expected a float with assumed decimal point",
                    ErrorTleWhat::ExpectedInteger => "expected an integer",
                    ErrorTleWhat::ExpectedSpace => "expected a space",
                    ErrorTleWhat::ExpectedString => "expected a string",
                    ErrorTleWhat::FloatWithAssumedDecimalPointTooLong => "the float with assumed decimal point is too long",
                    ErrorTleWhat::NoradIdMismatch => "the NORAD ids are different",
                    ErrorTleWhat::UnknownClassification => "unknown classification",
                }
            )
        })
    }
}

trait TrimStart {
    fn trim_ascii_start_polyfill(&self) -> &[u8];
}

impl TrimStart for [u8] {
    fn trim_ascii_start_polyfill(&self) -> &[u8] {
        let mut bytes = self;
        while let [first, rest @ ..] = bytes {
            if first.is_ascii_whitespace() {
                bytes = rest;
            } else {
                break;
            }
        }
        bytes
    }
}

trait FromU8: Sized {
    type Err;
    fn from_u8(s: &[u8]) -> core::result::Result<Self, Self::Err>;
}

impl FromU8 for i8 {
    type Err = core::num::ParseIntError;
    fn from_u8(s: &[u8]) -> core::result::Result<Self, Self::Err> {
        // SAFETY: parse calls from_str_radix which converts back to bytes.
        unsafe { core::str::from_utf8_unchecked(s) }.parse()
    }
}

impl FromU8 for u8 {
    type Err = core::num::ParseIntError;
    fn from_u8(s: &[u8]) -> core::result::Result<Self, Self::Err> {
        // SAFETY: parse calls from_str_radix which converts back to bytes.
        unsafe { core::str::from_utf8_unchecked(s) }.parse()
    }
}

impl FromU8 for u64 {
    type Err = core::num::ParseIntError;
    fn from_u8(s: &[u8]) -> core::result::Result<Self, Self::Err> {
        // SAFETY: parse calls from_str_radix which converts back to bytes.
        unsafe { core::str::from_utf8_unchecked(s) }.parse()
    }
}
impl FromU8 for f64 {
    type Err = core::num::ParseFloatError;
    fn from_u8(s: &[u8]) -> core::result::Result<Self, Self::Err> {
        // SAFETY: parse calls dec2flt which converts back to bytes.
        unsafe { core::str::from_utf8_unchecked(s) }.parse()
    }
}

trait Parse {
    fn parse<F: FromU8>(&self) -> core::result::Result<F, F::Err>;
}

impl Parse for [u8] {
    fn parse<F: FromU8>(&self) -> core::result::Result<F, F::Err> {
        FromU8::from_u8(self)
    }
}

trait DecimalPointAssumedRepresentation {
    fn parse_decimal_point_assumed(
        &self,
        line: ErrorTleLine,
        start: usize,
        end: usize,
    ) -> Result<f64>;
}

impl DecimalPointAssumedRepresentation for [u8] {
    fn parse_decimal_point_assumed(
        &self,
        line: ErrorTleLine,
        start: usize,
        end: usize,
    ) -> Result<f64> {
        let trimmed = self.trim_ascii_start_polyfill();
        if trimmed.is_empty() {
            return Err(Error::Tle {
                what: ErrorTleWhat::ExpectedFloatWithAssumedDecimalPoint,
                line,
                start,
                end,
            });
        }
        let mut raw_buffer = [0_u8; 16];
        let length;
        if trimmed[0] == b'-' {
            if trimmed.len() < 2 || trimmed.len() + 1 > raw_buffer.len() {
                return Err(Error::Tle {
                    what: ErrorTleWhat::FloatWithAssumedDecimalPointTooLong,
                    line,
                    start,
                    end,
                });
            }
            raw_buffer[0] = b'-';
            raw_buffer[1] = b'.';
            raw_buffer[2..trimmed.len() + 1].copy_from_slice(&trimmed[1..]);
            length = trimmed.len() + 1;
        } else if trimmed[0] == b'+' {
            if trimmed.len() < 2 || trimmed.len() > raw_buffer.len() {
                return Err(Error::Tle {
                    what: ErrorTleWhat::FloatWithAssumedDecimalPointTooLong,
                    line,
                    start,
                    end,
                });
            }
            raw_buffer[0] = b'.';
            raw_buffer[1..trimmed.len()].copy_from_slice(&trimmed[1..]);
            length = trimmed.len();
        } else {
            if trimmed.len() + 1 > raw_buffer.len() {
                return Err(Error::Tle {
                    what: ErrorTleWhat::FloatWithAssumedDecimalPointTooLong,
                    line,
                    start,
                    end,
                });
            }
            raw_buffer[0] = b'.';
            raw_buffer[1..trimmed.len() + 1].copy_from_slice(trimmed);
            length = trimmed.len() + 1;
        }
        // SAFETY: parse calls dec2flt which immediately converts back to bytes.
        raw_buffer[0..length]
            .parse::<f64>()
            .map_err(|_| Error::Tle {
                what: ErrorTleWhat::ExpectedFloatWithAssumedDecimalPoint,
                line,
                start,
                end,
            })
    }
}

/// A satellite's elements classification
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Classification {
    /// Declassfied objects or objects without a classification
    #[cfg_attr(feature = "serde", serde(rename = "U"))]
    Unclassified,

    /// Would cause "serious damage" to national security if it were publicly available
    #[cfg_attr(feature = "serde", serde(rename = "C"))]
    Classified,

    /// Would cause "damage" or be prejudicial to national security if publicly available
    #[cfg_attr(feature = "serde", serde(rename = "S"))]
    Secret,
}

/// General perturbations orbital data parsed from a TLE or OMM
///
/// Elements can be retrieved from either a Two-Line Element Set (TLE) or an Orbit Mean-Elements Message (OMM).
/// See [https://celestrak.com/NORAD/documentation/gp-data-formats.php](https://celestrak.com/NORAD/documentation/gp-data-formats.php)
/// for more information on the difference between the two formats.
///
/// The fields' documentation is adapted from [https://spaceflight.nasa.gov/realdata/sightings/SSapplications/Post/JavaSSOP/SSOP_Help/tle_def.html](https://spaceflight.nasa.gov/realdata/sightings/SSapplications/Post/JavaSSOP/SSOP_Help/tle_def.html).
///
/// See [sgp4::Elements::from_tle](struct.Elements.html#method.from_tle) to parse a TLE.
///
/// `serde_json` can be used to parse a JSON OMM object (into a `sgp4::Elements`)
///  or a JSON list of OMM objects (into a `Vec<sgp4::Elements>`).
///
/// # Example
/// ```
/// # fn main() -> anyhow::Result<()> {
/// let elements: sgp4::Elements = serde_json::from_str(
///     r#"{
///         "OBJECT_NAME": "ISS (ZARYA)",
///         "OBJECT_ID": "1998-067A",
///         "EPOCH": "2020-07-12T01:19:07.402656",
///         "MEAN_MOTION": 15.49560532,
///         "ECCENTRICITY": 0.0001771,
///         "INCLINATION": 51.6435,
///         "RA_OF_ASC_NODE": 225.4004,
///         "ARG_OF_PERICENTER": 44.9625,
///         "MEAN_ANOMALY": 5.1087,
///         "EPHEMERIS_TYPE": 0,
///         "CLASSIFICATION_TYPE": "U",
///         "NORAD_CAT_ID": 25544,
///         "ELEMENT_SET_NO": 999,
///         "REV_AT_EPOCH": 23587,
///         "BSTAR": 0.0049645,
///         "MEAN_MOTION_DOT": 0.00289036,
///         "MEAN_MOTION_DDOT": 0
///     }"#,
/// )?;
/// #     Ok(())
/// # }
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Elements {
    /// The name associated with the satellite
    #[cfg_attr(
        all(feature = "alloc", feature = "serde"),
        serde(rename = "OBJECT_NAME")
    )]
    #[cfg(feature = "alloc")]
    #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
    pub object_name: Option<alloc::string::String>,

    /// The satellite's international designator
    ///
    /// It consists of the launch year, the launch number of that year and
    /// a letter code representing the sequential identifier of a piece in a launch.
    #[cfg_attr(all(feature = "alloc", feature = "serde"), serde(rename = "OBJECT_ID"))]
    #[cfg(feature = "alloc")]
    #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
    pub international_designator: Option<alloc::string::String>,

    /// The catalog number USSPACECOM has designated for this object
    #[cfg_attr(
        feature = "serde",
        serde(rename = "NORAD_CAT_ID", deserialize_with = "u64_or_string")
    )]
    pub norad_id: u64,

    /// The elements' classification
    #[cfg_attr(feature = "serde", serde(rename = "CLASSIFICATION_TYPE"))]
    pub classification: Classification,

    /// The UTC timestamp of the elements
    #[cfg_attr(feature = "serde", serde(rename = "EPOCH"))]
    pub datetime: chrono::naive::NaiveDateTime,

    /// Time derivative of the mean motion
    #[cfg_attr(
        feature = "serde",
        serde(rename = "MEAN_MOTION_DOT", deserialize_with = "f64_or_string")
    )]
    pub mean_motion_dot: f64,

    /// Second time derivative of the mean motion
    #[cfg_attr(
        feature = "serde",
        serde(rename = "MEAN_MOTION_DDOT", deserialize_with = "f64_or_string")
    )]
    pub mean_motion_ddot: f64,

    /// Radiation pressure coefficient in earth radii⁻¹
    #[cfg_attr(
        feature = "serde",
        serde(rename = "BSTAR", deserialize_with = "f64_or_string")
    )]
    pub drag_term: f64,

    /// A running count of all 2 line element sets generated by USSPACECOM for this object
    #[cfg_attr(
        feature = "serde",
        serde(rename = "ELEMENT_SET_NO", deserialize_with = "u64_or_string")
    )]
    pub element_set_number: u64,

    /// Angle between the equator and the orbit plane in deg
    #[cfg_attr(
        feature = "serde",
        serde(rename = "INCLINATION", deserialize_with = "f64_or_string")
    )]
    pub inclination: f64,

    /// Angle between vernal equinox and the point where the orbit crosses the equatorial plane in deg
    #[cfg_attr(
        feature = "serde",
        serde(rename = "RA_OF_ASC_NODE", deserialize_with = "f64_or_string")
    )]
    pub right_ascension: f64,

    /// The shape of the orbit
    #[cfg_attr(
        feature = "serde",
        serde(rename = "ECCENTRICITY", deserialize_with = "f64_or_string")
    )]
    pub eccentricity: f64,

    /// Angle between the ascending node and the orbit's point of closest approach to the earth in deg
    #[cfg_attr(
        feature = "serde",
        serde(rename = "ARG_OF_PERICENTER", deserialize_with = "f64_or_string")
    )]
    pub argument_of_perigee: f64,

    /// Angle of the satellite location measured from perigee in deg
    #[cfg_attr(
        feature = "serde",
        serde(rename = "MEAN_ANOMALY", deserialize_with = "f64_or_string")
    )]
    pub mean_anomaly: f64,

    /// Mean number of orbits per day in day⁻¹ (Kozai convention)
    #[cfg_attr(
        feature = "serde",
        serde(rename = "MEAN_MOTION", deserialize_with = "f64_or_string")
    )]
    pub mean_motion: f64,

    /// The orbit number at epoch
    #[cfg_attr(
        feature = "serde",
        serde(rename = "REV_AT_EPOCH", deserialize_with = "u64_or_string")
    )]
    pub revolution_number: u64,

    /// NORAD internal use, always 0 in distributed data
    #[cfg_attr(
        feature = "serde",
        serde(rename = "EPHEMERIS_TYPE", deserialize_with = "u8_or_string")
    )]
    pub ephemeris_type: u8,
}

#[cfg(feature = "serde")]
fn u64_or_string<'de, D>(deserializer: D) -> core::result::Result<u64, D::Error>
where
    D: serde::de::Deserializer<'de>,
{
    match serde_json::value::Value::deserialize(deserializer)? {
        serde_json::value::Value::Number(number) => number
            .as_u64()
            .ok_or_else(|| serde::de::Error::custom("parsing the number as u64 failed")),
        serde_json::value::Value::String(string) => {
            string.parse().map_err(serde::de::Error::custom)
        }
        _ => Err(serde::de::Error::custom("expected a u64 or string")),
    }
}

#[cfg(feature = "serde")]
fn u8_or_string<'de, D>(deserializer: D) -> core::result::Result<u8, D::Error>
where
    D: serde::de::Deserializer<'de>,
{
    match serde_json::value::Value::deserialize(deserializer)? {
        serde_json::value::Value::Number(number) => match number.as_u64() {
            Some(value) => Ok(value as u8),
            None => Err(serde::de::Error::custom("parsing the number as u64 failed")),
        },
        serde_json::value::Value::String(string) => {
            string.parse().map_err(serde::de::Error::custom)
        }
        _ => Err(serde::de::Error::custom("expected a u64 or string")),
    }
}

#[cfg(feature = "serde")]
fn f64_or_string<'de, D>(deserializer: D) -> core::result::Result<f64, D::Error>
where
    D: serde::de::Deserializer<'de>,
{
    match serde_json::value::Value::deserialize(deserializer)? {
        serde_json::value::Value::Number(number) => number
            .as_f64()
            .ok_or_else(|| serde::de::Error::custom("parsing the number as f64 failed")),
        serde_json::value::Value::String(string) => {
            string.parse().map_err(serde::de::Error::custom)
        }
        _ => Err(serde::de::Error::custom("expected a f64 or string")),
    }
}

impl Elements {
    fn from_lines(line1: &[u8], line2: &[u8]) -> Result<Elements> {
        if line1.len() != 69 {
            return Err(Error::Tle {
                what: ErrorTleWhat::BadLength,
                line: ErrorTleLine::Line1,
                start: 0,
                end: line1.len(),
            });
        }
        if line2.len() != 69 {
            return Err(Error::Tle {
                what: ErrorTleWhat::BadLength,
                line: ErrorTleLine::Line2,
                start: 0,
                end: line2.len(),
            });
        }
        if line1[0] != b'1' {
            return Err(Error::Tle {
                what: ErrorTleWhat::BadFirstCharacter,
                line: ErrorTleLine::Line1,
                start: 0,
                end: 1,
            });
        }
        if line2[0] != b'2' {
            return Err(Error::Tle {
                what: ErrorTleWhat::BadFirstCharacter,
                line: ErrorTleLine::Line2,
                start: 0,
                end: 1,
            });
        }
        for index in [1, 8, 17, 32, 43, 52, 61, 63].iter() {
            if line1[*index] != b' ' {
                return Err(Error::Tle {
                    what: ErrorTleWhat::ExpectedSpace,
                    line: ErrorTleLine::Line1,
                    start: *index,
                    end: *index + 1,
                });
            }
        }
        for index in [1, 7, 16, 25, 33, 42, 51].iter() {
            if line2[*index] != b' ' {
                return Err(Error::Tle {
                    what: ErrorTleWhat::ExpectedSpace,
                    line: ErrorTleLine::Line2,
                    start: *index,
                    end: *index + 1,
                });
            }
        }
        let norad_id = line1[2..7]
            .trim_ascii_start_polyfill()
            .parse::<u64>()
            .map_err(|_| Error::Tle {
                what: ErrorTleWhat::ExpectedInteger,
                line: ErrorTleLine::Line1,
                start: 2,
                end: 7,
            })?;
        if norad_id
            != line2[2..7]
                .trim_ascii_start_polyfill()
                .parse::<u64>()
                .map_err(|_| Error::Tle {
                    what: ErrorTleWhat::ExpectedInteger,
                    line: ErrorTleLine::Line2,
                    start: 2,
                    end: 7,
                })?
        {
            return Err(Error::Tle {
                what: ErrorTleWhat::NoradIdMismatch,
                line: ErrorTleLine::Both,
                start: 2,
                end: 7,
            });
        }
        for (line, content) in [(ErrorTleLine::Line1, &line1), (ErrorTleLine::Line2, &line2)] {
            if (content[..68]
                .iter()
                .fold(0, |accumulator, character| match character {
                    b'-' => accumulator + 1,
                    character if (&b'0'..=&b'9').contains(&character) => {
                        accumulator + (character - b'0') as u16
                    }
                    _ => accumulator,
                })
                % 10) as u8
                != content[68] - b'0'
            {
                return Err(Error::Tle {
                    what: ErrorTleWhat::BadChecksum,
                    line,
                    start: 68,
                    end: 69,
                });
            }
        }
        Ok(Elements {
            #[cfg(feature = "alloc")]
            object_name: None,
            norad_id,
            classification: match line1[7] {
                b'U' => Classification::Unclassified,
                b'C' => Classification::Classified,
                b'S' => Classification::Secret,
                _ => {
                    return Err(Error::Tle {
                        what: ErrorTleWhat::UnknownClassification,
                        line: ErrorTleLine::Line1,
                        start: 7,
                        end: 8,
                    })
                }
            },
            #[cfg(feature = "alloc")]
            international_designator: if line1[9..17]
                .iter()
                .all(|character| character.is_ascii_whitespace())
            {
                None
            } else {
                Some(format!(
                    "{}-{}",
                    match line1[9..11].parse::<u8>().map_err(|_| Error::Tle {
                        what: ErrorTleWhat::ExpectedInteger,
                        line: ErrorTleLine::Line1,
                        start: 9,
                        end: 11,
                    })? {
                        launch_year if launch_year < 57 => 2000 + launch_year as u16,
                        launch_year => 1900 + launch_year as u16,
                    },
                    core::str::from_utf8(&line1[11..17])
                        .map_err(|_| Error::Tle {
                            what: ErrorTleWhat::ExpectedString,
                            line: ErrorTleLine::Line1,
                            start: 11,
                            end: 17,
                        })?
                        .trim()
                ))
            },
            datetime: {
                let day = line1[20..32]
                    .trim_ascii_start_polyfill()
                    .parse::<f64>()
                    .map_err(|_| Error::Tle {
                        what: ErrorTleWhat::ExpectedFloat,
                        line: ErrorTleLine::Line1,
                        start: 20,
                        end: 32,
                    })?;
                let seconds = day.fract() * (24.0 * 60.0 * 60.0);
                chrono::NaiveDate::from_yo(
                    match line1[18..20].parse::<u8>().map_err(|_| Error::Tle {
                        what: ErrorTleWhat::ExpectedFloat,
                        line: ErrorTleLine::Line1,
                        start: 18,
                        end: 20,
                    })? {
                        year if year < 57 => year as i32 + 2000,
                        year => year as i32 + 1900,
                    },
                    day as u32,
                )
                .and_time(chrono::NaiveTime::from_num_seconds_from_midnight(
                    seconds as u32,
                    (seconds.fract() * 1e9).round() as u32,
                ))
            },
            mean_motion_dot: line1[33..43]
                .trim_ascii_start_polyfill()
                .parse()
                .map_err(|_| Error::Tle {
                    what: ErrorTleWhat::ExpectedFloat,
                    line: ErrorTleLine::Line1,
                    start: 33,
                    end: 43,
                })?,
            mean_motion_ddot: line1[44..50].parse_decimal_point_assumed(
                ErrorTleLine::Line1,
                44,
                50,
            )? * 10.0_f64.powi(line1[50..52].parse::<i8>().map_err(|_| {
                Error::Tle {
                    what: ErrorTleWhat::ExpectedFloat,
                    line: ErrorTleLine::Line1,
                    start: 50,
                    end: 52,
                }
            })? as i32),
            drag_term: line1[53..59].parse_decimal_point_assumed(ErrorTleLine::Line1, 53, 59)?
                * 10.0_f64.powi(line1[59..61].parse::<i8>().map_err(|_| Error::Tle {
                    what: ErrorTleWhat::ExpectedFloat,
                    line: ErrorTleLine::Line1,
                    start: 59,
                    end: 61,
                })? as i32),
            ephemeris_type: line1[62..63]
                .trim_ascii_start_polyfill()
                .parse()
                .map_err(|_| Error::Tle {
                    what: ErrorTleWhat::ExpectedInteger,
                    line: ErrorTleLine::Line1,
                    start: 62,
                    end: 63,
                })?,
            element_set_number: line1[64..68].trim_ascii_start_polyfill().parse().map_err(
                |_| Error::Tle {
                    what: ErrorTleWhat::ExpectedInteger,
                    line: ErrorTleLine::Line1,
                    start: 64,
                    end: 68,
                },
            )?,
            inclination: line2[8..16]
                .trim_ascii_start_polyfill()
                .parse()
                .map_err(|_| Error::Tle {
                    what: ErrorTleWhat::ExpectedFloat,
                    line: ErrorTleLine::Line2,
                    start: 8,
                    end: 16,
                })?,
            right_ascension: line2[17..25]
                .trim_ascii_start_polyfill()
                .parse()
                .map_err(|_| Error::Tle {
                    what: ErrorTleWhat::ExpectedFloat,
                    line: ErrorTleLine::Line2,
                    start: 17,
                    end: 25,
                })?,
            eccentricity: line2[26..33].parse_decimal_point_assumed(ErrorTleLine::Line2, 26, 33)?,
            argument_of_perigee: line2[34..42].trim_ascii_start_polyfill().parse().map_err(
                |_| Error::Tle {
                    what: ErrorTleWhat::ExpectedFloat,
                    line: ErrorTleLine::Line2,
                    start: 34,
                    end: 42,
                },
            )?,
            mean_anomaly: line2[43..51]
                .trim_ascii_start_polyfill()
                .parse()
                .map_err(|_| Error::Tle {
                    what: ErrorTleWhat::ExpectedFloat,
                    line: ErrorTleLine::Line2,
                    start: 43,
                    end: 51,
                })?,
            mean_motion: line2[52..63]
                .trim_ascii_start_polyfill()
                .parse()
                .map_err(|_| Error::Tle {
                    what: ErrorTleWhat::ExpectedFloat,
                    line: ErrorTleLine::Line2,
                    start: 52,
                    end: 63,
                })?,
            revolution_number: line2[63..68]
                .trim_ascii_start_polyfill()
                .parse()
                .map_err(|_| Error::Tle {
                    what: ErrorTleWhat::ExpectedInteger,
                    line: ErrorTleLine::Line2,
                    start: 63,
                    end: 68,
                })?,
        })
    }

    /// Parses a Two-Line Element Set (TLE) with an optionnal title
    ///
    /// # Arguments
    ///
    /// * `object_name` - The name of the satellite, usually given by a third line placed before the TLE
    /// * `line1` - The first line of the TLE composed of 69 ASCII characters
    /// * `line2` - The second line of the TLE composed of 69 ASCII characters
    ///
    /// # Example
    ///
    /// ```
    /// # fn main() -> sgp4::Result<()> {
    /// let elements = sgp4::Elements::from_tle(
    ///     Some("ISS (ZARYA)".to_owned()),
    ///     "1 25544U 98067A   08264.51782528 -.00002182  00000-0 -11606-4 0  2927".as_bytes(),
    ///     "2 25544  51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537".as_bytes(),
    /// )?;
    /// #     Ok(())
    /// # }
    /// ```
    #[cfg(feature = "alloc")]
    pub fn from_tle(
        object_name: Option<alloc::string::String>,
        line1: &[u8],
        line2: &[u8],
    ) -> Result<Elements> {
        let mut result = Self::from_lines(line1, line2)?;
        result.object_name = object_name;
        Ok(result)
    }

    #[cfg(not(feature = "alloc"))]
    pub fn from_tle(line1: &[u8], line2: &[u8]) -> Result<Elements> {
        Self::from_lines(line1, line2)
    }

    /// Returns the number of years since UTC 1 January 2000 12h00 (J2000)
    ///
    /// This is the recommended method to calculate the epoch
    pub fn epoch(&self) -> f64 {
        // y₂₀₀₀ = (367 yᵤ - ⌊7 (yᵤ + ⌊(mᵤ + 9) / 12⌋) / 4⌋ + 275 ⌊mᵤ / 9⌋ + dᵤ - 730531) / 365.25
        //         + (3600 hᵤ + 60 minᵤ + sᵤ - 43200) / (24 × 60 × 60 × 365.25)
        //         + nsᵤ / (24 × 60 × 60 × 365.25 × 10⁹)
        (367 * self.datetime.year() as i32
            - (7 * (self.datetime.year() as i32 + (self.datetime.month() as i32 + 9) / 12)) / 4
            + 275 * self.datetime.month() as i32 / 9
            + self.datetime.day() as i32
            - 730531) as f64
            / 365.25
            + (self.datetime.num_seconds_from_midnight() as i32 - 43200) as f64
                / (24.0 * 60.0 * 60.0 * 365.25)
            + (self.datetime.nanosecond() as f64) / (24.0 * 60.0 * 60.0 * 1e9 * 365.25)
    }

    /// Returns the number of years since UTC 1 January 2000 12h00 (J2000) using the AFSPC expression
    ///
    /// This function should be used if compatibility with the AFSPC implementation is needed
    pub fn epoch_afspc_compatibility_mode(&self) -> f64 {
        // y₂₀₀₀ = (367 yᵤ - ⌊7 (yᵤ + ⌊(mᵤ + 9) / 12⌋) / 4⌋ + 275 ⌊mᵤ / 9⌋ + dᵤ
        //         + 1721013.5
        //         + (((nsᵤ / 10⁹ + sᵤ) / 60 + minᵤ) / 60 + hᵤ) / 24
        //         - 2451545)
        //         / 365.25
        ((367 * self.datetime.year() as u32
            - (7 * (self.datetime.year() as u32 + (self.datetime.month() + 9) / 12)) / 4
            + 275 * self.datetime.month() / 9
            + self.datetime.day()) as f64
            + 1721013.5
            + (((self.datetime.nanosecond() as f64 / 1e9 + self.datetime.second() as f64) / 60.0
                + self.datetime.minute() as f64)
                / 60.0
                + self.datetime.hour() as f64)
                / 24.0
            - 2451545.0)
            / 365.25
    }
}

/// Parses a multi-line TL/2LE string into a list of `Elements`
///
/// Each pair of lines must represent a TLE, for example as in
/// [https://celestrak.com/NORAD/elements/gp.php?GROUP=stations&FORMAT=2le](https://celestrak.com/NORAD/elements/gp.php?GROUP=stations&FORMAT=2le).
///
/// # Arguments
///
/// * `tles` - A string containing multiple lines
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn parse_2les(tles: &str) -> Result<alloc::vec::Vec<Elements>> {
    let mut line_buffer = "";
    let mut first = true;
    let mut elements_group = alloc::vec::Vec::new();
    for line in tles.lines() {
        if first {
            line_buffer = line;
        } else {
            elements_group.push(Elements::from_tle(
                None,
                line_buffer.as_bytes(),
                line.as_bytes(),
            )?);
        }
        first = !first;
    }
    Ok(elements_group)
}

/// Parses a multi-line TL/3LE string into a list of `Elements`
///
/// Each triplet of lines must represent a TLE with an object name, for example as in
/// [https://celestrak.com/NORAD/elements/gp.php?GROUP=stations&FORMAT=tle](https://celestrak.com/NORAD/elements/gp.php?GROUP=stations&FORMAT=tle).
///
/// # Arguments
///
/// * `tles` - A string containing multiple lines
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn parse_3les(tles: &str) -> Result<alloc::vec::Vec<Elements>> {
    let mut lines_buffer = ["", ""];
    let mut index = 0;
    let mut elements_group = alloc::vec::Vec::new();
    for line in tles.lines() {
        match index {
            0 | 1 => {
                lines_buffer[index] = line;
                index += 1;
            }
            _ => {
                elements_group.push(Elements::from_tle(
                    Some(lines_buffer[0].to_owned()),
                    lines_buffer[1].as_bytes(),
                    line.as_bytes(),
                )?);
                index = 0;
            }
        }
    }
    Ok(elements_group)
}

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

    fn assert_eq_f64(first: f64, second: f64) {
        if second == 0.0 {
            assert_eq!(first, 0.0);
        } else {
            assert!((first - second).abs() / second < f64::EPSILON);
        }
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_from_celestrak_omm() -> anyhow::Result<()> {
        let elements: Elements = serde_json::from_str(
            r#"{
                "OBJECT_NAME": "ISS (ZARYA)",
                "OBJECT_ID": "1998-067A",
                "EPOCH": "2020-07-12T01:19:07.402656",
                "MEAN_MOTION": 15.49560532,
                "ECCENTRICITY": 0.0001771,
                "INCLINATION": 51.6435,
                "RA_OF_ASC_NODE": 225.4004,
                "ARG_OF_PERICENTER": 44.9625,
                "MEAN_ANOMALY": 5.1087,
                "EPHEMERIS_TYPE": 0,
                "CLASSIFICATION_TYPE": "U",
                "NORAD_CAT_ID": 25544,
                "ELEMENT_SET_NO": 999,
                "REV_AT_EPOCH": 23587,
                "BSTAR": 0.0049645,
                "MEAN_MOTION_DOT": 0.00289036,
                "MEAN_MOTION_DDOT": 0
            }"#,
        )?;
        match elements.object_name.as_ref() {
            Some(object_name) => assert_eq!(object_name, "ISS (ZARYA)"),
            None => panic!(),
        }
        assert_eq!(elements.norad_id, 25544);
        assert!(matches!(
            elements.classification,
            Classification::Unclassified
        ));
        assert_eq!(
            elements.international_designator.as_ref().unwrap(),
            "1998-067A"
        );
        assert_eq!(
            elements.datetime,
            chrono::NaiveDate::from_yo(2020, 194).and_time(
                chrono::NaiveTime::from_num_seconds_from_midnight(4747, 402656000)
            )
        );
        assert_eq_f64(elements.epoch(), 20.527186712635181);
        assert_eq_f64(
            elements.epoch_afspc_compatibility_mode(),
            20.527186712635135,
        );
        assert_eq_f64(elements.mean_motion_dot, 0.00289036);
        assert_eq_f64(elements.mean_motion_ddot, 0.0);
        assert_eq_f64(elements.drag_term, 0.0049645);
        assert_eq!(elements.ephemeris_type, 0);
        assert_eq!(elements.element_set_number, 999);
        assert_eq_f64(elements.inclination, 51.6435);
        assert_eq_f64(elements.right_ascension, 225.4004);
        assert_eq_f64(elements.eccentricity, 0.0001771);
        assert_eq_f64(elements.argument_of_perigee, 44.9625);
        assert_eq_f64(elements.mean_anomaly, 5.1087);
        assert_eq_f64(elements.mean_motion, 15.49560532);
        assert_eq!(elements.revolution_number, 23587);
        Ok(())
    }

    #[test]
    fn test_from_space_track_omm() -> anyhow::Result<()> {
        let elements: Elements = serde_json::from_str(
            r#"{"CCSDS_OMM_VERS":"2.0",
                "COMMENT":"GENERATED VIA SPACE-TRACK.ORG API",
                "CREATION_DATE":"2020-12-13T17:26:09",
                "ORIGINATOR":"18 SPCS",
                "OBJECT_NAME":"ISS (ZARYA)",
                "OBJECT_ID":"1998-067A",
                "CENTER_NAME":"EARTH",
                "REF_FRAME":"TEME",
                "TIME_SYSTEM":"UTC",
                "MEAN_ELEMENT_THEORY":"SGP4",
                "EPOCH":"2020-12-13T16:36:04.502592",
                "MEAN_MOTION":"15.49181153",
                "ECCENTRICITY":"0.00017790",
                "INCLINATION":"51.6444",
                "RA_OF_ASC_NODE":"180.2777",
                "ARG_OF_PERICENTER":"128.5985",
                "MEAN_ANOMALY":"350.1361",
                "EPHEMERIS_TYPE":"0",
                "CLASSIFICATION_TYPE":"U",
                "NORAD_CAT_ID":"25544",
                "ELEMENT_SET_NO":"999",
                "REV_AT_EPOCH":"25984",
                "BSTAR":"0.00002412400000",
                "MEAN_MOTION_DOT":"0.00000888",
                "MEAN_MOTION_DDOT":"0.0000000000000",
                "SEMIMAJOR_AXIS":"6797.257",
                "PERIOD":"92.952",
                "APOAPSIS":"420.331",
                "PERIAPSIS":"417.912",
                "OBJECT_TYPE":"PAYLOAD",
                "RCS_SIZE":"LARGE",
                "COUNTRY_CODE":"ISS",
                "LAUNCH_DATE":"1998-11-20",
                "SITE":"TTMTR",
                "DECAY_DATE":null,
                "FILE":"2902442",
                "GP_ID":"167697146",
                "TLE_LINE0":"0 ISS (ZARYA)",
                "TLE_LINE1":"1 25544U 98067A   20348.69171878  .00000888  00000-0  24124-4 0  9995",
                "TLE_LINE2":"2 25544  51.6444 180.2777 0001779 128.5985 350.1361 15.49181153259845"
            }"#,
        )?;
        match elements.object_name.as_ref() {
            Some(object_name) => assert_eq!(object_name, "ISS (ZARYA)"),
            None => panic!(),
        }
        assert_eq!(elements.norad_id, 25544);
        assert!(matches!(
            elements.classification,
            Classification::Unclassified
        ));
        assert_eq!(
            elements.international_designator.as_ref().unwrap(),
            "1998-067A"
        );
        assert_eq!(
            elements.datetime,
            chrono::NaiveDate::from_yo(2020, 348).and_time(
                chrono::NaiveTime::from_num_seconds_from_midnight(59764, 502592000)
            )
        );
        assert_eq_f64(elements.epoch(), 20.95055912054757);
        assert_eq_f64(elements.epoch_afspc_compatibility_mode(), 20.95055912054749);
        assert_eq_f64(elements.mean_motion_dot, 0.00000888);
        assert_eq_f64(elements.mean_motion_ddot, 0.0);
        assert_eq_f64(elements.drag_term, 0.000024124);
        assert_eq!(elements.ephemeris_type, 0);
        assert_eq!(elements.element_set_number, 999);
        assert_eq_f64(elements.inclination, 51.6444);
        assert_eq_f64(elements.right_ascension, 180.2777);
        assert_eq_f64(elements.eccentricity, 0.0001779);
        assert_eq_f64(elements.argument_of_perigee, 128.5985);
        assert_eq_f64(elements.mean_anomaly, 350.1361);
        assert_eq_f64(elements.mean_motion, 15.49181153);
        assert_eq!(elements.revolution_number, 25984);
        Ok(())
    }

    #[test]
    fn test_from_celestrak_omms() -> anyhow::Result<()> {
        let elements_group: Vec<Elements> = serde_json::from_str(
            r#"[{
                "OBJECT_NAME": "ISS (ZARYA)",
                "OBJECT_ID": "1998-067A",
                "EPOCH": "2020-07-12T21:16:01.000416",
                "MEAN_MOTION": 15.49507896,
                "ECCENTRICITY": 0.0001413,
                "INCLINATION": 51.6461,
                "RA_OF_ASC_NODE": 221.2784,
                "ARG_OF_PERICENTER": 89.1723,
                "MEAN_ANOMALY": 280.4612,
                "EPHEMERIS_TYPE": 0,
                "CLASSIFICATION_TYPE": "U",
                "NORAD_CAT_ID": 25544,
                "ELEMENT_SET_NO": 999,
                "REV_AT_EPOCH": 23600,
                "BSTAR": -3.1515e-5,
                "MEAN_MOTION_DOT": -2.218e-5,
                "MEAN_MOTION_DDOT": 0
            },{
                "OBJECT_NAME": "KESTREL EYE IIM (KE2M)",
                "OBJECT_ID": "1998-067NE",
                "EPOCH": "2020-07-12T01:38:52.903968",
                "MEAN_MOTION": 15.70564504,
                "ECCENTRICITY": 0.0002758,
                "INCLINATION": 51.6338,
                "RA_OF_ASC_NODE": 155.6245,
                "ARG_OF_PERICENTER": 166.8841,
                "MEAN_ANOMALY": 193.2228,
                "EPHEMERIS_TYPE": 0,
                "CLASSIFICATION_TYPE": "U",
                "NORAD_CAT_ID": 42982,
                "ELEMENT_SET_NO": 999,
                "REV_AT_EPOCH": 15494,
                "BSTAR": 7.2204e-5,
                "MEAN_MOTION_DOT": 8.489e-5,
                "MEAN_MOTION_DDOT": 0
            }]"#,
        )?;
        assert_eq!(elements_group.len(), 2);
        Ok(())
    }

    #[test]
    fn test_from_tle() -> Result<()> {
        let elements = Elements::from_tle(
            Some("ISS (ZARYA)".to_owned()),
            "1 25544U 98067A   08264.51782528 -.00002182  00000-0 -11606-4 0  2927".as_bytes(),
            "2 25544  51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537".as_bytes(),
        )?;
        match elements.object_name.as_ref() {
            Some(object_name) => assert_eq!(object_name, "ISS (ZARYA)"),
            None => panic!(),
        }
        assert_eq!(elements.norad_id, 25544);
        assert!(matches!(
            elements.classification,
            Classification::Unclassified
        ));
        assert_eq!(
            elements.international_designator.as_ref().unwrap(),
            "1998-067A"
        );
        assert_eq!(
            elements.datetime,
            chrono::NaiveDate::from_yo(2008, 264).and_time(
                chrono::NaiveTime::from_num_seconds_from_midnight(44740, 104192001)
            )
        );
        assert_eq_f64(elements.epoch(), 8.720103559972621);
        assert_eq_f64(
            elements.epoch_afspc_compatibility_mode(),
            8.7201035599722125,
        );
        assert_eq_f64(elements.mean_motion_dot, -0.00002182);
        assert_eq_f64(elements.mean_motion_ddot, 0.0);
        assert_eq_f64(elements.drag_term, -0.11606e-4);
        assert_eq!(elements.ephemeris_type, 0);
        assert_eq!(elements.element_set_number, 292);
        assert_eq_f64(elements.inclination, 51.6416);
        assert_eq_f64(elements.right_ascension, 247.4627);
        assert_eq_f64(elements.eccentricity, 0.0006703);
        assert_eq_f64(elements.argument_of_perigee, 130.5360);
        assert_eq_f64(elements.mean_anomaly, 325.0288);
        assert_eq_f64(elements.mean_motion, 15.72125391);
        assert_eq!(elements.revolution_number, 56353);
        let elements = Elements::from_tle(
            None,
            "1 11801U          80230.29629788  .01431103  00000-0  14311-1 0    13".as_bytes(),
            "2 11801  46.7916 230.4354 7318036  47.4722  10.4117  2.28537848    13".as_bytes(),
        )?;
        assert!(elements.object_name.is_none());
        assert_eq!(elements.norad_id, 11801);
        assert!(matches!(
            elements.classification,
            Classification::Unclassified
        ));
        assert!(elements.international_designator.is_none());
        assert_eq!(
            elements.datetime,
            chrono::NaiveDate::from_yo(1980, 230).and_time(
                chrono::NaiveTime::from_num_seconds_from_midnight(25600, 136832000)
            )
        );
        assert_eq_f64(elements.epoch(), -19.373589875756331);
        assert_eq_f64(
            elements.epoch_afspc_compatibility_mode(),
            -19.373589875756632,
        );
        assert_eq_f64(elements.mean_motion_dot, 0.01431103);
        assert_eq_f64(elements.mean_motion_ddot, 0.0);
        assert_eq_f64(elements.drag_term, 0.014311);
        assert_eq!(elements.ephemeris_type, 0);
        assert_eq!(elements.element_set_number, 1);
        assert_eq_f64(elements.inclination, 46.7916);
        assert_eq_f64(elements.right_ascension, 230.4354);
        assert_eq_f64(elements.eccentricity, 0.7318036);
        assert_eq_f64(elements.argument_of_perigee, 47.4722);
        assert_eq_f64(elements.mean_anomaly, 10.4117);
        assert_eq_f64(elements.mean_motion, 2.28537848);
        assert_eq!(elements.revolution_number, 1);
        Ok(())
    }

    #[test]
    fn test_parse_2les() -> Result<()> {
        let elements_group = parse_2les(
            "1 25544U 98067A   20194.88612269 -.00002218  00000-0 -31515-4 0  9992\n\
             2 25544  51.6461 221.2784 0001413  89.1723 280.4612 15.49507896236008\n\
             1 42982U 98067NE  20194.06866787  .00008489  00000-0  72204-4 0  9997\n\
             2 42982  51.6338 155.6245 0002758 166.8841 193.2228 15.70564504154944\n",
        )?;
        assert_eq!(elements_group.len(), 2);
        Ok(())
    }

    #[test]
    fn test_parse_3les() -> Result<()> {
        let elements_group = parse_3les(
            "ISS (ZARYA)\n\
             1 25544U 98067A   20194.88612269 -.00002218  00000-0 -31515-4 0  9992\n\
             2 25544  51.6461 221.2784 0001413  89.1723 280.4612 15.49507896236008\n\
             KESTREL EYE IIM (KE2M)\n\
             1 42982U 98067NE  20194.06866787  .00008489  00000-0  72204-4 0  9997\n\
             2 42982  51.6338 155.6245 0002758 166.8841 193.2228 15.70564504154944\n",
        )?;
        assert_eq!(elements_group.len(), 2);
        Ok(())
    }
}