1use std::borrow::Cow;
63
64use crate::error::LogError;
65use crate::log::{FlightLog, LogFormat};
66use crate::{
67 aerospacenu_fcb, aerospacenu_gs, altimax, altimax_als, altimetercloud, altos, altos_eeprom,
68 altos_telem, altos_telem_csv, archive, arts2, arts2_raw, blueraven, blueraven_usb, capture,
69 eggtimer, entacore, entacore_raw, fluctus, fwgps, fwsummary, generic, gpx, kml, marsa, nmea,
70 packets, perfectflite, phone_launch, raven, raven_fipa, rdas, rrc3, rrc3_rff, rtx, sillygoose,
71 teensy, workbook, xls,
72};
73
74pub const FORMATS: &[LogFormat] = &[
76 LogFormat::RavenFipa,
77 LogFormat::Rrc3Rff,
78 LogFormat::Arts2Odf,
79 LogFormat::RtxRaw,
80 LogFormat::AltimaxAls,
81 LogFormat::EntacoreXtra,
82 LogFormat::EntacoreDump,
83 LogFormat::RadioPacketRtf,
84 LogFormat::EggtimerRtf,
85 LogFormat::AerospaceNuGroundStationText,
86 LogFormat::BlueRavenUsb,
87 LogFormat::TeensyTabs,
88 LogFormat::TeensyNamed,
89 LogFormat::RadioPacketText,
90 LogFormat::AltimaxXls,
91 LogFormat::Marsa,
92 LogFormat::ConsoleCapture,
93 LogFormat::Kml,
94 LogFormat::Gpx,
95 LogFormat::Nmea0183,
96 LogFormat::FeatherweightGpsCsv,
97 LogFormat::FeatherweightSummaryCsv,
98 LogFormat::RdasText,
99 LogFormat::AltosEeprom,
100 LogFormat::AltosTelemetry,
101 LogFormat::AltosTelemetryCsv,
102 LogFormat::Arts2Csv,
103 LogFormat::Arts2RawCsv,
104 LogFormat::RtxCsv,
105 LogFormat::RtxText,
106 LogFormat::PerfectFlitePf2,
107 LogFormat::PerfectFlitePfa,
108 LogFormat::AltosCsv,
109 LogFormat::RavenFipCsv,
110 LogFormat::BlueRavenCsv,
111 LogFormat::Rrc3Csv,
112 LogFormat::AltimeterCloudCsv,
113 LogFormat::EntacoreAimCsv,
114 LogFormat::SillyGooseText,
115 LogFormat::FluctusCsv,
116 LogFormat::AerospaceNuFcbCsv,
117 LogFormat::PhoneLaunchCsv,
118 LogFormat::EggtimerText,
119 LogFormat::EggtimerCsv,
120 LogFormat::PerfectFliteCsv,
121 LogFormat::PerfectFliteText,
122 LogFormat::GenericTable,
123];
124
125pub fn decode(bytes: &[u8]) -> Cow<'_, str> {
131 let utf16 = |bytes: &[u8], unit: fn([u8; 2]) -> u16| {
132 let (pairs, odd) = bytes.as_chunks::<2>();
133 let odd = (!odd.is_empty()).then_some(char::REPLACEMENT_CHARACTER);
135 let text: String = char::decode_utf16(pairs.iter().map(|pair| unit(*pair)))
136 .map(|c| c.unwrap_or(char::REPLACEMENT_CHARACTER))
137 .chain(odd)
138 .collect();
139 Cow::Owned(match text.strip_prefix("\u{ef}\u{bb}\u{bf}") {
140 Some(rest) => rest.to_owned(),
141 None => text,
142 })
143 };
144 if let Some(rest) = bytes.strip_prefix(b"\xff\xfe") {
145 utf16(rest, u16::from_le_bytes)
146 } else if let Some(rest) = bytes.strip_prefix(b"\xfe\xff") {
147 utf16(rest, u16::from_be_bytes)
148 } else {
149 let bytes = bytes.strip_prefix(b"\xef\xbb\xbf").unwrap_or(bytes);
150 String::from_utf8_lossy(bytes)
151 }
152}
153
154pub fn detect(bytes: &[u8]) -> Option<LogFormat> {
157 detect_binary(bytes).or_else(|| detect_text(&decode(bytes)))
158}
159
160fn detect_binary(bytes: &[u8]) -> Option<LogFormat> {
162 if raven_fipa::recognizes(bytes) {
163 Some(LogFormat::RavenFipa)
164 } else if rrc3_rff::recognizes(bytes) {
165 Some(LogFormat::Rrc3Rff)
166 } else if arts2_raw::recognizes_odf(bytes) {
167 Some(LogFormat::Arts2Odf)
168 } else if rtx::recognizes_raw(bytes) {
169 Some(LogFormat::RtxRaw)
170 } else if altimax_als::recognizes(bytes) {
171 Some(LogFormat::AltimaxAls)
172 } else if entacore_raw::recognizes_xtra(bytes) {
173 Some(LogFormat::EntacoreXtra)
174 } else if entacore_raw::recognizes_dump(bytes) {
175 Some(LogFormat::EntacoreDump)
176 } else {
177 None
178 }
179}
180
181fn detect_text(text: &str) -> Option<LogFormat> {
182 let mut lines = text
184 .split(['\r', '\n'])
185 .map(str::trim)
186 .filter(|line| !line.is_empty());
187 let first = lines.next()?;
188 if packets::recognizes_rtf(text) {
191 return Some(LogFormat::RadioPacketRtf);
192 }
193 if eggtimer::recognizes_rtf(text) {
194 return Some(LogFormat::EggtimerRtf);
195 }
196 if aerospacenu_gs::recognizes(text) {
197 return Some(LogFormat::AerospaceNuGroundStationText);
198 }
199 if blueraven_usb::recognizes(text) {
201 return Some(LogFormat::BlueRavenUsb);
202 }
203 if teensy::recognizes_tabs(text) {
205 return Some(LogFormat::TeensyTabs);
206 }
207 if teensy::recognizes_named(text) {
208 return Some(LogFormat::TeensyNamed);
209 }
210 if packets::recognizes_text(text) {
212 return Some(LogFormat::RadioPacketText);
213 }
214 if altimax::recognizes(text) {
216 return Some(LogFormat::AltimaxXls);
217 }
218 if marsa::recognizes(text) {
220 return Some(LogFormat::Marsa);
221 }
222 if capture::recognizes(text) {
224 return Some(LogFormat::ConsoleCapture);
225 }
226 if kml::recognizes(text) {
229 return Some(LogFormat::Kml);
230 }
231 if gpx::recognizes(text) {
232 return Some(LogFormat::Gpx);
233 }
234 if nmea::recognizes(text) {
235 return Some(LogFormat::Nmea0183);
236 }
237 if fwgps::recognizes(text) {
238 return Some(LogFormat::FeatherweightGpsCsv);
239 }
240 if fwsummary::recognizes(text) {
241 return Some(LogFormat::FeatherweightSummaryCsv);
242 }
243 if rdas::recognizes(text) {
244 return Some(LogFormat::RdasText);
245 }
246 if altos_eeprom::recognizes(text) {
247 return Some(LogFormat::AltosEeprom);
248 }
249 if altos_telem::recognizes(text) {
250 return Some(LogFormat::AltosTelemetry);
251 }
252 if altos_telem_csv::recognizes(text) {
253 return Some(LogFormat::AltosTelemetryCsv);
254 }
255 let altos_header =
256 |line: &str| line.starts_with("#version,") || line.starts_with("version,serial,");
257 if arts2::recognizes(text) {
259 return Some(LogFormat::Arts2Csv);
260 }
261 if arts2_raw::recognizes_csv(text) {
262 return Some(LogFormat::Arts2RawCsv);
263 }
264 if let Some(format) = rtx::export_format(text) {
265 return Some(format);
266 }
267 if first.to_ascii_lowercase().contains("perfectflite") {
268 let pfa = text
271 .split(['\r', '\n'])
272 .any(|line| line.trim_start().starts_with("**!!"));
273 Some(if pfa {
274 LogFormat::PerfectFlitePfa
275 } else {
276 LogFormat::PerfectFlitePf2
277 })
278 } else if first.starts_with('#') && !altos_header(first) {
279 std::iter::once(first)
282 .chain(lines)
283 .find(|line| !line.starts_with('#') || altos_header(line))
284 .filter(|line| altos_header(line))
285 .map(|_| LogFormat::AltosCsv)
286 } else if altos_header(first) || altos::recognizes_table(text) {
287 Some(LogFormat::AltosCsv)
290 } else if first.starts_with("Time") && first.contains("Axial Accel (Gs)") {
291 Some(LogFormat::RavenFipCsv)
294 } else if blueraven::recognizes(text) {
295 Some(LogFormat::BlueRavenCsv)
296 } else if rrc3::recognizes(text) {
297 Some(LogFormat::Rrc3Csv)
298 } else if altimetercloud::recognizes(text) {
299 Some(LogFormat::AltimeterCloudCsv)
300 } else if entacore::recognizes(text) {
301 Some(LogFormat::EntacoreAimCsv)
302 } else if sillygoose::recognizes(text) {
303 Some(LogFormat::SillyGooseText)
304 } else if fluctus::recognizes(text) {
305 Some(LogFormat::FluctusCsv)
306 } else if aerospacenu_fcb::recognizes(text) {
307 Some(LogFormat::AerospaceNuFcbCsv)
308 } else if phone_launch::recognizes(text) {
309 Some(LogFormat::PhoneLaunchCsv)
310 } else if eggtimer::recognizes_text(text) {
311 Some(LogFormat::EggtimerText)
312 } else if eggtimer::recognizes(text) {
313 Some(LogFormat::EggtimerCsv)
314 } else if perfectflite::is_headerless_row(first) {
315 Some(LogFormat::PerfectFliteText)
316 } else {
317 match perfectflite::export_separator(first) {
318 Some(',') => Some(LogFormat::PerfectFliteCsv),
319 Some(_) => Some(LogFormat::PerfectFliteText),
320 None => None,
321 }
322 }
323 .or_else(|| generic::recognizes(text).then_some(LogFormat::GenericTable))
326}
327
328pub fn read(bytes: &[u8]) -> Result<FlightLog, LogError> {
338 if archive::is_archive(bytes) {
339 return Err(LogError::Archive {
340 message: "the file is a zip archive, which holds files rather than a log, or a format \
341 built on one, such as a spreadsheet's `.xlsx`. An archive's files are read \
342 one by one once unpacked (`archive::unpack`). A workbook's sheets are read \
343 one by one (`workbook::read`)"
344 .to_owned(),
345 });
346 }
347 if xls::recognizes(bytes) {
348 return Err(LogError::Workbook {
349 message: "the file is an Excel `.xls` worksheet, which holds a sheet of cells rather \
350 than a log. Its sheet is read once written out as text (`xls::read`)"
351 .to_owned(),
352 });
353 }
354 let binary = detect_binary(bytes);
356 let text = if binary.is_some() {
357 Cow::Borrowed("")
358 } else {
359 decode(bytes)
360 };
361 match binary.or_else(|| detect_text(&text)) {
362 Some(LogFormat::PerfectFlitePf2) => perfectflite::read(&text),
363 Some(LogFormat::PerfectFlitePfa) => perfectflite::read_pfa(&text),
364 Some(LogFormat::PerfectFliteCsv | LogFormat::PerfectFliteText) => {
365 perfectflite::read_export(&text)
366 }
367 Some(LogFormat::AltosCsv) => altos::read(&text),
368 Some(LogFormat::RavenFipCsv) => raven::read(&text),
369 Some(LogFormat::BlueRavenCsv) => blueraven::read(&text),
370 Some(LogFormat::BlueRavenUsb) => blueraven_usb::read(&text),
371 Some(LogFormat::TeensyTabs) => teensy::read(&text),
372 Some(LogFormat::TeensyNamed) => teensy::read_named(&text),
373 Some(LogFormat::RadioPacketText) => packets::read(&text),
374 Some(LogFormat::RadioPacketRtf) => packets::read_rtf(&text),
375 Some(LogFormat::AltimaxXls) => altimax::read(&text),
376 Some(LogFormat::Marsa) => marsa::read(&text),
377 Some(LogFormat::Rrc3Csv) => rrc3::read(&text),
378 Some(LogFormat::EggtimerCsv) => eggtimer::read(&text),
379 Some(LogFormat::EggtimerText) => eggtimer::read_text(&text),
380 Some(LogFormat::AltimeterCloudCsv) => altimetercloud::read(&text),
381 Some(LogFormat::EntacoreAimCsv) => entacore::read(&text),
382 Some(LogFormat::SillyGooseText) => sillygoose::read(&text),
383 Some(LogFormat::FluctusCsv) => fluctus::read(&text),
384 Some(LogFormat::Arts2Csv) => arts2::read(&text),
385 Some(LogFormat::Arts2RawCsv) => arts2_raw::read_csv(&text),
386 Some(LogFormat::FeatherweightGpsCsv) => fwgps::read(&text),
387 Some(LogFormat::Kml) => kml::read(&text),
388 Some(LogFormat::Gpx) => gpx::read(&text),
389 Some(LogFormat::Nmea0183) => nmea::read(&text),
390 Some(LogFormat::AerospaceNuFcbCsv) => aerospacenu_fcb::read(&text),
391 Some(LogFormat::AerospaceNuGroundStationText) => aerospacenu_gs::read(&text),
392 Some(LogFormat::PhoneLaunchCsv) => phone_launch::read(&text),
393 Some(LogFormat::EggtimerRtf) => eggtimer::read_rtf(&text),
394 Some(LogFormat::RavenFipa) => raven_fipa::read(bytes),
395 Some(LogFormat::Rrc3Rff) => rrc3_rff::read(bytes),
396 Some(LogFormat::Arts2Odf) => arts2_raw::read_odf(bytes),
397 Some(LogFormat::RtxRaw) => rtx::read_raw(bytes),
398 Some(LogFormat::AltimaxAls) => altimax_als::read(bytes),
399 Some(LogFormat::EntacoreXtra) => entacore_raw::read_xtra(bytes),
400 Some(LogFormat::EntacoreDump) => entacore_raw::read_dump_one(bytes),
401 Some(LogFormat::RtxCsv | LogFormat::RtxText) => rtx::read_export(&text),
402 Some(LogFormat::FeatherweightSummaryCsv) => fwsummary::read(&text),
403 Some(LogFormat::RdasText) => rdas::read(&text),
404 Some(LogFormat::AltosTelemetry) => altos_telem::read(&text),
405 Some(LogFormat::AltosTelemetryCsv) => altos_telem_csv::read(&text),
406 Some(LogFormat::AltosEeprom) => altos_eeprom::read(&text),
407 Some(LogFormat::GenericTable) => generic::read(&text),
408 Some(LogFormat::ConsoleCapture) => Err(capture::needs_a_layout(&text)),
410 Some(LogFormat::BinaryRecords) => Err(LogError::Layout {
412 message: "a file of binary records is read by a layout the caller states \
413 (`records::read`)"
414 .to_owned(),
415 }),
416 None if bytes.iter().all(u8::is_ascii_whitespace) => Err(LogError::Unrecognized {
419 message: if bytes.is_empty() {
420 "the file is empty".to_owned()
421 } else {
422 "the file holds only blank space".to_owned()
423 },
424 }),
425 None => {
426 let known: Vec<&str> = FORMATS.iter().map(|format| format.name()).collect();
427 Err(LogError::Unrecognized {
428 message: format!(
429 "the file is in none of the layouts HPR Sim reads so far: {}",
430 known.join(", ")
431 ),
432 })
433 }
434 }
435}
436
437pub fn read_one(
460 bytes: &[u8],
461 sheet: Option<usize>,
462 recording: Option<usize>,
463) -> Result<FlightLog, LogError> {
464 let choice = |message: String| Err(LogError::Choice { message });
465 let sheets = if archive::is_archive(bytes) {
466 match workbook::read(bytes) {
467 Ok(sheets) => Some(sheets),
468 Err(LogError::NotThisFormat { .. }) => return read(bytes),
471 Err(error) => return Err(error),
472 }
473 } else if xls::recognizes(bytes) {
474 Some(xls::read(bytes)?)
475 } else {
476 None
477 };
478 if let Some(sheets) = sheets {
479 if recording.is_some() {
480 return choice(
481 "the file is a spreadsheet's workbook, which holds sheets, not recordings: \
482 choose a sheet"
483 .to_owned(),
484 );
485 }
486 let count = sheets.len();
487 if let Some(index) = sheet {
488 return match sheets.into_iter().nth(index) {
489 Some(chosen) => chosen.log,
490 None => choice(format!(
491 "the workbook has {count} {}, numbered from 0: it has no sheet {index}",
492 if count == 1 { "sheet" } else { "sheets" }
493 )),
494 };
495 }
496 if count == 1 {
498 return sheets
499 .into_iter()
500 .next()
501 .map_or(Err(LogError::NoData { format: "workbook" }), |one| one.log);
502 }
503 let mut reading: Vec<(usize, workbook::SheetLog)> = sheets
504 .into_iter()
505 .enumerate()
506 .filter(|(_, sheet)| sheet.log.is_ok())
507 .collect();
508 return match reading.len() {
509 1 => reading
511 .pop()
512 .map_or(Err(LogError::NoData { format: "workbook" }), |(_, one)| {
513 one.log
514 }),
515 0 => choice(format!(
516 "none of the workbook's {count} sheets reads as a log: a table on one is read by \
517 a column mapping, with its sheet chosen"
518 )),
519 _ => {
520 let named = workbook::listed(
521 reading
522 .iter()
523 .map(|(index, sheet)| (*index, sheet.name.as_str())),
524 |index, name| format!("{index} ({name})"),
525 );
526 choice(format!(
527 "{} of the workbook's {count} sheets read as logs, sheets {named}: choose one",
528 reading.len(),
529 ))
530 }
531 };
532 }
533 if detect(bytes) == Some(LogFormat::EntacoreDump) {
534 if sheet.is_some() {
535 return choice(
536 "the file is an Entacore AIM raw dump, which holds recordings, not sheets: \
537 choose a recording"
538 .to_owned(),
539 );
540 }
541 let mut recordings = entacore_raw::read_dump(bytes)?;
542 let count = recordings.len();
543 return match recording {
544 Some(index) if index < count => Ok(recordings.swap_remove(index)),
545 Some(index) => choice(format!(
546 "the dump holds {count} recordings, numbered from 0: it has no recording {index}"
547 )),
548 None if count == 1 => recordings.pop().ok_or(LogError::NoData {
550 format: "Entacore AIM raw dump",
551 }),
552 None => choice(format!(
553 "the dump holds {count} recordings: choose one, numbered from 0"
554 )),
555 };
556 }
557 if sheet.is_some() || recording.is_some() {
558 return choice(
559 "the file holds one record, not a workbook's sheets or a dump's recordings: choose \
560 neither"
561 .to_owned(),
562 );
563 }
564 read(bytes)
565}
566
567#[cfg(test)]
568mod tests {
569 use super::*;
570
571 #[test]
572 fn an_archive_is_refused_as_one_to_unpack() {
573 for bytes in [&b"PK\x03\x04 the rest"[..], b"PK\x05\x06"] {
574 match read(bytes) {
575 Err(LogError::Archive { message }) => {
576 assert!(message.contains("archive::unpack"), "{message}");
577 }
578 other => panic!("expected an archive refusal, got {other:?}"),
579 }
580 }
581 }
582
583 #[test]
584 fn each_format_is_recognized_by_its_marks() {
585 let cases = [
586 ("PerfectFlite Pnut\n", Some(LogFormat::PerfectFlitePf2)),
587 (
588 "\u{feff}\n\n#version,serial,flight,time\n",
589 Some(LogFormat::AltosCsv),
590 ),
591 (
592 "# Altus Metrum flight log\n# serial 1\nversion,serial,flight,time\n",
593 Some(LogFormat::AltosCsv),
594 ),
595 ("#Component=Raven\n", None),
596 ("# MET Acc Vel iAlt pAlt\n", Some(LogFormat::Arts2Csv)),
597 (
598 "MET,Acc(HI),Acc/Baro(LO),Baro(HI),State\n",
599 Some(LogFormat::Arts2RawCsv),
600 ),
601 ("MET,Acc,Baro,State\n", None),
602 ("\x09\x00\x00\x00Ozark.odf", Some(LogFormat::Arts2Odf)),
603 ("\x09\x00\x00\x00Ozark.od", None),
604 (
605 "UTC Time,Latitude,Longitude,Altitude,Velocity,VDOP,NavStatus,Sats,SOG,COG\r\n",
606 Some(LogFormat::RtxCsv),
607 ),
608 (
609 "\u{feff}UTC\tLat\t\tLon\t\tAlt\tVel\tVDOP\tNav\tSats\tSOG\tCOG\r\n",
610 Some(LogFormat::RtxText),
611 ),
612 ("UTC\tLat\tLon\tAlt\tVel\tVDOP\tNav\tSats\tSOG\tCOG\n", None),
613 ("UTC Time,Latitude,Longitude,Altitude\n", None),
614 (
615 "sep=;\ntime (ms);deltaTime (ms);status;baro-altitude (m)\n",
616 Some(LogFormat::FluctusCsv),
617 ),
618 ("T;Alt;Veloc;FAlt\n", Some(LogFormat::EggtimerCsv)),
619 ("0.00\t3\t71.5F\t9.2\n", Some(LogFormat::PerfectFliteText)),
620 ("0.00\t3\t21.9C\t9.2\n", Some(LogFormat::PerfectFliteText)),
621 ("0.00\t3\t71.5\t9.2\n", None),
622 ("0.00\t3\t71.5F\t9.2\t1\n", None),
623 ("0.00\t3\tF\t9.2\n", None),
624 (
625 "Time,Altitude,Temp,Voltage\n",
626 Some(LogFormat::PerfectFliteCsv),
627 ),
628 (
629 "Flight_Time_(s),Sync,Gyro_X\n",
630 Some(LogFormat::BlueRavenCsv),
631 ),
632 ("Flight_Time_(s),Sync\n", None),
633 ("Sync,Flight_Time_(s),Gyro_X\n", None),
634 (
635 "timestampMs\tpressurePa\ttempK\taltitudeM\n",
636 Some(LogFormat::SillyGooseText),
637 ),
638 (
639 "#foo\n#version,serial,flight,time\n",
640 Some(LogFormat::AltosCsv),
641 ),
642 ("# a note\nTime,Altitude,Velocity\n", None),
643 (
644 "PerfectFlite Alt15K/WD\nApogee: 900\n**!!Data:\n1200\n",
645 Some(LogFormat::PerfectFlitePfa),
646 ),
647 (
648 "Year,Month,Day,Time,Flight_Time_(s),Axial Accel (Gs)\n",
649 None,
650 ),
651 (
652 "Time,Altitude,Velocity\r0.00,0,0\r0.05,1,8\r",
653 Some(LogFormat::PerfectFliteCsv),
654 ),
655 (
656 "Time@Axial Accel (Gs),Axial Accel (Gs),bILBA\n",
657 Some(LogFormat::RavenFipCsv),
658 ),
659 (
660 "Time,LiftOff,Axial Accel (Gs),Baro (Atm)\n",
661 Some(LogFormat::RavenFipCsv),
662 ),
663 (
664 "Time, Altitude, Velocity\n",
665 Some(LogFormat::PerfectFliteCsv),
666 ),
667 (
668 "Time\tAltitude\tTemp.\tVoltage\n",
669 Some(LogFormat::PerfectFliteText),
670 ),
671 ("time_s,altitude_ft,temperature,voltage\n", None),
673 ("Time,Pressure\n", None),
674 ("time,altitude\n", None),
675 ("Time,Altitude\n", None),
676 (
677 "Time,Altitude,Pressure,Velocity,Temperature,Events,Voltages\n",
678 Some(LogFormat::Rrc3Csv),
679 ),
680 (
681 "T,Alt,Veloc,FAlt,FVeloc,LDA,LowV,Apogee,N-O,Drogue,Main\r\r\n",
682 Some(LogFormat::EggtimerCsv),
683 ),
684 (
685 "Year,Month,Day,Time,Flight_Time_(s),Sync,Gyro_X\n",
686 Some(LogFormat::BlueRavenCsv),
687 ),
688 (
689 "<?xml version=\"1.0\"?>\n<!-- a track -->\n<kml xmlns=\"http://www.opengis.net/kml/2.2\"></kml>\n",
690 Some(LogFormat::Kml),
691 ),
692 (
693 "<?xml version=\"1.0\"?>\n<gpx></gpx>\n",
694 Some(LogFormat::Gpx),
695 ),
696 (
697 "\u{fffd}\u{fffd}x\r\n\
698 $GPGGA,120000.00,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*67\r\n\
699 $GPRMC,120001.00,A,4807.038,N,01131.000,E,022.4,084.4,230394,003.1,W*4B\r\n\
700 $GPGSA,A,3,04,05,,09,12,,,24,,,,,2.5,1.3,2.1*39\r\n",
701 Some(LogFormat::Nmea0183),
702 ),
703 (
705 "t=1 rx $GPGGA,120000.00,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*67\n",
706 None,
707 ),
708 (
709 "UTCTIME,UNIXTIME,ALT,LAT,LON,#SATS,FIX,HORZV,VERTV,HEAD,FLAGS\n",
710 Some(LogFormat::FeatherweightGpsCsv),
711 ),
712 (
713 "TRACKER,DATE,TIME,LAT,LON,ALT,FIX,HORZV,VERTV,HEAD,FLAGS,#TOT\r\n",
714 Some(LogFormat::FeatherweightGpsCsv),
715 ),
716 ("TRACKER,DATE,TIME,RSSI\n", None),
717 (
718 "{\"log_format\": 14, \"product\": \"EasyMini-v2.0\"}\n46 00",
719 Some(LogFormat::AltosEeprom),
720 ),
721 ("{\"product\": \"EasyMini-v2.0\"}\n", None),
722 (
723 "~\nConfig version: 1.27\nmanufacturer altusmetrum.org\nA 1 00 00\n",
724 Some(LogFormat::AltosEeprom),
725 ),
726 ("Config version: 1.27\nA 1 00 00\n", None),
727 ("", None),
728 ];
729 for (text, format) in cases {
730 assert_eq!(detect(text.as_bytes()), format, "{text:?}");
731 }
732 }
733
734 #[test]
735 fn utf16_is_read_by_its_byte_order_mark() {
736 let text = "Time\tAltitude é\n";
737 let mut le = vec![0xff, 0xfe];
738 let mut be = vec![0xfe, 0xff];
739 for unit in text.encode_utf16() {
740 le.extend(unit.to_le_bytes());
741 be.extend(unit.to_be_bytes());
742 }
743 assert_eq!(decode(&le), text);
744 assert_eq!(decode(&be), text);
745 le.push(b'x');
747 assert_eq!(decode(&le), format!("{text}\u{fffd}"));
748 assert_eq!(decode(&[0xff, 0xfe, 0x3d, 0xd8]), "\u{fffd}");
749 assert_eq!(decode(b"\xef\xbb\xbfa\xff"), "a\u{fffd}");
750
751 let mut inner = vec![0xff, 0xfe];
754 for unit in "\u{ef}\u{bb}\u{bf}Time\u{ef}\u{bb}\u{bf}".encode_utf16() {
755 inner.extend(unit.to_le_bytes());
756 }
757 assert_eq!(decode(&inner), "Time\u{ef}\u{bb}\u{bf}");
758 }
759
760 #[test]
761 fn a_layout_no_reader_knows_is_refused_naming_those_that_exist() {
762 let error = read(b"Time,Pressure\n0,101325\n").unwrap_err();
763 let LogError::Unrecognized { message } = &error else {
764 panic!("refused for another reason: {error:?}");
765 };
766 for format in FORMATS {
767 assert!(message.contains(format.name()), "{message}");
768 }
769 }
770
771 #[test]
772 fn an_empty_file_is_refused_as_empty_not_as_every_layout() {
773 for (bytes, said) in [
774 (&b""[..], "the file is empty"),
775 (&b"\n \r\n\t\n"[..], "the file holds only blank space"),
776 ] {
777 let error = read(bytes).unwrap_err();
778 let LogError::Unrecognized { message } = &error else {
779 panic!("refused for another reason: {error:?}");
780 };
781 assert_eq!(message, said);
782 }
783 }
784}