Skip to main content

hpr_flightdata/
raven.rs

1//! The Featherweight Raven's flight logs, as the Featherweight Interface Program (FIP) exports
2//! them to a comma-separated file.
3//!
4//! The Raven samples its sensors at different rates, so the export gives each channel its own
5//! clock: a `Time@` column, then the channel's values, then, in most exports, a status column
6//! named `bILBA`. One header line names the columns; each row below holds the next sample of every
7//! channel, so a row's cells for different channels were taken at different times:
8//!
9//! ```text
10//! Time@Axial Accel (Gs),Axial Accel (Gs),bILBA,Time@Baro (Atm),Baro (Atm),bILBA,…
11//! 0,1.02,b0000,0.04375,0.97,b0000,…
12//! 0.0025,1.01,b0000,0.09375,0.97,b0000,…
13//! ```
14//!
15//! **Channels.** The names the reader knows, each read into the record's SI unit
16//! ([`Quantity::unit`]); the column keeps the file's name, brackets and all:
17//!
18//! | Column | Quantity | From |
19//! |---|---|---|
20//! | `Axial Accel (Gs)`, `Lateral Accel (Gs)` | acceleration | g, × 9.80665 m/s² (standard gravity) |
21//! | `Baro (Atm)` | pressure | atm, × 101,325 Pa |
22//! | `Current Draw (A)` | current | A |
23//! | `Temperature (F)` | temperature | °F |
24//! | `Volts Battery (V)`, `Volts Pyro Apogee (V)` and the other `Volts … (V)` | voltage | V |
25//! | `Velocity (Accel-Ft/Sec)`, `[Velocity (Accel-Ft/Sec)]` | speed | ft/s |
26//! | `[Velocity (Accel-MPH)]` | speed | mph, × 0.44704 m/s |
27//! | `[Altitude (Accel-Ft)]` | inertial altitude | ft |
28//! | `[Altitude (Baro-Ft-AGL)]`, `Altitude (Ft-AGL)` | altitude above the pad | ft |
29//! | `[Altitude (Baro-Ft-ASL)]` | altitude above sea level | ft |
30//! | `LiftOff` | a number, as written | |
31//! | `bILBA` | a number: the status bits | |
32//!
33//! A column the reader doesn't know is kept as written, as [`Quantity::Unrecognized`], with a
34//! note. The bracketed names are figures the FIP works out from what the Raven recorded rather
35//! than recordings: their names say so (`Accel`, `Baro`), and each sits on the clock of the sensor
36//! it comes from.
37//!
38//! **The status column.** Each `bILBA` cell is `b` and four binary digits, such as `b1100`, and is
39//! kept as a [`Quantity::Number`] channel, beside the channel it follows, holding the digits'
40//! value read with the leftmost digit the most significant: `b0101` is 5, `b1100` is 12. No
41//! published source says what the digits mean. Featherweight's Raven manual (*Raven User's
42//! Manual, updated for the Raven4*, 2020-08-15) says the Raven records "all flight events used for
43//! deployment logic" at 20 Hz and that the FIP can plot them, but it describes neither the export
44//! nor this column; Debrief uses the column only to recognize the format. The letters `I`, `L`,
45//! `B` and `A` may name flight events (`L` liftoff, `B` burnout and `A` apogee would fit the
46//! manual's words), but that is a guess, so the reader states no events from them.
47//!
48//! **Rows of different lengths.** The channels run for different spans, and a channel with no
49//! sample in a row is written as two empty cells, its time's and its value's, *without* its status
50//! cell. In an export with status columns, a row is therefore one cell shorter for each channel
51//! that has stopped, and every channel after it is shifted one cell to the left of its header; an
52//! export without them keeps every row as wide as its header. The reader walks each row channel by
53//! channel: two empty cells are a channel with no sample in that row, anything else a sample with
54//! its status, and the row must end where the last channel does. This rule is the files', not a
55//! document's: Debrief's reader assumes every row as wide as the header, which in an export with
56//! status columns reads every channel after the first one to stop from the wrong cells. Debrief's
57//! public sample of a Raven flight bears the rule out row for row, as do the 79 Raven exports in
58//! the private collection of flights this project checks against.
59//!
60//! **Layouts.** Four were seen: each channel's clock and status (16 channels); each channel's clock
61//! without status columns (13, 16 or 18 channels); a two-channel export headed `Time-Axial Accel
62//! (Gs), Axial Accel (Gs), bILBA, Time (s), Altitude (Ft-AGL), bILBA`, with a space after each
63//! comma; and an export with one `Time` column for every channel, which in the one such file read
64//! repeats whole rows. A column whose name starts with `Time` starts a clock; the columns up to the
65//! next clock are its channels, each followed by its status column if it has one.
66//!
67//! **The primary track.** The record's time and altitude are `[Altitude (Baro-Ft-AGL)]`'s, on its
68//! own clock: the Raven's barometric altitude above the pad. The two-channel layout has no such
69//! column; its `Altitude (Ft-AGL)` names no sensor, and is taken instead, with a note: it is the
70//! only altitude above the pad the file holds, and in the one such file read it runs at 20 Hz, the
71//! rate the manual gives for the barometer (the accelerometer's is 400 Hz). A file with neither is
72//! refused: working an altitude out of `Baro (Atm)` is a reading, not this reader's to make. No
73//! column is a vertical speed from the barometer, so [`FlightLog::vertical_speed_m_s`] is `None`;
74//! the velocities are the accelerometer's, kept as channels. The temperature and battery voltage
75//! fill [`FlightLog::temperature_k`] and [`FlightLog::battery_v`] only when they share the
76//! altitude's clock, as they do in the one-clock layout; otherwise they are channels only.
77//!
78//! **Cells.** `-1.#QNAN` and the other ways Windows writes a value that isn't a number, as some
79//! exports write the accelerometer's derived channels before or after their data, are gaps,
80//! `NaN`, counted in a note; so is an empty value in a sample that has a time. Within a channel,
81//! a time that repeats the one before is dropped with a note saying how many of the repeats
82//! differed from the sample they repeat (the one-clock layout's repeated rows are identical
83//! copies); a time that goes back is refused, naming the line. A byte-order mark is dropped, lines
84//! may end in CR, LF or both, and the cells may be padded with spaces.
85//!
86//! **Where this comes from.** The layout, the `Time@`/`bILBA` header and the units follow the
87//! reader in Debrief (`lib/parsers/featherweightFip.ts` and `lib/parsers/multiTimebase.ts`, MIT,
88//! the project owner's own; see `THIRD-PARTY-NOTICES.md`), which was written from exported files
89//! and cites no document; the clocks' rates are Featherweight's manual's. Where this reader departs
90//! from Debrief's: it keeps every channel on its own clock where Debrief resamples them onto the
91//! densest; it walks the rows as above; it reads the layouts without status columns or with one
92//! clock, which Debrief doesn't recognize; it takes the altitude above the pad from the export's
93//! own column where Debrief works one out from the pressure; and it refuses a time that goes back
94//! where Debrief sorts the samples.
95
96use hpr_core::gravity::STANDARD_GRAVITY_MPS2;
97
98use crate::error::LogError;
99use crate::log::{Channel, FlightLog, LogFormat, Quantity, Stated};
100use crate::perfectflite::FOOT_M;
101use crate::table::finite;
102
103/// The format's name in errors.
104const FORMAT: &str = "Raven FIP CSV";
105
106/// Pascals in a standard atmosphere, exactly (ISO 2533).
107const ATM_PA: f64 = 101_325.0;
108
109/// Meters per second in a mile per hour, exactly (the international mile, 1,609.344 m, per 3,600 s).
110const MPH_M_S: f64 = 0.447_04;
111
112/// The name of a status column, as the FIP writes it (compared without regard to case).
113const STATUS: &str = "bilba";
114
115/// The name of the barometric altitude above the pad, the primary track, brackets stripped.
116const BARO_AGL: &str = "altitude (baro-ft-agl)";
117
118/// The two-channel layout's altitude above the pad, which names no sensor.
119const BARE_AGL: &str = "altitude (ft-agl)";
120
121/// How a known column's values become SI.
122#[derive(Debug, Clone, Copy, PartialEq)]
123enum Scale {
124    /// Multiplied by a factor.
125    By(f64),
126    /// Degrees Fahrenheit to kelvin.
127    Fahrenheit,
128}
129
130/// The columns the reader knows, brackets stripped and in lower case, with what each measures and
131/// how its values become SI. The `Volts … (V)` columns are matched by their shape instead
132/// ([`known`]).
133const KNOWN: [(&str, Quantity, Scale); 12] = [
134    (
135        "axial accel (gs)",
136        Quantity::Acceleration,
137        Scale::By(STANDARD_GRAVITY_MPS2),
138    ),
139    (
140        "lateral accel (gs)",
141        Quantity::Acceleration,
142        Scale::By(STANDARD_GRAVITY_MPS2),
143    ),
144    ("baro (atm)", Quantity::Pressure, Scale::By(ATM_PA)),
145    ("current draw (a)", Quantity::Current, Scale::By(1.0)),
146    ("temperature (f)", Quantity::Temperature, Scale::Fahrenheit),
147    (
148        "velocity (accel-ft/sec)",
149        Quantity::Speed,
150        Scale::By(FOOT_M),
151    ),
152    ("velocity (accel-mph)", Quantity::Speed, Scale::By(MPH_M_S)),
153    (
154        "altitude (accel-ft)",
155        Quantity::InertialAltitude,
156        Scale::By(FOOT_M),
157    ),
158    (BARO_AGL, Quantity::AltitudeAboveGround, Scale::By(FOOT_M)),
159    (BARE_AGL, Quantity::AltitudeAboveGround, Scale::By(FOOT_M)),
160    (
161        "altitude (baro-ft-asl)",
162        Quantity::AltitudeMsl,
163        Scale::By(FOOT_M),
164    ),
165    ("liftoff", Quantity::Number, Scale::By(1.0)),
166];
167
168/// A column name brackets stripped, trimmed and in lower case, as [`KNOWN`] lists them.
169fn key(name: &str) -> String {
170    let name = name.trim();
171    let name = name
172        .strip_prefix('[')
173        .and_then(|inner| inner.strip_suffix(']'))
174        .unwrap_or(name);
175    name.trim().to_ascii_lowercase()
176}
177
178/// What a known column measures and how it becomes SI; `None` for a column the reader doesn't know.
179fn known(name: &str) -> Option<(Quantity, Scale)> {
180    let key = key(name);
181    if key.starts_with("volts ") && key.ends_with("(v)") {
182        return Some((Quantity::Voltage, Scale::By(1.0)));
183    }
184    KNOWN
185        .iter()
186        .find(|(known, _, _)| *known == key)
187        .map(|(_, quantity, scale)| (*quantity, *scale))
188}
189
190/// Whether a header cell starts a clock: `Time@…`, `Time-…`, `Time (s)` or `Time`.
191fn is_clock(name: &str) -> bool {
192    name.get(..4)
193        .is_some_and(|start| start.eq_ignore_ascii_case("time"))
194}
195
196/// One data column of a clock: its value cells, and its status cells if it has a status column.
197struct Column {
198    name: String,
199    quantity: Quantity,
200    scale: Scale,
201    values: Vec<f64>,
202    status: Option<Vec<f64>>,
203    /// Cells left empty in samples that have a time.
204    empty: usize,
205    /// Cells that aren't a number, such as `-1.#QNAN`, and the first of them as written.
206    not_numbers: usize,
207    not_number_example: String,
208}
209
210/// A clock and the columns on it.
211struct Clock {
212    name: String,
213    time_s: Vec<f64>,
214    columns: Vec<Column>,
215    /// Repeated times dropped, and how many of them differed from the sample they repeat.
216    repeats: usize,
217    differing_repeats: usize,
218}
219
220impl Clock {
221    /// Cells a sample takes: the time, each value and each status.
222    fn sample_width(&self) -> usize {
223        1 + self.columns.len() + self.columns.iter().filter(|c| c.status.is_some()).count()
224    }
225
226    /// Cells a row gives the clock when it has no sample: the time and each value, empty.
227    fn empty_width(&self) -> usize {
228        1 + self.columns.len()
229    }
230}
231
232/// Reads a Featherweight Raven's FIP CSV export from its text.
233///
234/// # Errors
235///
236/// [`LogError::NotThisFormat`] if the first line isn't a FIP export's header (a clock column first,
237/// and a channel name the Raven writes); [`LogError::Syntax`] for a header the reader can't lay
238/// out, a file with no altitude above the pad, a row whose cells don't fall into its channels, a
239/// time or value that isn't a number, a value too large to convert to SI, or a time that goes
240/// back; [`LogError::NoData`] if the altitude has no samples.
241pub fn read(text: &str) -> Result<FlightLog, LogError> {
242    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
243    let mut lines = numbered_lines(text).filter(|(_, line)| !line.trim().is_empty());
244    let Some((header_line, header)) = lines.next() else {
245        return Err(LogError::NotThisFormat {
246            format: FORMAT,
247            message: "the file is empty".to_owned(),
248        });
249    };
250    let mut notes = Notes::default();
251    let mut clocks = header_clocks(header, header_line, &mut notes)?;
252
253    for (number, line) in lines {
254        read_row(&mut clocks, line, number, RowEnd::Exact)?;
255    }
256    build(clocks, header_line, notes)
257}
258
259/// Reads the rows of a FIP export whose header line is missing, as in a sheet the export was
260/// pasted into below no header, under `header`: the header line the FIP wrote for that export,
261/// which the caller states, such as the 16 channels' with status columns:
262///
263/// ```text
264/// Time@Axial Accel (Gs),Axial Accel (Gs),bILBA,Time@Baro (Atm),Baro (Atm),bILBA,…
265/// ```
266///
267/// The rows are read as [`read`] reads them, but for one thing a sheet does: it writes every row
268/// as wide as its widest, so a row may end in empty cells past its last channel's sample. The rows
269/// are numbered from 1 in errors, and a first row whose first cell begins with `Time`, as a
270/// header's first clock name does, is refused: the file has its own, and [`read`] reads it.
271///
272/// ```
273/// use hpr_flightdata::raven;
274///
275/// // Invented rows of a two-channel export, the second channel stopped in the last row, and that
276/// // row ended by a sheet's padding.
277/// let header = "Time@Axial Accel (Gs),Axial Accel (Gs),bILBA,\
278///               Time@[Altitude (Baro-Ft-AGL)],[Altitude (Baro-Ft-AGL)],bILBA";
279/// let rows = "0,1.02,b0000,0,0,b0000\n0.05,1.01,b0000,0.05,1,b0000\n0.1,1.0,b0000,,,\n";
280/// let log = raven::read_rows(header, rows)?;
281/// assert_eq!(log.time_s, [0.0, 0.05]);
282/// assert_eq!(log.channels[0].values.len(), 3);
283/// # Ok::<(), hpr_flightdata::error::LogError>(())
284/// ```
285///
286/// # Errors
287///
288/// [`LogError::Mapping`] when `header` isn't a FIP export's header, as [`read`] would refuse it;
289/// [`LogError::Syntax`] when a row's first cell is a clock's name, as a header's is; and what
290/// [`read`] refuses in the rows.
291pub fn read_rows(header: &str, rows: &str) -> Result<FlightLog, LogError> {
292    rows_under(header, rows, &[])
293}
294
295/// Reads the rows of a FIP export whose header line is missing, as [`read_rows`] does, from a
296/// sheet whose columns `pasted`, numbered from 1, hold another table pasted over the export's
297/// cells. A stopped channel shifts every channel after it one cell to the left, so a column of the
298/// sheet holds different channels' cells in different rows, and a pasted column hides a cell of
299/// whichever channel is there.
300///
301/// The rule: a channel whose sample, in any row, has a cell in a pasted column is left out whole,
302/// with a note naming it and counting the rows; every other channel is read as [`read_rows`]
303/// reads it. To walk a row, each channel's cells must still say whether it has a sample: one of
304/// its time's and values' cells outside the pasted columns not empty; or, where some are pasted
305/// over and the rest empty, and the channel has its own clock and a status, the cell after them, a
306/// sample's status, `b` and digits, where a stopped channel's next cell is another channel's time.
307/// That cell pasted over or empty, a status left empty or another channel stopped too, or a clock
308/// of more channels, the row is refused.
309///
310/// ```
311/// use hpr_flightdata::raven;
312///
313/// // Invented rows of a three-channel export whose fourth and fifth columns another table was
314/// // pasted over, 7 and 8: the second channel is left out.
315/// let header = "Time@Axial Accel (Gs),Axial Accel (Gs),bILBA,\
316///               Time@Baro (Atm),Baro (Atm),bILBA,\
317///               Time@[Altitude (Baro-Ft-AGL)],[Altitude (Baro-Ft-AGL)],bILBA";
318/// let rows = "0,1.02,b0000,7,8,b0000,0,0,b0000\n0.05,1.01,b0000,7,8,b0000,0.05,1,b0000\n";
319/// let log = raven::read_rows_around(header, rows, &[4, 5])?;
320/// assert_eq!(log.channels.len(), 4);
321/// assert_eq!(log.time_s, [0.0, 0.05]);
322/// # Ok::<(), hpr_flightdata::error::LogError>(())
323/// ```
324///
325/// # Errors
326///
327/// As [`read_rows`]'s; and [`LogError::Syntax`] for a row in which the pasted cells hide whether a
328/// channel has a sample, and [`LogError::Mapping`] for a pasted column numbered 0.
329pub fn read_rows_around(header: &str, rows: &str, pasted: &[usize]) -> Result<FlightLog, LogError> {
330    if pasted.contains(&0) {
331        return Err(LogError::Mapping {
332            message: "the pasted columns are numbered from 1, and one is 0".to_owned(),
333        });
334    }
335    let pasted: Vec<usize> = pasted.iter().map(|column| column - 1).collect();
336    rows_under(header, rows, &pasted)
337}
338
339/// What a row is read from ([`read_row`]).
340#[derive(Debug, Clone, Copy, PartialEq, Eq)]
341enum RowEnd<'a> {
342    /// An export's own: the row ends where its last channel does.
343    Exact,
344    /// A sheet's, which writes every row as wide as its widest, so the row may end in empty cells,
345    /// and whose cells `pasted` (0-based) hold another table's values.
346    Padded { pasted: &'a [usize] },
347}
348
349/// The rows of an export under a stated header, the cells `pasted` (0-based) another table's
350/// ([`read_rows`], [`read_rows_around`]).
351fn rows_under(header: &str, rows: &str, pasted: &[usize]) -> Result<FlightLog, LogError> {
352    let mut notes = Notes::default();
353    let mut clocks = header_clocks(header, 0, &mut notes).map_err(|error| LogError::Mapping {
354        message: format!("the header stated for a Raven FIP export's rows: {error}"),
355    })?;
356    let rows = rows.strip_prefix('\u{feff}').unwrap_or(rows);
357    let mut lines = numbered_lines(rows)
358        .filter(|(_, line)| !line.trim().is_empty())
359        .peekable();
360    if let Some((number, line)) = lines.peek()
361        && line
362            .split(',')
363            .next()
364            .is_some_and(|first| is_clock(first.trim()))
365    {
366        return Err(syntax(
367            *number,
368            format!(
369                "the rows open with a header line, {:?}: the export has its own, and is read \
370                 whole",
371                short(line)
372            ),
373        ));
374    }
375    // The rows in which a pasted column covers each clock's sample.
376    let mut covered = vec![0usize; clocks.len()];
377    for (number, line) in lines {
378        let row = read_row(&mut clocks, line, number, RowEnd::Padded { pasted })?;
379        for (rows, hidden) in covered.iter_mut().zip(row) {
380            *rows += usize::from(hidden);
381        }
382    }
383    notes.push(
384        "read under a header line the caller stated, the rows' own header missing".to_owned(),
385    );
386    let mut kept = Vec::with_capacity(clocks.len());
387    for (clock, rows) in clocks.into_iter().zip(covered) {
388        if rows == 0 {
389            kept.push(clock);
390            continue;
391        }
392        let names: Vec<String> = clock
393            .columns
394            .iter()
395            .map(|column| format!("{:?}", short(&column.name)))
396            .collect();
397        notes.push(format!(
398            "{} left out: the pasted columns cover its cells in {rows} rows",
399            names.join(", ")
400        ));
401    }
402    // Line 0 is the stated header: what `build` finds wrong with it is the caller's to fix.
403    build(kept, 0, notes).map_err(|error| match error {
404        LogError::Syntax {
405            line: 0, message, ..
406        } => LogError::Mapping {
407            message: format!("the header stated for a Raven FIP export's rows: {message}"),
408        },
409        other => other,
410    })
411}
412
413/// The file's lines, numbered from 1, ended by CR, LF or CR LF.
414fn numbered_lines(text: &str) -> impl Iterator<Item = (usize, &str)> {
415    let mut rest = Some(text);
416    let mut number = 0;
417    std::iter::from_fn(move || {
418        let current = rest?;
419        number += 1;
420        match current.find(['\r', '\n']) {
421            Some(end) => {
422                let skip = if current[end..].starts_with("\r\n") {
423                    2
424                } else {
425                    1
426                };
427                rest = Some(&current[end + skip..]);
428                Some((number, &current[..end]))
429            }
430            None => {
431                rest = None;
432                (!current.is_empty()).then_some((number, current))
433            }
434        }
435    })
436}
437
438/// The clocks the header lays out, each with its columns.
439fn header_clocks(header: &str, line: usize, notes: &mut Notes) -> Result<Vec<Clock>, LogError> {
440    let names: Vec<&str> = header.split(',').map(str::trim).collect();
441    let is_raven = names.first().is_some_and(|first| is_clock(first))
442        && names.iter().any(|name| known(name).is_some());
443    if !is_raven {
444        return Err(LogError::NotThisFormat {
445            format: FORMAT,
446            message: format!(
447                "its first line, {:?}, isn't a FIP export's header, a clock such as \
448                 `Time@Axial Accel (Gs)` and the Raven's channels",
449                short(header)
450            ),
451        });
452    }
453    let mut clocks: Vec<Clock> = Vec::new();
454    for (index, name) in names.iter().enumerate() {
455        let column_number = index + 1;
456        if name.is_empty() {
457            return Err(syntax(
458                line,
459                format!("the header's column {column_number} has no name"),
460            ));
461        }
462        if is_clock(name) {
463            if let Some(last) = clocks.last()
464                && last.columns.is_empty()
465            {
466                return Err(syntax(
467                    line,
468                    format!("the clock {:?} has no channel", short(&last.name)),
469                ));
470            }
471            clocks.push(Clock {
472                name: (*name).to_owned(),
473                time_s: Vec::new(),
474                columns: Vec::new(),
475                repeats: 0,
476                differing_repeats: 0,
477            });
478            continue;
479        }
480        // Invariant: the first name is a clock's, checked above, so a clock is open here.
481        let Some(clock) = clocks.last_mut() else {
482            continue;
483        };
484        if name.eq_ignore_ascii_case(STATUS) {
485            match clock.columns.last_mut() {
486                Some(column) if column.status.is_none() => column.status = Some(Vec::new()),
487                _ => {
488                    return Err(syntax(
489                        line,
490                        format!("the status column {column_number} follows no channel of its own"),
491                    ));
492                }
493            }
494            continue;
495        }
496        let (quantity, scale) = known(name).unwrap_or_else(|| {
497            notes.push(format!(
498                "the column {:?} isn't one this reader knows, and was kept as written",
499                short(name)
500            ));
501            (Quantity::Unrecognized, Scale::By(1.0))
502        });
503        clock.columns.push(Column {
504            name: (*name).to_owned(),
505            quantity,
506            scale,
507            values: Vec::new(),
508            status: None,
509            empty: 0,
510            not_numbers: 0,
511            not_number_example: String::new(),
512        });
513    }
514    if let Some(last) = clocks.last()
515        && last.columns.is_empty()
516    {
517        return Err(syntax(
518            line,
519            format!("the clock {:?} has no channel", short(&last.name)),
520        ));
521    }
522    Ok(clocks)
523}
524
525/// Reads one row into the clocks: each clock either has a sample in it, its time, values and
526/// statuses, or two or more empty cells, its time's and its values', without its status cells.
527/// `end` says what the row is read from. Returns, by clock, whether a pasted cell covers its sample
528/// in this row, a sample then not read.
529fn read_row(
530    clocks: &mut [Clock],
531    line: &str,
532    number: usize,
533    end: RowEnd,
534) -> Result<Vec<bool>, LogError> {
535    let pasted: &[usize] = match end {
536        RowEnd::Exact => &[],
537        RowEnd::Padded { pasted } => pasted,
538    };
539    let cells: Vec<&str> = line.split(',').map(str::trim).collect();
540    let mut covered = vec![false; clocks.len()];
541    let mut at = 0;
542    for (clock, covered) in clocks.iter_mut().zip(&mut covered) {
543        let empty_width = clock.empty_width();
544        let Some(head) = cells.get(at..at + empty_width) else {
545            return Err(syntax(
546                number,
547                format!(
548                    "the row ends at cell {} before the clock {:?}'s cells",
549                    cells.len(),
550                    short(&clock.name)
551                ),
552            ));
553        };
554        let known = |k: &usize| !pasted.contains(&(at + k));
555        let filled = (0..empty_width).filter(known).any(|k| !head[k].is_empty());
556        let hidden = (0..empty_width).any(|k| !known(&k));
557        let width = clock.sample_width();
558        let sampled = if filled || !hidden {
559            filled
560        } else {
561            // The pasted cells hide the time and value: for a clock of one channel with a status,
562            // the cell after them tells, the sample's status or the next clock's time. Empty, it
563            // could be either: a status left empty, or a stopped clock's time. A clock of more
564            // channels has a value there, not a status.
565            let one_status = clock.columns.len() == 1 && width > empty_width;
566            let after = (one_status && !pasted.contains(&(at + empty_width)))
567                .then(|| cells.get(at + empty_width).copied());
568            match after {
569                Some(Some(cell)) if !cell.is_empty() => status_cell(cell).is_some(),
570                // The row ends there: no room for a sample.
571                Some(None) => false,
572                _ => {
573                    return Err(syntax(
574                        number,
575                        format!(
576                            "the pasted columns hide whether the clock {:?} has a sample in the row",
577                            short(&clock.name)
578                        ),
579                    ));
580                }
581            }
582        };
583        if !sampled {
584            at += empty_width;
585            continue;
586        }
587        let Some(sample) = cells.get(at..at + width) else {
588            return Err(syntax(
589                number,
590                format!(
591                    "the row ends at cell {} inside the clock {:?}'s sample",
592                    cells.len(),
593                    short(&clock.name)
594                ),
595            ));
596        };
597        if (at..at + width).any(|k| pasted.contains(&k)) {
598            *covered = true;
599        } else {
600            read_sample(clock, sample, number, at)?;
601        }
602        at += width;
603    }
604    // A sheet's padding past the last channel holds nothing but the pasted cells; anything else
605    // there is a cell no channel takes.
606    let rest_filled = cells
607        .iter()
608        .enumerate()
609        .skip(at)
610        .any(|(k, cell)| !cell.is_empty() && !pasted.contains(&k));
611    let fits = match end {
612        RowEnd::Exact => at == cells.len(),
613        RowEnd::Padded { .. } => !rest_filled,
614    };
615    if !fits {
616        return Err(syntax(
617            number,
618            format!(
619                "the row has {} cells and its channels' samples take {at}",
620                cells.len()
621            ),
622        ));
623    }
624    Ok(covered)
625}
626
627/// Reads one clock's sample, its cells starting at the row's cell `first` (0-based).
628fn read_sample(
629    clock: &mut Clock,
630    sample: &[&str],
631    number: usize,
632    first: usize,
633) -> Result<(), LogError> {
634    let time = sample[0];
635    let time_s = time
636        .parse::<f64>()
637        .ok()
638        .filter(|value| value.is_finite())
639        .ok_or_else(|| {
640            syntax(
641                number,
642                format!(
643                    "the time {:?} in cell {} isn't a finite number",
644                    short(time),
645                    first + 1
646                ),
647            )
648        })?;
649    // Each column's value, and its status where it has one, as they stand in the row.
650    let mut parsed: Vec<(f64, Option<f64>)> = Vec::with_capacity(clock.columns.len());
651    let mut at = 1;
652    for column in &mut clock.columns {
653        let cell = sample[at];
654        let value = value_cell(column, cell).ok_or_else(|| {
655            syntax(
656                number,
657                format!(
658                    "{:?} in cell {}, under {:?}, isn't a number",
659                    short(cell),
660                    first + at + 1,
661                    short(&column.name)
662                ),
663            )
664        })?;
665        // A finite cell that its unit's conversion makes infinite, such as `1.7e308` g or °F, is
666        // refused on its line (ADR-258 §3).
667        let value = finite(value, FORMAT, number, &column.name)?;
668        at += 1;
669        let status = if column.status.is_some() {
670            let cell = sample[at];
671            let status = status_cell(cell).ok_or_else(|| {
672                syntax(
673                    number,
674                    format!(
675                        "the status {:?} in cell {} isn't `b` and binary digits",
676                        short(cell),
677                        first + at + 1
678                    ),
679                )
680            })?;
681            at += 1;
682            Some(status)
683        } else {
684            None
685        };
686        parsed.push((value, status));
687    }
688    if let Some(&last) = clock.time_s.last() {
689        if time_s < last {
690            return Err(syntax(
691                number,
692                format!(
693                    "the time {time_s} s on the clock {:?} comes before the one above it, {last} s",
694                    short(&clock.name)
695                ),
696            ));
697        }
698        if time_s == last {
699            clock.repeats += 1;
700            let same = clock
701                .columns
702                .iter()
703                .zip(&parsed)
704                .all(|(column, (value, status))| {
705                    same_bits(column.values.last(), Some(value))
706                        && same_bits(
707                            column.status.as_ref().and_then(|statuses| statuses.last()),
708                            status.as_ref(),
709                        )
710                });
711            if !same {
712                clock.differing_repeats += 1;
713            }
714            return Ok(());
715        }
716    }
717    clock.time_s.push(time_s);
718    for (column, (value, status)) in clock.columns.iter_mut().zip(parsed) {
719        column.values.push(value);
720        if let (Some(statuses), Some(status)) = (column.status.as_mut(), status) {
721            statuses.push(status);
722        }
723    }
724    Ok(())
725}
726
727/// Whether two optional values are the same number, `NaN` matching `NaN`.
728fn same_bits(a: Option<&f64>, b: Option<&f64>) -> bool {
729    match (a, b) {
730        (Some(a), Some(b)) => a.to_bits() == b.to_bits(),
731        (None, None) => true,
732        _ => false,
733    }
734}
735
736/// A value cell in SI; `NaN`, counted, for an empty cell or one that isn't a number in the way
737/// Windows writes them; `None` for anything else that isn't a number.
738fn value_cell(column: &mut Column, cell: &str) -> Option<f64> {
739    if cell.is_empty() {
740        column.empty += 1;
741        return Some(f64::NAN);
742    }
743    match cell.parse::<f64>() {
744        Ok(value) if value.is_finite() => Some(si(column.scale, value)),
745        Ok(_) => Some(not_a_number(column, cell)),
746        Err(_) if is_windows_non_number(cell) => Some(not_a_number(column, cell)),
747        Err(_) => None,
748    }
749}
750
751/// Counts a cell that isn't a number and returns the gap it leaves.
752fn not_a_number(column: &mut Column, cell: &str) -> f64 {
753    if column.not_numbers == 0 {
754        column.not_number_example = short(cell);
755    }
756    column.not_numbers += 1;
757    f64::NAN
758}
759
760/// Whether a cell is how Microsoft's C runtime writes a value that isn't a finite number:
761/// `1.#QNAN`, `1.#SNAN`, `1.#IND` or `1.#INF`, perhaps signed and followed by digits.
762fn is_windows_non_number(cell: &str) -> bool {
763    let unsigned = cell.trim_start_matches(['-', '+']);
764    let Some(rest) = unsigned.strip_prefix("1.#") else {
765        return false;
766    };
767    let word = rest.trim_end_matches(|c: char| c.is_ascii_digit());
768    ["QNAN", "SNAN", "IND", "INF"]
769        .iter()
770        .any(|known| word.eq_ignore_ascii_case(known))
771}
772
773/// A status cell's value: `b` and binary digits, the leftmost the most significant, so `b0101`
774/// is 5; `NaN` for an empty cell; `None` for anything else, or more digits than an `f64` holds
775/// exactly.
776fn status_cell(cell: &str) -> Option<f64> {
777    if cell.is_empty() {
778        return Some(f64::NAN);
779    }
780    let digits = cell.strip_prefix(['b', 'B'])?;
781    if digits.is_empty() || digits.len() > 52 || !digits.bytes().all(|b| b == b'0' || b == b'1') {
782        return None;
783    }
784    // At most 52 binary digits, so the value is below 2⁵² and exact as an f64.
785    u64::from_str_radix(digits, 2).ok().map(|bits| bits as f64)
786}
787
788/// A value in SI.
789fn si(scale: Scale, value: f64) -> f64 {
790    match scale {
791        Scale::By(factor) => value * factor,
792        Scale::Fahrenheit => (value - 32.0) * 5.0 / 9.0 + 273.15,
793    }
794}
795
796/// The record from the clocks read: every channel, the primary track, and the notes.
797fn build(clocks: Vec<Clock>, header_line: usize, mut notes: Notes) -> Result<FlightLog, LogError> {
798    let mut log = FlightLog {
799        format: LogFormat::RavenFipCsv,
800        logger: "Featherweight Raven".to_owned(),
801        serial_number: None,
802        firmware: None,
803        flight_number: None,
804        stated: Stated::default(),
805        time_s: Vec::new(),
806        altitude_m: Vec::new(),
807        vertical_speed_m_s: None,
808        temperature_k: None,
809        battery_v: None,
810        channels: Vec::new(),
811        events: Vec::new(),
812        notes: Vec::new(),
813    };
814    for clock in clocks {
815        if clock.repeats > 0 {
816            notes.push(format!(
817                "the clock {:?} repeats the time before it {} times; the repeats were dropped, \
818                 {} of them differing from the sample they repeat",
819                short(&clock.name),
820                clock.repeats,
821                clock.differing_repeats
822            ));
823        }
824        for column in clock.columns {
825            if column.not_numbers > 0 {
826                notes.push(format!(
827                    "the column {:?} holds {} cells that aren't a number, such as {:?}: they are \
828                     gaps",
829                    short(&column.name),
830                    column.not_numbers,
831                    column.not_number_example
832                ));
833            }
834            if column.empty > 0 {
835                notes.push(format!(
836                    "the column {:?} leaves {} samples' values empty: they are gaps",
837                    short(&column.name),
838                    column.empty
839                ));
840            }
841            log.channels.push(Channel {
842                column: column.name,
843                quantity: column.quantity,
844                time_s: clock.time_s.clone(),
845                values: column.values,
846            });
847            if let Some(status) = column.status {
848                log.channels.push(Channel {
849                    column: "bILBA".to_owned(),
850                    quantity: Quantity::Number,
851                    time_s: clock.time_s.clone(),
852                    values: status,
853                });
854            }
855        }
856    }
857
858    let primary = log
859        .channels
860        .iter()
861        .find(|channel| key(&channel.column) == BARO_AGL)
862        .or_else(|| {
863            let bare = log
864                .channels
865                .iter()
866                .find(|channel| key(&channel.column) == BARE_AGL);
867            if let Some(channel) = bare {
868                log.notes.push(format!(
869                    "the file has no `[Altitude (Baro-Ft-AGL)]`; its {:?}, which names no sensor, \
870                     was taken as the altitude above the pad",
871                    channel.column
872                ));
873            }
874            bare
875        });
876    let Some(primary) = primary else {
877        return Err(syntax(
878            header_line,
879            "the file has no altitude above the pad, `[Altitude (Baro-Ft-AGL)]` or `Altitude \
880             (Ft-AGL)`"
881                .to_owned(),
882        ));
883    };
884    if primary.time_s.is_empty() {
885        return Err(LogError::NoData { format: FORMAT });
886    }
887    log.time_s.clone_from(&primary.time_s);
888    log.altitude_m.clone_from(&primary.values);
889    // The temperature and battery voltage fill the primary track only on the altitude's clock.
890    let on_primary_clock = |channel: &&Channel| channel.time_s == log.time_s;
891    let temperature = log
892        .channels_of(Quantity::Temperature)
893        .find(on_primary_clock)
894        .map(|channel| channel.values.clone());
895    let battery = log
896        .channels_of(Quantity::Voltage)
897        .filter(|channel| key(&channel.column).contains("battery"))
898        .find(on_primary_clock)
899        .map(|channel| channel.values.clone());
900    log.temperature_k = temperature;
901    log.battery_v = battery;
902
903    log.notes.extend(notes.kept);
904    if notes.left_out > 0 {
905        log.notes.push(format!(
906            "and {} more notes, left out so that a broken file's list stays short",
907            notes.left_out
908        ));
909    }
910    Ok(log)
911}
912
913/// The most notes a log keeps; past it, one more note counts the rest.
914const MAX_NOTES: usize = 20;
915
916/// Notes as the reader meets them: the first [`MAX_NOTES`] kept, the rest only counted, so a
917/// header of many unknown columns can't fill memory with them.
918#[derive(Default)]
919struct Notes {
920    kept: Vec<String>,
921    left_out: usize,
922}
923
924impl Notes {
925    fn push(&mut self, note: String) {
926        if self.kept.len() < MAX_NOTES {
927            self.kept.push(note);
928        } else {
929            self.left_out += 1;
930        }
931    }
932}
933
934fn syntax(line: usize, message: String) -> LogError {
935    LogError::Syntax {
936        format: FORMAT,
937        line,
938        message,
939    }
940}
941
942/// Text from the file as an error or note quotes it: cut to [`QUOTED_CHARS`] characters, so a
943/// binary file's "first line" doesn't fill the message.
944fn short(text: &str) -> String {
945    if text.chars().count() <= QUOTED_CHARS {
946        text.to_owned()
947    } else {
948        let mut cut: String = text.chars().take(QUOTED_CHARS - 1).collect();
949        cut.push('…');
950        cut
951    }
952}
953
954/// The most characters of the file an error or note quotes.
955const QUOTED_CHARS: usize = 80;
956
957#[cfg(test)]
958mod tests {
959    use super::*;
960
961    const HEADER: &str = "Time@Axial Accel (Gs),Axial Accel (Gs),bILBA,\
962                          Time@Baro (Atm),Baro (Atm),bILBA,\
963                          Time@[Altitude (Baro-Ft-AGL)],[Altitude (Baro-Ft-AGL)],bILBA";
964
965    fn close(a: f64, b: f64) -> bool {
966        (a - b).abs() <= 1e-12 * b.abs().max(1.0)
967    }
968
969    /// Each channel on its own clock, in SI, the statuses read as binary numbers, the primary
970    /// track the barometric altitude's.
971    #[test]
972    fn reads_each_channel_on_its_own_clock() {
973        let text = format!(
974            "{HEADER}\r\n\
975             0,1,b0000,0.01,1,b0000,0.01,0,b0000\r\n\
976             0.0025,2,b0101,0.06,0.5,b1100,0.06,100,b1100\r\n"
977        );
978        let log = read(&text).unwrap();
979        assert_eq!(log.format, LogFormat::RavenFipCsv);
980        assert_eq!(log.logger, "Featherweight Raven");
981        let columns: Vec<&str> = log.channels.iter().map(|c| c.column.as_str()).collect();
982        assert_eq!(
983            columns,
984            [
985                "Axial Accel (Gs)",
986                "bILBA",
987                "Baro (Atm)",
988                "bILBA",
989                "[Altitude (Baro-Ft-AGL)]",
990                "bILBA"
991            ]
992        );
993        assert_eq!(log.channels[0].time_s, [0.0, 0.0025]);
994        assert_eq!(log.channels[0].values, [9.806_65, 2.0 * 9.806_65]);
995        assert_eq!(log.channels[1].values, [0.0, 5.0]);
996        assert_eq!(log.channels[2].values, [101_325.0, 50_662.5]);
997        assert_eq!(log.channels[3].values, [0.0, 12.0]);
998        assert_eq!(log.time_s, [0.01, 0.06]);
999        assert_eq!(log.altitude_m, [0.0, 30.48]);
1000        assert!(log.vertical_speed_m_s.is_none());
1001        assert!(log.events.is_empty());
1002        assert!(log.notes.is_empty(), "{:?}", log.notes);
1003    }
1004
1005    /// A channel with no sample in a row is two empty cells without its status, and the channels
1006    /// after it move one cell left; the row must end where its channels do.
1007    #[test]
1008    fn a_stopped_channel_drops_its_status_cell() {
1009        let text = format!(
1010            "{HEADER}\n\
1011             0,1,b0000,0.01,1,b0000,0.01,0,b0000\n\
1012             0.0025,1,b0000,,,0.06,10,b1000\n\
1013             0.005,1,b0000,,,,\n\
1014             ,,,,,\n"
1015        );
1016        let log = read(&text).unwrap();
1017        assert_eq!(log.channels[0].time_s, [0.0, 0.0025, 0.005]);
1018        assert_eq!(log.channels[2].time_s, [0.01]);
1019        assert_eq!(log.time_s, [0.01, 0.06]);
1020        assert!(close(log.altitude_m[1], 3.048));
1021        assert_eq!(log.channels[5].values, [0.0, 8.0]);
1022
1023        // The same row with the status cell kept is one cell too long.
1024        let text = format!("{HEADER}\n0.0025,1,b0000,,,,0.06,10,b1000\n");
1025        let error = read(&text).unwrap_err().to_string();
1026        assert!(error.contains("line 2:"), "{error}");
1027    }
1028
1029    /// Without status columns every row is as wide as the header; a stopped channel is two empty
1030    /// cells in place.
1031    #[test]
1032    fn without_status_columns_rows_keep_their_width() {
1033        let text = "Time@Axial Accel (Gs),Axial Accel (Gs),Time@Temperature (F),Temperature (F),\
1034                    Time@[Altitude (Baro-Ft-AGL)],[Altitude (Baro-Ft-AGL)]\n\
1035                    0,1,0.01,32,0.01,0\n\
1036                    0.0025,1,,,0.06,1\n";
1037        let log = read(text).unwrap();
1038        assert_eq!(log.channels.len(), 3);
1039        assert_eq!(log.channels[1].values, [273.15]);
1040        assert!(log.temperature_k.is_none(), "not on the altitude's clock");
1041        assert_eq!(log.time_s, [0.01, 0.06]);
1042    }
1043
1044    /// One clock for every channel: the temperature and battery share the altitude's clock and
1045    /// fill the primary track; a repeated row is dropped with a note.
1046    #[test]
1047    fn one_clock_layout_fills_the_track() {
1048        let text = "Time,LiftOff,Axial Accel (Gs),Temperature (F),Volts Battery (V),\
1049                    Volts Pyro Main (V),[Altitude (Baro-Ft-AGL)],[Velocity (Accel-MPH)]\n\
1050                    0,0,1,212,8.1,0.1,0,0\n\
1051                    0.001,0,1,212,8.1,0.1,0,0\n\
1052                    0.001,0,1,212,8.1,0.1,0,0\n\
1053                    0.002,1,5,212,8.0,0.1,1,10\n";
1054        let log = read(text).unwrap();
1055        assert_eq!(log.time_s, [0.0, 0.001, 0.002]);
1056        let temperature = log.temperature_k.as_deref().unwrap();
1057        assert!(close(temperature[0], 373.15));
1058        assert_eq!(log.battery_v.as_deref(), Some(&[8.1, 8.1, 8.0][..]));
1059        assert_eq!(log.channels[0].quantity, Quantity::Number);
1060        assert!(close(log.channels[6].values[2], 4.4704));
1061        assert_eq!(
1062            log.notes,
1063            [
1064                "the clock \"Time\" repeats the time before it 1 times; the repeats were dropped, 0 \
1065              of them differing from the sample they repeat"
1066            ]
1067        );
1068    }
1069
1070    /// The two-channel layout's spaced header and bare `Altitude (Ft-AGL)`, taken with a note.
1071    #[test]
1072    fn the_bare_altitude_is_taken_with_a_note() {
1073        let text = "Time-Axial Accel (Gs), Axial Accel (Gs), bILBA, Time (s), Altitude (Ft-AGL), \
1074                    bILBA\n0, 1, b0000, 0, 10, b1000\n";
1075        let log = read(text).unwrap();
1076        assert_eq!(log.altitude_m, [3.048]);
1077        assert!(log.notes[0].contains("names no sensor"), "{:?}", log.notes);
1078    }
1079
1080    /// Windows' `-1.#QNAN` and an empty value are gaps, counted; other junk is refused.
1081    #[test]
1082    fn windows_non_numbers_are_gaps() {
1083        let text = format!(
1084            "{HEADER}\n0,-1.#QNAN,b0000,0.01,,b0000,0.01,0,b0000\n\
1085             0.0025,1.#INF,b0000,0.06,1,b0000,0.06,0,b0000\n"
1086        );
1087        let log = read(&text).unwrap();
1088        assert!(log.channels[0].values.iter().all(|v| v.is_nan()));
1089        assert!(log.channels[2].values[0].is_nan());
1090        assert_eq!(log.notes.len(), 2, "{:?}", log.notes);
1091        assert!(log.notes[0].contains("2 cells that aren't a number, such as \"-1.#QNAN\""));
1092        assert!(log.notes[1].contains("leaves 1 samples' values empty"));
1093        assert!(is_windows_non_number("-1.#IND00"));
1094        assert!(!is_windows_non_number("1.#X"));
1095        let error = read(&format!("{HEADER}\n0,x,b0000,,,,\n")).unwrap_err();
1096        assert!(
1097            error.to_string().contains("line 2: \"x\" in cell 2"),
1098            "{error}"
1099        );
1100    }
1101
1102    /// The status digits: the leftmost the most significant; anything but `b` and binary digits
1103    /// refused.
1104    #[test]
1105    fn status_cells_are_binary_numbers() {
1106        assert_eq!(status_cell("b0101"), Some(5.0));
1107        assert_eq!(status_cell("b1000"), Some(8.0));
1108        assert_eq!(status_cell("b1111"), Some(15.0));
1109        assert!(status_cell("").unwrap().is_nan());
1110        for bad in ["0101", "b", "b012", "bx", &format!("b{}", "1".repeat(53))] {
1111            assert_eq!(status_cell(bad), None, "{bad}");
1112        }
1113    }
1114
1115    /// Each refusal names its line and what is wrong.
1116    #[test]
1117    fn malformed_files_are_refused_where_they_go_wrong() {
1118        let cases = [
1119            (String::new(), "the file is empty"),
1120            (
1121                "Time,Altitude\n0,0\n".to_owned(),
1122                "isn't a FIP export's header",
1123            ),
1124            (
1125                "Axial Accel (Gs),Time\n".to_owned(),
1126                "isn't a FIP export's header",
1127            ),
1128            (format!("{HEADER}\n"), "no data rows"),
1129            (
1130                "Time@Axial Accel (Gs),Axial Accel (Gs)\n0,1\n".to_owned(),
1131                "line 1: the file has no altitude above the pad",
1132            ),
1133            (
1134                "Time@x,Time@Axial Accel (Gs),Axial Accel (Gs)\n".to_owned(),
1135                "line 1: the clock \"Time@x\" has no channel",
1136            ),
1137            (
1138                "Time@Axial Accel (Gs),bILBA,Axial Accel (Gs)\n".to_owned(),
1139                "line 1: the status column 2 follows no channel",
1140            ),
1141            (
1142                "Time@Axial Accel (Gs),Axial Accel (Gs),,x\n".to_owned(),
1143                "line 1: the header's column 3 has no name",
1144            ),
1145            (
1146                format!("{HEADER}\n0,1,b0,0.5,1,b0,0.5,0,b0\n0,1,b0,0.4,1,b0,0.6,0,b0\n"),
1147                "line 3: the time 0.4 s on the clock \"Time@Baro (Atm)\" comes before",
1148            ),
1149            (
1150                format!("{HEADER}\nx,1,b0,,,,\n"),
1151                "line 2: the time \"x\" in cell 1",
1152            ),
1153            (
1154                format!("{HEADER}\n0,1,b0,0,1,b0,0,1,b2\n"),
1155                "line 2: the status \"b2\" in cell 9",
1156            ),
1157            (
1158                format!("{HEADER}\n0,1,b0,0,1\n"),
1159                "line 2: the row ends at cell 5",
1160            ),
1161            (
1162                format!("{HEADER}\n0,1,b0,,,0.1,1,b0,7\n"),
1163                "line 2: the row has 9 cells and its channels' samples take 8",
1164            ),
1165            (format!("{HEADER}\n0,1,b0,,,,\n"), "no data rows"),
1166        ];
1167        for (text, expected) in cases {
1168            let error = read(&text).unwrap_err().to_string();
1169            assert!(error.contains(expected), "{text:?}: {error}");
1170        }
1171    }
1172
1173    /// A value near the largest `f64` is finite as written and infinite once converted: in g to
1174    /// m/s², in atmospheres to pascals, in °F to kelvin. Each is refused on its line (ADR-258 §3).
1175    #[test]
1176    fn a_value_its_conversion_makes_infinite_is_refused() {
1177        let cases = [
1178            (
1179                format!("{HEADER}\n0,1,b0,0,1,b0,0,0,b0\n0.1,1.7e308,b0,,,,\n"),
1180                "Raven FIP CSV line 3: the column Axial Accel (Gs) holds a value too large for \
1181                 its unit's conversion to SI",
1182            ),
1183            (
1184                format!("{HEADER}\n0,1,b0,0,-1.7e308,b0,0,0,b0\n"),
1185                "Raven FIP CSV line 2: the column Baro (Atm) holds a value too large for its \
1186                 unit's conversion to SI",
1187            ),
1188            (
1189                "Time@Temperature (F),Temperature (F),\
1190                 Time@[Altitude (Baro-Ft-AGL)],[Altitude (Baro-Ft-AGL)]\n\
1191                 0,70,0,0\n0.1,1.7e308,0.1,1\n"
1192                    .to_owned(),
1193                "Raven FIP CSV line 3: the column Temperature (F) holds a value too large for \
1194                 its unit's conversion to SI",
1195            ),
1196        ];
1197        for (text, expected) in cases {
1198            assert_eq!(read(&text).unwrap_err().to_string(), expected, "{text:?}");
1199        }
1200    }
1201
1202    /// A byte-order mark is dropped; CR-only line ends read as lines; blank lines are skipped.
1203    #[test]
1204    fn marks_and_line_ends() {
1205        let text = format!("\u{feff}\r{HEADER}\r0,1,b0,0,1,b0,0,1,b0\r\r");
1206        let log = read(&text).unwrap();
1207        assert_eq!(log.altitude_m, [FOOT_M]);
1208        let lines: Vec<(usize, &str)> = numbered_lines("a\r\nb\rc\n\nd").collect();
1209        assert_eq!(lines, [(1, "a"), (2, "b"), (3, "c"), (4, ""), (5, "d")]);
1210    }
1211
1212    /// A header of many unknown columns keeps a short list of notes and counts the rest.
1213    #[test]
1214    fn notes_stay_few() {
1215        let unknown: String = (0..100).map(|i| format!(",u{i}")).collect();
1216        let text = format!("Time@[Altitude (Baro-Ft-AGL)],[Altitude (Baro-Ft-AGL)]{unknown}\n");
1217        let row = format!("0{}\n", ",1".repeat(101));
1218        let log = read(&format!("{text}{row}")).unwrap();
1219        assert_eq!(log.notes.len(), MAX_NOTES + 1);
1220        assert!(
1221            log.notes[MAX_NOTES].starts_with("and 80 more notes"),
1222            "{:?}",
1223            log.notes
1224        );
1225        assert_eq!(log.channels.len(), 101);
1226        assert_eq!(log.channels[100].quantity, Quantity::Unrecognized);
1227    }
1228
1229    /// A file that isn't text is refused with a short quote of it.
1230    #[test]
1231    fn a_long_line_is_quoted_short() {
1232        let junk = "\u{fffd}".repeat(100_000);
1233        let error = read(&junk).unwrap_err().to_string();
1234        assert!(error.len() < 400, "{} bytes", error.len());
1235    }
1236
1237    proptest::proptest! {
1238        /// Any text is read or refused, never a panic; what is read has increasing times and an
1239        /// altitude for each.
1240        #[test]
1241        fn any_text_is_read_or_refused(rows in proptest::collection::vec("[-0-9.b,x#QNA]{0,24}", 0..10)) {
1242            let text = format!("{HEADER}\n{}", rows.join("\n"));
1243            if let Ok(log) = read(&text) {
1244                proptest::prop_assert!(log.time_s.windows(2).all(|pair| pair[1] > pair[0]));
1245                proptest::prop_assert_eq!(log.time_s.len(), log.altitude_m.len());
1246                for channel in &log.channels {
1247                    proptest::prop_assert!(channel.time_s.windows(2).all(|pair| pair[1] > pair[0]));
1248                    proptest::prop_assert_eq!(channel.time_s.len(), channel.values.len());
1249                }
1250            }
1251        }
1252    }
1253
1254    /// Rows of [`HEADER`]'s export, the accelerometer stopping first: its two empty cells and no
1255    /// status, every channel after it one cell to the left.
1256    const ROWS: &str = "0,1.02,b0000,0,0.97,b0000,0,0,b0000\n\
1257                        0.05,1.01,b0000,0.05,0.97,b0000,0.05,1,b0000\n\
1258                        ,,0.1,0.96,b0000,0.1,3,b0000\n\
1259                        ,,,,0.15,6,b0000\n";
1260
1261    /// [`ROWS`] as a sheet writes them: every row as wide as the widest, 9 cells.
1262    fn padded() -> String {
1263        ROWS.lines()
1264            .map(|row| {
1265                let cells = row.split(',').count();
1266                format!("{row}{}\n", ",".repeat(9 - cells))
1267            })
1268            .collect()
1269    }
1270
1271    #[test]
1272    fn rows_a_sheet_padded_read_as_the_export_with_its_header() {
1273        let whole = read(&format!("{HEADER}\n{ROWS}")).unwrap();
1274        let rows = read_rows(HEADER, &padded()).unwrap();
1275        assert_eq!(rows.channels, whole.channels);
1276        assert_eq!(
1277            (&rows.time_s, &rows.altitude_m),
1278            (&whole.time_s, &whole.altitude_m)
1279        );
1280        assert_eq!(rows.time_s, [0.0, 0.05, 0.1, 0.15]);
1281        assert!(
1282            rows.notes
1283                .iter()
1284                .any(|note| note.contains("header line the caller stated"))
1285        );
1286        // Unpadded rows read the same.
1287        assert_eq!(read_rows(HEADER, ROWS).unwrap().channels, whole.channels);
1288    }
1289
1290    #[test]
1291    fn a_value_past_the_last_channel_is_refused_padded_or_not() {
1292        // The padding holds nothing; a value there is a cell no channel takes.
1293        let mut rows = padded();
1294        rows.push_str(",,,,0.2,7,b0000,,5\n");
1295        match read_rows(HEADER, &rows) {
1296            Err(LogError::Syntax { line, message, .. }) => {
1297                assert_eq!(line, 5);
1298                assert!(
1299                    message.contains("its channels' samples take 7"),
1300                    "{message}"
1301                );
1302            }
1303            other => panic!("expected a syntax refusal, got {other:?}"),
1304        }
1305        // A file with its header isn't a sheet: its padding is refused, as before.
1306        assert!(matches!(
1307            read(&format!("{HEADER}\n{}", padded())),
1308            Err(LogError::Syntax { line: 4, .. })
1309        ));
1310    }
1311
1312    #[test]
1313    fn rows_with_a_header_of_their_own_are_refused() {
1314        match read_rows(HEADER, &format!("{HEADER}\n{ROWS}")) {
1315            Err(LogError::Syntax { line, message, .. }) => {
1316                assert_eq!(line, 1);
1317                assert!(message.contains("open with a header line"), "{message}");
1318            }
1319            other => panic!("expected a syntax refusal, got {other:?}"),
1320        }
1321    }
1322
1323    #[test]
1324    fn a_stated_header_that_cant_read_the_rows_is_the_callers_to_fix() {
1325        for (header, says) in [
1326            ("Altitude,Speed", "isn't a FIP export's header"),
1327            (
1328                "Time@Axial Accel (Gs),Axial Accel (Gs),bILBA",
1329                "no altitude above the pad",
1330            ),
1331        ] {
1332            match read_rows(header, "0,1.02,b0000\n") {
1333                Err(LogError::Mapping { message }) => {
1334                    assert!(message.contains("the header stated"), "{message}");
1335                    assert!(message.contains(says), "{message}");
1336                }
1337                other => panic!("{header}: expected a mapping refusal, got {other:?}"),
1338            }
1339        }
1340    }
1341
1342    /// [`HEADER`] and a fourth channel, the accelerometer's velocity.
1343    fn header_with_velocity() -> String {
1344        format!("{HEADER},Time@[Velocity (Accel-Ft/Sec)],[Velocity (Accel-Ft/Sec)],bILBA")
1345    }
1346
1347    #[test]
1348    fn a_channel_pasted_over_in_any_row_is_left_out_and_the_rest_read() {
1349        // The export's rows, the first channel stopping in the third and the second in the
1350        // fourth, each row shifting left; then as a sheet holds them, 12 cells wide, with a table
1351        // pasted over its last two columns, which cover the velocity's value and status in the
1352        // first three rows and the padding in the last.
1353        let rows = [
1354            "0,1.02,b0000,0,0.97,b0000,0,0,b0000,0,0,b0000",
1355            "0.05,1.01,b0000,0.05,0.97,b0000,0.05,1,b0000,0.05,10,b0000",
1356            ",,0.1,0.96,b0000,0.1,3,b0000,0.1,20,b0000",
1357            ",,,,0.15,6,b0000,0.15,30,b0000",
1358        ];
1359        let sheet: String = rows
1360            .iter()
1361            .map(|row| {
1362                let mut cells: Vec<&str> = row.split(',').collect();
1363                cells.resize(12, "");
1364                cells[10] = "7";
1365                cells[11] = "8";
1366                format!("{}\n", cells.join(","))
1367            })
1368            .collect();
1369        let header = header_with_velocity();
1370        let log = read_rows_around(&header, &sheet, &[11, 12]).unwrap();
1371        let whole = read_rows(&header, &rows.join("\n")).unwrap();
1372        let unpasted: Vec<_> = whole
1373            .channels
1374            .iter()
1375            .filter(|c| c.column != "[Velocity (Accel-Ft/Sec)]")
1376            .collect();
1377        // Each channel's status column follows it; the velocity's went with it.
1378        assert_eq!(log.channels.len(), 6);
1379        assert!(log.channels.iter().zip(&unpasted).all(|(a, b)| a == *b));
1380        assert_eq!(
1381            (&log.time_s, &log.altitude_m),
1382            (&whole.time_s, &whole.altitude_m)
1383        );
1384        assert!(log.notes.iter().any(|note| note
1385            == "\"[Velocity (Accel-Ft/Sec)]\" left out: the pasted columns cover its cells in 3 rows"));
1386        // Nothing pasted over, the sheet's cells there are values no channel takes.
1387        assert!(matches!(
1388            read_rows(&header, &sheet),
1389            Err(LogError::Syntax { line: 1, .. })
1390        ));
1391    }
1392
1393    #[test]
1394    fn a_status_cell_tells_whether_a_pasted_over_channel_has_a_sample() {
1395        // Columns 4 and 5 pasted over: the pressure's time and value. In the first row its
1396        // status follows, so it had a sample there; in the second the altitude's time does, so
1397        // it had stopped, and the altitude is read from the cells after.
1398        let sheet = "0,1.02,b0000,7,8,b0000,0,0,b0000\n0.05,1.01,b0000,7,8,0.05,1,b0000,\n";
1399        let log = read_rows_around(HEADER, sheet, &[4, 5]).unwrap();
1400        assert_eq!(log.time_s, [0.0, 0.05]);
1401        assert_eq!(log.altitude_m, [0.0, 0.3048]);
1402        assert!(
1403            log.notes.iter().any(|note| note
1404                == "\"Baro (Atm)\" left out: the pasted columns cover its cells in 1 rows")
1405        );
1406        assert!(!log.channels.iter().any(|c| c.column == "Baro (Atm)"));
1407        // A stopped channel's own cells are both hidden, and so is the cell after them: the row
1408        // can't say whether it had a sample.
1409        let hidden = "0,1.02,b0000,7,8,b0000,0,0,b0000\n,,,7,8,6,b0000,,\n";
1410        match read_rows_around(HEADER, hidden, &[4, 5]) {
1411            Err(LogError::Syntax { line, message, .. }) => {
1412                assert_eq!(line, 2);
1413                assert!(
1414                    message.contains("hide whether the clock \"Time@Baro (Atm)\" has a sample"),
1415                    "{message}"
1416                );
1417            }
1418            other => panic!("expected a syntax refusal, got {other:?}"),
1419        }
1420        // An empty cell after the hidden ones is a sample's status left empty or the next clock
1421        // stopped too: refused, not read as either.
1422        for row in [
1423            "0.05,1.01,b0000,7,8,,,,",
1424            "0.05,1.01,b0000,7,8,,0.05,1,b0000",
1425        ] {
1426            let sheet = format!("0,1.02,b0000,7,8,b0000,0,0,b0000\n{row}\n");
1427            match read_rows_around(HEADER, &sheet, &[4, 5]) {
1428                Err(LogError::Syntax { line, message, .. }) => {
1429                    assert_eq!(line, 2, "{row}");
1430                    assert!(
1431                        message.contains("hide whether the clock \"Time@Baro (Atm)\" has a sample"),
1432                        "{row}: {message}"
1433                    );
1434                }
1435                other => panic!("{row}: expected a syntax refusal, got {other:?}"),
1436            }
1437        }
1438    }
1439
1440    /// A clock of two channels has its second value, not a status, after its time's and values'
1441    /// cells: the cell after them can't tell a sample from the next clock's time, so a row whose
1442    /// pasted columns hide such a clock's cells is refused, not read with the clock stopped.
1443    #[test]
1444    fn a_pasted_over_clock_of_two_channels_is_refused() {
1445        let header = "Time@A,Axial Accel (Gs),bILBA,Lateral Accel (Gs),bILBA,\
1446                      Time@B,[Altitude (Baro-Ft-AGL)],bILBA";
1447        let sheet = "0,1,b0000,2,b0000,0,0,b0000\n9,9,,5,,,,\n";
1448        match read_rows_around(header, sheet, &[1, 2]) {
1449            Err(LogError::Syntax { line, message, .. }) => {
1450                assert_eq!(line, 2);
1451                assert!(
1452                    message.contains("hide whether the clock \"Time@A\" has a sample"),
1453                    "{message}"
1454                );
1455            }
1456            other => panic!("expected a syntax refusal, got {other:?}"),
1457        }
1458    }
1459
1460    #[test]
1461    fn pasted_columns_are_numbered_from_1() {
1462        match read_rows_around(HEADER, ROWS, &[0]) {
1463            Err(LogError::Mapping { message }) => {
1464                assert!(message.contains("numbered from 1"), "{message}");
1465            }
1466            other => panic!("expected a mapping refusal, got {other:?}"),
1467        }
1468        // With none pasted, the rows read as `read_rows` reads them.
1469        assert_eq!(
1470            read_rows_around(HEADER, &padded(), &[]).unwrap(),
1471            read_rows(HEADER, &padded()).unwrap()
1472        );
1473    }
1474}