1use hpr_core::gravity::STANDARD_GRAVITY_MPS2;
270
271use crate::error::LogError;
272use crate::log::{Channel, Event, FlightLog, LogFormat, Quantity, Stated};
273use crate::perfectflite::FOOT_M;
274use crate::table::{self, Notes, finite, number, numbered_lines, short};
275
276const FORMAT: &str = "Eggtimer CSV";
278
279const MILLISECONDS_ABOVE: f64 = 5.0;
283
284const NEITHER_UNIT: (f64, f64) = (1.0, 30.0);
288
289const SPEED_MATCH_RELATIVE: f64 = 0.01;
293const SPEED_MATCH_FT_S: f64 = 1.0;
294
295const SPEED_MATCH_SHARE: f64 = 0.9;
301
302const FILTERED_SCALE: std::ops::RangeInclusive<f64> = 0.1..=2.0;
314
315pub const MAX_EVENTS_PER_MARKER: usize = 16;
320
321const GRAVITY_READING_G: f64 = 0.5;
324
325const MAX_LISTED: usize = 6;
327
328#[derive(Debug, Clone, Copy, PartialEq, Eq)]
330enum Kind {
331 Altitude,
333 FilteredAltitude,
335 RawSpeed,
337 FilteredSpeed,
339 AccelerationG,
341 AccelerationFtS2,
343 InertialSpeed,
345 InertialAltitude,
347 Marker,
350 Unknown,
352}
353
354impl Kind {
355 fn quantity(self) -> (Quantity, f64) {
357 match self {
358 Self::Altitude | Self::FilteredAltitude => (Quantity::AltitudeAboveGround, FOOT_M),
359 Self::RawSpeed | Self::FilteredSpeed | Self::InertialSpeed => (Quantity::Speed, FOOT_M),
360 Self::AccelerationG => (Quantity::Acceleration, STANDARD_GRAVITY_MPS2),
361 Self::AccelerationFtS2 => (Quantity::Acceleration, FOOT_M),
362 Self::InertialAltitude => (Quantity::InertialAltitude, FOOT_M),
363 Self::Marker | Self::Unknown => (Quantity::Unrecognized, 1.0),
364 }
365 }
366}
367
368const KNOWN: [(&str, Kind); 21] = [
371 ("Alt", Kind::Altitude),
372 ("FAlt", Kind::FilteredAltitude),
373 ("Filt_Alt", Kind::FilteredAltitude),
374 ("KAlt", Kind::FilteredAltitude),
375 ("Veloc", Kind::RawSpeed),
376 ("VRaw", Kind::RawSpeed),
377 ("FVeloc", Kind::FilteredSpeed),
378 ("KVeloc", Kind::FilteredSpeed),
379 ("VFilt", Kind::FilteredSpeed),
380 ("Accel", Kind::AccelerationG),
381 ("AccelG", Kind::AccelerationG),
382 ("FAccelG", Kind::AccelerationG),
383 ("AccelFPSS", Kind::AccelerationFtS2),
384 ("FAccelFPSS", Kind::AccelerationFtS2),
385 ("VAccel", Kind::InertialSpeed),
386 ("VelocAcc", Kind::InertialSpeed),
387 ("FAccelVel", Kind::InertialSpeed),
388 ("AltAccel", Kind::InertialAltitude),
389 ("AltAcc", Kind::InertialAltitude),
390 ("FAccelAlt", Kind::InertialAltitude),
391 ("LDA", Kind::Marker),
393];
394
395const MARKERS: [&str; 11] = [
398 "LowV", "Apogee", "N-O", "Drogue", "Main", "AUX", "BurnT", "CHA", "CHB", "MaxV", "MaxA",
399];
400
401fn kind_of(name: &str) -> Option<Kind> {
403 if let Some((_, kind)) = KNOWN.iter().find(|(known, _)| *known == name) {
404 return Some(*kind);
405 }
406 let numbered = |prefix: &str| {
407 name.strip_prefix(prefix)
408 .is_some_and(|digits| !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()))
409 };
410 (MARKERS.contains(&name) || numbered("CH") || numbered("BO#") || numbered("Boost#"))
411 .then_some(Kind::Marker)
412}
413
414fn header_separator(line: &str) -> Option<char> {
418 [',', ';'].into_iter().find(|&separator| {
419 let mut names = line.split(separator).map(str::trim);
420 names.next() == Some("T")
421 && names.next() == Some("Alt")
422 && names.any(|name| kind_of(name).is_some())
423 })
424}
425
426pub(crate) fn recognizes(text: &str) -> bool {
429 numbered_lines(text)
430 .map(|(_, line)| line.trim())
431 .find(|line| !line.is_empty())
432 .is_some_and(|line| header_separator(line).is_some())
433}
434
435struct Column {
437 name: String,
438 kind: Kind,
439}
440
441impl Column {
442 fn names_its_unit(&self) -> bool {
445 match self.kind {
446 Kind::AccelerationG => self.name.ends_with('G'),
447 Kind::AccelerationFtS2 => self.name.ends_with("FPSS"),
448 _ => false,
449 }
450 }
451}
452
453pub fn read(text: &str) -> Result<FlightLog, LogError> {
463 read_table(text, Checks::Csv)
464}
465
466#[derive(Debug, Clone, Copy, PartialEq, Eq)]
470enum Checks {
471 Csv,
472 Coast,
473}
474
475fn read_table(text: &str, checks: Checks) -> Result<FlightLog, LogError> {
478 let mut lines = numbered_lines(text).filter(|(_, line)| !line.trim().is_empty());
479 let Some((header_line, header)) = lines.next() else {
480 return Err(LogError::NotThisFormat {
481 format: FORMAT,
482 message: "the file is empty".to_owned(),
483 });
484 };
485 let Some(separator) = header_separator(header) else {
486 return Err(LogError::NotThisFormat {
487 format: FORMAT,
488 message: format!(
489 "its first line, {:?}, isn't an Eggtimer header row: `T`, `Alt` and the \
490 Eggtimer's columns, such as `Veloc` or `LDA`",
491 short(header)
492 ),
493 });
494 };
495 let mut notes = Notes::default();
496 let columns = header_columns(header, separator, header_line, &mut notes)?;
497 let rows_text = || {
498 numbered_lines(text)
499 .filter(|(number, line)| *number > header_line && !line.trim().is_empty())
500 };
501 let decimal_comma = separator != ','
502 && table::decimal_comma_shown(
503 rows_text().flat_map(|(_, line)| line.split(separator).map(str::trim)),
504 );
505 if separator != ',' {
506 notes.push(format!(
507 "the cells are separated by semicolons, as a European locale's export writes them; a \
508 number's decimal mark is a {}",
509 if decimal_comma { "comma" } else { "point" }
510 ));
511 }
512
513 let mut rows: Vec<(usize, Vec<f64>)> = Vec::new();
515 let mut cells_written = 0_usize;
516 let mut blank_rows = 0_usize;
517 for (number, line) in lines {
518 let cells: Vec<&str> = line.split(separator).map(str::trim).collect();
519 if cells.iter().all(|cell| cell.is_empty()) {
520 blank_rows += 1;
521 continue;
522 }
523 if cells.len() > columns.len() + 1 {
524 return Err(syntax(
525 number,
526 format!(
527 "the row has {} cells and the header names {}",
528 cells.len(),
529 columns.len() + 1
530 ),
531 ));
532 }
533 let values = row_values(&cells, &columns, number, decimal_comma)?;
534 cells_written = cells_written.saturating_add(cells.len());
535 rows.push((number, values));
536 if crate::log::too_sparse(columns.len() + 1, rows.len(), cells_written) {
537 return Err(syntax(
538 number,
539 format!(
540 "{} rows hold {cells_written} of the {} cells the header's {} columns name: \
541 too few for the header to be this file's",
542 rows.len(),
543 rows.len().saturating_mul(columns.len() + 1),
544 columns.len() + 1
545 ),
546 ));
547 }
548 }
549 if rows.is_empty() {
550 return Err(LogError::NoData { format: FORMAT });
551 }
552 build(columns, &rows, blank_rows, notes, header_line, checks)
553}
554
555fn header_columns(
558 header: &str,
559 separator: char,
560 line: usize,
561 notes: &mut Notes,
562) -> Result<Vec<Column>, LogError> {
563 let mut columns = Vec::new();
564 let mut after_lda = false;
565 for (index, name) in header.split(separator).map(str::trim).enumerate().skip(1) {
566 if name.is_empty() {
567 return Err(syntax(
568 line,
569 format!("the header's column {} has no name", index + 1),
570 ));
571 }
572 let kind = match kind_of(name) {
573 Some(kind) => kind,
574 None if after_lda => {
575 notes.push(format!(
576 "the column {:?} isn't one this reader knows; it comes after `LDA`, where the \
577 manuals put only event markers, and was read as one",
578 short(name)
579 ));
580 Kind::Marker
581 }
582 None => {
583 notes.push(format!(
584 "the column {:?} isn't one this reader knows, and was kept as written",
585 short(name)
586 ));
587 Kind::Unknown
588 }
589 };
590 after_lda |= name == "LDA";
591 columns.push(Column {
592 name: name.to_owned(),
593 kind,
594 });
595 }
596 Ok(columns)
597}
598
599fn row_values(
602 cells: &[&str],
603 columns: &[Column],
604 line: usize,
605 decimal_comma: bool,
606) -> Result<Vec<f64>, LogError> {
607 let mut values = Vec::with_capacity(cells.len());
608 for (index, cell) in cells.iter().enumerate() {
609 if cell.is_empty() {
610 if index == 0 {
611 return Err(syntax(
612 line,
613 "the time, the row's first cell, is empty".to_owned(),
614 ));
615 }
616 values.push(f64::NAN);
617 continue;
618 }
619 let Some(value) = table::number_in_mark(cell, decimal_comma) else {
620 let under = match index.checked_sub(1).and_then(|at| columns.get(at)) {
621 Some(column) => short(&column.name),
622 None => "T".to_owned(),
623 };
624 return Err(syntax(
625 line,
626 format!(
627 "{:?} in cell {}, under {under:?}, isn't a number",
628 short(cell),
629 index + 1
630 ),
631 ));
632 };
633 values.push(value);
634 }
635 Ok(values)
636}
637
638fn build(
640 mut columns: Vec<Column>,
641 rows: &[(usize, Vec<f64>)],
642 blank_rows: usize,
643 mut notes: Notes,
644 header_line: usize,
645 checks: Checks,
646) -> Result<FlightLog, LogError> {
647 let mut written_time = Vec::with_capacity(rows.len());
649 for (number, values) in rows {
650 let time = values.first().copied().unwrap_or(f64::NAN);
652 if let Some(&last) = written_time.last()
653 && time <= last
654 {
655 return Err(syntax(
656 *number,
657 format!("the time {time} comes at or before the one above it, {last}"),
658 ));
659 }
660 written_time.push(time);
661 }
662 let clock = time_unit(&written_time);
663 if let Some((_, median)) = clock
665 && checks == Checks::Csv
666 && median > NEITHER_UNIT.0
667 && median < NEITHER_UNIT.1
668 {
669 return Err(LogError::Unit {
670 format: FORMAT,
671 line: header_line,
672 message: format!(
673 "the median step between rows of `T` is {}. That is neither seconds nor \
674 milliseconds at the manuals' 1 to 33 samples a second (0.03 to 1 s, 30 to \
675 1,000 ms). A file whose decimal points were taken out writes 0.05 s as 5",
676 plain(median, 3)
677 ),
678 });
679 }
680 let units_per_second = clock.map_or(1.0, |(per_second, _)| per_second);
681 let time_s: Vec<f64> = written_time
682 .iter()
683 .map(|time| time / units_per_second)
684 .collect();
685
686 let written: Vec<Vec<f64>> = (1..=columns.len())
688 .map(|index| {
689 rows.iter()
690 .map(|(_, values)| values.get(index).copied().unwrap_or(f64::NAN))
691 .collect()
692 })
693 .collect();
694 let step_s: Vec<f64> = time_s.windows(2).map(|pair| pair[1] - pair[0]).collect();
695 let coast = match checks {
696 Checks::Csv => None,
697 Checks::Coast => Some(coast_units(
698 &columns,
699 &written,
700 &time_s,
701 clock,
702 header_line,
703 )?),
704 };
705 filtered_checks(&columns, &written, header_line)?;
706 let speeds = speed_checks(&mut columns, &written, &step_s, &mut notes);
707
708 let decided = |index: usize| {
712 coast
713 .as_ref()
714 .and_then(|units| units.altitudes.get(index).cloned().flatten())
715 };
716 let mut unit_notes = vec![match &coast {
717 Some(units) => units.clock.clone(),
718 None => time_note(clock),
719 }];
720 let mut kept: Vec<usize> = Vec::new();
721 match decided(0) {
722 Some((note, keep)) => {
723 unit_notes.push(note);
724 if keep {
725 kept.push(0);
726 }
727 }
728 None => unit_notes.push(altitude_note(&columns, &written)),
729 }
730 let mut noted: Vec<&str> = Vec::new();
731 for (index, (column, check)) in columns.iter().zip(&speeds).enumerate() {
732 let decision = decided(index).filter(|_| column.kind == Kind::FilteredAltitude);
733 let of_kept = check.filter(|check| {
734 matches!(column.kind, Kind::RawSpeed | Kind::FilteredSpeed)
735 && decided(check.altitude).is_some_and(|(_, keep)| keep)
736 });
737 if decision.as_ref().is_some_and(|(_, keep)| *keep) || of_kept.is_some() {
738 kept.push(index);
739 }
740 if noted.contains(&column.name.as_str()) {
741 continue;
742 }
743 let note = match (decision, of_kept) {
744 (Some((note, _)), _) => Some(note),
745 (None, Some(check)) => {
746 let altitude = columns
747 .get(check.altitude)
748 .map(|altitude| short(&altitude.name))
749 .unwrap_or_default();
750 Some(format!(
751 "`{}` kept as written: it is the change in `{altitude}` over the step, and \
752 `{altitude}` is kept as written",
753 short(&column.name)
754 ))
755 }
756 (None, None) => unit_note(column, *check, &columns),
757 };
758 if let Some(note) = note {
759 noted.push(&column.name);
760 unit_notes.push(note);
761 }
762 }
763 for index in kept {
764 if let Some(column) = columns.get_mut(index) {
765 column.kind = Kind::Unknown;
766 }
767 }
768 unit_notes.extend(gravity_note(&columns, &written, &written_time));
769 unit_notes.extend(marker_note(&columns));
770
771 let mut log = FlightLog {
772 format: LogFormat::EggtimerCsv,
773 logger: "Eggtimer".to_owned(),
774 serial_number: None,
775 firmware: None,
776 flight_number: None,
777 stated: Stated::default(),
778 time_s: time_s.clone(),
779 altitude_m: Vec::new(),
780 vertical_speed_m_s: None,
781 temperature_k: None,
782 battery_v: None,
783 channels: Vec::with_capacity(columns.len()),
784 events: Vec::new(),
785 notes: unit_notes,
786 };
787 for (column, values) in columns.iter().zip(&written) {
788 let gaps = values.iter().filter(|value| value.is_nan()).count();
789 if gaps > 0 {
790 notes.push(format!(
791 "the column {:?} leaves {gaps} {} empty: {}",
792 short(&column.name),
793 if gaps == 1 { "cell" } else { "cells" },
794 if gaps == 1 {
795 "it is a gap"
796 } else {
797 "they are gaps"
798 }
799 ));
800 }
801 let (quantity, factor) = column.kind.quantity();
803 let mut si = Vec::with_capacity(values.len());
804 for ((line, _), value) in rows.iter().zip(values) {
805 si.push(finite(value * factor, FORMAT, *line, &column.name)?);
806 }
807 log.channels.push(Channel {
808 column: column.name.clone(),
809 quantity,
810 time_s: time_s.clone(),
811 values: si,
812 });
813 }
814 log.events = events(&columns, &written, &time_s, &mut notes);
815
816 log.altitude_m = columns
820 .first()
821 .filter(|column| column.kind == Kind::Altitude)
822 .and(log.channels.first())
823 .map(|channel| channel.values.clone())
824 .unwrap_or_default();
825 let speed = |kind: Kind| {
826 columns
827 .iter()
828 .zip(&log.channels)
829 .find(|(column, _)| column.kind == kind)
830 .map(|(column, channel)| (column.name.as_str(), channel.values.clone()))
831 };
832 if let Some((_, values)) = speed(Kind::RawSpeed) {
833 log.vertical_speed_m_s = Some(values);
834 } else if let Some((name, values)) = speed(Kind::FilteredSpeed) {
835 log.notes.push(format!(
836 "the file has no raw velocity, `Veloc`, read as a speed; the vertical speed is its \
837 filtered barometric {name:?}"
838 ));
839 log.vertical_speed_m_s = Some(values);
840 }
841 if blank_rows > 0 {
842 log.notes.push(format!(
843 "{blank_rows} rows hold only empty cells, and were skipped"
844 ));
845 }
846 log.notes.extend(notes.into_vec());
847 Ok(log)
848}
849
850fn filtered_checks(columns: &[Column], written: &[Vec<f64>], line: usize) -> Result<(), LogError> {
854 let Some(altitude) = written.first() else {
856 return Ok(());
857 };
858 for (column, filtered) in columns.iter().zip(written) {
859 if column.kind != Kind::FilteredAltitude {
860 continue;
861 }
862 let (mut product, mut square) = (0.0_f64, 0.0_f64);
863 for (&f, &a) in filtered.iter().zip(altitude) {
864 if f.is_finite() && a.is_finite() {
865 product += f * a;
866 square += a * a;
867 }
868 }
869 if square == 0.0 {
870 continue;
871 }
872 let factor = product / square;
873 if FILTERED_SCALE.contains(&factor) {
874 continue;
875 }
876 let measured = if factor.is_finite() {
877 format!(
878 "it is {} times `Alt` by a least-squares fit",
879 plain(factor, 3)
880 )
881 } else {
882 "its least-squares factor on `Alt` isn't a finite number".to_owned()
883 };
884 return Err(LogError::Unit {
885 format: FORMAT,
886 line,
887 message: format!(
888 "`{}` isn't a filter of `Alt`: {measured}. That is outside the 0.1 to 2 a filter of \
889 the altitude can be, so the file's numbers can't be trusted. A file whose \
890 decimal points were taken out writes `12.34` as `1234`, 100 times over",
891 short(&column.name)
892 ),
893 });
894 }
895 Ok(())
896}
897
898#[derive(Debug, Clone, Copy)]
901struct SpeedCheck {
902 altitude: usize,
903 matching: usize,
904 rows: usize,
905}
906
907fn speed_checks(
913 columns: &mut [Column],
914 written: &[Vec<f64>],
915 step_s: &[f64],
916 notes: &mut Notes,
917) -> Vec<Option<SpeedCheck>> {
918 let filtered = columns
919 .iter()
920 .position(|column| column.kind == Kind::FilteredAltitude);
921 let mut checks = vec![None; columns.len()];
922 for (index, check) in checks.iter_mut().enumerate() {
923 let altitude = match columns.get(index).map(|column| column.kind) {
925 Some(Kind::RawSpeed) => Some(0),
926 Some(Kind::FilteredSpeed) => filtered,
927 _ => None,
928 };
929 let (Some(altitude), Some(speed)) = (altitude, written.get(index)) else {
930 continue;
931 };
932 let Some(altitude_values) = written.get(altitude) else {
933 continue;
934 };
935 let (matching, rows) = speed_matches(speed, altitude_values, step_s);
936 let enough = rows == 0 || matching as f64 >= SPEED_MATCH_SHARE * rows as f64;
938 if enough {
939 *check = Some(SpeedCheck {
940 altitude,
941 matching,
942 rows,
943 });
944 continue;
945 }
946 let altitude_name = columns
947 .get(altitude)
948 .map(|column| short(&column.name))
949 .unwrap_or_default();
950 if let Some(column) = columns.get_mut(index) {
951 notes.push(format!(
952 "`{}` kept as written, not read as a speed: it is the change in \
953 `{altitude_name}` over the step, within 1 % or 1 ft/s. That holds in only {matching} of \
954 {rows} rows after the first, under the 90 % the reader asks",
955 short(&column.name)
956 ));
957 column.kind = Kind::Unknown;
958 }
959 }
960 checks
961}
962
963fn speed_matches(speed: &[f64], altitude: &[f64], step_s: &[f64]) -> (usize, usize) {
966 let (mut rows, mut matching) = (0_usize, 0_usize);
967 for (row, step) in step_s.iter().enumerate() {
968 let (Some(&low), Some(&high), Some(&value)) =
969 (altitude.get(row), altitude.get(row + 1), speed.get(row + 1))
970 else {
971 continue;
972 };
973 let change = (high - low) / step;
974 if !(change.is_finite() && value.is_finite()) {
975 continue;
976 }
977 rows += 1;
978 if (value - change).abs() <= (SPEED_MATCH_RELATIVE * change.abs()).max(SPEED_MATCH_FT_S) {
979 matching += 1;
980 }
981 }
982 (matching, rows)
983}
984
985fn events(
989 columns: &[Column],
990 written: &[Vec<f64>],
991 time_s: &[f64],
992 notes: &mut Notes,
993) -> Vec<Event> {
994 struct Marker<'a> {
995 name: String,
996 values: &'a [f64],
997 kept: usize,
998 left_out: usize,
999 }
1000 let mut markers: Vec<Marker> = columns
1001 .iter()
1002 .zip(written)
1003 .filter(|(column, _)| column.kind == Kind::Marker)
1004 .map(|(column, values)| Marker {
1005 name: short(&column.name),
1006 values,
1007 kept: 0,
1008 left_out: 0,
1009 })
1010 .collect();
1011 let marked = |value: f64| value != 0.0 && !value.is_nan();
1012 let mut events = Vec::new();
1013 for (row, time) in time_s.iter().enumerate() {
1014 for marker in &mut markers {
1015 let value = marker.values.get(row).copied().unwrap_or(f64::NAN);
1016 let before = row
1017 .checked_sub(1)
1018 .and_then(|above| marker.values.get(above))
1019 .is_some_and(|&above| marked(above));
1020 if !marked(value) || before {
1021 continue;
1022 }
1023 if marker.kept < MAX_EVENTS_PER_MARKER {
1024 marker.kept += 1;
1025 events.push(Event {
1026 time_s: *time,
1027 name: marker.name.clone(),
1028 });
1029 } else {
1030 marker.left_out += 1;
1031 }
1032 }
1033 }
1034 for marker in markers.iter().filter(|marker| marker.left_out > 0) {
1035 notes.push(format!(
1036 "the marker {:?} rises {} more times than the {MAX_EVENTS_PER_MARKER} kept as events",
1037 marker.name, marker.left_out
1038 ));
1039 }
1040 events
1041}
1042
1043fn time_unit(written: &[f64]) -> Option<(f64, f64)> {
1048 let mut steps: Vec<f64> = written.windows(2).map(|pair| pair[1] - pair[0]).collect();
1049 if steps.is_empty() {
1050 return None;
1051 }
1052 steps.sort_by(f64::total_cmp);
1053 let middle = steps.len() / 2;
1056 let median = if steps.len().is_multiple_of(2) {
1057 (steps[middle - 1] + steps[middle]) / 2.0
1058 } else {
1059 steps[middle]
1060 };
1061 let per_second = if median > MILLISECONDS_ABOVE {
1062 1000.0
1063 } else {
1064 1.0
1065 };
1066 Some((per_second, median))
1067}
1068
1069fn clock_unit(per_second: f64) -> &'static str {
1071 if per_second == 1.0 {
1072 "seconds"
1073 } else {
1074 "milliseconds"
1075 }
1076}
1077
1078fn step_evidence(median: f64) -> String {
1080 format!(
1081 "the median step between rows is {}. A step above 5 is read as milliseconds. At \
1082 the manuals' 1 to 33 samples a second, a step is 0.03 to 1 in seconds and 30 to 1,000 in \
1083 milliseconds",
1084 plain(median, 4)
1085 )
1086}
1087
1088fn time_note(clock: Option<(f64, f64)>) -> String {
1091 match clock {
1092 Some((per_second, median)) => format!(
1093 "`T` read in {}, from the step: {}",
1094 clock_unit(per_second),
1095 step_evidence(median)
1096 ),
1097 None => "`T` read in seconds, assumed: the file holds one row, so there is no step \
1098 between rows to tell seconds from milliseconds"
1099 .to_owned(),
1100 }
1101}
1102
1103const COAST_WINDOW_S: f64 = 3.0;
1110
1111const COAST_SEARCH_S: f64 = 4.0;
1120
1121const COAST_JUMP_SHARE: f64 = 0.5;
1128
1129const LEVEL_ROWS: usize = 2;
1132
1133const COAST_ROWS: usize = 6;
1136
1137const COAST_TOP_S: f64 = 1.0;
1142
1143const COAST_BAND: (f64, f64) = (0.7, 1.3);
1147
1148const COAST_CUTS: usize = 16;
1153
1154#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1156enum MarkerRole {
1157 Detection,
1160 Motor,
1163 Charge,
1167}
1168
1169fn marker_role(name: &str) -> MarkerRole {
1171 let numbered = |prefix: &str| {
1172 name.strip_prefix(prefix)
1173 .is_some_and(|digits| !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()))
1174 };
1175 if ["LDA", "LowV", "MaxV", "MaxA"].contains(&name) {
1176 MarkerRole::Detection
1177 } else if name == "BurnT" || numbered("BO#") || numbered("Boost#") {
1178 MarkerRole::Motor
1179 } else {
1180 MarkerRole::Charge
1181 }
1182}
1183
1184struct Coast {
1186 window: String,
1188 slowing: Vec<Option<f64>>,
1192}
1193
1194fn level(values: &[f64], from: usize, to: usize, row: usize) -> f64 {
1198 let half = LEVEL_ROWS
1199 .min(row.saturating_sub(from))
1200 .min(to.saturating_sub(row));
1201 let mut near: Vec<f64> = values
1202 .get(row.saturating_sub(half)..=row.saturating_add(half).min(to))
1203 .unwrap_or_default()
1204 .iter()
1205 .copied()
1206 .filter(|value| value.is_finite())
1207 .collect();
1208 if near.is_empty() {
1209 return f64::NAN;
1210 }
1211 near.sort_by(f64::total_cmp);
1212 let middle = near.len() / 2;
1213 if near.len().is_multiple_of(2) {
1216 (near[middle - 1] + near[middle]) / 2.0
1217 } else {
1218 near[middle]
1219 }
1220}
1221
1222fn parabola(points: &[(f64, f64)]) -> Option<(f64, f64)> {
1225 let (mut s, mut t) = ([0.0_f64; 5], [0.0_f64; 3]);
1226 for &(x, y) in points {
1227 let mut power = 1.0;
1228 for (order, sum) in s.iter_mut().enumerate() {
1229 *sum += power;
1230 if let Some(moment) = t.get_mut(order) {
1231 *moment += power * y;
1232 }
1233 power *= x;
1234 }
1235 }
1236 let det = |m: [[f64; 3]; 3]| {
1239 m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1])
1240 - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
1241 + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0])
1242 };
1243 let matrix = [[s[0], s[1], s[2]], [s[1], s[2], s[3]], [s[2], s[3], s[4]]];
1244 let whole = det(matrix);
1245 let solve = |column: usize| {
1246 let mut m = matrix;
1247 for (row, value) in m.iter_mut().zip(t) {
1248 row[column] = value;
1249 }
1250 det(m) / whole
1251 };
1252 let (slope, half_curvature) = (solve(1), solve(2));
1253 (slope.is_finite() && half_curvature.is_finite()).then_some((slope, 2.0 * half_curvature))
1254}
1255
1256fn coast(columns: &[Column], written: &[Vec<f64>], time_s: &[f64]) -> Result<Coast, String> {
1259 let alt = written.first().map_or(&[][..], Vec::as_slice);
1261 let count = alt.len().min(time_s.len());
1262 let Some(last) = count.checked_sub(1) else {
1263 return Err("the table has no rows".to_owned());
1264 };
1265 let levels: Vec<f64> = (0..count).map(|row| level(alt, 0, last, row)).collect();
1266 let highest = |values: &[f64], from: usize| {
1267 values
1268 .iter()
1269 .enumerate()
1270 .filter(|(_, value)| value.is_finite())
1271 .fold(
1272 None,
1273 |best: Option<(usize, f64)>, (row, &value)| match best {
1274 Some((_, high)) if high >= value => best,
1275 _ => Some((from + row, value)),
1276 },
1277 )
1278 .map(|(row, _)| row)
1279 };
1280 let Some(top) = highest(&levels, 0).and_then(|row| {
1283 let from = row.saturating_sub(LEVEL_ROWS);
1284 highest(
1285 alt.get(from..=row.saturating_add(LEVEL_ROWS).min(last))?,
1286 from,
1287 )
1288 }) else {
1289 return Err("`Alt` holds no number".to_owned());
1290 };
1291 let time = |row: usize| time_s.get(row).copied().unwrap_or(f64::NAN);
1292 let marked = |values: &[f64], row: usize| {
1293 values
1294 .get(row)
1295 .is_some_and(|value| *value != 0.0 && !value.is_nan())
1296 };
1297 let markers = |role: MarkerRole| {
1298 columns
1299 .iter()
1300 .zip(written)
1301 .filter(move |(column, _)| {
1302 column.kind == Kind::Marker && marker_role(&column.name) == role
1303 })
1304 .map(|(column, values)| (short(&column.name), values.as_slice()))
1305 };
1306
1307 let mut end = top;
1309 let mut ending = "up to the altitude's top".to_owned();
1310 let charge = markers(MarkerRole::Charge)
1311 .filter_map(|(name, values)| {
1312 (0..=top)
1313 .find(|row| marked(values, *row))
1314 .map(|row| (row, name))
1315 })
1316 .min_by_key(|(row, _)| *row);
1317 if let Some((row, name)) = charge {
1318 let Some(before) = row.checked_sub(1) else {
1319 return Err(format!(
1320 "`{name}` is marked on the first row, before any coast"
1321 ));
1322 };
1323 end = before;
1324 ending = format!(
1325 "up to the row before the marker `{name}` at {} s",
1326 plain(time(row), 3)
1327 );
1328 }
1329 let first_from = |end: usize, from_s: f64| {
1332 let row = time_s
1333 .get(..=end)
1334 .map_or(0, |times| times.partition_point(|t| *t < from_s));
1335 (row <= end).then_some(row)
1336 };
1337 let motors: Vec<(String, &[f64])> = markers(MarkerRole::Motor).collect();
1338 let mut cuts = 0;
1341 let first = loop {
1342 let end_s = time(end);
1343 let Some(first) = first_from(end, end_s - COAST_WINDOW_S) else {
1344 return Err("the table holds no row before the window's end".to_owned());
1345 };
1346 if time(0) > end_s - COAST_WINDOW_S {
1347 return Err(format!(
1348 "the table starts {} s before the coast's end, {}, short of the {} s window",
1349 plain(end_s - time(0), 3),
1350 ending,
1351 plain(COAST_WINDOW_S, 1)
1352 ));
1353 }
1354 let rise = level(alt, 0, last, end) - level(alt, 0, last, first);
1355 if rise.is_nan() || rise <= 0.0 {
1356 return Err(format!(
1357 "`Alt` doesn't rise over the {} s {ending}",
1358 plain(COAST_WINDOW_S, 1)
1359 ));
1360 }
1361 let from = first_from(end, end_s - COAST_SEARCH_S).unwrap_or(end);
1362 let stop = (from..=end).find_map(|row| {
1363 let value = alt.get(row).copied().unwrap_or(f64::NAN);
1364 let level = levels.get(row).copied().unwrap_or(f64::NAN);
1365 if value.is_finite() && (value - level).abs() > COAST_JUMP_SHARE * rise {
1366 return Some((
1367 row,
1368 format!(
1369 "up to the row before `Alt` jumps at {} s",
1370 plain(time(row), 3)
1371 ),
1372 ));
1373 }
1374 motors
1375 .iter()
1376 .find(|(_, values)| {
1377 marked(values, row) && !row.checked_sub(1).is_some_and(|up| marked(values, up))
1378 })
1379 .map(|(name, _)| {
1380 (
1381 row,
1382 format!(
1383 "up to the row before the motor's marker `{name}` at {} s",
1384 plain(time(row), 3)
1385 ),
1386 )
1387 })
1388 });
1389 match stop {
1390 Some((row, why)) => {
1391 cuts += 1;
1392 if cuts > COAST_CUTS {
1393 return Err(format!(
1394 "the coast window is cut short more than {COAST_CUTS} times by jumps or \
1395 motor markers before the top, the last {why}"
1396 ));
1397 }
1398 let Some(before) = row.checked_sub(1) else {
1399 return Err(format!("the coast window ends at the first row, {why}"));
1400 };
1401 end = before;
1402 ending = why;
1403 }
1404 None => break first,
1405 }
1406 };
1407
1408 let (start_s, end_s) = (time(first), time(end));
1409 let window = format!(
1410 "the rows from {} s to {} s, {ending}",
1411 plain(start_s, 3),
1412 plain(end_s, 3)
1413 );
1414 let fit = |values: &[f64]| {
1415 let points: Vec<(f64, f64)> = (first..=end)
1416 .map(|row| (time(row) - end_s, level(values, first, end, row)))
1417 .filter(|(_, value)| value.is_finite())
1418 .collect();
1419 (points.len(), parabola(&points))
1420 };
1421 let (rows, alt_fit) = fit(alt);
1422 if rows < COAST_ROWS {
1423 return Err(format!(
1424 "over {window}, `Alt` holds {rows} numbers, under the {COAST_ROWS} the reader asks"
1425 ));
1426 }
1427 let Some((slope, curvature)) = alt_fit.filter(|(_, curvature)| *curvature < 0.0) else {
1428 return Err(format!(
1429 "over {window}, the parabola fitted to `Alt` doesn't turn down"
1430 ));
1431 };
1432 let top_after_s = -slope / curvature;
1433 if top_after_s.abs() > COAST_TOP_S {
1434 return Err(format!(
1435 "over {window}, the parabola fitted to `Alt` tops out {} s from the window's end, \
1436 further than the {} s the reader asks",
1437 plain(top_after_s, 2),
1438 plain(COAST_TOP_S, 1)
1439 ));
1440 }
1441 let slowing = columns
1442 .iter()
1443 .zip(written)
1444 .enumerate()
1445 .map(|(index, (column, values))| match column.kind {
1446 Kind::Altitude if index == 0 => Some(-curvature),
1447 Kind::FilteredAltitude => match fit(values) {
1448 (rows, Some((_, curvature))) if rows >= COAST_ROWS => Some(-curvature),
1449 _ => None,
1450 },
1451 _ => None,
1452 })
1453 .collect();
1454 Ok(Coast { window, slowing })
1455}
1456
1457fn gravity_ft_s2() -> f64 {
1459 STANDARD_GRAVITY_MPS2 / FOOT_M
1460}
1461
1462fn in_band(slowing_g: f64) -> bool {
1464 (COAST_BAND.0..=COAST_BAND.1).contains(&slowing_g)
1465}
1466
1467struct CoastUnits {
1471 clock: String,
1472 altitudes: Vec<Option<(String, bool)>>,
1473}
1474
1475fn coast_units(
1478 columns: &[Column],
1479 written: &[Vec<f64>],
1480 time_s: &[f64],
1481 clock: Option<(f64, f64)>,
1482 header_line: usize,
1483) -> Result<CoastUnits, LogError> {
1484 let refuse = |message: String| LogError::Unit {
1485 format: FORMAT,
1486 line: header_line,
1487 message,
1488 };
1489 let Some((per_second, median)) = clock else {
1490 return Err(refuse(
1491 "the clock `T` can't be settled: the table holds one row, so it has no step and no \
1492 coast to tell seconds from milliseconds"
1493 .to_owned(),
1494 ));
1495 };
1496 let unit = clock_unit(per_second);
1497 let coast = coast(columns, written, time_s).map_err(|why| {
1498 refuse(format!(
1499 "the clock `T` is in {unit} by its step, but no coast bears that out: {why}"
1500 ))
1501 })?;
1502 let g_ft = gravity_ft_s2();
1503 let slowing = coast.slowing.first().copied().flatten().unwrap_or(f64::NAN);
1504 let (in_feet, in_meters) = (slowing / g_ft, slowing / STANDARD_GRAVITY_MPS2);
1505 let length = if in_band(in_feet) {
1506 "feet"
1507 } else if in_band(in_meters) {
1508 "meters"
1509 } else {
1510 return Err(refuse(format!(
1511 "the clock `T` is in {unit} by its step. But on that clock `Alt` slows at {} g in \
1512 feet and {} g in meters over {}. Neither is in the {} to {} g the reader \
1513 takes",
1514 plain(in_feet, 3),
1515 plain(in_meters, 3),
1516 coast.window,
1517 plain(COAST_BAND.0, 1),
1518 plain(COAST_BAND.1, 1)
1519 )));
1520 };
1521 let band = format!("{} to {} g", plain(COAST_BAND.0, 1), plain(COAST_BAND.1, 1));
1522 let clock_note = format!(
1523 "`T` read in {unit}, from the step and the coast: {}. On that clock `Alt` slows at {} g \
1524 in {length} over {}. The reader takes {band} in feet or in meters, and a clock \
1525 1,000 times off would put that slowing 10⁶ times off",
1526 step_evidence(median),
1527 plain(if length == "feet" { in_feet } else { in_meters }, 3),
1528 coast.window
1529 );
1530 let alt_feet = length == "feet";
1531 let altitudes = columns
1532 .iter()
1533 .zip(&coast.slowing)
1534 .enumerate()
1535 .map(|(index, (column, slowing))| {
1536 let name = short(&column.name);
1537 match column.kind {
1538 Kind::Altitude if index == 0 && alt_feet => Some((
1539 format!(
1540 "`{name}` read in feet, from the manual and the coast: {ALTITUDE_MANUALS}. \
1541 Over {}, it slows at {} g in feet, within the {band} the reader takes. \
1542 In meters it would be {} g{}",
1543 coast.window,
1544 plain(in_feet, 3),
1545 plain(in_meters, 3),
1546 accelerometer_ratio(columns, written)
1547 ),
1548 false,
1549 )),
1550 Kind::Altitude if index == 0 => Some((
1551 format!(
1552 "`{name}` kept as written: the manuals give feet, but over {}, it slows \
1553 at {} g in feet and {} g in meters. The reader takes {band} in \
1554 feet. The record holds no barometric altitude",
1555 coast.window,
1556 plain(in_feet, 3),
1557 plain(in_meters, 3)
1558 ),
1559 true,
1560 )),
1561 Kind::FilteredAltitude => Some(match slowing.map(|value| value / g_ft) {
1562 Some(g) if in_band(g) => (
1563 format!(
1564 "`{name}` read in feet, from the manual and the coast: it is the \
1565 logger's filtered `Alt` (Quantum p38, Proton p45), in feet. Over \
1566 {}, it slows at {} g in feet, within the {band} the reader takes",
1567 coast.window,
1568 plain(g, 3)
1569 ),
1570 false,
1571 ),
1572 Some(g) => (
1573 format!(
1574 "`{name}` kept as written: the manuals give it in feet, as the \
1575 logger's filtered `Alt` (Quantum p38, Proton p45). But over {}, it \
1576 slows at {} g in feet, outside the {band} the reader takes",
1577 coast.window,
1578 plain(g, 3)
1579 ),
1580 true,
1581 ),
1582 None => (
1583 format!(
1584 "`{name}` kept as written: the manuals give it in feet, as the \
1585 logger's filtered `Alt` (Quantum p38, Proton p45). But no parabola \
1586 can be fitted to it over {}",
1587 coast.window
1588 ),
1589 true,
1590 ),
1591 }),
1592 _ => None,
1593 }
1594 })
1595 .collect();
1596 Ok(CoastUnits {
1597 clock: clock_note,
1598 altitudes,
1599 })
1600}
1601
1602fn altitude_note(columns: &[Column], written: &[Vec<f64>]) -> String {
1605 format!(
1606 "`Alt` read in feet, from the manual: {ALTITUDE_MANUALS}{}",
1607 accelerometer_ratio(columns, written)
1608 )
1609}
1610
1611const ALTITUDE_MANUALS: &str = "the Classic and TRS manuals (p37) state feet. The Quantum and \
1613 Proton manuals give every height in feet, and no Eggtimer manual \
1614 offers meters";
1615
1616fn accelerometer_ratio(columns: &[Column], written: &[Vec<f64>]) -> String {
1619 let mut note = String::new();
1620 let find = |names: &[&str]| {
1621 columns
1622 .iter()
1623 .zip(written)
1624 .find(|(column, _)| names.contains(&column.name.as_str()))
1625 };
1626 if let (Some((g_column, g)), Some((ft_column, ft_s2))) =
1627 (find(&["AccelG", "Accel"]), find(&["AccelFPSS"]))
1628 {
1629 let (mut product, mut square) = (0.0, 0.0);
1631 for (g, ft_s2) in g.iter().zip(ft_s2) {
1632 if g.is_finite() && ft_s2.is_finite() {
1633 product += g * ft_s2;
1634 square += g * g;
1635 }
1636 }
1637 let ratio = product / square;
1638 if ratio.is_finite() {
1639 note.push_str(&format!(
1640 ". The file's `{}` is {} times its `{}`, and one g is 32.17 ft/s²",
1641 ft_column.name,
1642 plain(ratio, 2),
1643 g_column.name
1644 ));
1645 }
1646 }
1647 note
1648}
1649
1650fn unit_note(column: &Column, check: Option<SpeedCheck>, columns: &[Column]) -> Option<String> {
1653 let name = short(&column.name);
1654 let evidence = |what: &str| match check {
1655 Some(check) if check.rows > 0 => format!(
1656 "It is the change in `{}` over the step, within 1 % or 1 ft/s. That holds in {} of {} \
1657 rows after the first, where the reader asks 90 %",
1658 columns
1659 .get(check.altitude)
1660 .map(|altitude| short(&altitude.name))
1661 .unwrap_or_default(),
1662 check.matching,
1663 check.rows
1664 ),
1665 Some(_) => format!("The file has one row, so no step to check it against {what} on"),
1666 None => format!("The file has no {what} to check it against"),
1667 };
1668 let note = match column.kind {
1669 Kind::FilteredAltitude => format!(
1670 "`{name}` read in feet, from the manual: it is the logger's filtered `Alt` (Quantum \
1671 p38, Proton p45), in the same unit"
1672 ),
1673 Kind::RawSpeed => format!(
1674 "`{name}` read in feet per second, from the manual: the Classic and TRS manuals (p37) \
1675 give the velocity in ft/sec. The Proton's manual (p45) gives it as the change in `Alt` over the \
1676 step. {}",
1677 evidence("`Alt`")
1678 ),
1679 Kind::FilteredSpeed => format!(
1680 "`{name}` read in feet per second, from the manual: the Proton's manual (p46) gives \
1681 it as the filtered altitude's change over the step. The Excel guide (p7) \
1682 graphs the velocity in ft/sec. {}",
1683 evidence("filtered altitude")
1684 ),
1685 Kind::AccelerationG if !column.names_its_unit() => format!(
1686 "`{name}` read in g, from the manual: the Proton's manual (p45) gives the \
1687 accelerometer's raw value in G's"
1688 ),
1689 Kind::AccelerationFtS2 if !column.names_its_unit() => format!(
1690 "`{name}` read in feet per second squared, from the manual: the Proton's manual \
1691 (p45) gives the accelerometer's data in ft/sec^2"
1692 ),
1693 Kind::InertialSpeed => format!(
1694 "`{name}` read in feet per second, from the manual: the Proton's manual (p45) gives \
1695 the accelerometer's velocity in ft/sec"
1696 ),
1697 Kind::InertialAltitude => format!(
1698 "`{name}` read in feet, from the manual: the Proton's manual (p45) gives the \
1699 accelerometer's distance traveled in ft"
1700 ),
1701 Kind::Altitude
1702 | Kind::AccelerationG
1703 | Kind::AccelerationFtS2
1704 | Kind::Marker
1705 | Kind::Unknown => return None,
1706 };
1707 Some(note)
1708}
1709
1710fn gravity_note(columns: &[Column], written: &[Vec<f64>], written_time: &[f64]) -> Option<String> {
1716 let ft_s2_per_g = STANDARD_GRAVITY_MPS2 / FOOT_M;
1717 let mut accelerations = columns
1718 .iter()
1719 .zip(written)
1720 .filter_map(|(column, values)| match column.kind {
1721 Kind::AccelerationG => Some((column, values, 1.0)),
1722 Kind::AccelerationFtS2 => Some((column, values, ft_s2_per_g)),
1723 _ => None,
1724 });
1725 let (column, values, per_g) = accelerations.next()?;
1726 let others = if accelerations.next().is_some() {
1727 ". The file's other acceleration columns are the same accelerometer's"
1728 } else {
1729 ""
1730 };
1731 let name = short(&column.name);
1732 let mut pad: Vec<f64> = written_time
1733 .iter()
1734 .zip(values)
1735 .filter(|(time, value)| **time < 0.0 && value.is_finite())
1736 .map(|(_, value)| value / per_g)
1737 .collect();
1738 let source = "The Proton's manual doesn't say, and its release notes (2.01C, p8) have it \
1739 calibrate the accelerometer as it is armed, standing up";
1740 if pad.is_empty() {
1741 return Some(format!(
1742 "`{name}` may or may not hold gravity, not known. The file has no rows before the \
1743 start of flight (`T` below 0) to read the pad on. {source}{others}"
1744 ));
1745 }
1746 pad.sort_by(f64::total_cmp);
1747 let middle = pad.len() / 2;
1750 let median = if pad.len().is_multiple_of(2) {
1751 (pad[middle - 1] + pad[middle]) / 2.0
1752 } else {
1753 pad[middle]
1754 };
1755 let reading = format!(
1756 "its median over the {} rows before the start of flight (`T` below 0) is {} g. An \
1757 accelerometer that keeps gravity reads 1 g standing still, and one that takes it out \
1758 reads 0. {source}{others}",
1759 pad.len(),
1760 plain(median, 2)
1761 );
1762 Some(if median.abs() < GRAVITY_READING_G {
1763 format!("`{name}` has gravity taken out, from the pad: {reading}")
1764 } else if (median - 1.0).abs() < GRAVITY_READING_G {
1765 format!("`{name}` holds gravity, from the pad: {reading}")
1766 } else {
1767 format!("`{name}` may or may not hold gravity, not known: {reading}")
1768 })
1769}
1770
1771fn marker_note(columns: &[Column]) -> Option<String> {
1773 let markers: Vec<String> = columns
1774 .iter()
1775 .filter(|column| column.kind == Kind::Marker)
1776 .map(|column| format!("`{}`", short(&column.name)))
1777 .take(MAX_LISTED + 1)
1778 .collect();
1779 let count = columns
1780 .iter()
1781 .filter(|column| column.kind == Kind::Marker)
1782 .count();
1783 if count == 0 {
1784 return None;
1785 }
1786 let speeds = if columns
1787 .iter()
1788 .any(|column| column.name == "MaxV" || column.name == "MaxA")
1789 {
1790 ". At that sample the Proton's release notes (1.02N, p13) put the top speed, ft/s, in \
1791 `MaxV` and the top acceleration, ft/s², in `MaxA`"
1792 } else {
1793 ""
1794 };
1795 Some(format!(
1796 "the marker columns, kept as written: {}. Each is 0 but at the sample that marks its \
1797 event. There the Quantum's and Proton's manuals (p38, p46) put the raw altitude, in \
1798 feet{speeds}",
1799 list(&markers, count)
1800 ))
1801}
1802
1803fn list(names: &[String], count: usize) -> String {
1806 if count > MAX_LISTED {
1807 let shown = MAX_LISTED - 1;
1808 return format!(
1809 "{} and {} more columns",
1810 names.get(..shown).unwrap_or(names).join(", "),
1811 count - shown
1812 );
1813 }
1814 match names {
1815 [] => String::new(),
1816 [only] => only.clone(),
1817 [rest @ .., last] => format!("{} and {last}", rest.join(", ")),
1818 }
1819}
1820
1821fn plain(value: f64, decimals: usize) -> String {
1823 let text = format!("{value:.decimals$}");
1824 if text.contains('.') {
1825 text.trim_end_matches('0').trim_end_matches('.').to_owned()
1826 } else {
1827 text
1828 }
1829}
1830
1831fn syntax(line: usize, message: String) -> LogError {
1832 LogError::Syntax {
1833 format: FORMAT,
1834 line,
1835 message,
1836 }
1837}
1838
1839const TEXT_FORMAT: &str = "Eggtimer text";
1843
1844pub const MAX_PREAMBLE_LINES: usize = 200;
1848
1849const MAX_PREAMBLE_ITEMS: usize = 40;
1852
1853const SAME_TIME_S: f64 = 0.000_5;
1856
1857const FLIGHT_PHASES: [&str; 10] = [
1859 "flight not started",
1860 "waiting for LDA",
1861 "LDA reached",
1862 "not used",
1863 "not used",
1864 "Mach lockout expired",
1865 "nose-over",
1866 "drogue",
1867 "main deployed",
1868 "landing detected",
1869];
1870
1871pub(crate) fn recognizes_text(text: &str) -> bool {
1874 split_download(text).is_some()
1875}
1876
1877struct Download<'a> {
1879 title: &'a str,
1881 before_title: usize,
1883 preamble: Vec<&'a str>,
1886 table: &'a str,
1888 header_line: usize,
1890}
1891
1892fn split_download(text: &str) -> Option<Download<'_>> {
1896 let mut title: Option<&str> = None;
1897 let mut pending: Option<&str> = None;
1899 let mut before_title = 0_usize;
1900 let mut preamble = Vec::new();
1901 let lines = numbered_lines(text).filter(|(_, line)| !line.trim().is_empty());
1902 for (number, line) in lines.take(MAX_PREAMBLE_LINES) {
1903 let trimmed = line.trim();
1904 if let Some(title) = title {
1905 if header_separator(trimmed) == Some(',') {
1906 let start = (line.as_ptr() as usize).checked_sub(text.as_ptr() as usize)?;
1908 return Some(Download {
1909 title,
1910 before_title,
1911 preamble,
1912 table: text.get(start..)?,
1913 header_line: number,
1914 });
1915 }
1916 preamble.push(trimmed);
1917 continue;
1918 }
1919 if let Some(words) = pending.take() {
1920 if trimmed == "Flight Settings" {
1921 title = Some(words);
1922 continue;
1923 }
1924 before_title += 1;
1925 }
1926 if let Some(rest) = trimmed.strip_prefix("Eggtimer ") {
1927 match rest.strip_suffix("Flight Settings") {
1928 Some(words) => title = Some(words.trim()),
1929 None => pending = Some(rest.trim()),
1930 }
1931 } else if header_separator(trimmed) == Some(',') {
1932 return None;
1934 } else if trimmed != "Flight Summary:" {
1935 before_title += 1;
1936 }
1937 }
1938 None
1939}
1940
1941fn title_words(words: &str) -> (String, Option<String>) {
1944 let words: Vec<&str> = words.split_whitespace().collect();
1945 match words.split_last() {
1946 Some((last, model)) if last.starts_with(|c: char| c.is_ascii_digit()) => {
1947 (short(&model.join(" ")), Some(short(last)))
1948 }
1949 _ => (short(&words.join(" ")), None),
1950 }
1951}
1952
1953#[derive(Default)]
1956struct Items {
1957 kept: Vec<String>,
1958 left_out: usize,
1959}
1960
1961impl Items {
1962 fn push(&mut self, item: String) {
1963 if self.kept.len() < MAX_PREAMBLE_ITEMS {
1964 self.kept.push(item);
1965 } else {
1966 self.left_out += 1;
1967 }
1968 }
1969
1970 fn is_empty(&self) -> bool {
1971 self.kept.is_empty()
1972 }
1973
1974 fn joined(&self, separator: &str) -> String {
1976 let mut text = self.kept.join(separator);
1977 if self.left_out > 0 {
1978 text.push_str(&format!("{separator}and {} more", self.left_out));
1979 }
1980 text
1981 }
1982}
1983
1984#[derive(Default)]
1986struct Preamble {
1987 settings: Items,
1989 names: usize,
1991 summary: Items,
1993 ground_m: Option<f64>,
1995 apogee_m: Option<f64>,
1997 times: Vec<(String, f64)>,
1999 marked_times: usize,
2001 unit_notes: Vec<String>,
2003}
2004
2005fn read_preamble(lines: &[&str]) -> Preamble {
2007 let mut preamble = Preamble::default();
2008 for line in lines {
2009 if let Some(body) = line.strip_prefix("...") {
2010 match body.rsplit_once("...") {
2011 Some((label, value)) => preamble.settings.push(format!(
2012 "`{}` {}",
2013 short(label.trim()),
2014 short(value.trim())
2015 )),
2016 None => preamble.names += 1,
2017 }
2018 continue;
2019 }
2020 let Some((key, value)) = line.split_once(':') else {
2021 preamble.summary.push(format!("`{}`", short(line)));
2022 continue;
2023 };
2024 let (key, value) = (key.trim(), value.trim());
2025 let as_written = format!("`{}`", short(&format!("{key}: {value}")));
2026 let event = key
2027 .strip_prefix("T @")
2028 .or_else(|| key.strip_prefix("Time @"))
2029 .map(str::trim)
2030 .filter(|name| !name.is_empty());
2031 match (key, event) {
2032 (_, Some(name)) if preamble.times.len() < MAX_PREAMBLE_LINES => {
2033 match summary_time(value) {
2034 Some((time_s, marked)) => {
2035 preamble.times.push((short(name), time_s));
2036 preamble.marked_times += usize::from(marked);
2037 }
2038 None => preamble.summary.push(as_written),
2039 }
2040 }
2041 ("ASL Alt." | "Apogee", _) => {
2042 let (field, what) = if key == "Apogee" {
2043 (
2044 &mut preamble.apogee_m,
2045 "the logger's apogee above its zero, kept beside the table's altitudes",
2046 )
2047 } else {
2048 (
2049 &mut preamble.ground_m,
2050 "the launch site's elevation above sea level, as the logger measured it",
2051 )
2052 };
2053 match (field.is_some(), height(value)) {
2054 (false, Some((height_m, unit))) => {
2055 *field = Some(height_m);
2056 preamble.unit_notes.push(format!(
2057 "`{key}` read in {unit}, from its unit mark: the flight summary \
2058 writes {}; {what} (TRS manual p36)",
2059 short(value)
2060 ));
2061 }
2062 (false, None) => {
2063 preamble.unit_notes.push(format!(
2064 "`{key}` kept as written, with no unit mark the reader knows: the \
2065 flight summary writes {:?}, where the TRS manual's writes `ft` (p36)",
2066 short(value)
2067 ));
2068 preamble.summary.push(as_written);
2069 }
2070 (true, _) => preamble.summary.push(as_written),
2071 }
2072 }
2073 ("Last Flight Phase", _) => {
2074 let meaning = value
2075 .parse::<usize>()
2076 .ok()
2077 .and_then(|code| FLIGHT_PHASES.get(code));
2078 preamble.summary.push(match meaning {
2079 Some(meaning) => format!("{as_written} ({meaning}, TRS manual p37)"),
2080 None => as_written,
2081 });
2082 }
2083 _ => preamble.summary.push(as_written),
2084 }
2085 }
2086 preamble
2087}
2088
2089fn height(value: &str) -> Option<(f64, &'static str)> {
2092 let mut words = value.split_whitespace();
2093 let written = number(words.next()?, false)?;
2094 let unit = words.next()?;
2095 if words.next().is_some() {
2096 return None;
2097 }
2098 match unit {
2099 "ft" => Some((written * FOOT_M, "feet")),
2100 "m" => Some((written, "meters")),
2101 _ => None,
2102 }
2103}
2104
2105fn summary_time(value: &str) -> Option<(f64, bool)> {
2108 let mut words = value.split_whitespace();
2109 let seconds = number(words.next()?, false)?;
2110 let marked = match (words.next(), words.next()) {
2111 (None, _) => false,
2112 (Some("secs." | "secs" | "sec." | "sec" | "s"), None) => true,
2113 _ => return None,
2114 };
2115 Some((seconds, marked))
2116}
2117
2118fn marker_for(summary_name: &str) -> Option<&'static str> {
2121 match summary_name {
2122 "Apogee" => Some("Apogee"),
2123 "Unlock" => Some("LowV"),
2124 "N-O" | "Nose-Over" => Some("N-O"),
2125 "Drogue" | "Drogue Deploy" => Some("Drogue"),
2126 "Main" | "Main Deploy" => Some("Main"),
2127 "LDA" => Some("LDA"),
2128 _ => None,
2129 }
2130}
2131
2132pub fn read_text(text: &str) -> Result<FlightLog, LogError> {
2142 read_download(text, TEXT_FORMAT, &|line| line)
2143}
2144
2145fn read_download(
2149 text: &str,
2150 format: &'static str,
2151 file_line: &dyn Fn(usize) -> usize,
2152) -> Result<FlightLog, LogError> {
2153 let Some(download) = split_download(text) else {
2154 return Err(LogError::NotThisFormat {
2155 format,
2156 message: format!(
2157 "no title `Eggtimer … Flight Settings` comes before an Eggtimer header row, \
2158 such as `T,Alt,Veloc,…`, within the first {MAX_PREAMBLE_LINES} lines that \
2159 aren't blank"
2160 ),
2161 });
2162 };
2163 let shift = download.header_line.saturating_sub(1);
2164 let mut log = read_table(download.table, Checks::Coast).map_err(|error| match error {
2165 LogError::Syntax { line, message, .. } => LogError::Syntax {
2166 format,
2167 line: file_line(line.saturating_add(shift)),
2168 message,
2169 },
2170 LogError::Unit { line, message, .. } => LogError::Unit {
2171 format,
2172 line: file_line(line.saturating_add(shift)),
2173 message,
2174 },
2175 LogError::NoData { .. } => LogError::NoData { format },
2176 LogError::NotThisFormat { message, .. } => LogError::NotThisFormat { format, message },
2177 other => other,
2178 })?;
2179 let (model, firmware) = title_words(download.title);
2180 log.format = LogFormat::EggtimerText;
2181 log.logger = if model.is_empty() {
2182 "Eggtimer".to_owned()
2183 } else {
2184 format!("Eggtimer {model}")
2185 };
2186 log.firmware = firmware;
2187 let preamble = read_preamble(&download.preamble);
2188 log.stated.apogee_m = preamble.apogee_m;
2189 log.stated.ground_elevation_msl_m = preamble.ground_m;
2190 log.notes.extend(preamble.unit_notes.iter().cloned());
2191 summary_events(&mut log, &preamble);
2192 if !preamble.settings.is_empty() {
2193 log.notes.push(format!(
2194 "the flight settings, as the file writes them: {}",
2195 preamble.settings.joined("; ")
2196 ));
2197 }
2198 if preamble.names > 0 {
2199 log.notes.push(format!(
2200 "{} of the flight settings holds no setting: the name its owner gave the flight \
2201 computer (TRS manual p24). The name is left out of the record as free text that may \
2202 name a person",
2203 if preamble.names == 1 {
2204 "1 line".to_owned()
2205 } else {
2206 format!("{} lines", preamble.names)
2207 }
2208 ));
2209 }
2210 if !preamble.summary.is_empty() {
2211 log.notes.push(format!(
2212 "the flight summary's other lines, as the file writes them: {}",
2213 preamble.summary.joined("; ")
2214 ));
2215 }
2216 if download.before_title > 0 {
2217 log.notes.push(format!(
2218 "{} lines before the title `Eggtimer … Flight Settings` weren't read",
2219 download.before_title
2220 ));
2221 }
2222 Ok(log)
2223}
2224
2225fn summary_events(log: &mut FlightLog, preamble: &Preamble) {
2233 if preamble.times.is_empty() {
2234 return;
2235 }
2236 let (mut same, mut own, mut differ, mut zero, mut past) = (
2237 Items::default(),
2238 Items::default(),
2239 Items::default(),
2240 Items::default(),
2241 Items::default(),
2242 );
2243 let last_s = log.time_s.last().copied().unwrap_or(0.0);
2244 let mut events = Vec::new();
2245 for (name, time_s) in &preamble.times {
2246 if *time_s == 0.0 {
2247 zero.push(format!("`{name}`"));
2248 continue;
2249 }
2250 if *time_s > last_s + SAME_TIME_S {
2251 past.push(format!("`{name}` {}", plain(*time_s, 3)));
2252 continue;
2253 }
2254 let marker = marker_for(name);
2255 let marked: Vec<f64> = log
2256 .events
2257 .iter()
2258 .filter(|event| Some(event.name.as_str()) == marker)
2259 .map(|event| event.time_s)
2260 .collect();
2261 match (marker, marked.first()) {
2262 (Some(marker), Some(_))
2263 if marked
2264 .iter()
2265 .any(|marked_s| (marked_s - time_s).abs() <= SAME_TIME_S) =>
2266 {
2267 same.push(format!("`{name}` at `{marker}`"));
2268 continue;
2269 }
2270 (Some(marker), Some(marked_s)) => differ.push(format!(
2271 "`{name}` at {} s, the marker `{marker}` at {} s",
2272 plain(*time_s, 3),
2273 plain(*marked_s, 3)
2274 )),
2275 _ => own.push(format!("`{name}`")),
2276 }
2277 events.push(Event {
2278 time_s: *time_s,
2279 name: name.clone(),
2280 });
2281 }
2282 let how = if preamble.marked_times == preamble.times.len() {
2283 "`T @` and `Time @` read in seconds, from their unit mark: the flight summary writes \
2284 `secs.` after each, as the TRS manual's download does (p36)"
2285 } else {
2286 "`T @` and `Time @` read in seconds, from the manual: the TRS manual's download writes \
2287 the flight summary's times in `secs.` (p36). The same download writes its LDA at \
2288 0.700 secs. as \"700ms into the flight\" (p37)"
2289 };
2290 if !(same.is_empty() && own.is_empty() && differ.is_empty()) {
2292 log.notes.push(how.to_owned());
2293 }
2294 if !same.is_empty() {
2295 log.notes.push(format!(
2296 "the flight summary's times are its table markers' to the millisecond, one event \
2297 each, the marker's: {}",
2298 same.joined(", ")
2299 ));
2300 }
2301 if !own.is_empty() {
2302 log.notes.push(format!(
2303 "the flight summary's times of no marker in the table, each an event of its own: {}",
2304 own.joined(", ")
2305 ));
2306 }
2307 if !differ.is_empty() {
2308 log.notes.push(format!(
2309 "the flight summary's times that differ from their markers' in the table, both kept \
2310 as events: {}",
2311 differ.joined("; ")
2312 ));
2313 }
2314 if !zero.is_empty() {
2315 log.notes.push(format!(
2316 "the flight summary's times of 0, no event, as the TRS manual writes zeroes for a \
2317 channel that didn't fire (p25): {}",
2318 zero.joined(", ")
2319 ));
2320 }
2321 if !past.is_empty() {
2322 log.notes.push(format!(
2323 "the flight summary's times past the table's last, {} s, kept as written and not \
2324 read as events. No event of the flight comes after its last sample, so those times \
2325 aren't in seconds: {}",
2326 plain(last_s, 3),
2327 past.joined(", ")
2328 ));
2329 }
2330 log.events.extend(events);
2331 log.events
2332 .sort_by(|first, second| first.time_s.total_cmp(&second.time_s));
2333}
2334
2335const RTF_FORMAT: &str = "Eggtimer RTF";
2339
2340pub const MAX_RTF_DEPTH: usize = 64;
2343
2344const MAX_CONTROL_WORD: usize = 32;
2347
2348const MAX_FALLBACK: usize = 16;
2351
2352const CP1252_80_9F: [Option<char>; 32] = [
2356 Some('\u{20ac}'),
2357 None,
2358 Some('\u{201a}'),
2359 Some('\u{0192}'),
2360 Some('\u{201e}'),
2361 Some('\u{2026}'),
2362 Some('\u{2020}'),
2363 Some('\u{2021}'),
2364 Some('\u{02c6}'),
2365 Some('\u{2030}'),
2366 Some('\u{0160}'),
2367 Some('\u{2039}'),
2368 Some('\u{0152}'),
2369 None,
2370 Some('\u{017d}'),
2371 None,
2372 None,
2373 Some('\u{2018}'),
2374 Some('\u{2019}'),
2375 Some('\u{201c}'),
2376 Some('\u{201d}'),
2377 Some('\u{2022}'),
2378 Some('\u{2013}'),
2379 Some('\u{2014}'),
2380 Some('\u{02dc}'),
2381 Some('\u{2122}'),
2382 Some('\u{0161}'),
2383 Some('\u{203a}'),
2384 Some('\u{0153}'),
2385 None,
2386 Some('\u{017e}'),
2387 Some('\u{0178}'),
2388];
2389
2390pub(crate) fn recognizes_rtf(text: &str) -> bool {
2393 text.trim_start_matches(|c: char| c == '\u{feff}' || c.is_whitespace())
2394 .starts_with("{\\rtf")
2395}
2396
2397#[derive(Debug, Default)]
2399struct Unwrapped {
2400 text: String,
2402 starts: Vec<usize>,
2404 at_line_start: bool,
2406 unmapped: usize,
2409 after_end: usize,
2411}
2412
2413impl Unwrapped {
2414 fn push(&mut self, c: char, line: usize) {
2416 if c == '\r' || c == '\n' {
2417 self.line_break(line);
2418 return;
2419 }
2420 if self.at_line_start {
2421 self.starts.push(line);
2422 self.at_line_start = false;
2423 }
2424 self.text.push(c);
2425 }
2426
2427 fn line_break(&mut self, line: usize) {
2429 if self.at_line_start {
2430 self.starts.push(line);
2431 }
2432 self.text.push('\n');
2433 self.at_line_start = true;
2434 }
2435
2436 fn file_line(&self, line: usize) -> usize {
2439 line.checked_sub(1)
2440 .and_then(|index| self.starts.get(index))
2441 .or(self.starts.last())
2442 .copied()
2443 .unwrap_or(1)
2444 }
2445}
2446
2447#[derive(Debug, Clone, Copy)]
2450struct Group {
2451 skip: bool,
2452 fallback: usize,
2453}
2454
2455fn rtf_syntax(line: usize, message: String) -> LogError {
2457 LogError::Syntax {
2458 format: RTF_FORMAT,
2459 line,
2460 message,
2461 }
2462}
2463
2464fn unwrap_rtf(document: &str) -> Result<Unwrapped, LogError> {
2467 let mut out = Unwrapped {
2468 at_line_start: true,
2469 ..Unwrapped::default()
2470 };
2471 let mut chars = document
2472 .strip_prefix('\u{feff}')
2473 .unwrap_or(document)
2474 .chars();
2475 let mut line = 1_usize;
2476 let mut groups: Vec<Group> = Vec::new();
2477 let mut opened = false;
2478 let mut code_page_1252 = true;
2479 let mut skip_fallback = 0_usize;
2481 while let Some(c) = chars.next() {
2482 match c {
2483 '\r' => {
2484 if chars.as_str().starts_with('\n') {
2485 chars.next();
2486 }
2487 line += 1;
2488 }
2489 '\n' => line += 1,
2490 '{' => {
2491 if groups.len() >= MAX_RTF_DEPTH {
2492 return Err(rtf_syntax(
2493 line,
2494 format!("the document's groups nest deeper than {MAX_RTF_DEPTH}"),
2495 ));
2496 }
2497 let group = groups.last().copied().unwrap_or(Group {
2498 skip: false,
2499 fallback: 1,
2500 });
2501 groups.push(group);
2502 opened = true;
2503 skip_fallback = 0;
2504 }
2505 '}' => {
2506 if groups.pop().is_none() {
2507 return Err(rtf_syntax(
2508 line,
2509 "a `}` closes a group that was never opened".to_owned(),
2510 ));
2511 }
2512 skip_fallback = 0;
2513 if groups.is_empty() {
2514 out.after_end = chars.filter(|c| !c.is_whitespace()).count();
2515 return Ok(out);
2516 }
2517 }
2518 _ if groups.is_empty() => {
2519 if !c.is_whitespace() {
2520 return Err(rtf_syntax(
2521 line,
2522 "text comes before the document's opening `{`".to_owned(),
2523 ));
2524 }
2525 }
2526 '\\' => {
2527 let skip = groups.last().is_some_and(|group| group.skip);
2528 let Some(next) = chars.next() else {
2529 break;
2530 };
2531 if next.is_ascii_alphabetic() {
2532 let mut word = String::new();
2533 word.push(next);
2534 while let Some(letter) = chars.as_str().chars().next() {
2535 if !letter.is_ascii_alphabetic() {
2536 break;
2537 }
2538 chars.next();
2539 if word.len() <= MAX_CONTROL_WORD {
2540 word.push(letter);
2541 }
2542 }
2543 let parameter = control_parameter(&mut chars);
2544 if chars.as_str().starts_with(' ') {
2545 chars.next();
2546 }
2547 control_word(
2548 &word,
2549 parameter,
2550 &mut ControlState {
2551 out: &mut out,
2552 groups: &mut groups,
2553 chars: &mut chars,
2554 line: &mut line,
2555 code_page_1252: &mut code_page_1252,
2556 skip_fallback: &mut skip_fallback,
2557 },
2558 );
2559 continue;
2560 }
2561 let symbol = match next {
2562 '\\' | '{' | '}' => Some(next),
2563 '\'' => {
2564 let high = chars.next().and_then(|c| c.to_digit(16));
2565 let low = chars.next().and_then(|c| c.to_digit(16));
2566 let (Some(high), Some(low)) = (high, low) else {
2567 return Err(rtf_syntax(
2568 line,
2569 "a `\\'` escape isn't followed by two hexadecimal digits"
2570 .to_owned(),
2571 ));
2572 };
2573 let c = code_page_character(high * 16 + low, code_page_1252);
2574 if c.is_none() && !skip && skip_fallback == 0 {
2575 out.unmapped += 1;
2576 }
2577 Some(c.unwrap_or(char::REPLACEMENT_CHARACTER))
2578 }
2579 '~' => Some('\u{a0}'),
2580 '_' => Some('-'),
2581 '\r' | '\n' => {
2582 if !skip {
2584 out.line_break(line);
2585 }
2586 if next == '\r' && chars.as_str().starts_with('\n') {
2587 chars.next();
2588 }
2589 line += 1;
2590 continue;
2591 }
2592 '*' => {
2595 if let Some(group) = groups.last_mut() {
2596 group.skip = true;
2597 }
2598 continue;
2599 }
2600 _ => None,
2602 };
2603 if let Some(c) = symbol
2604 && !skip
2605 {
2606 if skip_fallback > 0 {
2607 skip_fallback -= 1;
2608 } else {
2609 out.push(c, line);
2610 }
2611 }
2612 }
2613 _ => {
2614 if groups.last().is_some_and(|group| group.skip) {
2615 continue;
2616 }
2617 if skip_fallback > 0 {
2618 skip_fallback -= 1;
2619 } else if c == '\t' || !c.is_control() {
2620 out.push(c, line);
2621 }
2622 }
2623 }
2624 }
2625 if opened {
2626 Err(rtf_syntax(
2627 line,
2628 format!(
2629 "the document ends with {} groups open: its braces don't balance",
2630 groups.len()
2631 ),
2632 ))
2633 } else {
2634 Err(LogError::NotThisFormat {
2635 format: RTF_FORMAT,
2636 message: "the file holds no RTF group, `{\\rtf…}`".to_owned(),
2637 })
2638 }
2639}
2640
2641struct ControlState<'a, 'b> {
2643 out: &'a mut Unwrapped,
2644 groups: &'a mut Vec<Group>,
2645 chars: &'a mut std::str::Chars<'b>,
2646 line: &'a mut usize,
2647 code_page_1252: &'a mut bool,
2648 skip_fallback: &'a mut usize,
2649}
2650
2651fn control_word(word: &str, parameter: Option<i64>, state: &mut ControlState<'_, '_>) {
2653 let skip = state.groups.last().is_some_and(|group| group.skip);
2654 match word {
2655 "fonttbl" | "colortbl" | "stylesheet" | "info" | "pict" | "object" => {
2656 if let Some(group) = state.groups.last_mut() {
2657 group.skip = true;
2658 }
2659 }
2660 "uc" => {
2661 if let Some(group) = state.groups.last_mut() {
2662 group.fallback = usize::try_from(parameter.unwrap_or(1))
2663 .map_or(0, |count| count.min(MAX_FALLBACK));
2664 }
2665 }
2666 "ansicpg" => *state.code_page_1252 = parameter == Some(1252),
2667 "mac" | "pc" | "pca" => *state.code_page_1252 = false,
2668 "bin" => {
2669 let count = usize::try_from(parameter.unwrap_or(0)).unwrap_or(0);
2672 for _ in 0..count {
2673 match state.chars.next() {
2674 Some('\n') => *state.line += 1,
2675 Some(_) => {}
2676 None => break,
2677 }
2678 }
2679 }
2680 _ if skip => {}
2681 "u" => {
2682 let code = parameter.unwrap_or(0);
2684 let code = if code < 0 { code + 0x1_0000 } else { code };
2685 let c = u32::try_from(code)
2686 .ok()
2687 .and_then(char::from_u32)
2688 .unwrap_or(char::REPLACEMENT_CHARACTER);
2689 state.out.push(c, *state.line);
2690 *state.skip_fallback = state.groups.last().map_or(1, |group| group.fallback);
2691 }
2692 "par" | "line" | "sect" | "page" | "row" => state.out.line_break(*state.line),
2693 "tab" | "cell" => state.out.push('\t', *state.line),
2694 _ => {
2695 if let Some(c) = word_character(word) {
2696 state.out.push(c, *state.line);
2697 }
2698 }
2699 }
2700}
2701
2702fn control_parameter(chars: &mut std::str::Chars<'_>) -> Option<i64> {
2705 let mut ahead = chars.as_str().chars();
2706 let negative = ahead.next() == Some('-') && ahead.next().is_some_and(|c| c.is_ascii_digit());
2707 if negative {
2708 chars.next();
2709 }
2710 let mut value: Option<i64> = None;
2711 while let Some(digit) = chars.as_str().chars().next().and_then(|c| c.to_digit(10)) {
2712 chars.next();
2713 value = Some(
2714 value
2715 .unwrap_or(0)
2716 .saturating_mul(10)
2717 .saturating_add(i64::from(digit)),
2718 );
2719 }
2720 value.map(|value| if negative { -value } else { value })
2721}
2722
2723fn code_page_character(byte: u32, code_page_1252: bool) -> Option<char> {
2726 match byte {
2727 0..0x80 => char::from_u32(byte),
2728 _ if !code_page_1252 => None,
2729 0x80..0xa0 => usize::try_from(byte - 0x80)
2730 .ok()
2731 .and_then(|index| CP1252_80_9F.get(index))
2732 .copied()
2733 .flatten(),
2734 _ => char::from_u32(byte),
2735 }
2736}
2737
2738fn word_character(word: &str) -> Option<char> {
2740 match word {
2741 "emdash" => Some('\u{2014}'),
2742 "endash" => Some('\u{2013}'),
2743 "emspace" | "enspace" | "qmspace" => Some(' '),
2744 "bullet" => Some('\u{2022}'),
2745 "lquote" => Some('\u{2018}'),
2746 "rquote" => Some('\u{2019}'),
2747 "ldblquote" => Some('\u{201c}'),
2748 "rdblquote" => Some('\u{201d}'),
2749 _ => None,
2750 }
2751}
2752
2753fn row_like(line: &str) -> bool {
2757 line.trim_start()
2758 .starts_with(|c: char| c.is_ascii_digit() || matches!(c, '-' | '+' | '.'))
2759}
2760
2761fn later_titles(text: &str, after_line: usize) -> Vec<usize> {
2765 let lines: Vec<(usize, &str)> = numbered_lines(text)
2766 .map(|(number, line)| (number, line.trim()))
2767 .filter(|(number, line)| *number > after_line && !line.is_empty())
2768 .collect();
2769 lines
2770 .iter()
2771 .enumerate()
2772 .filter(|(index, (_, line))| {
2773 line.strip_prefix("Eggtimer ").is_some_and(|rest| {
2774 rest.ends_with("Flight Settings")
2775 || lines
2776 .get(index + 1)
2777 .is_some_and(|(_, next)| *next == "Flight Settings")
2778 })
2779 })
2780 .map(|(_, (number, _))| *number)
2781 .collect()
2782}
2783
2784pub fn read_rtf(text: &str) -> Result<FlightLog, LogError> {
2825 if !recognizes_rtf(text) {
2826 return Err(LogError::NotThisFormat {
2827 format: RTF_FORMAT,
2828 message: "the file doesn't open with `{\\rtf`, an RTF document's opening group"
2829 .to_owned(),
2830 });
2831 }
2832 let unwrapped = unwrap_rtf(text)?;
2833 let Some(first) = split_download(&unwrapped.text) else {
2834 return Err(LogError::NotThisFormat {
2835 format: RTF_FORMAT,
2836 message: format!(
2837 "the RTF document's text holds no Eggtimer terminal download. No title \
2838 `Eggtimer … Flight Settings` comes before an Eggtimer header row, such as \
2839 `T,Alt,Veloc,…`, within the first {MAX_PREAMBLE_LINES} lines that aren't blank"
2840 ),
2841 });
2842 };
2843 let others = later_titles(&unwrapped.text, first.header_line);
2844 let download = match others.first() {
2846 Some(&next_title) => {
2847 let last_row = numbered_lines(&unwrapped.text)
2848 .take_while(|(number, _)| *number < next_title)
2849 .filter(|(_, line)| row_like(line))
2850 .map(|(number, _)| number)
2851 .last()
2852 .unwrap_or(first.header_line)
2853 .max(first.header_line);
2854 let end = unwrapped
2856 .text
2857 .match_indices('\n')
2858 .nth(last_row.saturating_sub(1))
2859 .map_or(unwrapped.text.len(), |(at, _)| at);
2860 unwrapped.text.get(..end).unwrap_or(&unwrapped.text)
2861 }
2862 None => unwrapped.text.as_str(),
2863 };
2864 let mut log = read_download(download, RTF_FORMAT, &|line| unwrapped.file_line(line))?;
2865 log.format = LogFormat::EggtimerRtf;
2866 log.notes.insert(
2867 0,
2868 "the text was unwrapped from an RTF document, as a text editor saves a terminal \
2869 program's capture. The document's groups, control words and escapes were taken out, and its \
2870 paragraph and line breaks were read as the download's lines. A line named is the \
2871 document's"
2872 .to_owned(),
2873 );
2874 if !others.is_empty() {
2875 let lines: Vec<String> = others
2876 .iter()
2877 .take(MAX_LISTED)
2878 .map(|line| unwrapped.file_line(*line).to_string())
2879 .collect();
2880 let more = others.len().saturating_sub(MAX_LISTED);
2881 log.notes.push(format!(
2882 "the document holds {} Eggtimer downloads one after another. The first was read, as \
2883 a record holds one flight. The titles of those that weren't are on lines {}{}",
2884 others.len() + 1,
2885 lines.join(", "),
2886 if more > 0 {
2887 format!(" and {more} more")
2888 } else {
2889 String::new()
2890 }
2891 ));
2892 }
2893 if unwrapped.unmapped > 0 {
2894 log.notes.push(format!(
2895 "{} escaped bytes were read as U+FFFD. They are undefined in the document's code page, \
2896 or in a code page the reader doesn't map (it maps Windows 1252)",
2897 unwrapped.unmapped
2898 ));
2899 }
2900 if unwrapped.after_end > 0 {
2901 log.notes.push(format!(
2902 "{} characters after the document's closing brace weren't read",
2903 unwrapped.after_end
2904 ));
2905 }
2906 Ok(log)
2907}
2908
2909#[cfg(test)]
2910mod tests {
2911 use super::*;
2912
2913 const TRS: &str = "T,Alt,Veloc,FAlt,FVeloc,LDA,LowV,Apogee,N-O,Drogue,Main";
2914
2915 fn close(a: f64, b: f64) -> bool {
2916 (a - b).abs() <= 1e-12 * b.abs().max(1.0)
2917 }
2918
2919 fn prefix(note: &str) -> &str {
2922 note.split(": ").next().unwrap_or(note)
2923 }
2924
2925 #[test]
2926 fn recognizes_the_eggtimer_headers_and_no_others() {
2927 for header in [
2928 TRS,
2929 "T,Alt,Veloc,Filt_Alt,FVeloc,LDA,LowV,Apogee,N-O,Drogue,Main",
2930 "T,Alt,FAlt,FVeloc,LDA,LowV,Apogee,N-O,Drogue,Main,AUX",
2931 "T,Alt,Veloc,KAlt,KVeloc,LDA,BurnT,LowV,Apogee,N-O,CHA,CHB",
2932 "T, Alt, VRaw, VFilt",
2933 "T,Alt,Veloc,AccelG,AccelFPSS,VAccel,AltAccel,FAlt,FVeloc,FAccelG,FAccelFPSS,\
2934 FAccelVel,FAccelAlt,LDA,MaxV,MaxA,BO#1,LowV,Apogee,N-O,CH1,CH2",
2935 "T,Alt,Apogee",
2936 "T;Alt;Veloc;Filt_Alt;FVeloc;LDA;LowV;Apogee;N-O;Drogue;Main",
2937 ] {
2938 assert!(recognizes(&format!("\r\n{header}\r\n0,0\r\n")), "{header}");
2939 }
2940 for text in [
2941 "",
2942 "T,Alt\n",
2943 "T,Alt,Foo\n",
2944 "T\tAlt\tVeloc\n",
2945 "t,alt,veloc\n",
2946 "Time,Altitude,Velocity\n",
2947 "Time,Altitude,Pressure,Velocity,Temperature,Events,Voltages\n",
2948 "Alt,T,Veloc\n",
2949 "# T,Alt,Veloc\n",
2950 "T;Alt;Foo\n",
2951 "Time;Altitude;Pressure;Velocity;Temperature;Events;Voltages;\n",
2952 ] {
2953 assert!(!recognizes(text), "{text:?}");
2954 }
2955 assert_eq!(kind_of("CH12"), Some(Kind::Marker));
2956 assert_eq!(kind_of("Boost#3"), Some(Kind::Marker));
2957 assert_eq!(kind_of("CH"), None);
2958 assert_eq!(kind_of("BO#x"), None);
2959 }
2960
2961 #[test]
2964 fn reads_the_layout_in_seconds() {
2965 let text = format!(
2966 "{TRS}\n\
2967 0,0,0,0,0,0,0,0,0,0,0\n\
2968 0.05,10,200,2,40,0,0,0,0,0,0\n\
2969 0.1,25,300,7,100,25,0,0,0,0,0\n\
2970 0.15,30,100,13.5,130,0,0,30,0,0,0\n\
2971 0.2,29,-20,18,90,0,0,0,29,29,0\n"
2972 );
2973 let log = read(&text).unwrap();
2974 assert_eq!(log.format, LogFormat::EggtimerCsv);
2975 assert_eq!(log.logger, "Eggtimer");
2976 assert_eq!(log.time_s, [0.0, 0.05, 0.1, 0.15, 0.2]);
2977 assert!(close(log.altitude_m[2], 25.0 * 0.3048));
2978 let speed = log.vertical_speed_m_s.as_deref().unwrap();
2979 assert!(close(speed[1], 200.0 * 0.3048));
2980 assert_eq!(log.channels.len(), 10);
2981 assert_eq!(log.channels[2].quantity, Quantity::AltitudeAboveGround);
2982 assert!(close(log.channels[2].values[3], 13.5 * 0.3048));
2983 assert_eq!(log.channels[3].quantity, Quantity::Speed);
2984 assert_eq!(log.channels[4].column, "LDA");
2986 assert_eq!(log.channels[4].quantity, Quantity::Unrecognized);
2987 assert_eq!(log.channels[4].values, [0.0, 0.0, 25.0, 0.0, 0.0]);
2988 let events: Vec<(f64, &str)> = log
2989 .events
2990 .iter()
2991 .map(|event| (event.time_s, event.name.as_str()))
2992 .collect();
2993 assert_eq!(
2994 events,
2995 [
2996 (0.1, "LDA"),
2997 (0.15, "Apogee"),
2998 (0.2, "N-O"),
2999 (0.2, "Drogue")
3000 ]
3001 );
3002 assert_eq!(log.notes.len(), 6, "{:?}", log.notes);
3003 assert_eq!(
3004 log.notes[0],
3005 "`T` read in seconds, from the step: the median step between rows is 0.05. A \
3006 step above 5 is read as milliseconds. At the manuals' 1 to 33 samples a second, \
3007 a step is 0.03 to 1 in seconds and 30 to 1,000 in milliseconds"
3008 );
3009 assert_eq!(
3010 log.notes[1],
3011 "`Alt` read in feet, from the manual: the Classic and TRS manuals (p37) state feet. \
3012 The Quantum and Proton manuals give every height in feet, and no Eggtimer manual \
3013 offers meters"
3014 );
3015 assert_eq!(
3016 log.notes[2],
3017 "`Veloc` read in feet per second, from the manual: the Classic and TRS manuals (p37) \
3018 give the velocity in ft/sec. The Proton's manual (p45) gives it as the change in `Alt` over the \
3019 step. It is the change in `Alt` over the step, within 1 % or 1 ft/s. That holds in 4 \
3020 of 4 rows after the first, where the reader asks 90 %"
3021 );
3022 assert!(log.notes[3].starts_with("`FAlt` read in feet, from the manual: "));
3023 assert!(
3024 log.notes[4].starts_with("`FVeloc` read in feet per second, from the manual: ")
3025 && log.notes[4].contains("the change in `FAlt` over the step")
3026 && log.notes[4].contains("in 4 of 4 rows after the first"),
3027 "{}",
3028 log.notes[4]
3029 );
3030 assert_eq!(
3031 log.notes[5],
3032 "the marker columns, kept as written: `LDA`, `LowV`, `Apogee`, `N-O`, `Drogue` and \
3033 `Main`. Each is 0 but at the sample that marks its event. There the Quantum's \
3034 and Proton's manuals (p38, p46) put the raw altitude, in feet"
3035 );
3036 }
3037
3038 #[test]
3041 fn the_step_decides_the_time_unit() {
3042 let rows = |step: f64| -> String {
3043 (0..4)
3044 .map(|i| format!("{},{},{}\n", f64::from(i) * step, i * 10, 0))
3045 .collect()
3046 };
3047 let millis = read(&format!("T,Alt,LDA\n{}", rows(50.0))).unwrap();
3048 assert_eq!(millis.time_s, [0.0, 0.05, 0.1, 0.15]);
3049 assert!(millis.notes[0].starts_with("`T` read in milliseconds, from the step: "));
3050 assert!(millis.notes[0].contains("median step between rows is 50."));
3051 let slow = read(&format!("T,Alt,LDA\n{}", rows(1000.0))).unwrap();
3052 assert_eq!(prefix(&slow.notes[0]), prefix(&millis.notes[0]));
3053 assert!(slow.notes[0].contains("is 1000."));
3054
3055 for step in [5.0, 5.01] {
3058 let refused = read(&format!("T,Alt,LDA\n{}", rows(step)));
3059 assert!(matches!(refused, Err(LogError::Unit { .. })), "{step}");
3060 }
3061 let seconds = read(&format!("T,Alt,LDA\n{}", rows(0.5))).unwrap();
3062 assert_eq!(
3063 prefix(&seconds.notes[0]),
3064 "`T` read in seconds, from the step"
3065 );
3066
3067 let paused = read("T,Alt,LDA\n0,0,0\n0.05,1,0\n0.1,2,0\n100,3,0\n").unwrap();
3069 assert_eq!(paused.time_s, [0.0, 0.05, 0.1, 100.0]);
3070
3071 let one = read("T,Alt,LDA\n120,4,0\n").unwrap();
3072 assert_eq!(one.time_s, [120.0]);
3073 assert!(one.notes[0].starts_with("`T` read in seconds, assumed: "));
3074 }
3075
3076 #[test]
3079 fn reads_the_accelerometer_columns() {
3080 let text = "T,Alt,Veloc,AccelG,AccelFPSS,VAccel,AltAccel,LDA,MaxV,MaxA,CH1\r\
3081 -0.1,0,0,0,0,0,0,0,0,0,0\r\
3082 0,1,10,2,64.4,0,0,0,0,0,0\r\
3083 0.1,12,110,10,321.7,40,2,0,0,321,0\r\
3084 0.2,40,280,5,160.9,80,9,40,80,0,0\r";
3085 let log = read(text).unwrap();
3086 assert_eq!(log.time_s, [-0.1, 0.0, 0.1, 0.2]);
3087 let quantities: Vec<Quantity> = log.channels.iter().map(|c| c.quantity).collect();
3088 assert_eq!(
3089 quantities,
3090 [
3091 Quantity::AltitudeAboveGround,
3092 Quantity::Speed,
3093 Quantity::Acceleration,
3094 Quantity::Acceleration,
3095 Quantity::Speed,
3096 Quantity::InertialAltitude,
3097 Quantity::Unrecognized,
3098 Quantity::Unrecognized,
3099 Quantity::Unrecognized,
3100 Quantity::Unrecognized,
3101 ]
3102 );
3103 assert!(close(log.channels[2].values[2], 10.0 * 9.806_65));
3104 assert!(close(log.channels[3].values[2], 321.7 * 0.3048));
3105 assert!(close(log.channels[4].values[3], 80.0 * 0.3048));
3106 assert!(close(log.channels[5].values[3], 9.0 * 0.3048));
3107 assert_eq!(log.channels[7].values, [0.0, 0.0, 0.0, 80.0]);
3108 let names: Vec<&str> = log.events.iter().map(|event| event.name.as_str()).collect();
3109 assert_eq!(names, ["MaxA", "LDA", "MaxV"]);
3110 assert!(
3111 log.notes[1].ends_with(
3112 ". The file's `AccelFPSS` is 32.17 times its `AccelG`, and one g is 32.17 ft/s²"
3113 ),
3114 "{}",
3115 log.notes[1]
3116 );
3117 assert!(log.notes[2].starts_with("`Veloc` read in feet per second, from the manual: "));
3119 assert!(log.notes[3].starts_with("`VAccel` read in feet per second, from the manual: "));
3120 assert!(log.notes[4].starts_with("`AltAccel` read in feet, from the manual: "));
3121 assert_eq!(
3122 log.notes[5],
3123 "`AccelG` has gravity taken out, from the pad: its median over the 1 rows before the \
3124 start of flight (`T` below 0) is 0 g. An accelerometer that keeps gravity reads \
3125 1 g standing still, and one that takes it out reads 0. The Proton's manual doesn't \
3126 say, and its release notes (2.01C, p8) have it calibrate the accelerometer as it is \
3127 armed, standing up. The file's other acceleration columns are the same accelerometer's"
3128 );
3129 assert!(
3130 log.notes[6].starts_with(
3131 "the marker columns, kept as written: `LDA`, `MaxV`, `MaxA` and `CH1`. "
3132 ) && log.notes[6].ends_with(
3133 ". At that sample the Proton's release notes (1.02N, p13) put the top speed, \
3134 ft/s, in `MaxV` and the top acceleration, ft/s², in `MaxA`"
3135 ),
3136 "{}",
3137 log.notes[6]
3138 );
3139 assert_eq!(log.notes.len(), 7, "{:?}", log.notes);
3140 }
3141
3142 #[test]
3146 fn the_acceleration_unit_and_gravity_are_noted() {
3147 let log = read(
3148 "T,Alt,Accel,AccelFPSS,LDA
3149-0.1,0,1,32.2,0
31500,0,1.1,35.4,0
31510.1,3,6,193,3
3152",
3153 )
3154 .unwrap();
3155 let notes = log.notes.join("\n");
3156 assert!(
3157 notes.contains(
3158 "`Accel` read in g, from the manual: the Proton's manual (p45) gives the \
3159 accelerometer's raw value in G's"
3160 ),
3161 "{notes}"
3162 );
3163 assert!(
3164 notes.contains("The file's `AccelFPSS` is 32.17 times its `Accel`"),
3165 "{notes}"
3166 );
3167 assert!(
3168 notes.contains(
3169 "`Accel` holds gravity, from the pad: its median over the 1 rows before the start \
3170 of flight (`T` below 0) is 1 g"
3171 ),
3172 "{notes}"
3173 );
3174 assert!(!notes.contains("AccelG"), "{notes}");
3175 assert!(close(log.channels[1].values[0], 9.806_65));
3176
3177 let unsure = read(
3178 "T,Alt,AccelG,LDA
3179-0.2,0,3,0
3180-0.1,0,3,0
31810,1,4,0
3182",
3183 )
3184 .unwrap();
3185 assert!(
3186 unsure.notes.iter().any(|note| note.starts_with(
3187 "`AccelG` may or may not hold gravity, not known: its median over the 2 rows \
3188 before the start of flight (`T` below 0) is 3 g"
3189 )),
3190 "{:?}",
3191 unsure.notes
3192 );
3193 let no_pad = read(
3194 "T,Alt,FAccelFPSS,LDA
31950,0,0,0
31960.1,1,64,0
3197",
3198 )
3199 .unwrap();
3200 assert!(
3201 no_pad.notes.iter().any(|note| note.starts_with(
3202 "`FAccelFPSS` may or may not hold gravity, not known. The file has no rows before \
3203 the start of flight"
3204 )),
3205 "{:?}",
3206 no_pad.notes
3207 );
3208 let in_ft = read(
3210 "T,Alt,AccelFPSS,LDA
3211-0.1,0,32.2,0
32120,1,40,0
3213",
3214 )
3215 .unwrap();
3216 assert!(
3217 in_ft
3218 .notes
3219 .iter()
3220 .any(|note| note.starts_with("`AccelFPSS` holds gravity, from the pad: ")),
3221 "{:?}",
3222 in_ft.notes
3223 );
3224 }
3225
3226 #[test]
3229 fn a_speed_that_isnt_its_altitudes_change_is_kept_as_written() {
3230 let text = "T,Alt,Veloc,FAlt,FVeloc,LDA
32330,0,0,0,0,0
32341,10,10000,5,5,0
32352,30,20000,15,10,0
3236";
3237 let log = read(text).unwrap();
3238 assert_eq!(log.channels[1].column, "Veloc");
3239 assert_eq!(log.channels[1].quantity, Quantity::Unrecognized);
3240 assert_eq!(log.channels[1].values, [0.0, 10000.0, 20000.0]);
3241 assert_eq!(log.channels[3].quantity, Quantity::Speed);
3242 assert_eq!(
3243 log.vertical_speed_m_s.as_deref(),
3244 Some(&[0.0, 5.0 * 0.3048, 10.0 * 0.3048][..])
3245 );
3246 let notes = log.notes.join("\n");
3247 assert!(
3248 notes.contains(
3249 "`Veloc` kept as written, not read as a speed: it is the change in `Alt` over the \
3250 step, within 1 % or 1 ft/s. That holds in only 0 of 2 rows after the first, under \
3251 the 90 % the reader asks"
3252 ),
3253 "{notes}"
3254 );
3255 assert!(!notes.contains("`Veloc` read in"), "{notes}");
3256 assert!(notes.contains("the file has no raw velocity, `Veloc`, read as a speed"));
3257
3258 let rows = |misses: usize| -> String {
3260 (0..=10)
3261 .map(|i| {
3262 let speed = if i > 0 && i <= misses {
3263 99
3264 } else {
3265 10 * usize::from(i > 0)
3266 };
3267 format!("{i},{},{speed},0\n", 10 * i)
3268 })
3269 .collect()
3270 };
3271 let nine = read(&format!("T,Alt,Veloc,LDA\n{}", rows(1))).unwrap();
3272 assert_eq!(nine.channels[1].quantity, Quantity::Speed);
3273 assert!(
3274 nine.notes
3275 .iter()
3276 .any(|note| note.contains("in 9 of 10 rows after the first"))
3277 );
3278 let eight = read(&format!("T,Alt,Veloc,LDA\n{}", rows(2))).unwrap();
3279 assert_eq!(eight.channels[1].quantity, Quantity::Unrecognized);
3280 assert!(eight.vertical_speed_m_s.is_none());
3281 }
3282
3283 #[test]
3285 fn a_repeated_name_is_noted_once() {
3286 let log = read(
3287 "T,Alt,Veloc,Veloc,LDA
32880,0,0,0,0
32890.1,1,10,10,0
3290",
3291 )
3292 .unwrap();
3293 let veloc = log
3294 .notes
3295 .iter()
3296 .filter(|note| note.starts_with("`Veloc` read in"))
3297 .count();
3298 assert_eq!(veloc, 1, "{:?}", log.notes);
3299 assert_eq!(log.channels[2].quantity, Quantity::Speed);
3300 }
3301
3302 #[test]
3306 fn a_long_marker_name_rising_often_is_bounded() {
3307 let name = "X".repeat(100_000);
3308 let rows: String = (0..4000).map(|i| format!("{i},0,0,{}\n", i % 2)).collect();
3309 let text = format!("T,Alt,LDA,{name}\n{rows}");
3310 let log = read(&text).unwrap();
3311 assert_eq!(log.events.len(), MAX_EVENTS_PER_MARKER);
3312 assert!(
3313 log.events
3314 .iter()
3315 .all(|event| event.name.chars().count() <= 80)
3316 );
3317 assert!(log.events[0].name.ends_with('…'));
3318 assert_eq!(log.events[15].time_s, 31.0);
3319 let notes = log.notes.join("\n");
3320 assert!(
3321 notes.contains(&format!(
3322 "rises {} more times than the 16 kept as events",
3323 2000 - MAX_EVENTS_PER_MARKER
3324 )),
3325 "{}",
3326 short(¬es)
3327 );
3328 let bytes: usize = log.notes.iter().map(String::len).sum::<usize>()
3329 + log
3330 .events
3331 .iter()
3332 .map(|event| event.name.len())
3333 .sum::<usize>();
3334 assert!(bytes < 10_000, "{bytes} bytes of notes and event names");
3335 assert_eq!(log.channels[2].column.len(), 100_000);
3337 }
3338
3339 #[test]
3341 fn the_marker_note_stays_short() {
3342 let markers: String = (1..=40).map(|i| format!(",CH{i}")).collect();
3343 let text = format!(
3344 "T,Alt,LDA{markers}
33450,0{}
3346",
3347 ",0".repeat(41)
3348 );
3349 let log = read(&text).unwrap();
3350 let note = log
3351 .notes
3352 .iter()
3353 .find(|note| note.starts_with("the marker columns, kept as written: "))
3354 .unwrap();
3355 assert!(
3356 note.starts_with(
3357 "the marker columns, kept as written: `LDA`, `CH1`, `CH2`, `CH3`, `CH4` and 36 more \
3358 columns. "
3359 ),
3360 "{note}"
3361 );
3362 assert!(
3363 read(
3364 "T,Alt,Veloc
33650,0,0
3366"
3367 )
3368 .unwrap()
3369 .notes
3370 .iter()
3371 .all(|note| !note.contains("marker columns"))
3372 );
3373 }
3374
3375 #[test]
3377 fn each_run_of_a_marker_is_one_event() {
3378 let text = "T,Alt,Veloc,Apogee,Main\n\
3379 0,100,0,0,0\n0.5,101,2,101,0\n1,100,-2,101,0\n1.5,99,-2,0,0\n\
3380 2,98,-2,98,98\n2.5,97,-2,0,98\n";
3381 let log = read(text).unwrap();
3382 let events: Vec<(f64, &str)> = log
3383 .events
3384 .iter()
3385 .map(|event| (event.time_s, event.name.as_str()))
3386 .collect();
3387 assert_eq!(events, [(0.5, "Apogee"), (2.0, "Apogee"), (2.0, "Main")]);
3388 }
3389
3390 #[test]
3393 fn the_filtered_velocity_stands_in_for_the_raw_one() {
3394 let log = read("T,Alt,FAlt,FVeloc,LDA\n0,0,0,0,0\n0.05,2,1,20,0\n").unwrap();
3395 assert_eq!(
3396 log.vertical_speed_m_s.as_deref(),
3397 Some(&[0.0, 20.0 * 0.3048][..])
3398 );
3399 assert!(
3400 log.notes
3401 .iter()
3402 .any(|note| note
3403 .contains("the vertical speed is its filtered barometric \"FVeloc\""))
3404 );
3405 let old = read("T, Alt, VRaw, VFilt\n0, 0, 0, 0\n50, 1, 20, 4\n100, 3, 40, 12\n").unwrap();
3406 assert_eq!(old.time_s, [0.0, 0.05, 0.1]);
3407 assert_eq!(
3408 old.vertical_speed_m_s.as_deref(),
3409 Some(&[0.0, 20.0 * 0.3048, 40.0 * 0.3048][..])
3410 );
3411 assert!(old.notes[2].starts_with("`VRaw` read in feet per second, from the manual: "));
3412 assert!(
3413 old.notes[3].ends_with("The file has no filtered altitude to check it against"),
3414 "{}",
3415 old.notes[3]
3416 );
3417 assert!(old.notes[3].starts_with("`VFilt` read in feet per second, from the manual: "));
3418 assert!(
3419 read("T,Alt,LDA\n0,0,0\n")
3420 .unwrap()
3421 .vertical_speed_m_s
3422 .is_none()
3423 );
3424 }
3425
3426 fn filtered_flight(
3430 separator: &str,
3431 filtered_scale: f64,
3432 mark: impl Fn(String) -> String,
3433 ) -> String {
3434 let mut text = ["T", "Alt", "Veloc", "Filt_Alt", "FVeloc", "LDA", "Apogee"].join(separator);
3435 text.push('\n');
3436 let (mut altitude, mut filtered) = (0.0_f64, 0.0_f64);
3437 for row in 0..60_u32 {
3438 let t = f64::from(row) * 0.05;
3439 let next = (t * (200.0 - 30.0 * t)).max(0.0).round();
3441 let speed = if row == 0 {
3442 0.0
3443 } else {
3444 (next - altitude) / 0.05
3445 };
3446 let next_filtered = filtered + 0.2 * (next - filtered);
3447 let filtered_speed = if row == 0 {
3448 0.0
3449 } else {
3450 (next_filtered - filtered) / 0.05
3451 };
3452 altitude = next;
3453 filtered = next_filtered;
3454 let cells = [
3455 plain(t, 2),
3456 plain(altitude, 0),
3457 format!("{speed:.2}"),
3458 format!("{:.2}", filtered * filtered_scale),
3459 format!("{:.2}", filtered_speed * filtered_scale),
3460 "0".to_owned(),
3461 "0".to_owned(),
3462 ];
3463 let cells: Vec<String> = cells.into_iter().map(&mark).collect();
3464 text.push_str(&cells.join(separator));
3465 text.push('\n');
3466 }
3467 text
3468 }
3469
3470 fn channel<'a>(log: &'a FlightLog, name: &str) -> &'a Channel {
3471 log.channels.iter().find(|c| c.column == name).unwrap()
3472 }
3473
3474 #[test]
3475 fn semicolons_read_as_commas_do_with_either_decimal_mark() {
3476 let commas = read(&filtered_flight(",", 1.0, |cell| cell)).unwrap();
3477 let points = read(&filtered_flight(";", 1.0, |cell| cell)).unwrap();
3478 let decimal_commas =
3479 read(&filtered_flight(";", 1.0, |cell| cell.replace('.', ","))).unwrap();
3480 for log in [&points, &decimal_commas] {
3481 assert_eq!(log.time_s, commas.time_s);
3482 assert_eq!(log.altitude_m, commas.altitude_m);
3483 assert_eq!(log.vertical_speed_m_s, commas.vertical_speed_m_s);
3484 assert_eq!(log.channels, commas.channels);
3485 assert_eq!(log.notes[..commas.notes.len()], commas.notes[..]);
3486 }
3487 assert_eq!(
3488 channel(&points, "Filt_Alt").quantity,
3489 Quantity::AltitudeAboveGround
3490 );
3491 assert_eq!(channel(&points, "FVeloc").quantity, Quantity::Speed);
3492 assert!(!commas.notes.iter().any(|n| n.contains("semicolons")));
3493 assert!(points.notes.iter().any(|n| n.ends_with(
3494 "separated by semicolons, as a European locale's export writes them; a number's \
3495 decimal mark is a point"
3496 )));
3497 assert!(decimal_commas.notes.iter().any(|n| n.ends_with(
3498 "separated by semicolons, as a European locale's export writes them; a number's \
3499 decimal mark is a comma"
3500 )));
3501 let mixed = filtered_flight(";", 1.0, |cell| cell).replacen("0.25;", "0,25;", 1);
3504 assert!(matches!(
3505 read(&mixed),
3506 Err(LogError::Syntax { line: 7, ref message, .. }) if message.starts_with("\"0,25\"")
3507 ));
3508 let thousands = filtered_flight(";", 1.0, |cell| cell.replace('.', ",")).replacen(
3511 ";0;0\n",
3512 ";1.250;0\n",
3513 1,
3514 );
3515 assert!(matches!(read(&thousands), Err(LogError::Syntax { .. })));
3516 }
3517
3518 #[test]
3519 fn a_filtered_altitude_off_the_altitudes_scale_refuses_the_file() {
3520 let refused = read(&filtered_flight(";", 100.0, |cell| cell));
3523 assert!(
3524 matches!(
3525 &refused,
3526 Err(LogError::Unit { line: 1, message, .. }) if message.starts_with(
3527 "`Filt_Alt` isn't a filter of `Alt`: it is 92.319 times `Alt` by a \
3528 least-squares fit. That is outside the 0.1 to 2"
3529 )
3530 ),
3531 "{refused:?}"
3532 );
3533 for (scale, reads) in [(2.1, true), (0.11, true), (2.2, false), (0.105, false)] {
3537 match read(&filtered_flight(",", scale, |cell| cell)) {
3538 Ok(log) => {
3539 assert!(reads, "{scale}");
3540 assert_eq!(
3541 channel(&log, "Filt_Alt").quantity,
3542 Quantity::AltitudeAboveGround
3543 );
3544 }
3545 Err(error) => assert!(
3546 !reads && matches!(error, LogError::Unit { .. }),
3547 "{scale}: {error}"
3548 ),
3549 }
3550 }
3551 let huge = "T,Alt,FAlt\n0,1e200,1e200\n0.05,1e200,1e200\n";
3553 assert!(matches!(
3554 read(huge),
3555 Err(LogError::Unit { ref message, .. }) if message.contains("isn't a finite number")
3556 ));
3557 let flat = "T,Alt,FAlt\n0,0,0\n0.05,0,5\n0.1,0,9\n";
3559 assert_eq!(
3560 channel(&read(flat).unwrap(), "FAlt").quantity,
3561 Quantity::AltitudeAboveGround
3562 );
3563 }
3564
3565 #[test]
3566 fn a_step_neither_seconds_nor_milliseconds_refuses_the_file() {
3567 let stripped = "T,Alt,Veloc\n0,0,0\n5,10,200\n10,25,300\n15,40,300\n";
3569 assert!(matches!(
3570 read(stripped),
3571 Err(LogError::Unit { line: 1, ref message, .. })
3572 if message.starts_with("the median step between rows of `T` is 5. That")
3573 ));
3574 let one = read("T,Alt,Veloc\n0,0,0\n1,10,10\n2,25,15\n").unwrap();
3576 assert_eq!(one.time_s, [0.0, 1.0, 2.0]);
3577 let thirty = read("T,Alt,Veloc\n0,0,0\n30,1,33\n60,2,33\n").unwrap();
3578 assert_eq!(thirty.time_s, [0.0, 0.03, 0.06]);
3579 let over = "T,Alt,Veloc\n0,0,0\n1.01,10,10\n2.02,25,15\n";
3580 assert!(matches!(read(over), Err(LogError::Unit { .. })));
3581 let under = "T,Alt,Veloc\n0,0,0\n29.9,1,33\n59.8,2,33\n";
3582 assert!(matches!(read(under), Err(LogError::Unit { .. })));
3583 }
3584
3585 #[test]
3586 fn a_semicolon_in_a_channel_name_keeps_a_comma_file_a_comma_file() {
3587 let log = read("T,Alt,Veloc,LDA,Apogee,Dr;1\n0,0,0,0,0,0\n0.05,1,20,0,0,0\n").unwrap();
3588 assert_eq!(log.channels.last().unwrap().column, "Dr;1");
3589 assert!(!log.notes.iter().any(|n| n.contains("semicolons")));
3590 }
3591
3592 #[test]
3594 fn unknown_columns_are_kept_and_named_channels_are_markers() {
3595 let log = read("T,Alt,Veloc,Baro,LDA,Apogee,Drogue.1\n0,0,0,7,0,0,0\n0.05,4,80,8,4,0,4\n")
3596 .unwrap();
3597 assert_eq!(log.channels[2].quantity, Quantity::Unrecognized);
3598 assert_eq!(log.channels[2].values, [7.0, 8.0]);
3599 let names: Vec<&str> = log.events.iter().map(|event| event.name.as_str()).collect();
3600 assert_eq!(names, ["LDA", "Drogue.1"]);
3601 let notes = log.notes.join("\n");
3602 assert!(notes.contains("\"Baro\" isn't one this reader knows, and was kept as written"));
3603 assert!(notes.contains("\"Drogue.1\" isn't one this reader knows; it comes after `LDA`"));
3604 }
3605
3606 #[test]
3608 fn empty_rows_are_skipped_and_empty_cells_are_gaps() {
3609 let text = format!(
3610 "{TRS}\r\n0,0,0,0,0,0,0,0,0,0,0\r\n0.05,2,,1,20,0,0,0,0,0,0\r\n0.1,5,60\r\n\
3611 ,,,,,,,,,,\r\n,,,,,,,,,,\r\n , ,\r\n"
3612 );
3613 let log = read(&text).unwrap();
3614 assert_eq!(log.time_s, [0.0, 0.05, 0.1]);
3615 assert!(log.channels[1].values[1].is_nan());
3616 assert!(log.channels[2].values[2].is_nan());
3617 let notes = log.notes.join("\n");
3618 assert!(
3619 notes.contains("3 rows hold only empty cells, and were skipped"),
3620 "{notes}"
3621 );
3622 assert!(notes.contains("the column \"Veloc\" leaves 1 cell empty: it is a gap"));
3623 assert!(notes.contains("the column \"Main\" leaves 1 cell empty: it is a gap"));
3624 }
3625
3626 #[test]
3628 fn malformed_files_are_refused_where_they_go_wrong() {
3629 let cases = [
3630 (String::new(), "the file is empty"),
3631 ("\r\n\r\n".to_owned(), "the file is empty"),
3632 (
3633 "Time,Altitude\n0,0\n".to_owned(),
3634 "isn't an Eggtimer header row",
3635 ),
3636 (format!("{TRS}\n"), "no data rows"),
3637 (format!("{TRS}\n,,,,,,,,,,\n"), "no data rows"),
3638 (
3639 "T,Alt,,LDA\n".to_owned(),
3640 "line 1: the header's column 3 has no name",
3641 ),
3642 (
3643 "T,Alt,LDA\n0,0,0,0\n".to_owned(),
3644 "line 2: the row has 4 cells and the header names 3",
3645 ),
3646 (
3647 "T,Alt,LDA\n0,0,0\n0.05,x,0\n".to_owned(),
3648 "line 3: \"x\" in cell 2, under \"Alt\", isn't a number",
3649 ),
3650 (
3651 "T,Alt,LDA\n0,0,0\n0.05,1,NaN\n".to_owned(),
3652 "line 3: \"NaN\" in cell 3, under \"LDA\"",
3653 ),
3654 (
3655 "T,Alt,LDA\nx,0,0\n".to_owned(),
3656 "line 2: \"x\" in cell 1, under \"T\"",
3657 ),
3658 (
3659 "T,Alt,LDA\n,0,0\n".to_owned(),
3660 "line 2: the time, the row's first cell, is empty",
3661 ),
3662 (
3663 "T,Alt,LDA\n0,0,0\n0,1,0\n".to_owned(),
3664 "line 3: the time 0 comes at or before the one above it, 0",
3665 ),
3666 (
3667 "T,Alt,LDA\n\n1,0,0\n\n0.5,1,0\n".to_owned(),
3668 "line 5: the time 0.5 comes at or before",
3669 ),
3670 ];
3671 for (text, expected) in cases {
3672 let error = read(&text).unwrap_err().to_string();
3673 assert!(error.contains(expected), "{text:?}: {error}");
3674 }
3675 }
3676
3677 #[test]
3680 fn a_value_its_conversion_makes_infinite_is_refused() {
3681 let csv = "T,Alt,AccelG,LDA\n0,0,1,0\n0.05,1,-1.7e308,0\n";
3682 assert_eq!(
3683 read(csv).unwrap_err().to_string(),
3684 "Eggtimer CSV line 3: the column AccelG holds a value too large for its unit's \
3685 conversion to SI"
3686 );
3687 let rows: String = flight(1000.0, 0.05, G_FT, None, 15.0)
3689 .lines()
3690 .enumerate()
3691 .map(|(row, line)| {
3692 let cells: Vec<&str> = line.split(',').take(2).collect();
3693 let g = if row == 1 { "-1.7e308" } else { "1" };
3694 format!("{},{g},0\n", cells.join(","))
3695 })
3696 .collect();
3697 let text =
3698 format!("Eggtimer TRS 2.07 Flight Settings\n...Units...Feet\nT,Alt,AccelG,LDA\n{rows}");
3699 assert_eq!(
3700 read_text(&text).unwrap_err().to_string(),
3701 "Eggtimer text line 5: the column AccelG holds a value too large for its unit's \
3702 conversion to SI"
3703 );
3704 let largest = f64::MAX / 9.806_65;
3706 let log = read(&format!("T,Alt,AccelG\n0,0,{largest:e}\n")).unwrap();
3707 assert!(log.channels[1].values[0].is_finite());
3708 }
3709
3710 #[test]
3712 fn a_wide_header_over_short_rows_is_refused() {
3713 let names: String = (0..2000).map(|i| format!(",u{i}")).collect();
3714 let rows = "0\n".repeat(200);
3715 let text = format!("T,Alt,LDA{names}\n{rows}");
3716 let error = read(&text).unwrap_err().to_string();
3717 assert!(
3718 error.contains("too few for the header to be this file's"),
3719 "{error}"
3720 );
3721 }
3722
3723 #[test]
3725 fn line_ends() {
3726 let rows = ["T,Alt,Veloc,LDA", "0,0,0,0", "0.05,2,40,0", "0.1,6,80,6"];
3727 let reference = read(&rows.join("\n")).unwrap();
3728 for end in ["\r", "\n", "\r\n", "\r\r\n"] {
3729 let text = format!("{}{end}", rows.join(end));
3730 assert_eq!(read(&text).unwrap(), reference, "{end:?}");
3731 }
3732 assert_eq!(reference.events.len(), 1);
3733 }
3734
3735 #[test]
3738 fn notes_stay_few() {
3739 let unknown: String = (0..100).map(|i| format!(",u{i}")).collect();
3740 let text = format!("T,Alt,Veloc{unknown}\n0,0,0{}\n", ",1".repeat(100));
3741 let log = read(&text).unwrap();
3742 assert_eq!(log.channels.len(), 102);
3743 assert_eq!(log.notes.len(), 3 + 20 + 1, "{:?}", log.notes);
3745 assert!(
3746 log.notes[23].starts_with("and 80 more notes"),
3747 "{:?}",
3748 log.notes[23]
3749 );
3750 }
3751
3752 #[test]
3754 fn a_long_line_is_quoted_short() {
3755 let junk = "\u{fffd}".repeat(100_000);
3756 let error = read(&junk).unwrap_err().to_string();
3757 assert!(error.len() < 400, "{} bytes", error.len());
3758 }
3759
3760 #[test]
3761 fn numbers_are_written_plainly() {
3762 assert_eq!(plain(0.050_000_000_000_000_71, 4), "0.05");
3763 assert_eq!(plain(50.0, 4), "50");
3764 assert_eq!(plain(32.166, 2), "32.17");
3765 assert_eq!(plain(-0.0, 2), "-0");
3766 }
3767
3768 const G_FT: f64 = 32.174;
3770
3771 type Drogue = Option<(f64, f64)>;
3774
3775 fn flight(per_second: f64, step_s: f64, slowing: f64, drogue: Drogue, end_s: f64) -> String {
3783 let boost = 9.0 * slowing;
3784 let coast = |t: f64| boost / 2.0 + boost * (t - 1.0) - slowing * (t - 1.0).powi(2) / 2.0;
3785 let altitude = |t: f64| -> f64 {
3786 if t <= 1.0 {
3787 return boost * t * t / 2.0;
3788 }
3789 match drogue {
3790 Some((at, rate)) if t > at => {
3791 let angle = (slowing * (10.0 - at) / rate).atan();
3792 let stop = at + rate * angle / slowing;
3793 let rise = |t: f64| {
3794 coast(at)
3795 + rate * rate / slowing
3796 * ((angle - slowing * (t - at) / rate).cos() / angle.cos()).ln()
3797 };
3798 if t <= stop {
3799 rise(t)
3800 } else {
3801 rise(stop) - 40.0 * (t - stop)
3802 }
3803 }
3804 _ if t <= 10.0 => coast(t),
3805 _ => coast(10.0) - 40.0 * (t - 10.0),
3806 }
3807 };
3808 let count = (end_s / step_s).round() as usize;
3809 let times: Vec<f64> = (0..=count).map(|row| row as f64 * step_s).collect();
3810 let heights: Vec<f64> = times.iter().map(|t| altitude(*t).round()).collect();
3811 let at = |time: f64| (time / step_s).round() as usize;
3812 let top = at(match drogue {
3813 Some((time, rate)) if time < 10.0 => {
3814 time + rate * (slowing * (10.0 - time) / rate).atan() / slowing
3815 }
3816 _ => 10.0,
3817 });
3818 let deploy = at(drogue.map_or(10.5, |(time, _)| time));
3819 let mut text = String::new();
3820 for (row, (t, h)) in times.iter().zip(&heights).enumerate() {
3821 let speed = row
3822 .checked_sub(1)
3823 .map_or(0.0, |up| (h - heights[up]) / step_s);
3824 let mark = |on: bool| if on { *h } else { 0.0 };
3825 text.push_str(&format!(
3826 "{},{h},{speed:.2},{h:.2},{speed:.2},{},{},{},{},{},0\n",
3827 (t * per_second * 1000.0).round() / 1000.0,
3828 mark(row == at(0.1)),
3829 mark(row == at(5.0)),
3830 mark(row == top),
3831 mark(row == deploy),
3832 mark(row == deploy),
3833 ));
3834 }
3835 text
3836 }
3837
3838 fn table() -> String {
3841 format!("{TRS}\n{}", flight(1000.0, 0.05, G_FT, None, 15.0))
3842 }
3843
3844 fn download() -> String {
3846 format!(
3847 "Flight Summary:\n\
3848 \n\
3849 Eggtimer TRS 2.07 Flight Settings\n\
3850 ...Drogue <1=Normal,2=Backup,0=OFF>...1\n\
3851 ...Main Altitude <50-2000 by 50, 0=OFF>...300\n\
3852 ...Frequency (Ctrl-F to change)...915\n\
3853 ...ID Code...4\n\
3854 ...SECRET NAME\n\
3855 ASL Alt.: 1000 ft\n\
3856 Base Temp: 20.5 C\n\
3857 Last Flight Phase: 9\n\
3858 Apogee: 1448 ft\n\
3859 T @ Apogee: 10.000\n\
3860 Max Velocity: 290 ft/sec\n\
3861 T @ Max Velocity: 1.000\n\
3862 Time @ LDA:0.100\n\
3863 Altitude @ Main Deploy: 0 ft\n\
3864 T @ Main Deploy: 0.000\n\
3865 {}",
3866 table()
3867 )
3868 }
3869
3870 #[test]
3871 fn recognizes_the_terminal_download_and_no_other_layout() {
3872 let table = table();
3873 for text in [
3874 download(),
3875 format!("Eggtimer TRS 2.10 Flight Settings\r{table}"),
3876 format!("\u{feff}Eggtimer TRS 2.07\nFlight Settings\n...ID Code...0\n{table}"),
3877 format!("Flight Summary:\nEggtimer Flight Settings\n{table}"),
3878 format!("Saved Flight Summary\nEggtimer TRS 2.07 Flight Settings\n{table}"),
3879 ] {
3880 assert!(recognizes_text(&text), "{text:?}");
3881 assert!(read_text(&text).is_ok(), "{text:?}");
3882 }
3883 for text in [
3884 String::new(),
3885 table.clone(),
3886 download().replace("Flight Settings", "Settings"),
3887 format!("Eggtimer TRS 2.07\nFlight Summary:\n{table}"),
3888 format!("{table}Eggtimer TRS 2.07 Flight Settings\n{table}"),
3889 "Eggtimer TRS 2.07 Flight Settings\nTime,Altitude,Velocity\n0,0,0\n".to_owned(),
3890 "Eggtimer TRS 2.07 Flight Settings\nT,Alt\n0,0\n".to_owned(),
3891 format!(
3892 "Eggtimer TRS 2.07 Flight Settings\n{}{table}",
3893 "Beep Code: 0\n".repeat(MAX_PREAMBLE_LINES)
3894 ),
3895 "PerfectFlite Pnut\nEggtimer TRS 2.07 Flight Settings\n".to_owned(),
3896 ] {
3897 assert!(!recognizes_text(&text), "{text:?}");
3898 assert!(
3899 matches!(
3900 read_text(&text),
3901 Err(LogError::NotThisFormat {
3902 format: TEXT_FORMAT,
3903 ..
3904 })
3905 ),
3906 "{text:?}"
3907 );
3908 }
3909 let full = format!(
3911 "Eggtimer TRS 2.07 Flight Settings\n{}{table}",
3912 "Beep Code: 0\n".repeat(MAX_PREAMBLE_LINES - 2)
3913 );
3914 assert!(recognizes_text(&full));
3915 assert!(recognizes(&table) && !recognizes(&download()));
3917 }
3918
3919 #[test]
3922 fn reads_the_settings_the_summary_and_the_table() {
3923 let log = read_text(&download()).unwrap();
3924 assert_eq!(log.format, LogFormat::EggtimerText);
3925 assert_eq!(log.logger, "Eggtimer TRS");
3926 assert_eq!(log.firmware.as_deref(), Some("2.07"));
3927 assert_eq!(log.time_s.len(), 301);
3928 assert_eq!(log.time_s[..3], [0.0, 0.05, 0.1]);
3929 assert!(close(log.stated.apogee_m.unwrap(), 1448.0 * 0.3048));
3930 assert!(close(
3931 log.stated.ground_elevation_msl_m.unwrap(),
3932 1000.0 * 0.3048
3933 ));
3934 assert_eq!(log.stated.samples, None);
3935 let events: Vec<(f64, &str)> = log
3938 .events
3939 .iter()
3940 .map(|event| (event.time_s, event.name.as_str()))
3941 .collect();
3942 assert_eq!(
3943 events,
3944 [
3945 (0.1, "LDA"),
3946 (1.0, "Max Velocity"),
3947 (5.0, "LowV"),
3948 (10.0, "Apogee"),
3949 (10.5, "N-O"),
3950 (10.5, "Drogue")
3951 ]
3952 );
3953 let notes = &log.notes[6..];
3954 assert_eq!(
3955 notes,
3956 [
3957 "`ASL Alt.` read in feet, from its unit mark: the flight summary writes 1000 ft; \
3958 the launch site's elevation above sea level, as the logger measured it (TRS \
3959 manual p36)",
3960 "`Apogee` read in feet, from its unit mark: the flight summary writes 1448 ft; \
3961 the logger's apogee above its zero, kept beside the table's altitudes (TRS \
3962 manual p36)",
3963 "`T @` and `Time @` read in seconds, from the manual: the TRS manual's download \
3964 writes the flight summary's times in `secs.` (p36). The same download writes its LDA \
3965 at 0.700 secs. as \"700ms into the flight\" (p37)",
3966 "the flight summary's times are its table markers' to the millisecond, one event \
3967 each, the marker's: `Apogee` at `Apogee`, `LDA` at `LDA`",
3968 "the flight summary's times of no marker in the table, each an event of its own: \
3969 `Max Velocity`",
3970 "the flight summary's times of 0, no event, as the TRS manual writes zeroes for a \
3971 channel that didn't fire (p25): `Main Deploy`",
3972 "the flight settings, as the file writes them: `Drogue <1=Normal,2=Backup,0=OFF>` \
3973 1; `Main Altitude <50-2000 by 50, 0=OFF>` 300; `Frequency (Ctrl-F to change)` \
3974 915; `ID Code` 4",
3975 "1 line of the flight settings holds no setting: the name its owner gave the \
3976 flight computer (TRS manual p24). The name is left out of the record as free text \
3977 that may name a person",
3978 "the flight summary's other lines, as the file writes them: `Base Temp: 20.5 C`; \
3979 `Last Flight Phase: 9` (landing detected, TRS manual p37); `Max Velocity: 290 \
3980 ft/sec`; `Altitude @ Main Deploy: 0 ft`",
3981 ]
3982 );
3983 assert!(
3984 log.notes[0].starts_with("`T` read in milliseconds, from the step and the coast: ")
3985 );
3986 assert!(log.notes[1].starts_with("`Alt` read in feet, from the manual and the coast: "));
3987 assert!(log.notes[3].starts_with("`FAlt` read in feet, from the manual and the coast: "));
3988 let json = serde_json::to_string(&log).unwrap();
3990 assert!(!json.contains("SECRET"));
3991 }
3992
3993 #[test]
3996 fn summary_lines_read_by_what_they_state() {
3997 let text = format!(
3998 "Captured with a terminal\n\
3999 Eggtimer TRS 2.07 Flight Settings\n\
4000 Apogee: 9 m\n\
4001 Apogee: 30 ft\n\
4002 ASL Alt.: 1000\n\
4003 T @ Apogee: 10.100 secs.\n\
4004 T @ Nose-Over: 10.5 s\n\
4005 T @ Unlock: soon\n\
4006 a line with no colon\n\
4007 {}",
4008 table()
4009 );
4010 let log = read_text(&text).unwrap();
4011 assert_eq!(log.stated.apogee_m, Some(9.0));
4012 assert_eq!(log.stated.ground_elevation_msl_m, None);
4013 let names: Vec<(f64, &str)> = log
4014 .events
4015 .iter()
4016 .map(|event| (event.time_s, event.name.as_str()))
4017 .collect();
4018 assert_eq!(
4019 names,
4020 [
4021 (0.1, "LDA"),
4022 (5.0, "LowV"),
4023 (10.0, "Apogee"),
4024 (10.1, "Apogee"),
4025 (10.5, "N-O"),
4026 (10.5, "Drogue")
4027 ]
4028 );
4029 let has = |wanted: &str| log.notes.iter().any(|note| note == wanted);
4030 assert!(has(
4031 "`Apogee` read in meters, from its unit mark: the flight summary writes 9 m; the \
4032 logger's apogee above its zero, kept beside the table's altitudes (TRS manual p36)"
4033 ));
4034 assert!(has(
4035 "`ASL Alt.` kept as written, with no unit mark the reader knows: the flight summary \
4036 writes \"1000\", where the TRS manual's writes `ft` (p36)"
4037 ));
4038 assert!(has(
4039 "`T @` and `Time @` read in seconds, from their unit mark: the flight summary writes \
4040 `secs.` after each, as the TRS manual's download does (p36)"
4041 ));
4042 assert!(has(
4043 "the flight summary's times that differ from their markers' in the table, both kept \
4044 as events: `Apogee` at 10.1 s, the marker `Apogee` at 10 s"
4045 ));
4046 assert!(has(
4047 "the flight summary's times are its table markers' to the millisecond, one event \
4048 each, the marker's: `Nose-Over` at `N-O`"
4049 ));
4050 assert!(has(
4051 "the flight summary's other lines, as the file writes them: `Apogee: 30 ft`; `ASL \
4052 Alt.: 1000`; `T @ Unlock: soon`; `a line with no colon`"
4053 ));
4054 assert!(has(
4055 "1 lines before the title `Eggtimer … Flight Settings` weren't read"
4056 ));
4057 }
4058
4059 #[test]
4061 fn the_tables_errors_name_the_files_line() {
4062 let bad = download().replacen("\n100,1,", "\n100,x,", 1);
4063 assert_eq!(
4064 read_text(&bad).unwrap_err(),
4065 LogError::Syntax {
4066 format: TEXT_FORMAT,
4067 line: 22,
4068 message: "\"x\" in cell 2, under \"Alt\", isn't a number".to_owned(),
4069 }
4070 );
4071 let cr = bad.replace('\n', "\r");
4072 assert!(matches!(
4073 read_text(&cr),
4074 Err(LogError::Syntax { line: 22, .. })
4075 ));
4076 let download = download();
4077 let headless = download
4078 .split_once("0,0,0.00")
4079 .map(|(head, _)| head)
4080 .unwrap();
4081 assert_eq!(
4082 read_text(headless).unwrap_err(),
4083 LogError::NoData {
4084 format: TEXT_FORMAT
4085 }
4086 );
4087 }
4088
4089 #[test]
4091 fn the_preamble_notes_stay_short() {
4092 let settings: String = (0..150)
4093 .map(|index| format!("...Setting {index} {}...1\n", "y".repeat(500)))
4094 .collect();
4095 let times: String = (0..30)
4096 .map(|index| format!("T @ Thing {index}: {}.5\n", index + 1))
4097 .collect();
4098 let rows = flight(1.0, 0.05, G_FT, None, 40.0);
4100 let text = format!(
4101 "Eggtimer {} 9.99 Flight Settings\n{settings}{times}{TRS}\n{rows}",
4102 "Z".repeat(500)
4103 );
4104 let log = read_text(&text).unwrap();
4105 assert!(log.logger.chars().count() < 100);
4106 assert_eq!(log.firmware.as_deref(), Some("9.99"));
4107 assert_eq!(log.events.len(), 35);
4109 let settings = log
4110 .notes
4111 .iter()
4112 .find(|note| note.starts_with("the flight settings"))
4113 .unwrap();
4114 assert!(settings.ends_with("; and 110 more"), "{settings}");
4115 assert!(settings.len() < 40 * 100 + 200, "{} bytes", settings.len());
4116 for note in &log.notes {
4117 assert!(note.len() < 5_000, "{} bytes", note.len());
4118 }
4119 }
4120
4121 fn coast_download(table: &str, change: impl Fn(usize, &mut Vec<String>)) -> String {
4124 let rows: String = table
4125 .lines()
4126 .enumerate()
4127 .map(|(row, line)| {
4128 let mut cells: Vec<String> = line.split(',').map(str::to_owned).collect();
4129 change(row, &mut cells);
4130 format!("{}\n", cells.join(","))
4131 })
4132 .collect();
4133 format!("Eggtimer TRS 2.07 Flight Settings\n{TRS}\n{rows}")
4134 }
4135
4136 fn note_from<'a>(log: &'a FlightLog, prefix: &str) -> &'a str {
4138 log.notes
4139 .iter()
4140 .find(|note| note.starts_with(prefix))
4141 .unwrap_or_else(|| panic!("no note opens with {prefix:?}: {:#?}", log.notes))
4142 }
4143
4144 fn slowing_g(note: &str, unit: &str) -> f64 {
4146 let after = note.split("slows at ").nth(1).unwrap_or_default();
4147 let (number, rest) = after.split_once(" g in ").unwrap_or_default();
4148 if rest.starts_with(unit) {
4149 return number.parse().unwrap();
4150 }
4151 let other = rest.split(" and ").nth(1).unwrap_or_default();
4153 let (number, rest) = other.split_once(" g in ").unwrap_or_default();
4154 assert!(rest.starts_with(unit), "{note}");
4155 number.parse().unwrap()
4156 }
4157
4158 #[test]
4161 fn the_coast_bears_out_the_clock_and_feet() {
4162 for (per_second, unit) in [(1000.0, "milliseconds"), (1.0, "seconds")] {
4163 let text = coast_download(&flight(per_second, 0.05, G_FT, None, 15.0), |_, _| {});
4164 let log = read_text(&text).unwrap();
4165 assert_eq!(log.time_s.len(), 301);
4166 assert!(close(log.time_s[200], 10.0));
4167 let clock = note_from(&log, "`T` read in ");
4168 assert!(
4169 clock.starts_with(&format!(
4170 "`T` read in {unit}, from the step and the coast: the median step between \
4171 rows is "
4172 )),
4173 "{clock}"
4174 );
4175 assert!(
4177 clock.contains(
4178 " g in feet over the rows from 6.9 s to 9.9 s, up to the altitude's top. \
4179 The reader takes 0.7 to 1.3 g in feet or in meters, and a clock 1,000 \
4180 times off would put that slowing 10⁶ times off"
4181 ),
4182 "{clock}"
4183 );
4184 assert!((slowing_g(clock, "feet") - 1.0).abs() < 0.01, "{clock}");
4185 let alt = note_from(&log, "`Alt` ");
4186 assert!(
4187 alt.starts_with(
4188 "`Alt` read in feet, from the manual and the coast: the Classic and TRS \
4189 manuals (p37) state feet. The Quantum and Proton manuals give every height \
4190 in feet, and no Eggtimer manual offers meters. Over the rows from 6.9 s to \
4191 9.9 s, up to the altitude's top, it slows at "
4192 ),
4193 "{alt}"
4194 );
4195 assert!(alt.contains(" g in feet, within the 0.7 to 1.3 g the reader takes. In"));
4196 assert!((slowing_g(alt, "feet") - 1.0).abs() < 0.01, "{alt}");
4197 assert!(note_from(&log, "`FAlt` ").starts_with("`FAlt` read in feet, from the "));
4198 assert!(note_from(&log, "`Veloc` ").starts_with("`Veloc` read in feet per second"));
4199 assert_eq!(log.channels[0].quantity, Quantity::AltitudeAboveGround);
4200 assert_eq!(log.channels[2].quantity, Quantity::AltitudeAboveGround);
4201 assert!(close(log.altitude_m[200], 1448.0 * FOOT_M));
4202 assert!(log.vertical_speed_m_s.is_some());
4203 }
4204 }
4205
4206 #[test]
4210 fn an_altitude_in_meters_is_kept_as_written() {
4211 let text = coast_download(
4212 &flight(1000.0, 0.05, STANDARD_GRAVITY_MPS2, None, 15.0),
4213 |_, _| {},
4214 );
4215 let log = read_text(&text).unwrap();
4216 let clock = note_from(&log, "`T` ");
4217 assert!(clock.starts_with("`T` read in milliseconds, from the step and the coast"));
4218 assert!(
4219 clock.contains(" g in meters over the rows from "),
4220 "{clock}"
4221 );
4222 assert!((slowing_g(clock, "meters") - 1.0).abs() < 0.02, "{clock}");
4223 let alt = note_from(&log, "`Alt` ");
4224 assert!(
4225 alt.starts_with(
4226 "`Alt` kept as written: the manuals give feet, but over the rows from "
4227 ),
4228 "{alt}"
4229 );
4230 assert!(alt.ends_with(
4231 " g in meters. The reader takes 0.7 to 1.3 g in feet. The record holds no \
4232 barometric altitude"
4233 ));
4234 assert!((slowing_g(alt, "feet") - FOOT_M).abs() < 0.01, "{alt}");
4235 assert!((slowing_g(alt, "meters") - 1.0).abs() < 0.02, "{alt}");
4236 let falt = note_from(&log, "`FAlt` ");
4237 assert!(
4238 falt.starts_with(
4239 "`FAlt` kept as written: the manuals give it in feet, as the logger's filtered \
4240 `Alt` (Quantum p38, Proton p45). But over the rows from "
4241 ),
4242 "{falt}"
4243 );
4244 assert!(falt.ends_with(" g in feet, outside the 0.7 to 1.3 g the reader takes"));
4245 assert_eq!(
4246 note_from(&log, "`Veloc` "),
4247 "`Veloc` kept as written: it is the change in `Alt` over the step, and `Alt` is kept \
4248 as written"
4249 );
4250 assert_eq!(
4251 note_from(&log, "`FVeloc` "),
4252 "`FVeloc` kept as written: it is the change in `FAlt` over the step, and `FAlt` is \
4253 kept as written"
4254 );
4255 for channel in &log.channels[..4] {
4256 assert_eq!(
4257 channel.quantity,
4258 Quantity::Unrecognized,
4259 "{}",
4260 channel.column
4261 );
4262 }
4263 assert_eq!(log.channels[0].values[200], 441.0);
4265 assert!(log.altitude_m.is_empty());
4266 assert_eq!(log.vertical_speed_m_s, None);
4267 }
4268
4269 #[test]
4272 fn a_filtered_altitude_the_coast_doesnt_bear_out_is_kept() {
4273 let table = flight(1000.0, 0.05, G_FT, None, 15.0);
4274 let text = coast_download(&table, |row, cells| {
4275 let meters = |cells: &[String]| cells[1].parse::<f64>().unwrap() * FOOT_M;
4276 let up: Option<f64> = row
4277 .checked_sub(1)
4278 .and_then(|up| table.lines().nth(up))
4279 .map(|line| line.split(',').map(str::to_owned).collect::<Vec<_>>())
4280 .map(|cells| meters(&cells));
4281 let here = meters(cells);
4282 cells[3] = format!("{here:.2}");
4283 cells[4] = format!("{:.2}", up.map_or(0.0, |up| (here - up) / 0.05));
4284 });
4285 let log = read_text(&text).unwrap();
4286 assert!(note_from(&log, "`Alt` ").starts_with("`Alt` read in feet, from the manual and"));
4287 assert!(note_from(&log, "`FAlt` ").starts_with("`FAlt` kept as written: "));
4288 let falt = note_from(&log, "`FAlt` ");
4289 assert!(falt.ends_with(" g in feet, outside the 0.7 to 1.3 g the reader takes"));
4290 assert!((slowing_g(falt, "feet") - FOOT_M).abs() < 0.01, "{falt}");
4291 assert!(note_from(&log, "`FVeloc` ").starts_with("`FVeloc` kept as written: "));
4292 assert_eq!(log.channels[0].quantity, Quantity::AltitudeAboveGround);
4293 assert_eq!(log.channels[2].quantity, Quantity::Unrecognized);
4294 assert_eq!(log.channels[3].quantity, Quantity::Unrecognized);
4295 assert!(close(log.altitude_m[200], 1448.0 * FOOT_M));
4296 }
4297
4298 #[test]
4300 fn a_coast_cut_at_every_few_rows_is_refused_after_a_bounded_search() {
4301 let mut text = String::from("Eggtimer TRS 2.07 Flight Settings\nT,Alt,Apogee\n");
4305 for row in 0..20_000 {
4306 let spike = if row % 3 == 1 { 100_000 } else { 0 };
4307 text.push_str(&format!("{row},{},0\n", row + spike));
4308 }
4309 let error = read_text(&text).unwrap_err().to_string();
4310 assert!(
4311 error.contains(&format!(
4312 "the coast window is cut short more than {COAST_CUTS} times by jumps or motor \
4313 markers before the top"
4314 )),
4315 "{error}"
4316 );
4317 }
4318
4319 #[test]
4323 fn a_clock_the_coast_doesnt_bear_out_is_refused() {
4324 let text = coast_download(&flight(1000.0, 0.004, G_FT, None, 12.0), |_, _| {});
4325 let error = read_text(&text).unwrap_err();
4326 let LogError::Unit {
4327 format: TEXT_FORMAT,
4328 line: 2,
4329 message,
4330 } = &error
4331 else {
4332 panic!("{error:?}");
4333 };
4334 assert!(
4335 message.starts_with(
4336 "the clock `T` is in seconds by its step, but no coast bears that out: "
4337 ),
4338 "{message}"
4339 );
4340 let text = coast_download(&flight(1000.0, 0.05, 3.0 * G_FT, None, 15.0), |_, _| {});
4342 let error = read_text(&text).unwrap_err().to_string();
4343 assert!(
4344 error.starts_with(
4345 "Eggtimer text line 2: the clock `T` is in milliseconds by its step. But on that \
4346 clock `Alt` slows at 3 g in feet and 9.841 g in meters over the rows from "
4347 ),
4348 "{error}"
4349 );
4350 assert!(error.ends_with(". Neither is in the 0.7 to 1.3 g the reader takes"));
4351 let one = coast_download("0,0,0,0,0,0,0,0,0,0,0", |_, _| {});
4353 assert!(matches!(
4354 read_text(&one),
4355 Err(LogError::Unit { message, .. }) if message.starts_with(
4356 "the clock `T` can't be settled: the table holds one row"
4357 )
4358 ));
4359 let short = coast_download(&flight(1000.0, 0.05, G_FT, None, 1.5), |_, _| {});
4361 let error = read_text(&short).unwrap_err().to_string();
4362 assert!(
4363 error.contains("is in milliseconds by its step, but no coast bears that out: "),
4364 "{error}"
4365 );
4366 }
4367
4368 #[test]
4372 fn a_charge_before_the_top_ends_the_coast() {
4373 let text = coast_download(
4374 &flight(1000.0, 0.05, G_FT, Some((9.5, 10.0)), 15.0),
4375 |_, _| {},
4376 );
4377 let log = read_text(&text).unwrap();
4378 let alt = note_from(&log, "`Alt` ");
4379 assert!(
4380 alt.starts_with(
4381 "`Alt` read in feet, from the manual and the coast: the Classic and TRS manuals"
4382 ),
4383 "{alt}"
4384 );
4385 assert!(
4386 alt.contains(
4387 "Over the rows from 6.45 s to 9.45 s, up to the row before the marker `N-O` at \
4388 9.5 s, it slows at 1 g in feet"
4389 ),
4390 "{alt}"
4391 );
4392 }
4393
4394 #[test]
4399 fn a_canopy_that_would_pass_meters_for_feet_is_left_out() {
4400 let text = coast_download(
4401 &flight(
4402 1000.0,
4403 0.05,
4404 STANDARD_GRAVITY_MPS2,
4405 Some((1.85, 15.0)),
4406 15.0,
4407 ),
4408 |_, _| {},
4409 );
4410 let error = read_text(&text).unwrap_err().to_string();
4411 assert_eq!(
4412 error,
4413 "Eggtimer text line 2: the clock `T` is in milliseconds by its step, but no coast \
4414 bears that out: the table starts 1.8 s before the coast's end, up to the row before \
4415 the marker `N-O` at 1.85 s, short of the 3 s window"
4416 );
4417 }
4418
4419 #[test]
4422 fn a_jump_ends_the_coast() {
4423 let jumped = |at: usize| {
4424 coast_download(
4425 &flight(1000.0, 0.05, G_FT, None, 15.0),
4426 move |row, cells| {
4427 if row == at {
4428 cells[1] = "900".to_owned();
4429 }
4430 },
4431 )
4432 };
4433 let log = read_text(&jumped(190)).unwrap();
4434 assert!(
4435 note_from(&log, "`Alt` ").contains(
4436 "Over the rows from 6.45 s to 9.45 s, up to the row before `Alt` jumps at 9.5 s, \
4437 it slows at 1 g in feet"
4438 ),
4439 "{}",
4440 note_from(&log, "`Alt` ")
4441 );
4442 let log = read_text(&jumped(100)).unwrap();
4444 assert!(
4445 note_from(&log, "`Alt` ").contains("from 6.9 s to 9.9 s, up to the altitude's top")
4446 );
4447 let error = read_text(&jumped(160)).unwrap_err().to_string();
4449 assert!(
4450 error.contains(
4451 "up to the row before `Alt` jumps at 8 s, the parabola fitted to `Alt` tops out \
4452 2.05 s from the window's end, further than the 1 s the reader asks"
4453 ),
4454 "{error}"
4455 );
4456 }
4457
4458 #[test]
4459 fn markers_are_detections_motors_or_charges() {
4460 for name in ["LDA", "LowV", "MaxV", "MaxA"] {
4461 assert_eq!(marker_role(name), MarkerRole::Detection, "{name}");
4462 }
4463 for name in ["BurnT", "BO#1", "Boost#2"] {
4464 assert_eq!(marker_role(name), MarkerRole::Motor, "{name}");
4465 }
4466 for name in [
4467 "Apogee", "N-O", "Drogue", "Main", "AUX", "CHA", "CH3", "Boost#", "Sustain",
4468 ] {
4469 assert_eq!(marker_role(name), MarkerRole::Charge, "{name}");
4470 }
4471 }
4472
4473 #[test]
4474 fn a_parabola_and_a_level_are_fitted_exactly() {
4475 let points: Vec<(f64, f64)> = (0..10)
4476 .map(|step| {
4477 let x = f64::from(step) * 0.25 - 2.0;
4478 (x, 5.0 + 3.0 * x - 16.0 * x * x)
4479 })
4480 .collect();
4481 let (slope, curvature) = parabola(&points).unwrap();
4482 assert!((slope - 3.0).abs() < 1e-9 && (curvature + 32.0).abs() < 1e-9);
4483 assert_eq!(parabola(&points[..2]), None);
4484 let values = [1.0, 2.0, 300.0, 4.0, 5.0, f64::NAN, 7.0];
4486 assert_eq!(level(&values, 0, 6, 2), 4.0);
4487 assert_eq!(level(&values, 0, 6, 0), 1.0);
4488 assert_eq!(level(&values, 0, 6, 5), 6.0);
4489 assert_eq!(level(&values, 2, 3, 3), 4.0);
4490 }
4491
4492 #[test]
4493 fn the_title_names_the_model_and_firmware() {
4494 assert_eq!(
4495 title_words("TRS 2.07"),
4496 ("TRS".to_owned(), Some("2.07".to_owned()))
4497 );
4498 assert_eq!(title_words("TRS"), ("TRS".to_owned(), None));
4499 assert_eq!(title_words(""), (String::new(), None));
4500 assert_eq!(
4501 title_words("2.10"),
4502 (String::new(), Some("2.10".to_owned()))
4503 );
4504 assert_eq!(height("12 ft"), Some((12.0 * 0.3048, "feet")));
4505 assert_eq!(height("12"), None);
4506 assert_eq!(height("12 ft extra"), None);
4507 assert_eq!(summary_time("1.5 secs."), Some((1.5, true)));
4508 assert_eq!(summary_time("1.5"), Some((1.5, false)));
4509 assert_eq!(summary_time("1.5 hours"), None);
4510 }
4511
4512 proptest::proptest! {
4513 #[test]
4516 fn any_preamble_is_read_or_refused(
4517 lines in proptest::collection::vec("[.:@ A-Za-z0-9<>=,-]{0,30}", 0..12)
4518 ) {
4519 let text = format!(
4520 "Eggtimer TRS 2.07 Flight Settings\n{}\n{}",
4521 lines.join("\n"),
4522 table()
4523 );
4524 if let Ok(log) = read_text(&text) {
4525 proptest::prop_assert!(log.time_s.windows(2).all(|pair| pair[1] > pair[0]));
4526 proptest::prop_assert!(
4527 log.events.windows(2).all(|pair| pair[0].time_s <= pair[1].time_s)
4528 );
4529 }
4530 }
4531 }
4532
4533 proptest::proptest! {
4534 #[test]
4537 fn any_text_is_read_or_refused(
4538 rows in proptest::collection::vec("[-0-9.,x \r]{0,30}", 0..12)
4539 ) {
4540 let text = format!("{TRS}\n{}", rows.join("\n"));
4541 if let Ok(log) = read(&text) {
4542 proptest::prop_assert!(log.time_s.windows(2).all(|pair| pair[1] > pair[0]));
4543 proptest::prop_assert_eq!(log.time_s.len(), log.altitude_m.len());
4544 for channel in &log.channels {
4545 proptest::prop_assert_eq!(channel.time_s.len(), channel.values.len());
4546 }
4547 for event in &log.events {
4548 proptest::prop_assert!(log.time_s.contains(&event.time_s));
4549 }
4550 }
4551 }
4552 }
4553
4554 #[test]
4558 fn rtf_unwraps_to_its_text() {
4559 let document = "{\\rtf1\\ansi{\\fonttbl\\f0 Helvetica;}{\\colortbl;\\red0;}\
4560 {\\stylesheet{\\s0 Normal;}}{\\info{\\title Hidden}}{\\*\\generator X;}\
4561 a\\\\b\\{c\\}\\'85\\'41\\tab d\\par e\\line f\\~g\\_h\\-i\\u8364?j\
4562 {\\uc0\\u955 k}\\emdash\\b0\\par}";
4563 let text = unwrap_rtf(document).unwrap().text;
4564 assert_eq!(
4565 text,
4566 "a\\b{c}\u{2026}A\td\ne\nf\u{a0}g-hi\u{20ac}j\u{3bb}k\u{2014}\n"
4567 );
4568 }
4569
4570 #[test]
4573 fn rtf_lines_map_to_the_documents() {
4574 let unwrapped = unwrap_rtf("{\\rtf1\n\\f0 a\\\r\nb\\par\n\nc}").unwrap();
4575 assert_eq!(unwrapped.text, "a\nb\nc");
4576 assert_eq!(unwrapped.starts, [2, 3, 5]);
4577 assert_eq!(unwrapped.file_line(3), 5);
4578 assert_eq!(unwrapped.file_line(9), 5);
4579 assert_eq!(unwrapped.file_line(0), 5);
4580 }
4581
4582 #[test]
4585 fn rtf_numbers_binary_and_code_pages_are_bounded() {
4586 let huge = "9".repeat(400);
4587 let text = unwrap_rtf(&format!(
4588 "{{\\rtf1\\fs{huge} a\\u{huge}?\\u-3913?{{\\uc{huge}\\u65 bc}} d\\fs-{huge} e}}"
4589 ))
4590 .unwrap()
4591 .text;
4592 assert_eq!(text, "a\u{fffd}\u{f0b7}A de");
4593 assert_eq!(unwrap_rtf("{\\rtf1 a\\bin3 {}}b}").unwrap().text, "ab");
4594 let error = unwrap_rtf(&format!("{{\\rtf1 a\\bin{huge} b}}"))
4595 .unwrap_err()
4596 .to_string();
4597 assert_eq!(
4598 error,
4599 "Eggtimer RTF line 1: the document ends with 1 groups open: its braces don't balance"
4600 );
4601 let other = unwrap_rtf("{\\rtf1\\ansi\\ansicpg1251 \\'e0\\'41\\'81}").unwrap();
4602 assert_eq!(other.text, "\u{fffd}A\u{fffd}");
4603 assert_eq!(other.unmapped, 2);
4604 let undefined = unwrap_rtf("{\\rtf1\\ansi \\'81\\'e9\\'9f}").unwrap();
4605 assert_eq!(undefined.text, "\u{fffd}\u{e9}\u{178}");
4606 assert_eq!(undefined.unmapped, 1);
4607 let after = unwrap_rtf("{\\rtf1 a}\r\n x}").unwrap();
4608 assert_eq!((after.text.as_str(), after.after_end), ("a", 2));
4609 }
4610
4611 #[test]
4614 fn rtf_markup_is_refused_where_it_goes_wrong() {
4615 let deep = "{".repeat(MAX_RTF_DEPTH + 1);
4616 let cases = [
4617 (
4618 "}{\\rtf1 a}",
4619 "line 1: a `}` closes a group that was never opened",
4620 ),
4621 (
4622 "{\\rtf1\n{a}\n",
4623 "line 3: the document ends with 1 groups open",
4624 ),
4625 (
4626 deep.as_str(),
4627 "line 1: the document's groups nest deeper than 64",
4628 ),
4629 (
4630 "{\\rtf1\n\\'4g}",
4631 "line 2: a `\\'` escape isn't followed by two hexadecimal digits",
4632 ),
4633 (
4634 "x{\\rtf1 a}",
4635 "line 1: text comes before the document's opening `{`",
4636 ),
4637 ("", "the file holds no RTF group"),
4638 ];
4639 for (document, expected) in cases {
4640 let error = unwrap_rtf(document).unwrap_err().to_string();
4641 assert!(error.contains(expected), "{document:?}: {error}");
4642 }
4643 let nested = format!(
4645 "{}a{}",
4646 "{".repeat(MAX_RTF_DEPTH),
4647 "}".repeat(MAX_RTF_DEPTH)
4648 );
4649 assert_eq!(unwrap_rtf(&nested).unwrap().text, "a");
4650 }
4651
4652 #[test]
4654 fn rtf_without_a_download_is_refused_by_name() {
4655 for (text, expected) in [
4656 ("T,Alt\n0,0\n", "doesn't open with `{\\rtf`"),
4657 (
4658 "{\\rtf1 Eggtimer notes\\par T,Alt\\par 0,0}",
4659 "the RTF document's text holds no Eggtimer terminal download",
4660 ),
4661 ] {
4662 let error = read_rtf(text).unwrap_err();
4663 assert!(
4664 matches!(&error, LogError::NotThisFormat { format: "Eggtimer RTF", message }
4665 if message.contains(expected)),
4666 "{error}"
4667 );
4668 }
4669 }
4670
4671 proptest::proptest! {
4672 #[test]
4675 fn any_rtf_is_unwrapped_or_refused(
4676 body in "[{}\\\\a-z0-9 '\\-*~_?\r\n]{0,80}"
4677 ) {
4678 let document = format!("{{\\rtf1 {body}}}");
4679 if let Ok(unwrapped) = unwrap_rtf(&document) {
4680 proptest::prop_assert!(unwrapped.text.len() <= document.len());
4681 let text = &unwrapped.text;
4682 let lines = text.matches('\n').count()
4683 + usize::from(!text.is_empty() && !text.ends_with('\n'));
4684 proptest::prop_assert_eq!(lines, unwrapped.starts.len());
4685 }
4686 let _ = read_rtf(&document);
4687 }
4688 }
4689}