Skip to main content

hpr_flightdata/
fwsummary.rs

1//! Featherweight's summary files, as the Featherweight UI app exports a Blue Raven's or a GPS
2//! tracker's flight beside its data: the figures the logger worked out about the flight, one a
3//! row, and no samples.
4//!
5//! The Blue Raven "records three sets of data for each flight": "flight summary data such as
6//! maximum altitude and speed", a low-rate set and a high-rate set, and the app downloads the
7//! summary first "so that the flight performance is immediately available for review"
8//! (Featherweight, *Blue Raven User's Guide*, updated May 12 2026, p18). The app exports the
9//! summary as a file of its own, and a GPS tracker's flight gets one too. Each row is a figure's
10//! name, then its value, the unit written after the number:
11//!
12//! ```text
13//! Rocket Name,Club demo
14//! Max Altitude,2500.25 feet
15//! Max velocity,500.50 feet/sec
16//! Thrust tilt efficiency,98.50%
17//! Direction of 1st motion,-1.0000,0.0000,0.0000
18//! ```
19//!
20//! A file is a summary when its first line that isn't blank names `Rocket Name`, and a line among
21//! its first 200 names `Max Altitude` or `Launch time UTC`, figures only a summary states. A
22//! name is matched without regard to case or repeated spaces, and kept as written. A tracker's
23//! summary is told from a Blue Raven's by its `Launch time UTC`.
24//!
25//! **Figures.** Every row becomes a [`Figure`] in [`Stated::figures`], in the file's order: its
26//! name and value as written, and the value in SI where the reader knows the figure. The unit is
27//! the one the file writes after the number, read only when it is one the figure's name allows,
28//! as a header's unit is read for a column. Every length takes `feet` or `ft`, every speed
29//! `feet/sec` or `ft/sec`; the table gives the words the sample files write:
30//!
31//! | Figures | Quantity | Unit as written |
32//! |---|---|---|
33//! | `Max Altitude`, `Main chute deploy altitude` | [`Quantity::AltitudeAboveGround`] | `feet`, × 0.3048 m |
34//! | `Inertial navigation max alt` | [`Quantity::InertialAltitude`] | `feet` |
35//! | `Pad altitude ASL` (a Blue Raven's), `Pad altitude` (a tracker's) | [`Quantity::AltitudeMsl`], [`Quantity::GnssAltitude`] | `feet`, `ft` |
36//! | `Distance at launch`, `… at apogee`, `… at landing` | [`Quantity::Distance`] | `ft` |
37//! | `Max velocity`, `Drogue descent rate`, a tracker's `Max vertical velocity` and the other velocities | [`Quantity::Speed`] | `feet/sec`, `ft/sec`, × 0.3048 m/s |
38//! | `Max motor burn acceleration`, `Peak drag deceleration`, `Apo channel max accel` and the other outputs', `Max landing accel` | [`Quantity::Acceleration`] | `Gs`, × 9.806 65 m/s² (standard gravity) |
39//! | `Temperature on pad`, `Max Temperature`, `Min Temperature` | [`Quantity::Temperature`] | `F`, degrees Fahrenheit |
40//! | `Battery voltage on pad`, `Min Battery voltage`, `Battery voltage at landing` | [`Quantity::Voltage`] | `V` |
41//! | `Time to first burnout`, `Time to Apo channel fire` and the other outputs', `Time to gyro overload` | [`Quantity::Duration`] | `sec` |
42//! | `Launch rod angle`, `Tilt angle at burnout` | [`Quantity::Angle`] | `deg` |
43//! | `Roll rate at burnout` | [`Quantity::AngularRate`] | `deg/sec` |
44//! | `Pad gyro rates (deg/sec)` | [`Quantity::AngularRate`], one value an axis | its name's `deg/sec` |
45//! | `Pad Latitude`, `Pad Longtitude` (sic) | [`Quantity::Latitude`], [`Quantity::Longitude`] | `deg` |
46//! | `Thrust tilt efficiency` | [`Quantity::Number`], a fraction | `%`, ÷ 100 |
47//! | `Flight number`, `Number of ascent rolls` | [`Quantity::Number`] | none |
48//! | `Direction of 1st motion`, `Gravity direction on pad` | [`Quantity::Number`], one value an axis | none: a direction of unit length |
49//! | `Pad Low-G Accel`, `Pad Hi-G accel`, `Low-G accel pad offset`, `Hi-G accel pad offset` | [`Quantity::Unrecognized`], as written, one value an axis | none written (below) |
50//! | `Rocket Name`, `Firmware`, `Serial number`, `Launch date`, `Launch time`, `Landing Time`, `Build date`, `Build time`, `Launch time UTC`, `Launch time local time zone` | text, `None` | |
51//!
52//! The manual's description of the same summary as the logger's USB port prints it (p31–33)
53//! names its fields' units, and their words agree with the app's (the USB form scales some, such
54//! as accelerations in g × 10, which isn't compared): the maximum altitude and the
55//! pad's altitude in feet, the horizontal velocity at apogee, the drogue's velocity and the
56//! maximum velocity in feet a second, the motor's, drag's, deployments' and landing's
57//! accelerations in g, the tilt at burnout in degrees and the tilt efficiency in percent. Two
58//! figures the app writes are kept as written instead:
59//!
60//! - *`Main chute descent rate`*, whose value the app writes in `feet`, a length, where the
61//!   manual gives the USB summary's average descent under the main in "feet/second x 10". A
62//!   figure whose unit isn't one its name allows is kept as written, [`Quantity::Unrecognized`],
63//!   with a note, and isn't guessed into a speed.
64//! - *The four pad accelerations and offsets*, each three numbers with no unit. The manual gives the
65//!   USB summary's in "units of Gs x 10,000"; the app's are not scaled so, and no source states
66//!   what they are in.
67//!
68//! A name the reader doesn't know is kept as written too: as numbers, [`Quantity::Unrecognized`],
69//! if every cell is one, else as text. Each figure kept as written has a note, such as
70//! `` `Main chute descent rate` kept as written, in a unit that isn't a speed: the file writes
71//! `-18.0 feet` ``; for a name the reader doesn't know, `a figure HPR Sim doesn't know kept as
72//! written: …`, the name after the colon, as the survey's public report counts each note by the
73//! words before it. A temperature below absolute zero, and a latitude or longitude past its
74//! range, is kept as written too.
75//!
76//! **What the summary states.** The record's [`Stated::apogee_m`] is `Max Altitude` in SI: the
77//! barometer's altitude above the pad for a Blue Raven, and for a tracker its receiver's altitude
78//! above the `Pad altitude` it states. [`Stated::ground_elevation_msl_m`] is `Pad altitude ASL`,
79//! a Blue Raven's barometric altitude of the pad ("based on the barometric pressure", p33), or a
80//! tracker's `Pad altitude`, its receiver's. The serial number and firmware are the rows' text as
81//! written, and the flight number `Flight number` where it is a whole number. HPR Sim's
82//! cross-check of these against the file beside each summary is in `cargo xtask logs`' report.
83//!
84//! **No samples.** The record's clock, altitude track and channels are empty, as a GPS log's
85//! barometric track is, with a note saying so: the samples are in the file exported beside it,
86//! the Blue Raven's low-rate CSV ([`crate::blueraven`]) or the tracker's CSV ([`crate::fwgps`]).
87//!
88//! **Cells and rows.** Cells are separated by commas and trimmed of spaces; empty cells at a
89//! row's end are dropped, as some files pad every row to four cells. Blank lines are skipped;
90//! lines may end in CR, LF or both; a byte-order mark is dropped. A row whose name is empty or a
91//! number is refused, as is a name stated twice and a value too large for its unit's conversion.
92//! A row of nothing but commas, padding, is skipped as a blank line is. A figure's value as
93//! written is the row's text after the name, padding dropped from its end.
94//! A known figure whose cells aren't the numbers it needs, such as a direction with two
95//! components, is kept as written, with a note.
96//!
97//! **Where this comes from.** The layout, from the files themselves and the manual as cited;
98//! the summary's names, and the `Main chute descent rate` kept out of the speeds, agree with
99//! Debrief's reader (`lib/parsers/deviceSummary.ts`, MIT, the project owner's own; see
100//! `THIRD-PARTY-NOTICES.md`). Where this reader departs from Debrief's: it keeps every row, where
101//! Debrief keeps the few it compares; it keeps a stated zero, where Debrief drops it as "no
102//! measurement": the file's zero is what it says, and what a zero means is a reading, milestone
103//! [M7.2]'s; it keeps each sign as written, where Debrief takes the descent rates' and the
104//! deployments' magnitudes; it reads only the unit words the sample files write, where Debrief
105//! resolves any unit it knows, as the app "can be set to metric", so a metric summary's figures
106//! are kept as written here, with notes, until a sample of one is seen; and it recognizes a
107//! summary by its `Rocket Name` first and a figure only a summary states, where Debrief also
108//! counts its rows of names and values.
109//!
110//! [M7.2]: https://hpr.fusionspace.co/decisions-and-roadmap.html#m7-2
111
112use std::collections::HashMap;
113
114use hpr_core::gravity::STANDARD_GRAVITY_MPS2;
115
116use crate::error::LogError;
117use crate::log::{Figure, FlightLog, LogFormat, Quantity, Stated};
118use crate::perfectflite::FOOT_M;
119use crate::table::{Notes, finite, number, numbered_lines, short};
120
121/// The format's name in errors.
122const FORMAT: &str = "Featherweight summary CSV";
123
124/// How many lines that aren't blank, from the top, [`recognizes`] looks through for a figure only
125/// a summary states: the files hold 14 to 48 rows.
126const RECOGNITION_LINES: usize = 200;
127
128/// How a unit as written converts to SI.
129#[derive(Debug, Clone, Copy)]
130enum Conversion {
131    /// Multiply by this.
132    Scale(f64),
133    /// Degrees Fahrenheit to kelvins.
134    Fahrenheit,
135}
136
137impl Conversion {
138    fn apply(self, value: f64) -> f64 {
139        match self {
140            Self::Scale(scale) => value * scale,
141            Self::Fahrenheit => (value - 32.0) * 5.0 / 9.0 + 273.15,
142        }
143    }
144}
145
146/// The unit words a figure of a quantity may carry, each with its conversion. A word is matched
147/// as written, case and all: the files write these and no others.
148const LENGTH: &[(&str, Conversion)] = &[
149    ("feet", Conversion::Scale(FOOT_M)),
150    ("ft", Conversion::Scale(FOOT_M)),
151];
152const SPEED: &[(&str, Conversion)] = &[
153    ("feet/sec", Conversion::Scale(FOOT_M)),
154    ("ft/sec", Conversion::Scale(FOOT_M)),
155];
156const ACCELERATION: &[(&str, Conversion)] = &[("Gs", Conversion::Scale(STANDARD_GRAVITY_MPS2))];
157const TEMPERATURE: &[(&str, Conversion)] = &[("F", Conversion::Fahrenheit)];
158const VOLTAGE: &[(&str, Conversion)] = &[("V", Conversion::Scale(1.0))];
159const DURATION: &[(&str, Conversion)] = &[("sec", Conversion::Scale(1.0))];
160const DEGREES: &[(&str, Conversion)] = &[("deg", Conversion::Scale(1.0))];
161const DEGREES_PER_SECOND: &[(&str, Conversion)] = &[("deg/sec", Conversion::Scale(1.0))];
162const PERCENT: &[(&str, Conversion)] = &[("%", Conversion::Scale(0.01))];
163
164/// What a figure's name says it is.
165#[derive(Debug, Clone, Copy)]
166enum Kind {
167    /// Text, such as a date or a name.
168    Text,
169    /// One number, its unit one of `units` written after it.
170    Measured {
171        quantity: Quantity,
172        what: &'static str,
173        units: &'static [(&'static str, Conversion)],
174    },
175    /// `components` numbers with no unit written, in `quantity`'s unit as they are.
176    Bare {
177        quantity: Quantity,
178        components: usize,
179    },
180    /// Three numbers no source gives a unit for, kept as written.
181    Unstated,
182}
183
184/// A figure's name as the reader matches it: lowercase, its spaces run together.
185fn key(name: &str) -> String {
186    name.split_whitespace()
187        .collect::<Vec<_>>()
188        .join(" ")
189        .to_lowercase()
190}
191
192/// What the figure of a name (as [`key`] gives it) is; `None` for a name the reader doesn't know.
193fn kind(key: &str) -> Option<Kind> {
194    use Quantity as Q;
195    let measured = |quantity, what, units| Kind::Measured {
196        quantity,
197        what,
198        units,
199    };
200    let length = |quantity| measured(quantity, "length", LENGTH);
201    Some(match key {
202        "rocket name"
203        | "firmware"
204        | "serial number"
205        | "searial number"
206        | "launch date"
207        | "launch time"
208        | "landing time"
209        | "build date"
210        | "build time"
211        | "launch time utc"
212        | "launch time local time zone" => Kind::Text,
213        "max altitude" | "main chute deploy altitude" => length(Q::AltitudeAboveGround),
214        "inertial navigation max alt" => length(Q::InertialAltitude),
215        "pad altitude asl" => length(Q::AltitudeMsl),
216        "pad altitude" => length(Q::GnssAltitude),
217        "distance at launch" | "distance at apogee" | "distance at landing" => length(Q::Distance),
218        "max velocity"
219        | "max vertical velocity"
220        | "max horizontal velocity"
221        | "horiz. velocity at apogee"
222        | "horizontal velocity at apogee"
223        | "horizontal velocity at laniding"
224        | "horizontal velocity at landing"
225        | "vertical velocity at landing"
226        | "drogue descent rate"
227        | "main chute descent rate" => measured(Q::Speed, "speed", SPEED),
228        "max motor burn acceleration"
229        | "peak drag deceleration"
230        | "apo channel max accel"
231        | "main channel max accel"
232        | "3rd channel max accel"
233        | "4th channel max accel"
234        | "max landing accel" => measured(Q::Acceleration, "acceleration", ACCELERATION),
235        "temperature on pad" | "max temperature" | "min temperature" => {
236            measured(Q::Temperature, "temperature", TEMPERATURE)
237        }
238        "battery voltage on pad" | "min battery voltage" | "battery voltage at landing" => {
239            measured(Q::Voltage, "voltage", VOLTAGE)
240        }
241        "time to first burnout"
242        | "time to apo channel fire"
243        | "time to main channel fire"
244        | "time to third channel fire"
245        | "time to fourth channel fire"
246        | "time to gyro overload"
247        | "time to gyro over-range" => measured(Q::Duration, "length of time", DURATION),
248        "launch rod angle" | "tilt angle at burnout" => measured(Q::Angle, "angle", DEGREES),
249        "roll rate at burnout" => measured(Q::AngularRate, "rate of turn", DEGREES_PER_SECOND),
250        "pad latitude" => measured(Q::Latitude, "latitude", DEGREES),
251        "pad longtitude" | "pad longitude" => measured(Q::Longitude, "longitude", DEGREES),
252        "thrust tilt efficiency" => measured(Q::Number, "percentage", PERCENT),
253        "flight number" | "number of ascent rolls" => Kind::Bare {
254            quantity: Q::Number,
255            components: 1,
256        },
257        "direction of 1st motion" | "gravity direction on pad" => Kind::Bare {
258            quantity: Q::Number,
259            components: 3,
260        },
261        "pad gyro rates (deg/sec)" => Kind::Bare {
262            quantity: Q::AngularRate,
263            components: 3,
264        },
265        "pad low-g accel"
266        | "pad hi-g accel"
267        | "low-g accel pad offset"
268        | "hi-g accel pad offset" => Kind::Unstated,
269        _ => return None,
270    })
271}
272
273/// A row's first cell, trimmed.
274fn first_cell(line: &str) -> &str {
275    line.split(',').next().unwrap_or("").trim()
276}
277
278/// Whether `text` is a Featherweight summary: a first line that isn't blank naming `Rocket
279/// Name`, and `Max Altitude` or `Launch time UTC` named within the first [`RECOGNITION_LINES`].
280pub(crate) fn recognizes(text: &str) -> bool {
281    let mut names = numbered_lines(text)
282        .map(|(_, line)| line.trim())
283        .filter(|line| !line.is_empty())
284        .take(RECOGNITION_LINES)
285        .map(|line| key(first_cell(line)));
286    names.next().is_some_and(|name| name == "rocket name")
287        && names.any(|name| name == "max altitude" || name == "launch time utc")
288}
289
290/// A cell as a number and the unit written after it, such as `2500.25 feet` as 2500.25 and
291/// `feet`; `None` if it doesn't open with a finite number.
292fn measured_cell(cell: &str) -> Option<(f64, &str)> {
293    let bytes = cell.as_bytes();
294    let mut end = 0;
295    while let Some(&byte) = bytes.get(end) {
296        // An exponent's `e` belongs to the number only before a digit or a sign: `feet` doesn't.
297        let exponent = matches!(byte, b'e' | b'E')
298            && bytes
299                .get(end + 1)
300                .is_some_and(|next| next.is_ascii_digit() || matches!(next, b'-' | b'+'));
301        if !(byte.is_ascii_digit() || matches!(byte, b'-' | b'+' | b'.') || exponent) {
302            break;
303        }
304        end += 1;
305    }
306    let value = number(&cell[..end], false)?;
307    Some((value, cell[end..].trim()))
308}
309
310/// Reads a Featherweight summary.
311///
312/// # Errors
313///
314/// [`LogError::Unrecognized`] if the text isn't a summary; [`LogError::Syntax`] for a row whose
315/// name is empty or a number, a name stated twice, or a value too large for its unit's
316/// conversion to SI.
317pub fn read(text: &str) -> Result<FlightLog, LogError> {
318    if !recognizes(text) {
319        return Err(LogError::Unrecognized {
320            message: format!(
321                "not a {FORMAT}: its first line doesn't name `Rocket Name`, or no line names \
322                 `Max Altitude` or `Launch time UTC`"
323            ),
324        });
325    }
326    let mut figures = Vec::new();
327    let mut keys: Vec<String> = Vec::new();
328    let mut lines_of: HashMap<String, usize> = HashMap::new();
329    let mut notes = Notes::default();
330    for (line, row) in numbered_lines(text) {
331        // A row padded to four cells may be all padding, `,,,`: blank, as an empty line is.
332        if row
333            .trim_matches(|c: char| c == ',' || c.is_whitespace())
334            .is_empty()
335        {
336            continue;
337        }
338        let (name, value) = row.split_once(',').unwrap_or((row, ""));
339        let name = name.trim();
340        // The value as written, but for the padding: empty cells at the row's end dropped.
341        let value = value
342            .trim_end_matches(|c: char| c == ',' || c.is_whitespace())
343            .trim();
344        let cells: Vec<&str> = if value.is_empty() {
345            Vec::new()
346        } else {
347            value.split(',').map(str::trim).collect()
348        };
349        if name.is_empty() || number(name, false).is_some() {
350            return Err(syntax(
351                line,
352                format!(
353                    "a summary row opens with its figure's name, and this one opens with `{}`",
354                    short(name)
355                ),
356            ));
357        }
358        let key = key(name);
359        if let Some(first) = lines_of.insert(key.clone(), line) {
360            return Err(syntax(
361                line,
362                format!(
363                    "`{}` is stated twice, on line {first} and on this one",
364                    short(name)
365                ),
366            ));
367        }
368        figures.push(figure(name, value, &cells, kind(&key), line, &mut notes)?);
369        keys.push(key);
370    }
371    let tracker = keys.iter().any(|key| key == "launch time utc");
372    let find = |wanted: &str| {
373        keys.iter()
374            .position(|key| key == wanted)
375            .map(|index| &figures[index])
376    };
377    let si = |wanted: &str, quantity: Quantity| {
378        find(wanted)
379            .filter(|figure| figure.quantity == Some(quantity))
380            .and_then(|figure| figure.values.first().copied())
381    };
382    let text_of = |wanted: &str| {
383        find(wanted)
384            .filter(|figure| figure.quantity.is_none() && !figure.written.is_empty())
385            .map(|figure| figure.written.clone())
386    };
387    let stated = Stated {
388        apogee_m: si("max altitude", Quantity::AltitudeAboveGround),
389        ground_elevation_msl_m: if tracker {
390            si("pad altitude", Quantity::GnssAltitude)
391        } else {
392            si("pad altitude asl", Quantity::AltitudeMsl)
393        },
394        samples: None,
395        figures: Vec::new(),
396    };
397    #[allow(
398        clippy::cast_possible_truncation,
399        clippy::cast_sign_loss,
400        reason = "a whole number in range, so the cast is exact"
401    )]
402    let flight_number = si("flight number", Quantity::Number)
403        .filter(|number| number.fract() == 0.0 && (0.0..=f64::from(u32::MAX)).contains(number))
404        .map(|number| number as u32);
405    let mut all_notes = vec![format!(
406        "a summary holds no samples, so the record's clock and tracks are empty: the flight's \
407         samples are in the {} exported beside it",
408        if tracker {
409            "tracker's CSV"
410        } else {
411            "Blue Raven's low-rate CSV"
412        }
413    )];
414    all_notes.extend(notes.into_vec());
415    Ok(FlightLog {
416        format: LogFormat::FeatherweightSummaryCsv,
417        logger: if tracker {
418            "Featherweight GPS tracker"
419        } else {
420            "Featherweight Blue Raven"
421        }
422        .to_owned(),
423        serial_number: text_of("serial number").or_else(|| text_of("searial number")),
424        firmware: text_of("firmware"),
425        flight_number,
426        stated: Stated { figures, ..stated },
427        time_s: Vec::new(),
428        altitude_m: Vec::new(),
429        vertical_speed_m_s: None,
430        temperature_k: None,
431        battery_v: None,
432        channels: Vec::new(),
433        events: Vec::new(),
434        notes: all_notes,
435    })
436}
437
438/// One row's figure: `written` is its value as the file writes it, after the name, and `cells` the
439/// value's cells, trimmed.
440fn figure(
441    name: &str,
442    written: &str,
443    cells: &[&str],
444    kind: Option<Kind>,
445    line: usize,
446    notes: &mut Notes,
447) -> Result<Figure, LogError> {
448    let written = written.to_owned();
449    let bare: Option<Vec<f64>> = cells.iter().map(|cell| number(cell, false)).collect();
450    // Kept as written, each cell's number, its unit, if any, left in `written`.
451    let numbers: Option<Vec<f64>> = cells
452        .iter()
453        .map(|cell| measured_cell(cell).map(|(value, _)| value))
454        .collect();
455    // A note's part before its first `: ` is what the survey's public report counts, so it holds
456    // only the reader's own words and a name from its table; what the file writes comes after.
457    let as_written = |notes: &mut Notes, why: String| {
458        notes.push(match kind {
459            Some(_) => format!(
460                "`{}` kept as written, {why}: the file writes `{}`",
461                short(name),
462                short(&written)
463            ),
464            None => format!(
465                "a figure HPR Sim doesn't know kept as written: `{}`, the file writes `{}`",
466                short(name),
467                short(&written)
468            ),
469        });
470        match &numbers {
471            Some(values) if !values.is_empty() => Figure::new(
472                name,
473                written.clone(),
474                Some(Quantity::Unrecognized),
475                values.clone(),
476            ),
477            _ => Figure::new(name, written.clone(), None, Vec::new()),
478        }
479    };
480    let figure = match kind {
481        Some(Kind::Text) => Figure::new(name, written.clone(), None, Vec::new()),
482        Some(Kind::Measured {
483            quantity,
484            what,
485            units,
486        }) => match cells {
487            [cell] => match measured_cell(cell) {
488                Some((value, word)) => match units.iter().find(|(unit, _)| *unit == word) {
489                    Some((_, conversion)) => {
490                        let value = finite(conversion.apply(value), FORMAT, line, name)?;
491                        let impossible = match quantity {
492                            Quantity::Latitude => (value.abs() > 90.0).then_some("that large"),
493                            Quantity::Longitude => (value.abs() > 180.0).then_some("that large"),
494                            Quantity::Temperature => (value < 0.0).then_some("below absolute zero"),
495                            _ => None,
496                        };
497                        if let Some(impossible) = impossible {
498                            as_written(notes, format!("as no {what} is {impossible}"))
499                        } else {
500                            Figure::new(name, written.clone(), Some(quantity), vec![value])
501                        }
502                    }
503                    None if word.is_empty() => {
504                        as_written(notes, format!("with no unit, where a {what} needs one"))
505                    }
506                    None => as_written(notes, format!("in a unit that isn't a {what}")),
507                },
508                None => as_written(notes, "not a number".to_owned()),
509            },
510            [] => as_written(notes, "with no value".to_owned()),
511            _ => as_written(
512                notes,
513                format!("as {} cells, where a {what} is one", cells.len()),
514            ),
515        },
516        Some(Kind::Bare {
517            quantity,
518            components,
519        }) => match &bare {
520            Some(values) if values.len() == components => {
521                Figure::new(name, written.clone(), Some(quantity), values.clone())
522            }
523            _ => as_written(
524                notes,
525                format!(
526                    "as it isn't {components} plain number{}",
527                    plural(components)
528                ),
529            ),
530        },
531        Some(Kind::Unstated) => as_written(notes, "in a unit no source states".to_owned()),
532        None => as_written(notes, String::new()),
533    };
534    Ok(figure)
535}
536
537fn plural(count: usize) -> &'static str {
538    if count == 1 { "" } else { "s" }
539}
540
541fn syntax(line: usize, message: String) -> LogError {
542    LogError::Syntax {
543        format: FORMAT,
544        line,
545        message,
546    }
547}
548
549#[cfg(test)]
550mod tests {
551    use super::*;
552
553    const HEAD: &str = "Rocket Name,Demo\nMax Altitude,1000.00 feet\n";
554
555    fn figure_of<'a>(log: &'a FlightLog, name: &str) -> &'a Figure {
556        log.stated
557            .figures
558            .iter()
559            .find(|figure| figure.name == name)
560            .unwrap()
561    }
562
563    #[test]
564    fn a_summary_is_told_by_its_first_name_and_a_figure_only_it_states() {
565        assert!(recognizes(HEAD));
566        assert!(recognizes(
567            "\u{feff}\n rocket  name ,x\r\nLaunch time UTC,2026-01-01\r\n"
568        ));
569        // The name must open the file, and a summary's own figure must follow.
570        assert!(!recognizes("Max Altitude,1000 feet\nRocket Name,Demo\n"));
571        assert!(!recognizes("Rocket Name,Demo\nMax velocity,700 feet/sec\n"));
572        assert!(!recognizes(""));
573        // Past the first 200 lines that aren't blank, a figure isn't looked for.
574        let mut far = String::from("Rocket Name,Demo\n");
575        for i in 0..199 {
576            far.push_str(&format!("Other {i},1\n"));
577        }
578        far.push_str("Max Altitude,1 feet\n");
579        assert!(!recognizes(&far));
580        assert!(recognizes(&far.replacen("Other 198,1\n", "", 1)));
581    }
582
583    #[test]
584    fn each_unit_converts_as_its_word_says() {
585        let text = format!(
586            "{HEAD}Max velocity,100 feet/sec\nMax motor burn acceleration,2 Gs\n\
587             Temperature on pad,212 F\nTime to first burnout,1.5 sec\n\
588             Thrust tilt efficiency,99.5%\nBattery voltage on pad,4.1 V\n"
589        );
590        let log = read(&text).unwrap();
591        let value = |name| figure_of(&log, name).values[0];
592        assert_eq!(value("Max Altitude"), 1000.0 * 0.3048);
593        assert_eq!(value("Max velocity"), 100.0 * 0.3048);
594        assert_eq!(value("Max motor burn acceleration"), 2.0 * 9.806_65);
595        assert!((value("Temperature on pad") - 373.15).abs() < 1e-12);
596        assert_eq!(value("Time to first burnout"), 1.5);
597        assert_eq!(value("Thrust tilt efficiency"), 99.5 * 0.01);
598        assert_eq!(value("Battery voltage on pad"), 4.1);
599        assert_eq!(
600            figure_of(&log, "Temperature on pad").quantity,
601            Some(Quantity::Temperature)
602        );
603    }
604
605    #[test]
606    fn a_unit_the_name_doesnt_allow_is_kept_as_written() {
607        let text = format!("{HEAD}Main chute descent rate,-18.0 feet\n");
608        let log = read(&text).unwrap();
609        let rate = figure_of(&log, "Main chute descent rate");
610        assert_eq!(rate.quantity, Some(Quantity::Unrecognized));
611        assert_eq!(rate.values, [-18.0]);
612        assert_eq!(rate.written, "-18.0 feet");
613        assert!(
614            log.notes.contains(
615                &"`Main chute descent rate` kept as written, in a unit that isn't a speed: the \
616              file writes `-18.0 feet`"
617                    .to_owned()
618            )
619        );
620    }
621
622    #[test]
623    fn a_length_in_meters_is_kept_as_written_not_guessed() {
624        let log = read("Rocket Name,Demo\nMax Altitude,300 meters\n").unwrap();
625        assert_eq!(log.stated.apogee_m, None);
626        let apogee = figure_of(&log, "Max Altitude");
627        assert_eq!(apogee.quantity, Some(Quantity::Unrecognized));
628        assert_eq!(
629            log.notes[1],
630            "`Max Altitude` kept as written, in a unit that isn't a length: the file writes `300 \
631             meters`"
632        );
633    }
634
635    #[test]
636    fn a_duplicate_name_or_a_numeric_name_is_refused() {
637        let twice = read(&format!("{HEAD}MAX  altitude,1 feet\n")).unwrap_err();
638        assert_eq!(
639            twice.to_string(),
640            "Featherweight summary CSV line 3: `MAX  altitude` is stated twice, on line 2 and on \
641             this one"
642        );
643        let numeric = read(&format!("{HEAD}12.5,feet\n")).unwrap_err();
644        assert!(
645            numeric.to_string().ends_with(
646                "line 3: a summary row opens with its figure's name, and this one opens with `12.5`"
647            ),
648            "{numeric}"
649        );
650        let empty = read(&format!("{HEAD},3\n")).unwrap_err();
651        assert!(empty.to_string().contains("line 3:"), "{empty}");
652    }
653
654    #[test]
655    fn a_value_too_large_for_its_conversion_is_refused() {
656        // 1.7 × 10³⁰⁸ is finite, and × 9.806 65 isn't, written with an exponent or without.
657        let plain = format!("17{}", "0".repeat(307));
658        for value in ["1.7e308", plain.as_str()] {
659            let error = read(&format!("{HEAD}Max landing accel,{value} Gs\n")).unwrap_err();
660            assert_eq!(
661                error.to_string(),
662                "Featherweight summary CSV line 3: the column Max landing accel holds a value too \
663                 large for its unit's conversion to SI"
664            );
665        }
666        // A cell past the largest f64 isn't a number at all, so it is kept as written.
667        let log = read(&format!("{HEAD}Max landing accel,1e309 Gs\n")).unwrap();
668        assert_eq!(figure_of(&log, "Max landing accel").quantity, None);
669    }
670
671    #[test]
672    fn an_exponent_is_part_of_the_number_and_feet_isnt() {
673        assert_eq!(measured_cell("1.5e3 feet"), Some((1500.0, "feet")));
674        assert_eq!(measured_cell("2E-1 Gs"), Some((0.2, "Gs")));
675        assert_eq!(measured_cell("12feet"), Some((12.0, "feet")));
676        assert_eq!(measured_cell("98.50%"), Some((98.5, "%")));
677        assert_eq!(measured_cell("feet"), None);
678        assert_eq!(measured_cell(""), None);
679    }
680}