1use std::fmt::Write as _;
14
15use serde::{Deserialize, Serialize};
16
17use crate::curve::{ThrustCurve, cut_off};
18use crate::delay::DelayList;
19use crate::error::MotorError;
20use crate::text::{NO_CURVE, ParseWarning, Parsed, WarningKind, check_writable, finite};
21
22const FORMAT: &str = ".eng";
23
24#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
26pub struct EngFile {
27 pub entries: Vec<EngEntry>,
29 pub trailing_comments: Vec<String>,
31}
32
33#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
35pub struct EngEntry {
36 pub comments: Vec<String>,
38 pub name: String,
40 pub diameter_mm: f64,
42 pub length_mm: f64,
44 pub delays: String,
46 pub propellant_mass_kg: f64,
48 pub total_mass_kg: f64,
50 pub manufacturer: String,
52 pub points: Vec<(f64, f64)>,
54}
55
56impl EngEntry {
57 pub fn delays(&self) -> DelayList {
59 DelayList::parse(&self.delays)
60 }
61
62 pub fn thrust_curve(&self) -> Result<ThrustCurve, MotorError> {
69 let (times, thrusts) = self.points.iter().copied().unzip();
70 ThrustCurve::new(times, thrusts)
71 }
72}
73
74enum State {
76 Header,
78 Points(EngEntry, usize),
80 Skip,
82}
83
84fn is_stamp(comment: &str) -> bool {
90 hpr_core::tool::is_stamp(comment)
91}
92
93pub fn parse(text: &str) -> Result<Parsed<EngFile>, MotorError> {
109 let text = text.strip_prefix('\u{feff}').unwrap_or(text);
110 let text = text.replace("\r\n", "\n").replace('\r', "\n");
111 let mut entries = Vec::new();
112 let mut warnings = Vec::new();
113 let mut errors = Vec::new();
114 let mut comments = Vec::new();
115 let mut state = State::Header;
116
117 for (index, raw) in text.split('\n').enumerate() {
118 let line = index + 1;
119 let trimmed = raw.trim();
120 if trimmed.is_empty() {
121 continue;
122 }
123 if let Some(comment) = trimmed.strip_prefix(';') {
124 if let State::Points(entry, header_line) = std::mem::replace(&mut state, State::Header)
125 {
126 match finish(entry, header_line, &mut warnings) {
127 Ok(entry) => entries.push(entry),
128 Err(error) => errors.push(error),
129 }
130 }
131 if !comment.is_empty() && !is_stamp(comment) {
132 comments.push(comment.to_owned());
133 }
134 continue;
135 }
136 let fields: Vec<&str> = trimmed.split_whitespace().collect();
137 let next = match std::mem::replace(&mut state, State::Skip) {
138 State::Skip => Ok(State::Skip),
139 State::Header => header(&fields, std::mem::take(&mut comments), line, &mut warnings)
140 .map(|entry| State::Points(entry, line)),
141 State::Points(mut entry, header_line) => match fields.len() {
142 2 => {
143 add_point(&mut entry, &fields, line).map(|()| State::Points(entry, header_line))
144 }
145 n if n >= 7 && !fields.iter().all(|field| field.parse::<f64>().is_ok()) => {
147 match finish(entry, header_line, &mut warnings) {
148 Ok(entry) => entries.push(entry),
149 Err(error) => errors.push(error),
150 }
151 warnings.push(ParseWarning::new(
152 line,
153 WarningKind::Unusual,
154 "a new header with no comment line before it",
155 ));
156 header(&fields, std::mem::take(&mut comments), line, &mut warnings)
157 .map(|entry| State::Points(entry, line))
158 }
159 _ => Err(syntax(
160 line,
161 format!("expected `time thrust` or a header, found {trimmed:?}"),
162 )),
163 },
164 };
165 state = next.unwrap_or_else(|error| {
166 errors.push(error);
167 comments.clear();
168 State::Skip
169 });
170 }
171 if let State::Points(entry, header_line) = state {
172 match finish(entry, header_line, &mut warnings) {
173 Ok(entry) => entries.push(entry),
174 Err(error) => errors.push(error),
175 }
176 }
177 if entries.is_empty() {
178 return Err(errors
179 .into_iter()
180 .next()
181 .unwrap_or_else(|| syntax(1, "no motor entries".into())));
182 }
183 for error in errors {
184 let line = match &error {
185 MotorError::Syntax { line, .. } => *line,
186 _ => 0,
187 };
188 warnings.push(ParseWarning::new(
189 line,
190 WarningKind::Skipped,
191 format!("an entry was left out, so {NO_CURVE}: {error}"),
192 ));
193 }
194 warnings.sort_by_key(|warning| warning.line);
195 Ok(Parsed {
196 value: EngFile {
197 entries,
198 trailing_comments: comments,
199 },
200 warnings,
201 })
202}
203
204fn add_point(entry: &mut EngEntry, fields: &[&str], line: usize) -> Result<(), MotorError> {
205 let time = number(fields[0], "time", line)?;
206 let thrust = number(fields[1], "thrust", line)?;
207 point(entry, time, thrust, line)
208}
209
210pub fn write(file: &EngFile) -> Result<String, MotorError> {
228 if file.entries.is_empty() {
229 return Err(MotorError::Inconsistent(
230 "a .eng file needs an entry".into(),
231 ));
232 }
233 let mut out = String::new();
234 write_comment(&mut out, &format!(" {}", hpr_core::tool::stamp()))?;
235 for entry in &file.entries {
236 for comment in entry.comments.iter().filter(|comment| !is_stamp(comment)) {
237 write_comment(&mut out, comment)?;
238 }
239 let one_token = |field: &str| !field.is_empty() && !field.contains(char::is_whitespace);
242 let words = entry
243 .manufacturer
244 .split_whitespace()
245 .collect::<Vec<_>>()
246 .join(" ");
247 if !one_token(&entry.name) || entry.name.starts_with(';') {
248 return Err(MotorError::Inconsistent(format!(
249 "the .eng name {:?} must be one token that doesn't start with `;`",
250 entry.name
251 )));
252 }
253 if !one_token(&entry.delays) {
254 return Err(MotorError::Inconsistent(format!(
255 "the .eng delays {:?} must be one token",
256 entry.delays
257 )));
258 }
259 if entry.manufacturer.is_empty() || words != entry.manufacturer {
260 return Err(MotorError::Inconsistent(format!(
261 "the .eng manufacturer {:?} must be words separated by single spaces",
262 entry.manufacturer
263 )));
264 }
265 check_envelope(entry)?;
266 if let Some((last, peak)) = cut_off(entry.points.iter().map(|&(_, thrust)| thrust)) {
269 return Err(MotorError::Inconsistent(format!(
270 "the entry {:?} ends at {last} N, above half its peak thrust of {peak} N; a curve \
271 ends at zero thrust",
272 entry.name
273 )));
274 }
275 if entry.points.is_empty() {
276 return Err(MotorError::Inconsistent(format!(
277 "the .eng entry {:?} has no points",
278 entry.name
279 )));
280 }
281 let mut previous = 0.0;
282 for &(time, thrust) in &entry.points {
283 check_writable(time, "time (s)", true)?;
284 check_writable(thrust, "thrust (N)", false)?;
285 if time < previous {
286 return Err(MotorError::Domain {
287 what: "time (s), which decreases",
288 value: time,
289 });
290 }
291 previous = time;
292 }
293 let _ = writeln!(
295 out,
296 "{} {} {} {} {} {} {}",
297 entry.name,
298 entry.diameter_mm,
299 entry.length_mm,
300 entry.delays,
301 entry.propellant_mass_kg,
302 entry.total_mass_kg,
303 entry.manufacturer
304 );
305 for (time, thrust) in &entry.points {
306 let _ = writeln!(out, " {time} {thrust}");
307 }
308 out.push_str(";\n");
309 }
310 for comment in file
311 .trailing_comments
312 .iter()
313 .filter(|comment| !is_stamp(comment))
314 {
315 write_comment(&mut out, comment)?;
316 }
317 Ok(out)
318}
319
320fn write_comment(out: &mut String, comment: &str) -> Result<(), MotorError> {
321 if comment.trim().is_empty()
322 || comment.contains(['\n', '\r'])
323 || comment.ends_with(char::is_whitespace)
324 {
325 return Err(MotorError::Inconsistent(format!(
326 "the .eng comment {comment:?} must be non-empty, one line, without trailing whitespace"
327 )));
328 }
329 out.push(';');
330 out.push_str(comment);
331 out.push('\n');
332 Ok(())
333}
334
335fn header(
336 fields: &[&str],
337 comments: Vec<String>,
338 line: usize,
339 warnings: &mut Vec<ParseWarning>,
340) -> Result<EngEntry, MotorError> {
341 if fields.len() < 7 {
342 return Err(syntax(
343 line,
344 format!(
345 "a header needs 7 fields (name, diameter, length, delays, propellant mass, total \
346 mass, manufacturer); found {}",
347 fields.len()
348 ),
349 ));
350 }
351 if fields.len() > 7 {
352 warnings.push(ParseWarning::new(
353 line,
354 WarningKind::Unusual,
355 format!(
356 "the header has {} fields; fields 7 onward are read as the manufacturer",
357 fields.len()
358 ),
359 ));
360 }
361 let entry = EngEntry {
362 comments,
363 name: fields[0].to_owned(),
364 diameter_mm: number(fields[1], "diameter", line)?,
365 length_mm: number(fields[2], "length", line)?,
366 delays: fields[3].to_owned(),
367 propellant_mass_kg: number(fields[4], "propellant mass", line)?,
368 total_mass_kg: number(fields[5], "total mass", line)?,
369 manufacturer: fields[6..].join(" "),
370 points: Vec::new(),
371 };
372 check_envelope(&entry).map_err(|error| syntax(line, error.to_string()))?;
373 Ok(entry)
374}
375
376fn check_envelope(entry: &EngEntry) -> Result<(), MotorError> {
378 for (value, what) in [
379 (entry.diameter_mm, "diameter (mm)"),
380 (entry.length_mm, "length (mm)"),
381 ] {
382 if !(value.is_finite() && value > 0.0) {
383 return Err(MotorError::Domain { what, value });
384 }
385 }
386 check_writable(entry.propellant_mass_kg, "propellant mass (kg)", true)?;
387 check_writable(entry.total_mass_kg, "total mass (kg)", true)
388}
389
390fn point(entry: &mut EngEntry, time: f64, thrust: f64, line: usize) -> Result<(), MotorError> {
391 if time < 0.0 {
392 return Err(syntax(line, format!("negative time {time}")));
393 }
394 if let Some(&(previous, _)) = entry.points.last()
395 && time < previous
396 {
397 return Err(syntax(
398 line,
399 format!("time {time} s is before the previous point's {previous} s"),
400 ));
401 }
402 entry.points.push((time, thrust));
403 Ok(())
404}
405
406fn finish(
410 entry: EngEntry,
411 header_line: usize,
412 warnings: &mut Vec<ParseWarning>,
413) -> Result<EngEntry, MotorError> {
414 if entry.points.is_empty() {
415 return Err(syntax(
416 header_line,
417 format!("the entry {:?} has no points", entry.name),
418 ));
419 }
420 if let Some((last, peak)) = cut_off(entry.points.iter().map(|&(_, thrust)| thrust)) {
421 return Err(syntax(
422 header_line,
423 format!(
424 "the entry {:?} ends at {last} N, above half its peak thrust of {peak} N, so the \
425 file looks cut off. A curve ends at zero thrust",
426 entry.name
427 ),
428 ));
429 }
430 let mut warn = |kind: WarningKind, message: String| {
431 warnings.push(ParseWarning::new(
432 header_line,
433 kind,
434 format!("{}: {message}", entry.name),
435 ));
436 };
437 if entry.propellant_mass_kg >= entry.total_mass_kg {
438 warn(
439 WarningKind::Unusual,
440 format!(
441 "propellant mass {} kg is not below the total mass {} kg",
442 entry.propellant_mass_kg, entry.total_mass_kg
443 ),
444 );
445 }
446 for warning in entry.delays().warnings {
447 warn(warning.kind, warning.message);
448 }
449 if let Some(&(_, last)) = entry.points.last()
450 && last != 0.0
451 {
452 warn(
453 WarningKind::Unusual,
454 format!("the curve ends at {last} N, not zero"),
455 );
456 }
457 if entry.points.iter().any(|&(_, thrust)| thrust < 0.0) {
458 warn(WarningKind::Unusual, "the curve has negative thrust".into());
459 }
460 Ok(entry)
461}
462
463fn number(text: &str, what: &'static str, line: usize) -> Result<f64, MotorError> {
464 finite(text, what).map_err(|_| syntax(line, format!("can't read the {what} {text:?}")))
465}
466
467fn syntax(line: usize, message: String) -> MotorError {
468 MotorError::Syntax {
469 format: FORMAT,
470 line,
471 message,
472 }
473}
474
475#[cfg(test)]
476pub(crate) mod tests {
477 use proptest::prelude::*;
478
479 use super::*;
480 use crate::delay::Delay;
481
482 const TWO_MOTORS: &str = "\
483; Two motors in one file.
484A8 18 70 3-5 0.00312 0.01642 Estes
485 0.041 0.512
486 0.3 3.12
487 0.73 0
488;
489; second
490C6 18 70 0-3-5-7 .0108 0.0231 E
491\t0.031\t0.946
492 1.86 0
493";
494
495 #[test]
498 fn multiple_blocks_parse_separately() {
499 let parsed = parse(TWO_MOTORS).unwrap();
500 let file = &parsed.value;
501 assert_eq!(file.entries.len(), 2);
502 let (a8, c6) = (&file.entries[0], &file.entries[1]);
503 assert_eq!(a8.comments, [" Two motors in one file."]);
504 assert_eq!(a8.name, "A8");
505 assert_eq!(a8.points, [(0.041, 0.512), (0.3, 3.12), (0.73, 0.0)]);
506 assert_eq!(c6.comments, [" second"]);
507 assert_eq!(c6.name, "C6");
508 assert_eq!(c6.propellant_mass_kg, 0.0108);
509 assert_eq!(c6.manufacturer, "E");
510 assert_eq!(c6.points, [(0.031, 0.946), (1.86, 0.0)]);
511 let unseparated = "A8 18 70 3 0.003 0.016 Estes\n 0.1 1\n 0.2 0\nB4 18 70 4 0.006 0.02 E\n 0.1 2\n 0.3 0\n";
513 let parsed = parse(unseparated).unwrap();
514 assert_eq!(parsed.value.entries.len(), 2);
515 assert_eq!(parsed.value.entries[1].points, [(0.1, 2.0), (0.3, 0.0)]);
516 assert!(parsed.warnings.iter().any(|w| w.line == 4));
517 }
518
519 #[test]
522 fn delay_lists_and_plugged_markers_parse() {
523 let delays = |raw: &str| {
524 let text = format!("M1 54 400 {raw} 1 2 X\n 0.5 100\n 1 0\n");
525 parse(&text).unwrap().value.entries[0].delays().delays
526 };
527 let s = Delay::Seconds;
528 assert_eq!(delays("6-10-14"), [s(6.0), s(10.0), s(14.0)]);
529 assert_eq!(delays("5,8,11"), [s(5.0), s(8.0), s(11.0)]);
530 assert_eq!(delays("P"), [Delay::Plugged]);
531 assert_eq!(
532 delays("6-10-14-P"),
533 [s(6.0), s(10.0), s(14.0), Delay::Plugged]
534 );
535 assert_eq!(delays("100"), [Delay::Plugged]);
536 assert_eq!(delays("1000"), [Delay::Plugged]);
537 assert_eq!(delays("14-12-10"), [s(14.0), s(12.0), s(10.0)]);
538 let text = "M1 54 400 6-10-14-P 1 2 X\n 0.5 100\n 1 0\n";
540 let file = parse(text).unwrap().value;
541 assert_eq!(file.entries[0].delays, "6-10-14-P");
542 assert_eq!(parse(&write(&file).unwrap()).unwrap().value, file);
543 }
544
545 #[test]
547 fn rejects_non_monotonic_time() {
548 let text = "F1 29 100 P 0.03 0.08 X\n 0.1 20\n 0.5 25\n 0.4 10\n 0.9 0\n";
549 match parse(text) {
550 Err(MotorError::Syntax { line: 4, .. }) => {}
551 other => panic!("expected a syntax error on line 4, got {other:?}"),
552 }
553 assert!(parse("F1 29 100 P 0.03 0.08 X\n -0.1 20\n 0.9 0\n").is_err());
554 let step = parse("F1 29 100 P 0.03 0.08 X\n 0.1 20\n 0.5 20\n 0.5 0\n").unwrap();
556 let curve = step.value.entries[0].thrust_curve().unwrap();
557 assert_eq!(curve.times_s(), &[0.0, 0.1, 0.5, 0.5]);
558 let entry = EngEntry {
560 points: vec![(0.5, 1.0), (0.4, 0.0)],
561 ..step.value.entries[0].clone()
562 };
563 assert!(entry.thrust_curve().is_err());
564 assert!(
565 write(&EngFile {
566 entries: vec![entry],
567 trailing_comments: vec![]
568 })
569 .is_err()
570 );
571 }
572
573 #[test]
574 fn a_broken_entry_is_skipped_with_a_warning() {
575 let text = "; one\nA1 18 70 3 0.003 0.016 X\n 0.1 1\n 0.05 0\n;\n; two\nB4 18 70 4 0.006 0.02 X\n 0.1 2\n 0.3 0\n;\nC6 18 70 x 0.01 0.02 X\n";
576 let parsed = parse(text).unwrap();
577 assert_eq!(parsed.value.entries.len(), 1);
578 assert_eq!(parsed.value.entries[0].name, "B4");
579 assert_eq!(parsed.value.entries[0].comments, [" two"]);
580 let skipped: Vec<usize> = parsed
581 .warnings
582 .iter()
583 .filter(|w| w.message.starts_with("an entry was left out"))
584 .map(|w| w.line)
585 .collect();
586 assert_eq!(skipped, [4, 11]);
587
588 let text = "A1 18 70 3 0.003 0.016 X\n 0.1 1\n 0.2 5 1 2 3 4 5\n 0.3 0\n;\nB4 18 70 4 0.006 0.02 X\n 0.1 2\n 0.3 0\n";
591 let parsed = parse(text).unwrap();
592 let names: Vec<&str> = parsed
593 .value
594 .entries
595 .iter()
596 .map(|e| e.name.as_str())
597 .collect();
598 assert_eq!(names, ["B4"]);
599 assert!(
600 parsed
601 .warnings
602 .iter()
603 .any(|w| w.line == 3 && w.kind == WarningKind::Skipped)
604 );
605
606 let text = "A8 18 70 3 0.003 0.016 E\n 0.1 1\n 0.2 0\n1266-J760-WT-19A 54 400 P 0.5 1 AT\n 0.1 900\n 1.5 0\n";
608 let parsed = parse(text).unwrap();
609 let names: Vec<&str> = parsed
610 .value
611 .entries
612 .iter()
613 .map(|e| e.name.as_str())
614 .collect();
615 assert_eq!(names, ["A8", "1266-J760-WT-19A"]);
616 assert!(
617 parsed
618 .warnings
619 .iter()
620 .all(|w| w.kind != WarningKind::Skipped)
621 );
622 }
623
624 #[test]
625 fn reads_real_world_whitespace_and_numbers() {
626 let text = "\u{feff};c\r\n H128W 29 194 6-10-14 .0906 0.1966 AT\r\n\t0.02\t156.\r\n 068.5 0\r\n;\r\n; trailer \r\n";
627 let parsed = parse(text).unwrap();
628 let entry = &parsed.value.entries[0];
629 assert_eq!(entry.propellant_mass_kg, 0.0906);
630 assert_eq!(entry.points, [(0.02, 156.0), (68.5, 0.0)]);
631 assert_eq!(parsed.value.trailing_comments, [" trailer"]);
632 let parsed = parse("K1 54 400 ;P 1 2 Contrail Rockets\n 1 1\n 2 0\n").unwrap();
634 assert_eq!(parsed.value.entries[0].manufacturer, "Contrail Rockets");
635 assert_eq!(parsed.value.entries[0].delays, ";P");
636 assert_eq!(parsed.warnings.len(), 2, "{:?}", parsed.warnings);
637 let written = write(&parsed.value).unwrap();
638 assert_eq!(parse(&written).unwrap().value, parsed.value);
639 let mut spaced = parsed.value.clone();
640 spaced.entries[0].manufacturer = "Contrail Rockets".into();
641 assert!(
642 write(&spaced).is_err(),
643 "a double space would read back as one"
644 );
645 let parsed = parse("K1 54 4e2 P +1 2E0 X\n 1e-1 1.5e3\n 2 0\n").unwrap();
647 assert_eq!(parsed.value.entries[0].length_mm, 400.0);
648 assert_eq!(parsed.value.entries[0].points[0], (0.1, 1500.0));
649 }
650
651 #[test]
652 fn rejects_malformed_files() {
653 let bad = [
654 "",
655 "; only a comment\n",
656 "F1 29 100 P 0.03 0.08\n 0.1 20\n",
657 "F1 29 100 P 0.03 0.08 X\n",
658 "F1 29 100 P 0.03 0.08 X\n;\n 0.1 20\n",
659 "F1 29 100 P 0.03 0.08 X\n 0.1 20 3\n",
660 "F1 29 100 P 0.03 0.08 X\n 0.1 inf\n",
661 "F1 29 100 P 0.03 0.08 X\n NaN 20\n",
662 "F1 0 100 P 0.03 0.08 X\n 0.1 20\n",
663 "F1 29 100 P -0.03 0.08 X\n 0.1 20\n",
664 "F1 29 1e999 P 0.03 0.08 X\n 0.1 20\n",
665 ];
666 for text in bad {
667 assert!(parse(text).is_err(), "{text:?}");
668 }
669 }
670
671 #[test]
672 fn warns_about_accepted_oddities() {
673 let parsed = parse("F1 29 100 4-,6 0.09 0.08 X\n 0.1 20\n 0.2 5\n").unwrap();
674 let messages: Vec<&str> = parsed.warnings.iter().map(|w| w.message.as_str()).collect();
675 assert_eq!(messages.len(), 3, "{messages:?}");
676 }
677
678 #[test]
679 fn writes_what_it_reads() {
680 let file = parse(TWO_MOTORS).unwrap().value;
681 let text = write(&file).unwrap();
682 assert_eq!(parse(&text).unwrap().value, file);
683 assert_eq!(write(&parse(&text).unwrap().value).unwrap(), text);
684 let mut signed = file.clone();
686 signed.entries[0].points[2].1 = -0.0;
687 let back = parse(&write(&signed).unwrap()).unwrap().value;
688 assert!(back.entries[0].points[2].1.is_sign_negative());
689 }
690
691 #[test]
696 fn the_first_line_names_the_program_and_stamps_do_not_pile_up() {
697 let file = parse(TWO_MOTORS).unwrap().value;
698 let text = write(&file).unwrap();
699 let first = format!(
700 "; FusionSpace HPR {} · FS-ACHERNAR · SW · TOOL 001\n",
701 env!("CARGO_PKG_VERSION")
702 );
703 assert!(text.starts_with(&first), "{text}");
704 assert_eq!(first, format!("; {}\n", hpr_core::tool::stamp()));
705 assert_eq!(text.matches("TOOL 001").count(), 1);
706 assert!(!text.contains("TOOL 005"));
707 let read = parse(&text).unwrap();
708 let messages = |warnings: &[ParseWarning]| {
710 warnings
711 .iter()
712 .map(|w| (w.kind, w.message.clone()))
713 .collect::<Vec<_>>()
714 };
715 assert_eq!(
716 messages(&read.warnings),
717 messages(&parse(TWO_MOTORS).unwrap().warnings)
718 );
719 assert_eq!(read.value, file);
720
721 let mut dotted = file.clone();
723 dotted.entries[0]
724 .comments
725 .push(" 2 · 3 s burn, by hpr-sim".to_owned());
726 dotted.entries[1]
727 .comments
728 .push(" FS · SW · TOOL 005".to_owned());
729 let back = parse(&write(&dotted).unwrap()).unwrap().value;
730 assert_eq!(back, dotted);
731
732 let mut stamped = file.clone();
734 stamped.entries[0]
735 .comments
736 .insert(0, " hpr-sim 0.0.9 · FS · SW · TOOL 005".to_owned());
737 stamped.entries[1]
738 .comments
739 .push(format!(" {}", hpr_core::tool::stamp()));
740 stamped
741 .trailing_comments
742 .push("hpr-sim 9.9 · FS · SW · TOOL 005".to_owned());
743 assert_eq!(write(&stamped).unwrap(), text);
744 let earlier = format!("; hpr-sim 0.0.9 · FS · SW · TOOL 005\n{TWO_MOTORS}");
746 let earlier = parse(&earlier).unwrap().value;
747 assert_eq!(earlier, file);
748 assert_eq!(write(&earlier).unwrap(), text);
749 }
750
751 #[test]
755 fn a_file_stamped_tool_005_reads_without_it_and_writes_back_with_one_stamp() {
756 let file = parse(TWO_MOTORS).unwrap().value;
757 let text = write(&file).unwrap();
758 for old in [
759 format!(
760 "; hpr-sim {} · FS · SW · TOOL 005\n",
761 env!("CARGO_PKG_VERSION")
762 ),
763 "; hpr-sim 0.1.0 · FS · SW · TOOL 005\n".to_owned(),
764 ] {
765 let stamped = format!("{old}{TWO_MOTORS}");
766 let read = parse(&stamped).unwrap();
767 assert_eq!(read.value, file, "{old}");
768 assert!(
769 read.value
770 .entries
771 .iter()
772 .flat_map(|entry| &entry.comments)
773 .chain(&read.value.trailing_comments)
774 .all(|comment| !comment.contains("TOOL 005")),
775 "{old}"
776 );
777 let back = write(&read.value).unwrap();
778 assert_eq!(back, text, "{old}");
779 assert_eq!(back.matches(" · SW · TOOL ").count(), 1, "{back}");
780 assert!(!back.contains("TOOL 005"), "{back}");
781 let both = format!("{old}; {}\n{TWO_MOTORS}{old}", hpr_core::tool::stamp());
783 assert_eq!(write(&parse(&both).unwrap().value).unwrap(), text, "{old}");
784 }
785 }
786
787 #[test]
792 fn a_file_stamped_hpr_sim_with_either_designation_reads_without_it() {
793 let file = parse(TWO_MOTORS).unwrap().value;
794 let text = write(&file).unwrap();
795 assert!(text.starts_with("; FusionSpace HPR "), "{text}");
796 for old in [
797 "; hpr-sim 0.1.0 · FS-ACHERNAR · SW · TOOL 001\n",
798 "; hpr-sim 0.1.0 · FS · SW · TOOL 005\n",
799 ";hpr-sim 0.0.9 · FS-ACHERNAR · SW · TOOL 001\n",
800 ] {
801 let read = parse(&format!("{old}{TWO_MOTORS}")).unwrap();
802 assert_eq!(read.value, file, "{old}");
803 assert!(
804 read.value
805 .entries
806 .iter()
807 .flat_map(|entry| &entry.comments)
808 .chain(&read.value.trailing_comments)
809 .all(|comment| !comment.contains("hpr-sim")),
810 "{old}"
811 );
812 let back = write(&read.value).unwrap();
813 assert_eq!(back, text, "{old}");
814 assert_eq!(back.matches(" · SW · TOOL ").count(), 1, "{back}");
815 assert!(!back.contains("hpr-sim"), "{back}");
816 let both = format!("{old}; {}\n{TWO_MOTORS}{old}", hpr_core::tool::stamp());
818 assert_eq!(write(&parse(&both).unwrap().value).unwrap(), text, "{old}");
819 }
820 }
821
822 pub(crate) fn bits(file: &EngFile) -> Vec<u64> {
824 file.entries
825 .iter()
826 .flat_map(|e| {
827 [
828 e.diameter_mm,
829 e.length_mm,
830 e.propellant_mass_kg,
831 e.total_mass_kg,
832 ]
833 .into_iter()
834 .chain(e.points.iter().flat_map(|&(t, f)| [t, f]))
835 .map(f64::to_bits)
836 .collect::<Vec<_>>()
837 })
838 .collect()
839 }
840
841 fn token() -> impl Strategy<Value = String> {
842 "[A-Za-z0-9_./()-]{1,12}".prop_filter("not a comment", |s| !s.starts_with(';'))
843 }
844
845 fn comment() -> impl Strategy<Value = String> {
846 "[ -~]{0,20}[!-~]".prop_map(|s| s)
847 }
848
849 fn masses() -> impl Strategy<Value = f64> {
850 prop_oneof![Just(-0.0), Just(0.0), 1e-300..1e3f64]
851 }
852
853 fn entries() -> impl Strategy<Value = EngEntry> {
854 (
855 prop::collection::vec(comment(), 0..3),
856 (token(), token(), "[A-Za-z;]{1,6}( [A-Za-z0-9;]{1,6}){0,2}"),
857 (1e-3..1e4f64, 1e-3..1e5f64, masses(), masses()),
858 prop::collection::vec(
859 (
860 prop_oneof![Just(-0.0), 0.0..10.0f64],
861 prop_oneof![Just(-0.0), -1.0..1e5f64],
862 ),
863 1..30,
864 ),
865 )
866 .prop_map(
867 |(comments, (name, delays, manufacturer), (d, l, p, t), mut points)| {
868 points.sort_by(|a, b| a.0.total_cmp(&b.0));
869 if cut_off(points.iter().map(|&(_, f)| f)).is_some()
872 && let Some(last) = points.last_mut()
873 {
874 last.1 = 0.0;
875 }
876 EngEntry {
877 comments,
878 name,
879 diameter_mm: d,
880 length_mm: l,
881 delays,
882 propellant_mass_kg: p,
883 total_mass_kg: t,
884 manufacturer,
885 points,
886 }
887 },
888 )
889 }
890
891 proptest! {
892 #[test]
893 fn write_parse_round_trips_bit_for_bit(
894 entries in prop::collection::vec(entries(), 1..4),
895 trailing_comments in prop::collection::vec(comment(), 0..2),
896 ) {
897 let file = EngFile { entries, trailing_comments };
898 let text = write(&file).unwrap();
899 let back = parse(&text).unwrap().value;
900 prop_assert_eq!(&back, &file);
901 prop_assert_eq!(bits(&back), bits(&file));
902 }
903 }
904
905 #[test]
909 fn a_curve_cut_off_above_half_its_peak_is_refused() {
910 let cut = "G84 24 228 5 0.077 0.172 CTI\n 0.1 100\n 0.4 60\n";
911 let Err(MotorError::Syntax { line, message, .. }) = parse(cut) else {
912 panic!("a cut curve was read");
913 };
914 assert_eq!(line, 1);
915 assert!(
916 message.contains("ends at 60 N, above half its peak thrust of 100 N"),
917 "{message}"
918 );
919 let tail = "G84 24 228 5 0.077 0.172 CTI\n 0.1 100\n 0.4 10\n";
920 let parsed = parse(tail).unwrap();
921 assert_eq!(parsed.value.entries.len(), 1);
922 assert!(
923 parsed
924 .warnings
925 .iter()
926 .any(|w| w.kind == WarningKind::Unusual
927 && w.message.contains("ends at 10 N, not zero")),
928 "{:?}",
929 parsed.warnings
930 );
931 let both = format!("{cut};\nB4 18 70 3 0.006 0.02 E\n 0.1 5\n 0.5 0\n");
932 let parsed = parse(&both).unwrap();
933 let names: Vec<&str> = parsed
934 .value
935 .entries
936 .iter()
937 .map(|e| e.name.as_str())
938 .collect();
939 assert_eq!(names, ["B4"]);
940 assert!(
941 parsed
942 .warnings
943 .iter()
944 .any(|w| w.kind == WarningKind::Skipped && w.message.contains("looks cut off"))
945 );
946 let mut file = parse(tail).unwrap().value;
947 file.entries[0].points[1].1 = 60.0;
948 let Err(MotorError::Inconsistent(message)) = write(&file) else {
949 panic!("a cut curve was written");
950 };
951 assert!(message.contains("ends at 60 N"), "{message}");
952 }
953}