1use std::borrow::Cow;
183use std::collections::HashMap;
184
185use roxmltree::{Document, Node, NodeId, ParsingOptions};
186
187use crate::error::LogError;
188use crate::log::{Channel, Event, FlightLog, LogFormat, Quantity, Stated};
189use crate::perfectflite::FOOT_M;
190use crate::table::{Notes, number, short};
191
192const FORMAT: &str = "KML";
194
195pub const MAX_TRACKS: usize = 256;
198
199pub const MAX_POINTS: usize = 1_000_000;
202
203pub const MAX_DOCUMENTS: usize = 8;
206
207pub const MAX_NODES: u32 = 4_000_000;
211
212pub const MAX_DEPTH: usize = 64;
217
218pub const MAX_MIDNIGHTS: i64 = 7;
222
223const ALTOS_STEP_S: std::ops::RangeInclusive<f64> = 0.5..=2.0;
227
228const PROLOG_ITEMS: usize = 64;
231
232const NS_PER_S: i64 = 1_000_000_000;
234
235const DAY_NS: i64 = 86_400 * NS_PER_S;
237
238pub(crate) fn recognizes(text: &str) -> bool {
243 root_is(text, "kml")
244}
245
246pub(crate) fn root_is(text: &str, name: &str) -> bool {
250 prolog(text).is_some_and(|(root, _)| {
251 text[root..]
252 .strip_prefix('<')
253 .and_then(|after| after.strip_prefix(name))
254 .is_some_and(|after| {
255 after.starts_with(|c: char| c.is_ascii_whitespace() || c == '>' || c == '/')
256 })
257 })
258}
259
260pub(crate) fn doctype_offset(text: &str) -> Option<usize> {
263 prolog(text).and_then(|(_, doctype)| doctype)
264}
265
266fn prolog(text: &str) -> Option<(usize, Option<usize>)> {
271 let mut rest = text.strip_prefix('\u{feff}').unwrap_or(text);
272 let mut doctype = None;
273 for _ in 0..PROLOG_ITEMS {
274 rest = rest.trim_start();
275 let (open, close) = if rest.starts_with("<?") {
276 ("<?", "?>")
277 } else if rest.starts_with("<!--") {
278 ("<!--", "-->")
279 } else if rest.starts_with("<!DOCTYPE") {
280 let length = doctype_length(rest)?;
281 doctype = Some(text.len() - rest.len());
282 rest = &rest[length..];
283 continue;
284 } else {
285 break;
286 };
287 let end = rest[open.len()..].find(close)?;
288 rest = &rest[open.len() + end + close.len()..];
289 }
290 Some((text.len() - rest.len(), doctype))
291}
292
293fn doctype_length(text: &str) -> Option<usize> {
296 let mut quote: Option<u8> = None;
297 let mut brackets = 0usize;
298 for (index, byte) in text.bytes().enumerate() {
299 match (quote, byte) {
300 (Some(open), _) if byte == open => quote = None,
301 (Some(_), _) => {}
302 (None, b'"' | b'\'') => quote = Some(byte),
303 (None, b'[') => brackets += 1,
304 (None, b']') => brackets = brackets.saturating_sub(1),
305 (None, b'>') if brackets == 0 => return Some(index + 1),
306 (None, _) => {}
307 }
308 }
309 None
310}
311
312pub fn read(text: &str) -> Result<FlightLog, LogError> {
321 read_within(text, MAX_NODES)
322}
323
324fn read_within(text: &str, max_nodes: u32) -> Result<FlightLog, LogError> {
326 let text = text.strip_prefix('\u{feff}').unwrap_or(text);
327 let (pieces, more) = split_documents(text, max_nodes)?;
328 let mut copies = 0;
329 let mut left_out = usize::from(more);
330 let mut first: Option<(&str, Document<'_>)> = None;
331 let mut later: Vec<Document<'_>> = Vec::new();
332 let mut nodes_left = max_nodes;
335 let mut parse_within = |piece| {
336 let document = parse(piece, nodes_left)?;
337 let used = u32::try_from(document.descendants().count()).unwrap_or(u32::MAX);
338 nodes_left = nodes_left.saturating_sub(used);
339 Ok::<_, LogError>(document)
340 };
341 for piece in pieces {
342 if let Some((first_text, _)) = &first {
343 if piece.trim() == first_text.trim() {
344 copies += 1;
345 } else if later.len() + 1 >= MAX_DOCUMENTS {
346 left_out += 1;
347 } else {
348 later.push(parse_within(piece)?);
349 }
350 } else {
351 first = Some((piece, parse_within(piece)?));
352 }
353 }
354 let Some((_, first)) = first else {
355 return Err(LogError::NoData { format: FORMAT });
357 };
358 let mut reader = Reader {
359 copies,
360 documents_left_out: left_out,
361 later_documents: later.len(),
362 ..Reader::default()
363 };
364 for (index, document) in std::iter::once(&first).chain(&later).enumerate() {
365 let root = document.root_element();
366 if root.tag_name().name() != "kml" {
367 return Err(LogError::NotThisFormat {
368 format: FORMAT,
369 message: format!(
370 "the root element is {:?}, not `kml`",
371 short(root.tag_name().name())
372 ),
373 });
374 }
375 reader.read_document(document, index);
376 }
377 let about = About::of(&first, &reader);
378 reader.finish(about)
379}
380
381fn split_documents(text: &str, max_nodes: u32) -> Result<(Vec<&str>, bool), LogError> {
385 let mut pieces = Vec::new();
386 let mut rest = text;
387 loop {
388 match parse_xml(rest, max_nodes) {
389 Ok(_) => {
390 pieces.push(rest);
391 return Ok((pieces, false));
392 }
393 Err(XmlFailure::Xml(roxmltree::Error::UnexpectedDeclaration(position))) => {
394 let at = offset_of(rest, position)
395 .filter(|&at| at > 0 && rest[at..].starts_with("<?xml"))
396 .ok_or_else(|| {
397 xml_error(&XmlFailure::Xml(roxmltree::Error::UnexpectedDeclaration(
398 position,
399 )))
400 })?;
401 pieces.push(&rest[..at]);
402 rest = &rest[at..];
403 if pieces.len() >= 2 * MAX_DOCUMENTS {
404 return Ok((pieces, true));
405 }
406 }
407 Err(failure) => return Err(xml_error(&failure)),
408 }
409 }
410}
411
412#[derive(Debug)]
414enum XmlFailure {
415 Deep { deepest: usize, line: usize },
417 Xml(roxmltree::Error),
419}
420
421fn parse_xml(text: &str, nodes: u32) -> Result<Document<'_>, XmlFailure> {
424 let (deepest, line) = nesting(text);
425 if deepest > MAX_DEPTH {
426 return Err(XmlFailure::Deep { deepest, line });
427 }
428 let options = ParsingOptions {
429 nodes_limit: nodes,
430 ..ParsingOptions::default()
431 };
432 Document::parse_with_options(text, options).map_err(XmlFailure::Xml)
433}
434
435fn parse(text: &str, nodes: u32) -> Result<Document<'_>, LogError> {
437 parse_xml(text, nodes).map_err(|failure| xml_error(&failure))
438}
439
440fn xml_error(failure: &XmlFailure) -> LogError {
442 let (line, message) = match failure {
443 XmlFailure::Deep { deepest, line } => (
444 *line,
445 format!(
446 "the XML nests elements {deepest} deep, past the {MAX_DEPTH} this reader reads, \
447 so that the parser can't exhaust its stack"
448 ),
449 ),
450 XmlFailure::Xml(error) => (
451 usize::try_from(error.pos().row).unwrap_or(usize::MAX),
452 match error {
453 roxmltree::Error::DtdDetected => "the file declares a document type, which this \
454 reader refuses so that no entity can expand"
455 .to_owned(),
456 roxmltree::Error::NodesLimitReached => {
457 format!("the file holds more than {MAX_NODES} XML nodes over its documents")
458 }
459 error => format!("the XML isn't well formed: {error}"),
460 },
461 ),
462 };
463 LogError::Syntax {
464 format: FORMAT,
465 line,
466 message,
467 }
468}
469
470pub(crate) fn nesting(text: &str) -> (usize, usize) {
476 let bytes = text.as_bytes();
477 let mut index = 0;
478 let mut depth = 0usize;
479 let mut deepest = 0usize;
480 let mut past_at = None;
481 while index < bytes.len() {
482 if bytes[index] != b'<' {
483 index += 1;
484 continue;
485 }
486 let rest = &bytes[index..];
487 if let Some(skip) = skipped(rest, b"<!--", b"-->")
488 .or_else(|| skipped(rest, b"<![CDATA[", b"]]>"))
489 .or_else(|| skipped(rest, b"<?", b"?>"))
490 {
491 index += skip;
492 continue;
493 }
494 let closing = rest.starts_with(b"</");
495 let declaration = rest.starts_with(b"<!");
496 let mut cursor = index + 1;
497 let mut quote: Option<u8> = None;
498 let mut last = 0u8;
499 while cursor < bytes.len() {
500 let byte = bytes[cursor];
501 match quote {
502 Some(open) if byte == open => quote = None,
503 Some(_) => {}
504 None if byte == b'"' || byte == b'\'' => quote = Some(byte),
505 None if byte == b'>' => break,
506 None => {}
507 }
508 if !byte.is_ascii_whitespace() {
509 last = byte;
510 }
511 cursor += 1;
512 }
513 if !declaration {
514 if closing {
515 depth = depth.saturating_sub(1);
516 } else {
517 depth += 1;
518 deepest = deepest.max(depth);
519 if depth > MAX_DEPTH && past_at.is_none() {
520 past_at = Some(index);
521 }
522 if last == b'/' {
523 depth -= 1;
524 }
525 }
526 }
527 index = cursor + 1;
528 }
529 let line = past_at.map_or(0, |at| {
530 bytes[..at].iter().filter(|&&byte| byte == b'\n').count() + 1
531 });
532 (deepest, line)
533}
534
535fn skipped(rest: &[u8], opening: &[u8], closing: &[u8]) -> Option<usize> {
538 if !rest.starts_with(opening) {
539 return None;
540 }
541 let from = opening.len();
542 let found = rest[from..]
543 .windows(closing.len())
544 .position(|window| window == closing)
545 .map(|at| from + at + closing.len());
546 Some(found.unwrap_or(rest.len()))
547}
548
549fn offset_of(text: &str, position: roxmltree::TextPos) -> Option<usize> {
551 let mut line_start = 0;
552 for _ in 1..position.row {
553 line_start += text.get(line_start..)?.find('\n')? + 1;
554 }
555 let line = text.get(line_start..)?;
556 let column = usize::try_from(position.col).ok()?.checked_sub(1)?;
557 line.char_indices()
558 .map(|(index, _)| index)
559 .chain(std::iter::once(line.len()))
560 .nth(column)
561 .map(|index| line_start + index)
562}
563
564#[derive(Debug, Clone, Copy, PartialEq, Eq)]
566enum Mode {
567 Absolute,
569 RelativeToGround,
571 RelativeToSeaFloor,
573 Ignored(Option<&'static str>),
576 Unnamed,
578}
579
580impl Mode {
581 fn of(geometry: Node<'_, '_>) -> Self {
583 let Some(text) = child(geometry, "altitudeMode").map(|node| all_text(node)) else {
584 return Self::Ignored(None);
585 };
586 match text.trim() {
587 "absolute" => Self::Absolute,
588 "relativeToGround" => Self::RelativeToGround,
589 "relativeToSeaFloor" => Self::RelativeToSeaFloor,
590 "clampToGround" => Self::Ignored(Some("clampToGround")),
591 "clampToSeaFloor" => Self::Ignored(Some("clampToSeaFloor")),
592 _ => Self::Unnamed,
593 }
594 }
595}
596
597#[derive(Debug, Clone, Copy, PartialEq, Eq)]
599pub(crate) enum Clock {
600 Utc,
602 Local,
604 AltOs,
606 Seconds,
608 TimeOfDay,
610}
611
612impl Clock {
613 fn word(self) -> &'static str {
615 match self {
616 Self::Utc | Self::Local => "`when`",
617 Self::AltOs => "`time`",
618 Self::Seconds => "`Seconds`",
619 Self::TimeOfDay => "`UTC`",
620 }
621 }
622}
623
624#[derive(Debug, Clone, Copy, PartialEq)]
626enum AltosTime {
627 Absent,
629 Unset,
631 Seconds(f64),
633 Unsettled(f64),
635}
636
637#[derive(Debug, Clone, Copy, Default)]
639struct Midnights {
640 days: usize,
642 dropped: usize,
644}
645
646#[derive(Debug, Clone, Copy, PartialEq, Eq)]
648struct Stamp<'a> {
649 clock: Clock,
650 ns: i64,
651 raw: &'a str,
652}
653
654#[derive(Debug, Clone, Copy, PartialEq, Eq)]
656enum Layout {
657 AltOs,
659 Seconds,
661 BeeLine,
663}
664
665#[derive(Debug, Clone, Copy, PartialEq)]
667struct Remark<'a> {
668 layout: Layout,
669 alt: f64,
671 time: Option<(i64, &'a str)>,
673 sats: f64,
675 offset: f64,
677}
678
679fn remark(text: &str) -> Option<Remark<'_>> {
681 let mut tokens = [""; 6];
682 let mut count = 0;
683 for token in text.split_ascii_whitespace() {
684 *tokens.get_mut(count)? = token;
685 count += 1;
686 }
687 let tokens = &tokens[..count];
688 if let [offset, sats, utc, time] = tokens
689 && utc.eq_ignore_ascii_case("UTC")
690 && let Some(sats) = sats.strip_prefix("sats:")
691 {
692 return Some(Remark {
693 layout: Layout::BeeLine,
694 alt: f64::NAN,
695 time: Some((time_of_day_ns(time)?, *time)),
696 sats: number(sats, false)?,
697 offset: number(offset, false)?,
698 });
699 }
700 match tokens {
701 [alt_key, alt, time_key, time, sats_key, sats]
702 if alt_key.eq_ignore_ascii_case("alt")
703 && time_key.eq_ignore_ascii_case("time")
704 && sats_key.eq_ignore_ascii_case("sats") =>
705 {
706 Some(Remark {
707 layout: Layout::AltOs,
708 alt: number(alt, false)?,
709 time: Some((decimal_ns(time)?, *time)),
710 sats: number(sats, false)?,
711 offset: f64::NAN,
712 })
713 }
714 [alt_key, alt, seconds_key, seconds]
715 if alt_key.eq_ignore_ascii_case("alt")
716 && seconds_key.eq_ignore_ascii_case("seconds") =>
717 {
718 Some(Remark {
719 layout: Layout::Seconds,
720 alt: number(alt, false)?,
721 time: Some((decimal_ns(seconds)?, *seconds)),
722 sats: f64::NAN,
723 offset: f64::NAN,
724 })
725 }
726 _ => None,
727 }
728}
729
730fn decimal_ns(text: &str) -> Option<i64> {
734 let (negative, digits) = match text.as_bytes().first()? {
735 b'-' => (true, &text[1..]),
736 b'+' => (false, &text[1..]),
737 _ => (false, text),
738 };
739 let (whole, fraction) = digits.split_once('.').unwrap_or((digits, ""));
740 if whole.is_empty() && fraction.is_empty()
741 || digits.ends_with('.')
742 || !whole
743 .bytes()
744 .chain(fraction.bytes())
745 .all(|b| b.is_ascii_digit())
746 || whole.len() > 10
747 {
748 return None;
749 }
750 let seconds: i64 = if whole.is_empty() {
751 0
752 } else {
753 whole.parse().ok()?
754 };
755 let mut nanos: i64 = 0;
756 for digit in fraction.bytes().chain(std::iter::repeat(b'0')).take(9) {
757 nanos = nanos * 10 + i64::from(digit - b'0');
758 }
759 let total = seconds.checked_mul(NS_PER_S)?.checked_add(nanos)?;
760 Some(if negative { -total } else { total })
761}
762
763fn time_of_day_ns(text: &str) -> Option<i64> {
767 let mut parts = text.split(':');
768 let (hours, minutes, seconds) = (parts.next()?, parts.next()?, parts.next()?);
769 if parts.next().is_some()
770 || hours.len() != 2
771 || minutes.len() != 2
772 || !hours
773 .bytes()
774 .chain(minutes.bytes())
775 .all(|b| b.is_ascii_digit())
776 || seconds.split('.').next().map(str::len) != Some(2)
777 || !seconds.bytes().take(2).all(|b| b.is_ascii_digit())
778 {
779 return None;
780 }
781 let hours: i64 = hours.parse().ok()?;
782 let minutes: i64 = minutes.parse().ok()?;
783 let seconds = decimal_ns(seconds).filter(|ns| (0..61 * NS_PER_S).contains(ns))?;
784 (hours < 24 && minutes < 60).then_some((hours * 3_600 + minutes * 60) * NS_PER_S + seconds)
785}
786
787pub(crate) fn when_ns(text: &str) -> Option<(Clock, i64)> {
792 let text = text.trim();
793 let (date, rest) = text.split_once('T')?;
794 let mut fields = date.split('-');
795 let (year, month, day) = (fields.next()?, fields.next()?, fields.next()?);
796 if fields.next().is_some()
797 || year.len() != 4
798 || month.len() != 2
799 || day.len() != 2
800 || !year
801 .bytes()
802 .chain(month.bytes())
803 .chain(day.bytes())
804 .all(|b| b.is_ascii_digit())
805 {
806 return None;
807 }
808 let (year, month, day): (i64, i64, i64) =
809 (year.parse().ok()?, month.parse().ok()?, day.parse().ok()?);
810 if !(1..=12).contains(&month) || day < 1 || day > days_in_month(year, month) {
811 return None;
812 }
813 let (time, clock, offset_s) = if let Some(time) = rest.strip_suffix('Z') {
814 (time, Clock::Utc, 0)
815 } else if let Some(at) = rest.rfind(['+', '-']).filter(|&at| at >= 8) {
816 let (time, zone) = rest.split_at(at);
817 let sign = if zone.starts_with('-') { -1 } else { 1 };
818 let (hours, minutes) = zone[1..].split_once(':')?;
819 if hours.len() != 2 || minutes.len() != 2 {
820 return None;
821 }
822 let hours: i64 = hours.parse().ok()?;
823 let minutes: i64 = minutes.parse().ok()?;
824 if minutes > 59 || hours * 60 + minutes > 14 * 60 {
826 return None;
827 }
828 (time, Clock::Utc, sign * (hours * 3_600 + minutes * 60))
829 } else {
830 (rest, Clock::Local, 0)
831 };
832 let of_day = time_of_day_ns(time)?;
833 let days = days_from_civil(year, month, day);
834 let ns = days
835 .checked_mul(DAY_NS)?
836 .checked_add(of_day)?
837 .checked_sub(offset_s.checked_mul(NS_PER_S)?)?;
838 Some((clock, ns))
839}
840
841fn days_in_month(year: i64, month: i64) -> i64 {
843 match month {
844 2 if year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) => 29,
845 2 => 28,
846 4 | 6 | 9 | 11 => 30,
847 _ => 31,
848 }
849}
850
851fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
854 let year = if month <= 2 { year - 1 } else { year };
855 let era = year.div_euclid(400);
856 let year_of_era = year - era * 400;
857 let shifted_month = (month + 9) % 12;
858 let day_of_year = (153 * shifted_month + 2) / 5 + day - 1;
859 let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
860 era * 146_097 + day_of_era - 719_468
861}
862
863fn tuple(text: &str, gx: bool) -> Option<(f64, f64, Option<f64>)> {
867 let mut parts: [&str; 3] = [""; 3];
868 let count = if gx {
869 fill(&mut parts, text.split_ascii_whitespace())?
870 } else {
871 fill(&mut parts, text.split(','))?
872 };
873 let value = |part: &str| number(part, false);
874 match count {
875 2 => Some((value(parts[0])?, value(parts[1])?, None)),
876 3 => Some((value(parts[0])?, value(parts[1])?, Some(value(parts[2])?))),
877 _ => None,
878 }
879}
880
881fn fill<'t>(slots: &mut [&'t str], parts: impl Iterator<Item = &'t str>) -> Option<usize> {
883 let mut count = 0;
884 for part in parts {
885 *slots.get_mut(count)? = part;
886 count += 1;
887 }
888 Some(count)
889}
890
891fn tuples(text: &str) -> Vec<Cow<'_, str>> {
894 let mut out: Vec<Cow<'_, str>> = Vec::new();
895 let mut current: Option<Cow<'_, str>> = None;
896 for token in text.split_ascii_whitespace() {
897 current = Some(match current.take() {
898 Some(previous) if previous.ends_with(',') || token.starts_with(',') => {
899 let mut joined = previous.into_owned();
900 joined.push_str(token);
901 Cow::Owned(joined)
902 }
903 Some(previous) => {
904 out.push(previous);
905 Cow::Borrowed(token)
906 }
907 None => Cow::Borrowed(token),
908 });
909 }
910 out.extend(current);
911 out
912}
913
914fn child<'a, 'input>(node: Node<'a, 'input>, name: &str) -> Option<Node<'a, 'input>> {
916 node.children()
917 .find(|child| child.is_element() && child.tag_name().name() == name)
918}
919
920fn all_text(node: Node<'_, '_>) -> String {
922 node.children()
923 .filter(|child| child.is_text())
924 .filter_map(|child| child.text())
925 .collect()
926}
927
928fn clean(name: &str) -> String {
930 short(&name.split_whitespace().collect::<Vec<_>>().join(" "))
931}
932
933struct Track<'a> {
935 label: String,
937 placemark: Option<(usize, NodeId)>,
939 point: bool,
941 mode: Mode,
942 lat: Vec<f64>,
943 lon: Vec<f64>,
944 alt: Vec<f64>,
946 stamps: Vec<Option<Stamp<'a>>>,
947 remarks: Vec<Option<Remark<'a>>>,
948}
949
950#[derive(Default)]
952struct Reader<'a> {
953 tracks: Vec<Track<'a>>,
954 tracks_left_out: usize,
955 points: usize,
956 points_left_out: usize,
957 copies: usize,
958 later_documents: usize,
959 documents_left_out: usize,
960 other_geometries: usize,
962 empty_geometries: usize,
964 loose_comments: usize,
966 stray_comments: usize,
968 unknown_comments: usize,
970 outside_comments: usize,
973 longest_outside: usize,
974 memory_dump: bool,
975 bad_tuples: usize,
976 bad_tuple_example: Option<String>,
977 out_of_range: usize,
978 bad_whens: usize,
979 bad_when_example: Option<String>,
980 notes: Notes,
981}
982
983impl<'a> Reader<'a> {
984 fn read_document(&mut self, document: &'a Document<'a>, index: usize) {
986 for node in document.root().children() {
987 if node.is_comment() {
988 let text = node.text().unwrap_or_default();
989 self.outside_comments += 1;
990 self.longest_outside = self.longest_outside.max(text.chars().count());
991 self.memory_dump |= text.trim_start().starts_with("BRBDATA");
992 }
993 }
994 for node in document.root_element().descendants() {
995 if node.is_comment() {
996 if !node
997 .parent()
998 .is_some_and(|parent| parent.tag_name().name() == "coordinates")
999 {
1000 self.loose_comments += 1;
1001 }
1002 continue;
1003 }
1004 if !node.is_element() {
1005 continue;
1006 }
1007 match node.tag_name().name() {
1008 "LineString" | "Point" | "Track" => self.read_geometry(node, index),
1009 "Polygon" | "Model" => self.other_geometries += 1,
1010 _ => {}
1011 }
1012 }
1013 }
1014
1015 fn read_geometry(&mut self, node: Node<'a, 'a>, document: usize) {
1017 if self.tracks.len() >= MAX_TRACKS {
1018 self.tracks_left_out += 1;
1019 return;
1020 }
1021 let placemark = node
1022 .ancestors()
1023 .skip(1)
1024 .find(|ancestor| ancestor.is_element() && ancestor.tag_name().name() == "Placemark");
1025 let label = placemark
1026 .and_then(|placemark| child(placemark, "name"))
1027 .map(|name| clean(&all_text(name)))
1028 .filter(|name| !name.is_empty())
1029 .unwrap_or_else(|| "track".to_owned());
1030 let point = node.tag_name().name() == "Point";
1031 let mut track = Track {
1032 label,
1033 placemark: placemark.map(|placemark| (document, placemark.id())),
1034 point,
1035 mode: Mode::of(node),
1036 lat: Vec::new(),
1037 lon: Vec::new(),
1038 alt: Vec::new(),
1039 stamps: Vec::new(),
1040 remarks: Vec::new(),
1041 };
1042 if node.tag_name().name() == "Track" {
1043 self.read_gx_track(node, &mut track);
1044 } else if let Some(coordinates) = child(node, "coordinates") {
1045 self.read_coordinates(coordinates, &mut track);
1046 }
1047 if point
1048 && let Some(when) = placemark
1049 .and_then(|placemark| child(placemark, "TimeStamp"))
1050 .and_then(|stamp| child(stamp, "when"))
1051 .and_then(|when| when.text())
1052 {
1053 let stamp = self.stamp_of_when(when);
1054 track.stamps.fill(stamp);
1055 }
1056 if track.lat.is_empty() {
1057 self.empty_geometries += 1;
1058 } else {
1059 self.tracks.push(track);
1060 }
1061 }
1062
1063 fn push(
1065 &mut self,
1066 track: &mut Track<'a>,
1067 raw: &str,
1068 read: Option<(f64, f64, Option<f64>)>,
1069 ) -> bool {
1070 if self.points >= MAX_POINTS {
1071 self.points_left_out += 1;
1072 return false;
1073 }
1074 self.points += 1;
1075 let (lon, lat, alt) = read.unwrap_or_else(|| {
1076 self.bad_tuples += 1;
1077 if self.bad_tuple_example.is_none() {
1078 self.bad_tuple_example = Some(short(raw));
1079 }
1080 (f64::NAN, f64::NAN, Some(f64::NAN))
1081 });
1082 let (lon, lat) =
1083 if lon.is_nan() || ((-180.0..=180.0).contains(&lon) && (-90.0..=90.0).contains(&lat)) {
1084 (lon, lat)
1085 } else {
1086 self.out_of_range += 1;
1087 (f64::NAN, f64::NAN)
1088 };
1089 track.lon.push(lon);
1090 track.lat.push(lat);
1091 track.alt.push(alt.unwrap_or(f64::NAN));
1092 track.stamps.push(None);
1093 track.remarks.push(None);
1094 true
1095 }
1096
1097 fn read_coordinates(&mut self, coordinates: Node<'a, 'a>, track: &mut Track<'a>) {
1099 let mut open = false;
1101 for node in coordinates.children() {
1102 if node.is_text() {
1103 for raw in tuples(node.text().unwrap_or_default()) {
1104 open = self.push(track, &raw, tuple(&raw, false));
1105 }
1106 } else if node.is_comment() {
1107 let text = node.text().unwrap_or_default();
1108 if !open {
1109 self.stray_comments += 1;
1110 continue;
1111 }
1112 open = false;
1113 match (remark(text), track.remarks.last_mut()) {
1114 (Some(read), Some(slot)) => *slot = Some(read),
1115 _ => self.unknown_comments += 1,
1116 }
1117 }
1118 }
1119 }
1120
1121 fn read_gx_track(&mut self, node: Node<'a, 'a>, track: &mut Track<'a>) {
1123 let named = |name: &'static str| {
1124 node.children()
1125 .filter(move |child| child.is_element() && child.tag_name().name() == name)
1126 };
1127 let (whens, coords) = (named("when").count(), named("coord").count());
1128 if whens != coords {
1129 self.notes.push(format!(
1130 "a `gx:Track` of {:?} holds {whens} `when` and {coords} `gx:coord`, where the \
1131 standard has as many of each. The first {} of each are paired, the rest left out",
1132 track.label,
1133 whens.min(coords)
1134 ));
1135 }
1136 for (when, coord) in named("when").zip(named("coord")) {
1137 let raw = coord.text().unwrap_or_default();
1138 if !self.push(track, raw, tuple(raw, true)) {
1139 break;
1140 }
1141 let stamp = self.stamp_of_when(when.text().unwrap_or_default());
1142 if let Some(slot) = track.stamps.last_mut() {
1143 *slot = stamp;
1144 }
1145 }
1146 }
1147
1148 fn stamp_of_when(&mut self, raw: &'a str) -> Option<Stamp<'a>> {
1150 let read = when_ns(raw).map(|(clock, ns)| Stamp {
1151 clock,
1152 ns,
1153 raw: raw.trim(),
1154 });
1155 if read.is_none() {
1156 self.bad_whens += 1;
1157 if self.bad_when_example.is_none() {
1158 self.bad_when_example = Some(short(raw.trim()));
1159 }
1160 }
1161 read
1162 }
1163
1164 fn finish(mut self, about: About) -> Result<FlightLog, LogError> {
1166 if self.tracks.is_empty() {
1167 return Err(LogError::NoData { format: FORMAT });
1168 }
1169 let mut notes = vec![
1170 "the record's altitude track is empty: a KML file holds tracks of positions, not an \
1171 altimeter's record over time, so every value is a channel"
1172 .to_owned(),
1173 ];
1174 notes.extend(about.note.clone());
1175 self.document_notes(&mut notes);
1176
1177 let altos_time = self.altos_time();
1178 if altos_time == AltosTime::Unset {
1179 notes.push(
1180 "the comments' `time` is 0 beside every point, as AltOS leaves it unset in \
1181 most of its exports: those points have no time"
1182 .to_owned(),
1183 );
1184 }
1185 self.stamp_from_remarks(matches!(altos_time, AltosTime::Seconds(_)));
1186 let midnights = self.pass_midnight();
1187 let times = self.times(&mut notes, midnights);
1188 let names = self.names();
1189 let altos_alt_meters = agreement(&self.tracks, Layout::AltOs).0 > 0;
1191
1192 let mut channels = Vec::new();
1193 let mut events = Vec::new();
1194 let mut decided = Decided::default();
1195 for ((track, time_s), name) in self.tracks.iter().zip(×).zip(&names) {
1196 if track.point
1197 && let Some(&time) = time_s.first()
1198 && time.is_finite()
1199 {
1200 events.push(Event {
1201 time_s: time,
1202 name: track.label.clone(),
1203 });
1204 }
1205 let mut add = |suffix: &str, quantity: Quantity, values: Vec<f64>| {
1206 channels.push(Channel {
1207 column: format!("{name} {suffix}"),
1208 quantity,
1209 time_s: time_s.clone(),
1210 values,
1211 });
1212 };
1213 add("latitude", Quantity::Latitude, track.lat.clone());
1214 add("longitude", Quantity::Longitude, track.lon.clone());
1215 let altitudes = track.alt.iter().filter(|alt| !alt.is_nan()).count();
1216 let remark_alt: Vec<f64> = track
1217 .remarks
1218 .iter()
1219 .map(|remark| remark.map_or(f64::NAN, |remark| remark.alt))
1220 .collect();
1221 let differs =
1222 track.alt.iter().zip(&remark_alt).any(|(tuple, comment)| {
1223 !comment.is_nan() && !(tuple - comment).abs().le(&1e-6)
1224 });
1225 let layout = track
1226 .remarks
1227 .iter()
1228 .flatten()
1229 .map(|remark| remark.layout)
1230 .next();
1231 let (both, differing) = track
1234 .alt
1235 .iter()
1236 .zip(&remark_alt)
1237 .filter(|(tuple, comment)| !tuple.is_nan() && !comment.is_nan())
1238 .fold((0, 0), |(both, differing), (tuple, comment)| {
1239 (
1240 both + 1,
1241 differing + usize::from((tuple - comment).abs() > 1e-6),
1242 )
1243 });
1244 let barometric = (layout == Some(Layout::AltOs) && differing * 2 > both)
1245 .then_some((both, differing));
1246 if altitudes > 0 {
1247 let (suffix, quantity) = decided.altitude(track, &about, barometric);
1248 add(suffix, quantity, track.alt.clone());
1249 }
1250 if differs {
1251 let (suffix, quantity) = decided.remark_altitude(layout, altos_alt_meters);
1252 add(suffix, quantity, remark_alt);
1253 }
1254 if matches!(altos_time, AltosTime::Unsettled(_)) && layout == Some(Layout::AltOs) {
1255 let written: Vec<f64> = track
1257 .remarks
1258 .iter()
1259 .map(|remark| {
1260 remark
1261 .and_then(|remark| remark.time)
1262 .map_or(f64::NAN, |(ns, _)| ns as f64 / NS_PER_S as f64)
1263 })
1264 .collect();
1265 add("time", Quantity::Unrecognized, written);
1266 }
1267 let sats: Vec<f64> = track
1268 .remarks
1269 .iter()
1270 .map(|remark| remark.map_or(f64::NAN, |remark| remark.sats))
1271 .collect();
1272 if sats.iter().any(|sats| !sats.is_nan()) {
1273 add("satellites", Quantity::Number, sats);
1274 }
1275 let offsets: Vec<f64> = track
1276 .remarks
1277 .iter()
1278 .map(|remark| remark.map_or(f64::NAN, |remark| remark.offset))
1279 .collect();
1280 if offsets.iter().any(|offset| !offset.is_nan()) {
1281 add("offset", Quantity::Number, offsets);
1282 }
1283 }
1284 notes.extend(decided.notes(&self.tracks, altos_time));
1285 notes.extend(self.notes.into_vec());
1286
1287 Ok(FlightLog {
1288 format: LogFormat::Kml,
1289 logger: about.logger,
1290 serial_number: about.serial_number,
1291 firmware: about.firmware,
1292 flight_number: about.flight_number,
1293 stated: Stated {
1294 apogee_m: about.apogee_m,
1295 ..Stated::default()
1296 },
1297 time_s: Vec::new(),
1298 altitude_m: Vec::new(),
1299 vertical_speed_m_s: None,
1300 temperature_k: None,
1301 battery_v: None,
1302 channels,
1303 events,
1304 notes,
1305 })
1306 }
1307
1308 fn document_notes(&self, notes: &mut Vec<String>) {
1310 if self.copies > 0 {
1311 notes.push(format!(
1312 "the file holds its KML document {} times over, one after another, each the same: \
1313 it is read once",
1314 self.copies + 1
1315 ));
1316 }
1317 if self.later_documents > 0 {
1318 notes.push(format!(
1319 "the file holds {} more KML documents after the first, different from it: their \
1320 tracks are read after the first's",
1321 self.later_documents
1322 ));
1323 }
1324 if self.documents_left_out > 0 {
1325 notes.push(format!(
1326 "the file holds more KML documents than the {MAX_DOCUMENTS} read: the rest are \
1327 left out"
1328 ));
1329 }
1330 if self.outside_comments > 0 {
1331 let whose = if self.memory_dump {
1332 ", as Big Red Bee's BeeLine writes its memory in hexadecimal there"
1333 } else {
1334 ""
1335 };
1336 notes.push(format!(
1337 "the file holds {} comments outside its document, the longest {} characters{whose}: \
1338 they are not read",
1339 self.outside_comments, self.longest_outside
1340 ));
1341 }
1342 if self.loose_comments > 0 {
1343 notes.push(format!(
1344 "the document holds {} comments outside any `coordinates`: they are not read",
1345 self.loose_comments
1346 ));
1347 }
1348 if self.stray_comments > 0 {
1349 notes.push(format!(
1350 "{} comments in `coordinates` follow no point's tuple: they are not read",
1351 self.stray_comments
1352 ));
1353 }
1354 if self.unknown_comments > 0 {
1355 notes.push(format!(
1356 "{} comments beside points are in no layout this reader knows: they are not read",
1357 self.unknown_comments
1358 ));
1359 }
1360 if self.bad_tuples > 0 {
1361 notes.push(format!(
1362 "{} coordinate tuples aren't two or three numbers, such as {:?}: their points are \
1363 gaps",
1364 self.bad_tuples,
1365 self.bad_tuple_example.as_deref().unwrap_or_default()
1366 ));
1367 }
1368 if self.out_of_range > 0 {
1369 notes.push(format!(
1370 "{} points have a latitude beyond ±90° or a longitude beyond ±180°: their \
1371 positions are gaps",
1372 self.out_of_range
1373 ));
1374 }
1375 if self.bad_whens > 0 {
1376 notes.push(format!(
1377 "{} `when` aren't a date and time of day, such as {:?}: those points have no time",
1378 self.bad_whens,
1379 self.bad_when_example.as_deref().unwrap_or_default()
1380 ));
1381 }
1382 if self.other_geometries > 0 {
1383 notes.push(format!(
1384 "the file holds {} polygons or models, which aren't tracks: they are not read",
1385 self.other_geometries
1386 ));
1387 }
1388 if self.empty_geometries > 0 {
1389 notes.push(format!(
1390 "{} geometries hold no point: they are left out",
1391 self.empty_geometries
1392 ));
1393 }
1394 if self.tracks_left_out > 0 {
1395 notes.push(format!(
1396 "the file holds {} more geometries than the {MAX_TRACKS} read: they are left out",
1397 self.tracks_left_out
1398 ));
1399 }
1400 if self.points_left_out > 0 {
1401 notes.push(format!(
1402 "the file holds {} more points than the {MAX_POINTS} read: they are left out",
1403 self.points_left_out
1404 ));
1405 }
1406 }
1407
1408 fn altos_time(&self) -> AltosTime {
1412 let tracks = || {
1413 self.tracks.iter().map(|track| {
1414 track
1415 .remarks
1416 .iter()
1417 .flatten()
1418 .filter(|remark| remark.layout == Layout::AltOs)
1419 .filter_map(|remark| remark.time.map(|(ns, _)| ns))
1420 })
1421 };
1422 let mut all = tracks().flatten().peekable();
1423 if all.peek().is_none() {
1424 return AltosTime::Absent;
1425 }
1426 if all.all(|ns| ns == 0) {
1427 return AltosTime::Unset;
1428 }
1429 let mut steps: Vec<i64> = Vec::new();
1430 for times in tracks() {
1431 let times: Vec<i64> = times.collect();
1432 steps.extend(
1433 times
1434 .windows(2)
1435 .map(|pair| pair[1].saturating_sub(pair[0]))
1436 .filter(|step| *step > 0),
1437 );
1438 }
1439 steps.sort_unstable();
1440 let median = steps
1441 .get(steps.len() / 2)
1442 .map_or(f64::NAN, |step| *step as f64 / NS_PER_S as f64);
1443 if ALTOS_STEP_S.contains(&median) {
1444 AltosTime::Seconds(median)
1445 } else {
1446 AltosTime::Unsettled(median)
1447 }
1448 }
1449
1450 fn stamp_from_remarks(&mut self, altos_seconds: bool) {
1453 for track in &mut self.tracks {
1454 for (stamp, remark) in track.stamps.iter_mut().zip(&track.remarks) {
1455 let Some(remark) = remark else { continue };
1456 let clock = match remark.layout {
1457 Layout::AltOs if !altos_seconds => continue,
1458 Layout::AltOs => Clock::AltOs,
1459 Layout::Seconds => Clock::Seconds,
1460 Layout::BeeLine => Clock::TimeOfDay,
1461 };
1462 if stamp.is_none()
1463 && let Some((ns, raw)) = remark.time
1464 {
1465 *stamp = Some(Stamp { clock, ns, raw });
1466 }
1467 }
1468 }
1469 }
1470
1471 fn pass_midnight(&mut self) -> Midnights {
1475 let mut days: i64 = 0;
1476 let mut previous: Option<i64> = None;
1477 let mut passed = Midnights::default();
1478 for stamp in self
1479 .tracks
1480 .iter_mut()
1481 .flat_map(|track| track.stamps.iter_mut())
1482 .filter(|stamp| stamp.is_some_and(|stamp| stamp.clock == Clock::TimeOfDay))
1483 {
1484 if passed.dropped > 0 {
1485 *stamp = None;
1486 passed.dropped += 1;
1487 continue;
1488 }
1489 let Some(read) = stamp.as_mut() else { continue };
1490 let mut ns = read.ns + days * DAY_NS;
1493 if previous.is_some_and(|previous| ns < previous - DAY_NS / 2) {
1494 if days >= MAX_MIDNIGHTS {
1495 *stamp = None;
1496 passed.dropped = 1;
1497 continue;
1498 }
1499 days += 1;
1500 ns += DAY_NS;
1501 }
1502 read.ns = ns;
1503 previous = Some(ns);
1504 }
1505 passed.days = usize::try_from(days).unwrap_or(0);
1506 passed
1507 }
1508
1509 fn times(&self, notes: &mut Vec<String>, midnights: Midnights) -> Vec<Vec<f64>> {
1511 let all = || {
1512 self.tracks
1513 .iter()
1514 .flat_map(|track| track.stamps.iter().flatten())
1515 };
1516 let zero = all().next().copied();
1517 let points: usize = self.tracks.iter().map(|track| track.lat.len()).sum();
1518 let mut other_clock = 0;
1519 let times: Vec<Vec<f64>> = self
1520 .tracks
1521 .iter()
1522 .map(|track| {
1523 track
1524 .stamps
1525 .iter()
1526 .map(|stamp| match (stamp, zero) {
1527 (Some(stamp), Some(zero)) if stamp.clock == zero.clock => stamp
1528 .ns
1529 .checked_sub(zero.ns)
1530 .map_or(f64::NAN, |ns| ns as f64 / NS_PER_S as f64),
1531 (Some(_), _) => {
1532 other_clock += 1;
1533 f64::NAN
1534 }
1535 (None, _) => f64::NAN,
1536 })
1537 .collect()
1538 })
1539 .collect();
1540 let untimed = times.iter().flatten().filter(|time| time.is_nan()).count();
1541 match zero {
1542 None => notes.push(format!(
1543 "the file gives none of its {points} points a time: their times are gaps"
1544 )),
1545 Some(zero) => {
1546 let zone = match zero.clock {
1547 Clock::TimeOfDay => " UTC",
1548 _ => "",
1549 };
1550 notes.push(format!(
1551 "the log's zero is the first point the file times: {} {}{zone}",
1552 zero.clock.word(),
1553 short(zero.raw)
1554 ));
1555 if untimed > 0 {
1556 notes.push(format!(
1557 "{untimed} of the file's {points} points have no time: their times are \
1558 gaps"
1559 ));
1560 }
1561 }
1562 }
1563 if other_clock > 0 {
1564 notes.push(format!(
1565 "{other_clock} points are timed on another clock than the first timed point's, \
1566 so they can't share its zero: their times are gaps"
1567 ));
1568 }
1569 if midnights.days > 0 {
1570 notes.push(format!(
1571 "the time of day steps back past midnight {} times: a day is added at each",
1572 midnights.days
1573 ));
1574 }
1575 if midnights.dropped > 0 {
1576 notes.push(format!(
1577 "the time of day steps back past midnight more than {MAX_MIDNIGHTS} times, more \
1578 than a logger's memory holds. The {} times of day from there on are gaps",
1579 midnights.dropped
1580 ));
1581 }
1582 let mut backs = 0;
1583 let mut largest: f64 = 0.0;
1584 for track in × {
1585 let mut previous = f64::NAN;
1586 for &time in track.iter().filter(|time| !time.is_nan()) {
1587 if time < previous {
1588 backs += 1;
1589 largest = largest.max(previous - time);
1590 }
1591 previous = time;
1592 }
1593 }
1594 if backs > 0 {
1595 notes.push(format!(
1596 "the times go back {backs} times within a track, by up to {largest:.3} s: the \
1597 points are kept in the file's order"
1598 ));
1599 }
1600 times
1601 }
1602
1603 fn names(&self) -> Vec<String> {
1606 let mut parts: HashMap<(usize, NodeId), usize> = HashMap::new();
1607 for key in self.tracks.iter().filter_map(|track| track.placemark) {
1608 *parts.entry(key).or_default() += 1;
1609 }
1610 let mut seen_parts: HashMap<(usize, NodeId), usize> = HashMap::new();
1611 let mut used: HashMap<String, usize> = HashMap::new();
1612 self.tracks
1613 .iter()
1614 .map(|track| {
1615 let mut name = track.label.clone();
1616 if let Some(key) = track.placemark
1617 && parts.get(&key).copied().unwrap_or(0) > 1
1618 {
1619 let part = seen_parts.entry(key).or_default();
1620 *part += 1;
1621 name = format!("{name} part {part}");
1622 }
1623 let count = used.entry(name.clone()).or_default();
1624 *count += 1;
1625 if *count > 1 {
1626 name = format!("{name} ({count})");
1627 }
1628 name
1629 })
1630 .collect()
1631 }
1632}
1633
1634#[derive(Debug, Default)]
1636struct About {
1637 logger: String,
1638 writer: Writer,
1639 serial_number: Option<String>,
1640 firmware: Option<String>,
1641 flight_number: Option<u32>,
1642 apogee_m: Option<f64>,
1643 note: Option<String>,
1644}
1645
1646#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
1648enum Writer {
1649 Fw2kml,
1650 Rtx,
1651 AltOs,
1652 BeeLine,
1653 GpsVisualizer,
1654 #[default]
1655 Unknown,
1656}
1657
1658impl About {
1659 fn of(document: &Document<'_>, reader: &Reader<'_>) -> Self {
1661 let root = document.root_element();
1662 let top = child(root, "Document").unwrap_or(root);
1663 let title = child(top, "name").map(|name| clean(&all_text(name)));
1664 let snippet = child(top, "Snippet").map(|node| all_text(node));
1665 let mut about = Self::default();
1666 if let Some(rest) = title
1667 .as_deref()
1668 .and_then(|title| title.strip_prefix("AO Flight#"))
1669 {
1670 about.writer = Writer::AltOs;
1671 let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();
1672 about.flight_number = digits.parse().ok();
1673 about.serial_number = rest
1674 .split_once("S/N:")
1675 .map(|(_, serial)| serial.trim().to_owned())
1676 .filter(|serial| !serial.is_empty());
1677 let mut product = None;
1678 for line in snippet.as_deref().unwrap_or_default().lines() {
1679 let Some((key, value)) = line.split_once(':') else {
1680 continue;
1681 };
1682 let value = value.trim();
1683 match key.trim() {
1684 "Product" if !value.is_empty() => product = Some(short(value)),
1685 "Firmware" if !value.is_empty() => about.firmware = Some(short(value)),
1686 "Max baro height" => about.apogee_m = stated_height_m(value),
1687 _ => {}
1688 }
1689 }
1690 about.logger = product.map_or_else(|| "AltOS".to_owned(), |p| format!("AltOS {p}"));
1691 return about;
1692 }
1693 about.writer = if title.as_deref() == Some("RTx/GPS Flight") {
1694 Writer::Rtx
1695 } else if root.descendants().any(|node| {
1696 node.is_element()
1697 && node.tag_name().name() == "name"
1698 && node
1699 .parent()
1700 .is_some_and(|parent| parent.tag_name().name() == "Placemark")
1701 && all_text(node).trim_start().starts_with("fw2kml")
1702 }) {
1703 Writer::Fw2kml
1704 } else if snippet
1705 .as_deref()
1706 .is_some_and(|text| text.contains("GPS Visualizer"))
1707 {
1708 Writer::GpsVisualizer
1709 } else if reader.memory_dump
1710 || reader
1711 .tracks
1712 .iter()
1713 .flat_map(|track| track.remarks.iter().flatten())
1714 .any(|remark| remark.layout == Layout::BeeLine)
1715 {
1716 Writer::BeeLine
1717 } else {
1718 Writer::Unknown
1719 };
1720 about.logger = match about.writer {
1721 Writer::Fw2kml => "fw2kml",
1722 Writer::Rtx => "Missile Works RTx",
1723 Writer::BeeLine => "Big Red Bee BeeLine",
1724 Writer::GpsVisualizer => "GPS Visualizer",
1725 Writer::AltOs | Writer::Unknown => "KML",
1726 }
1727 .to_owned();
1728 about
1729 }
1730}
1731
1732fn stated_height_m(text: &str) -> Option<f64> {
1734 let (value, unit) = text.trim().split_once(char::is_whitespace)?;
1735 let value = number(value, false)?;
1736 match unit.trim() {
1737 "ft" => Some(value * FOOT_M),
1738 "m" => Some(value),
1739 _ => None,
1740 }
1741}
1742
1743#[derive(Default)]
1745struct Decided {
1746 meters: usize,
1748 barometric: usize,
1750 barometric_both: usize,
1753 barometric_differing: usize,
1754 gps_visualizer: usize,
1756 ignored: Vec<&'static str>,
1758 unnamed: usize,
1760 altos_alt: Option<bool>,
1762 seconds_alt: bool,
1764}
1765
1766impl Decided {
1767 fn altitude(
1771 &mut self,
1772 track: &Track<'_>,
1773 about: &About,
1774 barometric: Option<(usize, usize)>,
1775 ) -> (&'static str, Quantity) {
1776 if about.writer == Writer::GpsVisualizer {
1777 self.gps_visualizer += 1;
1778 return ("altitude", Quantity::Unrecognized);
1779 }
1780 match track.mode {
1781 Mode::Absolute => {
1782 self.meters += 1;
1783 if let Some((both, differing)) = barometric {
1784 self.barometric += 1;
1785 self.barometric_both += both;
1786 self.barometric_differing += differing;
1787 ("altitude", Quantity::AltitudeMsl)
1788 } else {
1789 ("altitude", Quantity::GnssAltitude)
1790 }
1791 }
1792 Mode::RelativeToGround => {
1793 self.meters += 1;
1794 ("height above ground", Quantity::Distance)
1795 }
1796 Mode::RelativeToSeaFloor => {
1797 self.meters += 1;
1798 ("height above sea floor", Quantity::Distance)
1799 }
1800 Mode::Ignored(mode) => {
1801 self.ignored
1802 .push(mode.unwrap_or("clampToGround, the default, as none is stated"));
1803 ("altitude", Quantity::Unrecognized)
1804 }
1805 Mode::Unnamed => {
1806 self.unnamed += 1;
1807 ("altitude", Quantity::Unrecognized)
1808 }
1809 }
1810 }
1811
1812 fn remark_altitude(
1817 &mut self,
1818 layout: Option<Layout>,
1819 altos_meters: bool,
1820 ) -> (&'static str, Quantity) {
1821 if layout == Some(Layout::AltOs) {
1822 self.altos_alt = Some(altos_meters);
1823 let quantity = if altos_meters {
1824 Quantity::GnssAltitude
1825 } else {
1826 Quantity::Unrecognized
1827 };
1828 ("GPS altitude", quantity)
1829 } else {
1830 self.seconds_alt = true;
1831 ("Alt", Quantity::Unrecognized)
1832 }
1833 }
1834
1835 fn notes(&self, tracks: &[Track<'_>], altos_time: AltosTime) -> Vec<String> {
1837 let mut notes = Vec::new();
1838 let total = tracks.len();
1839 if self.meters > 0 {
1840 notes.push(format!(
1841 "`coordinates` read in meters, from the KML standard: OGC 07-147r2 states a \
1842 tuple's altitude in meters, and {} of the file's {total} tracks carry one",
1843 self.meters
1844 ));
1845 }
1846 if self.barometric > 0 {
1847 notes.push(format!(
1848 "`coordinates` read in meters as the barometer's altitude above sea level, from \
1849 the GPS altitude AltOS writes beside each point. In {} tracks the tuple's altitude \
1850 differs from the comment's `alt` at {} of the {} points that carry both, more \
1851 than half. That is because AltOS's KML export has reported both altitudes since \
1852 AltOS 1.8.3",
1853 self.barometric, self.barometric_differing, self.barometric_both
1854 ));
1855 }
1856 if self.gps_visualizer > 0 {
1857 let (first, highest) = extent(tracks.iter().flat_map(|track| track.alt.iter()));
1858 notes.push(format!(
1859 "`coordinates` kept as written, as GPS Visualizer takes a source's altitude as \
1860 meters unless the source's header names feet. {} tracks carry an altitude, the \
1861 highest {:.0} above the first",
1862 self.gps_visualizer,
1863 highest - first
1864 ));
1865 }
1866 if !self.ignored.is_empty() {
1867 let mut modes = self.ignored.clone();
1868 modes.sort_unstable();
1869 modes.dedup();
1870 notes.push(format!(
1871 "`coordinates` kept as written, in a track whose altitude mode tells a viewer to \
1872 ignore its altitude: {} tracks, in mode {}",
1873 self.ignored.len(),
1874 modes.join(", ")
1875 ));
1876 }
1877 if self.unnamed > 0 {
1878 notes.push(format!(
1879 "`coordinates` kept as written, in an altitude mode the KML standard doesn't \
1880 name: {} tracks",
1881 self.unnamed
1882 ));
1883 }
1884 let (equal, both) = agreement(tracks, Layout::AltOs);
1885 match self.altos_alt {
1886 Some(true) => notes.push(format!(
1887 "`alt` read in meters, from the coordinates. It equals the tuple's altitude, in \
1888 meters by the KML standard, at {equal} of the {both} points that carry both"
1889 )),
1890 Some(false) => notes.push(format!(
1891 "`alt` kept as written, as it equals the tuple's altitude at no point, so nothing \
1892 in the file shows its unit: {both} points carry both"
1893 )),
1894 None => {}
1895 }
1896 if self.seconds_alt {
1897 let (equal, both) = agreement(tracks, Layout::Seconds);
1898 notes.push(format!(
1899 "`Alt` kept as written, in a unit the file doesn't state: it equals the tuple's \
1900 altitude at {equal} of the {both} points that carry both"
1901 ));
1902 }
1903 notes.extend(clock_notes(tracks, altos_time));
1904 notes
1905 }
1906}
1907
1908fn extent<'v>(values: impl Iterator<Item = &'v f64>) -> (f64, f64) {
1910 let mut first = None;
1911 let mut highest = f64::NEG_INFINITY;
1912 for &value in values.filter(|value| !value.is_nan()) {
1913 first.get_or_insert(value);
1914 highest = highest.max(value);
1915 }
1916 first.map_or((0.0, 0.0), |first| (first, highest))
1917}
1918
1919fn agreement(tracks: &[Track<'_>], layout: Layout) -> (usize, usize) {
1922 let mut both = 0;
1923 let mut equal = 0;
1924 for track in tracks {
1925 for (tuple, remark) in track.alt.iter().zip(&track.remarks) {
1926 if let Some(remark) = remark
1927 && remark.layout == layout
1928 && !remark.alt.is_nan()
1929 && !tuple.is_nan()
1930 {
1931 both += 1;
1932 equal += usize::from((tuple - remark.alt).abs() <= 1e-6);
1933 }
1934 }
1935 }
1936 (equal, both)
1937}
1938
1939fn clock_notes(tracks: &[Track<'_>], altos_time: AltosTime) -> Vec<String> {
1941 let mut notes = Vec::new();
1942 let stamps = || {
1943 tracks
1944 .iter()
1945 .flat_map(|track| track.stamps.iter().flatten())
1946 };
1947 let count = |clock: Clock| stamps().filter(|stamp| stamp.clock == clock).count();
1948 let span = |clock: Clock| {
1949 let (low, high) = stamps()
1950 .filter(|stamp| stamp.clock == clock)
1951 .fold((i64::MAX, i64::MIN), |(low, high), stamp| {
1952 (low.min(stamp.ns), high.max(stamp.ns))
1953 });
1954 if low > high {
1955 0.0
1956 } else {
1957 high.saturating_sub(low) as f64 / NS_PER_S as f64
1958 }
1959 };
1960 let utc = count(Clock::Utc);
1961 if utc > 0 {
1962 notes.push(format!(
1963 "`when` read in UTC, from the KML standard: {utc} times state their zone, `Z` or an \
1964 offset, as XML Schema's date-time allows"
1965 ));
1966 }
1967 let local = count(Clock::Local);
1968 if local > 0 {
1969 notes.push(format!(
1970 "`when` kept as written, in a zone the file doesn't state: {local} times state none, \
1971 so the log's clock has an unknown offset from UTC"
1972 ));
1973 }
1974 let (low, high) = (ALTOS_STEP_S.start(), ALTOS_STEP_S.end());
1975 match altos_time {
1976 AltosTime::Seconds(median) => notes.push(format!(
1977 "`time` read in seconds, from the steps between points. The median step between a \
1978 track's points of distinct times is {median:.2} s. That is within the {low} to \
1979 {high} s a GPS receiver reporting once a second gives"
1980 )),
1981 AltosTime::Unsettled(median) if median.is_nan() => notes.push(
1982 "`time` kept as written, as its steps between points don't show its unit. No track \
1983 holds two points of distinct times, so those points have no time"
1984 .to_owned(),
1985 ),
1986 AltosTime::Unsettled(median) => notes.push(format!(
1987 "`time` kept as written, as its steps between points don't show its unit. The \
1988 median step between a track's points of distinct times is {median:.3} read as \
1989 seconds. That is outside the {low} to {high} s a GPS receiver reporting once a \
1990 second gives, so those points have no time"
1991 )),
1992 AltosTime::Absent | AltosTime::Unset => {}
1993 }
1994 if count(Clock::Seconds) > 0 {
1995 notes.push(format!(
1996 "`Seconds` read in seconds, from its name: the points run {:.3} s from first to last",
1997 span(Clock::Seconds)
1998 ));
1999 }
2000 if count(Clock::TimeOfDay) > 0 {
2001 notes.push(format!(
2002 "`UTC` read in hours, minutes and seconds of the UTC day, from its name and layout: \
2003 the points run {:.0} s from first to last",
2004 span(Clock::TimeOfDay)
2005 ));
2006 }
2007 notes
2008}
2009
2010#[cfg(test)]
2011mod tests {
2012 use super::*;
2013
2014 fn path(mode: &str, coordinates: &str) -> String {
2016 format!(
2017 "<?xml version=\"1.0\"?><kml xmlns=\"http://www.opengis.net/kml/2.2\"><Document>\
2018 <Placemark><name>Flight</name><LineString>{mode}<coordinates>{coordinates}\
2019 </coordinates></LineString></Placemark></Document></kml>"
2020 )
2021 }
2022
2023 #[test]
2024 fn a_kml_root_is_recognized_after_its_prolog() {
2025 for text in [
2026 "<kml xmlns=\"http://www.opengis.net/kml/2.2\">",
2027 "\u{feff}<?xml version=\"1.0\"?>\r\n<!-- a -->\n<!--b--><kml>",
2028 " <kml/>",
2029 ] {
2030 assert!(recognizes(text), "{text:?}");
2031 }
2032 for text in [
2033 "<kmlx>",
2034 "<gpx>",
2035 "<?xml version=\"1.0\"?><gpx><kml/></gpx>",
2036 "<!-- unclosed <kml>",
2037 "Time,Altitude\n",
2038 "",
2039 ] {
2040 assert!(!recognizes(text), "{text:?}");
2041 }
2042 }
2043
2044 #[test]
2045 fn whens_read_with_their_zone() {
2046 let base = days_from_civil(2026, 5, 23) * DAY_NS;
2047 assert_eq!(days_from_civil(1970, 1, 1), 0);
2048 assert_eq!(days_from_civil(2000, 3, 1), 11_017);
2049 let hour = 3_600 * NS_PER_S;
2050 let cases = [
2051 (
2052 "2026-05-23T10:15:00Z",
2053 Clock::Utc,
2054 base + 10 * hour + 900 * NS_PER_S,
2055 ),
2056 (
2057 "2026-05-23T10:15:00.25Z",
2058 Clock::Utc,
2059 base + 10 * hour + 900_250_000_000,
2060 ),
2061 (
2062 "2026-05-23T12:15:00+02:00",
2063 Clock::Utc,
2064 base + 10 * hour + 900 * NS_PER_S,
2065 ),
2066 (
2067 "2026-05-23T05:15:00-05:00",
2068 Clock::Utc,
2069 base + 10 * hour + 900 * NS_PER_S,
2070 ),
2071 (
2072 " 2026-05-23T10:15:00 ",
2073 Clock::Local,
2074 base + 10 * hour + 900 * NS_PER_S,
2075 ),
2076 (
2077 "2024-02-29T00:00:00Z",
2078 Clock::Utc,
2079 days_from_civil(2024, 2, 29) * DAY_NS,
2080 ),
2081 (
2082 "2026-05-23T10:15:00+14:00",
2083 Clock::Utc,
2084 base - 4 * hour + 900 * NS_PER_S,
2085 ),
2086 ];
2087 for (text, clock, ns) in cases {
2088 assert_eq!(when_ns(text), Some((clock, ns)), "{text}");
2089 }
2090 for text in [
2091 "2026",
2092 "2026-05",
2093 "2026-05-23",
2094 "2026-02-29T00:00:00Z",
2095 "2026-13-01T00:00:00Z",
2096 "2026-05-23T24:00:00Z",
2097 "2026-05-23T10:15Z",
2098 "2026-05-23T10:15:00+2:00",
2099 "2026-05-23T10:15:00+15:00",
2100 "2026-05-23T10:15:00+14:01",
2101 "2026-05-23T10:15:00-14:30",
2102 "2026-05-23 10:15:00Z",
2103 "26-05-23T10:15:00Z",
2104 "2026-05-23T10:15:00.Z",
2105 "2026-05-23T10:15:00.5e3Z",
2106 "",
2107 ] {
2108 assert_eq!(when_ns(text), None, "{text}");
2109 }
2110 }
2111
2112 #[test]
2113 fn decimals_read_exactly_to_the_nanosecond() {
2114 assert_eq!(decimal_ns("123.4500000"), Some(123_450_000_000));
2115 assert_eq!(decimal_ns("-0.25"), Some(-250_000_000));
2116 assert_eq!(decimal_ns("1"), Some(NS_PER_S));
2117 assert_eq!(decimal_ns(".5"), Some(500_000_000));
2118 assert_eq!(decimal_ns("0.1234567899"), Some(123_456_789));
2119 for text in ["", "-", ".", "1e3", "1.2.3", "nan", "12345678901", "+-1"] {
2120 assert_eq!(decimal_ns(text), None, "{text}");
2121 }
2122 assert_eq!(time_of_day_ns("12:34:56"), Some(45_296 * NS_PER_S));
2123 assert_eq!(time_of_day_ns("00:00:00.5"), Some(NS_PER_S / 2));
2124 for text in [
2125 "24:00:00",
2126 "1:00:00",
2127 "12:60:00",
2128 "12:00:61",
2129 "12:00:+5",
2130 "12:00:-0",
2131 "12:00:+5.5",
2132 "12:00",
2133 "12:00:00:00",
2134 ] {
2135 assert_eq!(time_of_day_ns(text), None, "{text}");
2136 }
2137 }
2138
2139 #[test]
2140 fn tuples_take_two_or_three_numbers_whatever_the_spacing() {
2141 let read: Vec<Option<(f64, f64, Option<f64>)>> =
2142 tuples(" -97.1,35.2,402\n\t-97.1, 35.2 , 415\r\n-97.2,35.3 -97.3,35.4,-0.5 ")
2143 .iter()
2144 .map(|raw| tuple(raw, false))
2145 .collect();
2146 assert_eq!(
2147 read,
2148 [
2149 Some((-97.1, 35.2, Some(402.0))),
2150 Some((-97.1, 35.2, Some(415.0))),
2151 Some((-97.2, 35.3, None)),
2152 Some((-97.3, 35.4, Some(-0.5))),
2153 ]
2154 );
2155 assert_eq!(
2156 tuple("-97.1,35.2,00850", false),
2157 Some((-97.1, 35.2, Some(850.0)))
2158 );
2159 for raw in [
2160 "-97.1",
2161 "-97.1,35.2,1,2",
2162 "-97.1,,1",
2163 "a,b",
2164 "-97.1,35.2,",
2165 "1,inf",
2166 ] {
2167 assert_eq!(tuple(raw, false), None, "{raw}");
2168 }
2169 assert_eq!(
2170 tuple(" -97.1 35.2 402.5 ", true),
2171 Some((-97.1, 35.2, Some(402.5)))
2172 );
2173 assert_eq!(tuple("-97.1 35.2", true), Some((-97.1, 35.2, None)));
2174 for raw in ["", "-97.1,35.2,402", "1 2 3 4"] {
2175 assert_eq!(tuple(raw, true), None, "{raw}");
2176 }
2177 }
2178
2179 #[test]
2180 fn each_comment_layout_reads() {
2181 let altos = remark(" alt 7.5000000 time -0.2500000 sats 5 ").unwrap();
2182 assert_eq!(
2183 (altos.layout, altos.alt, altos.time, altos.sats),
2184 (Layout::AltOs, 7.5, Some((-250_000_000, "-0.2500000")), 5.0)
2185 );
2186 assert!(altos.offset.is_nan());
2187 let seconds = remark(" Alt 250.125 Seconds 9.5 ").unwrap();
2188 assert_eq!(
2189 (seconds.layout, seconds.alt, seconds.time),
2190 (Layout::Seconds, 250.125, Some((9_500_000_000, "9.5")))
2191 );
2192 assert!(seconds.sats.is_nan());
2193 let beeline = remark(" 1003 sats:8 UTC 12:34:56 ").unwrap();
2194 assert_eq!(
2195 (beeline.layout, beeline.offset, beeline.sats, beeline.time),
2196 (
2197 Layout::BeeLine,
2198 1_003.0,
2199 8.0,
2200 Some((45_296 * NS_PER_S, "12:34:56"))
2201 )
2202 );
2203 assert!(beeline.alt.is_nan());
2204 for text in [
2205 " Name : a rocket ",
2206 " Capture Date: 01/02/2030 ",
2207 " base : 0m or 0 feet ",
2208 " alt 9 time x sats 5 ",
2209 " alt 9 time 1 sats 5 extra ",
2210 " 1 sats:x UTC 12:34:56 ",
2211 " 1 sats:4 UTC 25:00:00 ",
2212 "",
2213 ] {
2214 assert_eq!(remark(text), None, "{text:?}");
2215 }
2216 }
2217
2218 #[test]
2219 fn a_comment_belongs_to_the_tuple_right_before_it() {
2220 let log = read(&path(
2221 "<altitudeMode>absolute</altitudeMode>",
2222 "<!-- header -->\n-97.1,35.2,400 <!-- alt 401 time 0.5 sats 4 -->\n\
2223 -97.1,35.2,410 <!-- alt 411 time 1.5 sats 5 --> <!-- second -->\n-97.1,35.2,420",
2224 ))
2225 .unwrap();
2226 let columns: Vec<&str> = log.channels.iter().map(|c| c.column.as_str()).collect();
2227 assert_eq!(
2228 columns,
2229 [
2230 "Flight latitude",
2231 "Flight longitude",
2232 "Flight altitude",
2233 "Flight GPS altitude",
2234 "Flight satellites"
2235 ]
2236 );
2237 let gps = &log.channels[3];
2238 assert_eq!(gps.values[..2], [401.0, 411.0]);
2239 assert!(gps.values[2].is_nan());
2240 assert_eq!(gps.time_s[..2], [0.0, 1.0]);
2241 assert!(gps.time_s[2].is_nan());
2242 assert_eq!(log.channels[2].quantity, Quantity::AltitudeMsl);
2243 for expected in [
2245 "2 comments in `coordinates` follow no point's",
2246 "1 of the file's 3 points",
2247 ] {
2248 assert!(
2249 log.notes.iter().any(|note| note.contains(expected)),
2250 "{expected}: {:?}",
2251 log.notes
2252 );
2253 }
2254 }
2255
2256 #[test]
2257 fn the_altitude_mode_sets_the_quantity() {
2258 let quantity = |mode: &str| {
2259 let log = read(&path(mode, "-97.1,35.2,400 -97.1,35.2,410")).unwrap();
2260 (log.channels[2].column.clone(), log.channels[2].quantity)
2261 };
2262 assert_eq!(
2263 quantity("<altitudeMode>absolute</altitudeMode>"),
2264 ("Flight altitude".to_owned(), Quantity::GnssAltitude)
2265 );
2266 assert_eq!(
2267 quantity("<altitudeMode>relativeToGround</altitudeMode>"),
2268 ("Flight height above ground".to_owned(), Quantity::Distance)
2269 );
2270 assert_eq!(
2271 quantity(
2272 "<gx:altitudeMode xmlns:gx=\"http://www.google.com/kml/ext/2.2\">relativeToSeaFloor</gx:altitudeMode>"
2273 ),
2274 (
2275 "Flight height above sea floor".to_owned(),
2276 Quantity::Distance
2277 )
2278 );
2279 for mode in [
2280 "",
2281 "<altitudeMode>clampToGround</altitudeMode>",
2282 "<altitudeMode>up</altitudeMode>",
2283 ] {
2284 assert_eq!(
2285 quantity(mode),
2286 ("Flight altitude".to_owned(), Quantity::Unrecognized),
2287 "{mode}"
2288 );
2289 }
2290 let log = read(&path("", "-97.1,35.2 -97.1,35.3")).unwrap();
2292 assert_eq!(log.channels.len(), 2);
2293 }
2294
2295 #[test]
2296 fn concatenated_documents_split_at_each_declaration() {
2297 let one = path("<altitudeMode>absolute</altitudeMode>", "-97.1,35.2,400");
2298 let twice = format!("{one}\n{one}\n");
2299 let (pieces, more) = split_documents(&twice, MAX_NODES).unwrap();
2300 assert_eq!(pieces.len(), 2);
2301 assert!(!more);
2302 assert!(pieces.iter().all(|piece| piece.trim() == one));
2303 let log = read(&format!("{one}\n{one}\n{one}")).unwrap();
2304 assert_eq!(log.channels.len(), 3);
2305 assert!(
2306 log.notes.iter().any(|n| n.contains("3 times over")),
2307 "{:?}",
2308 log.notes
2309 );
2310 let other = path("<altitudeMode>absolute</altitudeMode>", "-97.2,35.3,500");
2311 let log = read(&format!("{one}{other}")).unwrap();
2312 let columns: Vec<&str> = log.channels.iter().map(|c| c.column.as_str()).collect();
2313 assert_eq!(columns[3], "Flight (2) latitude");
2314 assert!(log.notes.iter().any(|n| n.contains("1 more KML documents")));
2315 assert!(matches!(
2317 read(&format!("{one}<kml/>")),
2318 Err(LogError::Syntax { .. })
2319 ));
2320 }
2321
2322 #[test]
2323 fn hostile_documents_are_refused() {
2324 let dtd = "<?xml version=\"1.0\"?><!DOCTYPE kml [<!ENTITY a \"aaaa\">]><kml>&a;</kml>";
2325 let error = read(dtd).unwrap_err();
2326 assert!(error.to_string().contains("document type"), "{error}");
2327 assert!(matches!(
2328 read("<kml><Placemark>"),
2329 Err(LogError::Syntax { .. })
2330 ));
2331 assert!(matches!(read("<kml/>"), Err(LogError::NoData { .. })));
2332 assert!(matches!(
2333 read("<gpx/>"),
2334 Err(LogError::NotThisFormat { .. })
2335 ));
2336 }
2337
2338 #[test]
2339 fn tracks_past_the_cap_are_counted() {
2340 let pins: String = (0..MAX_TRACKS + 3)
2341 .map(|index| {
2342 format!("<Placemark><Point><coordinates>-100,40,{index}</coordinates></Point></Placemark>")
2343 })
2344 .collect();
2345 let log = read(&format!("<kml><Document>{pins}</Document></kml>")).unwrap();
2346 assert_eq!(log.channels.len(), 3 * MAX_TRACKS);
2348 assert_eq!(log.channels[3].column, "track (2) latitude");
2349 assert!(
2350 log.notes
2351 .iter()
2352 .any(|note| note.starts_with("the file holds 3 more geometries than the 256")),
2353 "{:?}",
2354 log.notes
2355 );
2356 }
2357
2358 #[test]
2359 fn a_document_type_in_the_prolog_is_stepped_past() {
2360 for text in [
2361 "<?xml version=\"1.0\"?><!DOCTYPE kml><kml/>",
2362 "<!DOCTYPE kml [<!ENTITY a \"x>y\"> <!ENTITY b 'z]'>]>\n<!-- c --><kml>&a;</kml>",
2363 ] {
2364 assert!(recognizes(text), "{text:?}");
2365 }
2366 for text in ["<!DOCTYPE kml [<!ENTITY a \"x\">", "<!DOCTYPE gpx><gpx/>"] {
2367 assert!(!recognizes(text), "{text:?}");
2368 }
2369 }
2370
2371 #[test]
2372 fn nesting_is_counted_past_comments_quotes_and_closed_tags() {
2373 assert_eq!(
2374 nesting("<a><b/><c x='>' y=\"<d>\"><!-- <e> --></c></a>"),
2375 (2, 0)
2376 );
2377 assert_eq!(nesting("<a><![CDATA[<b><c>]]><?p <q>?></a>"), (1, 0));
2378 let deep = format!("<k>\n{}", "<a>".repeat(MAX_DEPTH));
2379 assert_eq!(nesting(&deep), (MAX_DEPTH + 1, 2));
2380 let error = read(&deep).unwrap_err();
2381 assert!(
2382 matches!(&error, LogError::Syntax { line: 2, message, .. }
2383 if message.contains(&format!("nests elements {} deep", MAX_DEPTH + 1))),
2384 "{error:?}"
2385 );
2386 }
2387
2388 #[test]
2389 fn the_node_limit_is_the_files_over_all_its_documents() {
2390 let one = path("<altitudeMode>absolute</altitudeMode>", "-97.1,35.2,400");
2391 let other = path("<altitudeMode>absolute</altitudeMode>", "-97.2,35.3,500");
2392 let nodes = u32::try_from(Document::parse(&one).unwrap().descendants().count()).unwrap();
2393 assert!(read_within(&one, nodes).is_ok());
2395 assert!(read_within(&other, nodes).is_ok());
2396 let both = format!("{one}{other}");
2397 for budget in [nodes, nodes + 1, 2 * nodes - 1] {
2398 let error = read_within(&both, budget).unwrap_err();
2399 assert!(
2400 error.to_string().contains("XML nodes over its documents"),
2401 "{budget}: {error}"
2402 );
2403 }
2404 assert!(read_within(&both, 2 * nodes).is_ok());
2405 assert!(read_within(&format!("{one}\n{one}"), nodes).is_ok());
2407 }
2408
2409 fn beeline<'t>(times: impl Iterator<Item = &'t str>) -> String {
2411 let coordinates: String = times
2412 .enumerate()
2413 .map(|(index, time)| format!("-100,40,{index} <!-- {index} sats:8 UTC {time} -->\n"))
2414 .collect();
2415 path("<altitudeMode>absolute</altitudeMode>", &coordinates)
2416 }
2417
2418 #[test]
2419 fn midnight_is_passed_at_most_max_midnights_times() {
2420 let alternate = |count| beeline(["23:00:00", "00:00:00"].into_iter().cycle().take(count));
2421 let day_s = 86_400.0;
2422 let log = read(&alternate(15)).unwrap();
2424 let time = &log.channels[0].time_s;
2425 assert!(time.iter().all(|time| time.is_finite()), "{time:?}");
2426 assert_eq!(time[13], 7.0 * day_s - 23.0 * 3_600.0);
2427 assert_eq!(time[14], 7.0 * day_s);
2428 assert!(
2429 log.notes
2430 .iter()
2431 .any(|note| note.contains("midnight 7 times"))
2432 );
2433 let log = read(&alternate(16)).unwrap();
2435 assert!(log.channels[0].time_s[15].is_nan());
2436 assert!(log.channels[0].time_s[..15].iter().all(|t| t.is_finite()));
2437 assert!(
2438 log.notes.iter().any(|note| note.starts_with(
2439 "the time of day steps back past midnight more than 7 times, more than a \
2440 logger's memory holds. The 1 times of day from there on are gaps"
2441 )),
2442 "{:?}",
2443 log.notes
2444 );
2445 let log = read(&alternate(230_000)).unwrap();
2448 let time = &log.channels[0].time_s;
2449 assert_eq!(time.iter().filter(|time| time.is_finite()).count(), 15);
2450 assert!(
2451 log.notes
2452 .iter()
2453 .any(|note| note.contains("The 229985 times of day from there on are gaps")),
2454 "{:?}",
2455 log.notes
2456 );
2457 }
2458
2459 fn altos(alts: [&str; 3], times: [&str; 3]) -> String {
2462 let coordinates: String = (0..3)
2463 .map(|index| {
2464 format!(
2465 "-100,40,{} <!-- alt {} time {} sats 5 -->\n",
2466 100 * (index + 1),
2467 alts[index],
2468 times[index]
2469 )
2470 })
2471 .collect();
2472 path("<altitudeMode>absolute</altitudeMode>", &coordinates)
2473 }
2474
2475 fn quantity_of(log: &FlightLog, column: &str) -> Option<Quantity> {
2477 log.channels
2478 .iter()
2479 .find(|channel| channel.column == column)
2480 .map(|channel| channel.quantity)
2481 }
2482
2483 fn noted(log: &FlightLog, opening: &str) -> bool {
2485 log.notes.iter().any(|note| note.starts_with(opening))
2486 }
2487
2488 #[test]
2489 fn an_altos_track_is_the_barometers_where_most_of_its_points_differ() {
2490 let seconds = ["1", "2", "3"];
2491 let barometric = "`coordinates` read in meters as the barometer's altitude above sea \
2492 level, from the GPS altitude AltOS writes beside each point. ";
2493 let log = read(&altos(["100", "200", "333"], seconds)).unwrap();
2496 assert_eq!(
2497 quantity_of(&log, "Flight altitude"),
2498 Some(Quantity::GnssAltitude)
2499 );
2500 assert_eq!(
2501 quantity_of(&log, "Flight GPS altitude"),
2502 Some(Quantity::GnssAltitude)
2503 );
2504 assert!(!noted(&log, barometric), "{:?}", log.notes);
2505 assert!(noted(
2506 &log,
2507 "`alt` read in meters, from the coordinates. It equals the tuple's altitude, in meters \
2508 by the KML standard, at 2 of the 3 points that carry both"
2509 ));
2510 let log = read(&altos(["100", "222", "333"], seconds)).unwrap();
2512 assert_eq!(
2513 quantity_of(&log, "Flight altitude"),
2514 Some(Quantity::AltitudeMsl)
2515 );
2516 assert_eq!(
2517 quantity_of(&log, "Flight GPS altitude"),
2518 Some(Quantity::GnssAltitude)
2519 );
2520 assert!(
2521 noted(
2522 &log,
2523 &format!(
2524 "{barometric}In 1 tracks the tuple's altitude differs from the comment's \
2525 `alt` at 2 of the 3 points that carry both"
2526 )
2527 ),
2528 "{:?}",
2529 log.notes
2530 );
2531 let log = read(&altos(["111", "222", "333"], seconds)).unwrap();
2533 assert_eq!(
2534 quantity_of(&log, "Flight GPS altitude"),
2535 Some(Quantity::Unrecognized)
2536 );
2537 assert!(noted(
2538 &log,
2539 "`alt` kept as written, as it equals the tuple's altitude at no point, so nothing in \
2540 the file shows its unit: 3 points carry both"
2541 ));
2542 let log = read(&altos(["100", "200", "300"], seconds)).unwrap();
2544 assert_eq!(
2545 quantity_of(&log, "Flight altitude"),
2546 Some(Quantity::GnssAltitude)
2547 );
2548 assert_eq!(quantity_of(&log, "Flight GPS altitude"), None);
2549 assert!(!log.notes.iter().any(|note| note.starts_with("`alt`")));
2550 }
2551
2552 #[test]
2553 fn altos_time_is_read_in_seconds_only_where_its_steps_are_about_a_second() {
2554 let alts = ["100", "200", "300"];
2555 let log = read(&altos(alts, ["10", "11", "12"])).unwrap();
2556 assert_eq!(log.channels[0].time_s, [0.0, 1.0, 2.0]);
2557 assert_eq!(quantity_of(&log, "Flight time"), None);
2558 assert!(noted(
2559 &log,
2560 "`time` read in seconds, from the steps between points. The median step between a \
2561 track's points of distinct times is 1.00 s. That is within the 0.5 to 2 s"
2562 ));
2563 for (times, seconds) in [
2565 (["0", "0.5", "1"], true),
2566 (["0", "2", "4"], true),
2567 (["0", "0.49", "0.98"], false),
2568 (["0", "2.01", "4.02"], false),
2569 (["100", "200", "300"], false),
2570 ] {
2571 let log = read(&altos(alts, times)).unwrap();
2572 let timed = log.channels[0].time_s.iter().all(|time| time.is_finite());
2573 assert_eq!(timed, seconds, "{times:?}");
2574 assert_eq!(
2575 quantity_of(&log, "Flight time").is_none(),
2576 seconds,
2577 "{times:?}"
2578 );
2579 }
2580 let log = read(&altos(alts, ["100", "200", "300"])).unwrap();
2582 assert!(log.channels[0].time_s.iter().all(|time| time.is_nan()));
2583 let time = log
2584 .channels
2585 .iter()
2586 .find(|channel| channel.column == "Flight time")
2587 .unwrap();
2588 assert_eq!(
2589 (time.quantity, &time.values[..]),
2590 (Quantity::Unrecognized, &[100.0, 200.0, 300.0][..])
2591 );
2592 assert!(noted(
2593 &log,
2594 "`time` kept as written, as its steps between points don't show its unit. The median \
2595 step between a track's points of distinct times is 100.000 read as seconds."
2596 ));
2597 let log = read(&path(
2599 "<altitudeMode>absolute</altitudeMode>",
2600 "-100,40,100 <!-- alt 100 time 5 sats 5 -->",
2601 ))
2602 .unwrap();
2603 assert!(noted(
2604 &log,
2605 "`time` kept as written, as its steps between points don't show its unit. No track \
2606 holds two points of distinct times"
2607 ));
2608 }
2609
2610 proptest::proptest! {
2611 #[test]
2614 fn any_text_is_read_or_refused(
2615 mode in "(absolute|relativeToGround|clampToGround|x|)",
2616 coordinates in "[-0-9.,:\\s]{0,60}",
2617 comment in "(alt|Alt|time|Seconds|sats|sats:|UTC|[0-9.:-]| ){0,40}",
2618 when in "[-0-9:TZ.+]{0,30}",
2619 raw in "\\PC{0,80}",
2620 ) {
2621 let texts = [
2622 path(&format!("<altitudeMode>{mode}</altitudeMode>"), &format!("{coordinates}<!--{comment}-->{coordinates}")),
2623 format!("<kml><Placemark><name>p</name><gx:Track xmlns:gx=\"g\"><when>{when}</when><gx:coord>{coordinates}</gx:coord></gx:Track></Placemark></kml>"),
2624 format!("<kml><Placemark><TimeStamp><when>{when}</when></TimeStamp><Point><coordinates>{coordinates}</coordinates></Point></Placemark></kml>"),
2625 format!("<kml>{raw}</kml>"),
2626 raw.clone(),
2627 ];
2628 for text in texts {
2629 if let Ok(log) = read(&text) {
2630 proptest::prop_assert!(log.time_s.is_empty() && log.altitude_m.is_empty());
2631 for channel in &log.channels {
2632 proptest::prop_assert_eq!(channel.time_s.len(), channel.values.len());
2633 }
2634 for event in &log.events {
2635 proptest::prop_assert!(event.time_s.is_finite());
2636 }
2637 }
2638 }
2639 }
2640 }
2641}