1use std::fmt::Write as _;
14
15use roxmltree::{Document, Node, ParsingOptions};
16use serde::{Deserialize, Serialize};
17
18use crate::curve::{ThrustCurve, cut_off};
19use crate::delay::DelayList;
20use crate::error::MotorError;
21use crate::text::{
22 NO_CURVE, NOTHING_DEPENDS, ParseWarning, Parsed, WORKED_OUT, WarningKind, check_writable,
23 finite,
24};
25
26const FORMAT: &str = ".rse";
27
28const RENDERING: [&str; 12] = [
30 "tDiv", "tStep", "tFix", "FDiv", "FStep", "FFix", "mDiv", "mStep", "mFix", "cgDiv", "cgStep",
31 "cgFix",
32];
33
34#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
36pub struct RseFile {
37 pub engines: Vec<RseEngine>,
39}
40
41#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
43pub struct RseEngine {
44 pub manufacturer: String,
46 pub code: String,
48 pub motor_type: Option<String>,
50 pub diameter_mm: f64,
52 pub length_mm: f64,
54 pub initial_mass_g: f64,
56 pub propellant_mass_g: f64,
58 pub delays: Option<String>,
60 pub auto_calc_mass: Option<bool>,
62 pub auto_calc_cg: Option<bool>,
64 pub average_thrust_n: Option<f64>,
66 pub peak_thrust_n: Option<f64>,
68 pub throat_diameter_mm: Option<f64>,
70 pub exit_diameter_mm: Option<f64>,
72 pub total_impulse_ns: Option<f64>,
74 pub burn_time_s: Option<f64>,
76 pub mass_fraction_pct: Option<f64>,
78 pub isp_s: Option<f64>,
80 pub comments: Option<String>,
82 pub points: Vec<RsePoint>,
84}
85
86#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
88pub struct RsePoint {
89 pub time_s: f64,
91 pub thrust_n: f64,
93 pub mass_g: Option<f64>,
95 pub cg_mm: Option<f64>,
97}
98
99impl RseEngine {
100 pub fn delays(&self) -> DelayList {
102 DelayList::parse(self.delays.as_deref().unwrap_or(""))
103 }
104
105 pub fn thrust_curve(&self) -> Result<ThrustCurve, MotorError> {
111 let (times, thrusts) = self.points.iter().map(|p| (p.time_s, p.thrust_n)).unzip();
112 ThrustCurve::new(times, thrusts)
113 }
114}
115
116pub fn parse(text: &str) -> Result<Parsed<RseFile>, MotorError> {
132 let text = text.strip_prefix('\u{feff}').unwrap_or(text);
133 check_nesting(text)?;
134 let options = ParsingOptions {
135 allow_dtd: false,
136 ..ParsingOptions::default()
137 };
138 let doc = Document::parse_with_options(text, options).map_err(|error| {
139 syntax(
140 error.pos().row as usize,
141 format!("not well-formed XML: {error}"),
142 )
143 })?;
144 let lines = Lines::new(text);
145 let mut warnings = Vec::new();
146 let mut engines = Vec::new();
147 let mut errors = Vec::new();
148 let is_engine = |node: &Node<'_, '_>| node.has_tag_name("engine");
149 for node in doc.descendants().filter(is_engine) {
150 if node
151 .ancestors()
152 .skip(1)
153 .any(|ancestor| is_engine(&ancestor))
154 {
155 warnings.push(ParseWarning::new(
156 lines.of(node),
157 WarningKind::Dropped,
158 format!("an <engine> inside another engine was left out, so {NO_CURVE}"),
159 ));
160 continue;
161 }
162 let mut engine_warnings = Vec::new();
163 match engine(&lines, node, &mut engine_warnings) {
164 Ok(engine) => {
165 engines.push(engine);
166 warnings.append(&mut engine_warnings);
167 }
168 Err(error) => errors.push(error),
169 }
170 }
171 if engines.is_empty() {
172 return Err(errors
173 .into_iter()
174 .next()
175 .unwrap_or_else(|| syntax(1, "no <engine> elements".into())));
176 }
177 for error in errors {
178 let line = match &error {
179 MotorError::Syntax { line, .. } => *line,
180 _ => 0,
181 };
182 warnings.push(ParseWarning::new(
183 line,
184 WarningKind::Skipped,
185 format!("an engine was left out, so {NO_CURVE}: {error}"),
186 ));
187 }
188 warnings.sort_by_key(|warning| warning.line);
189 Ok(Parsed {
190 value: RseFile { engines },
191 warnings,
192 })
193}
194
195struct Lines {
198 starts: Vec<usize>,
199}
200
201impl Lines {
202 fn new(text: &str) -> Self {
203 let starts = std::iter::once(0)
204 .chain(text.match_indices('\n').map(|(i, _)| i + 1))
205 .collect();
206 Self { starts }
207 }
208
209 fn of(&self, node: Node<'_, '_>) -> usize {
211 self.starts
212 .partition_point(|&start| start <= node.range().start)
213 }
214}
215
216pub fn write(file: &RseFile) -> Result<String, MotorError> {
230 if file.engines.is_empty() {
231 return Err(MotorError::Inconsistent(
232 "a .rse file needs an engine".into(),
233 ));
234 }
235 let mut out = format!(
238 "<!-- {} -->\n<engine-database>\n <engine-list>\n",
239 hpr_core::tool::stamp()
240 );
241 for engine in &file.engines {
242 write_engine(&mut out, engine)?;
243 }
244 out.push_str(" </engine-list>\n</engine-database>\n");
245 Ok(out)
246}
247
248fn write_engine(out: &mut String, engine: &RseEngine) -> Result<(), MotorError> {
249 check_dimensions(engine.diameter_mm, engine.length_mm)?;
250 check_writable(engine.initial_mass_g, "initial mass (g)", true)?;
251 check_writable(engine.propellant_mass_g, "propellant mass (g)", true)?;
252 if engine.points.len() < 2 {
253 return Err(MotorError::Inconsistent(format!(
254 "the .rse engine {:?} needs at least two points",
255 engine.code
256 )));
257 }
258 if let Some((last, peak)) = cut_off(engine.points.iter().map(|point| point.thrust_n)) {
260 return Err(MotorError::Inconsistent(format!(
261 "the .rse engine {:?} ends at {last} N, above half its peak thrust of {peak} N; a \
262 curve ends at zero thrust",
263 engine.code
264 )));
265 }
266 let mut attributes: Vec<(&str, String)> = vec![
267 ("mfg", xml_text(&engine.manufacturer, true)?),
268 ("code", xml_text(&engine.code, true)?),
269 ];
270 let mut text = |name, value: &Option<String>| -> Result<(), MotorError> {
271 if let Some(value) = value {
272 attributes.push((name, xml_text(value, true)?));
273 }
274 Ok(())
275 };
276 text("Type", &engine.motor_type)?;
277 attributes.push(("dia", engine.diameter_mm.to_string()));
278 attributes.push(("len", engine.length_mm.to_string()));
279 attributes.push(("initWt", engine.initial_mass_g.to_string()));
280 attributes.push(("propWt", engine.propellant_mass_g.to_string()));
281 if let Some(delays) = &engine.delays {
282 attributes.push(("delays", xml_text(delays, true)?));
283 }
284 for (name, flag) in [
285 ("auto-calc-mass", engine.auto_calc_mass),
286 ("auto-calc-cg", engine.auto_calc_cg),
287 ] {
288 if let Some(flag) = flag {
289 attributes.push((name, if flag { "1" } else { "0" }.to_owned()));
290 }
291 }
292 for (name, value) in [
293 ("avgThrust", engine.average_thrust_n),
294 ("peakThrust", engine.peak_thrust_n),
295 ("throatDia", engine.throat_diameter_mm),
296 ("exitDia", engine.exit_diameter_mm),
297 ("Itot", engine.total_impulse_ns),
298 ("burn-time", engine.burn_time_s),
299 ("massFrac", engine.mass_fraction_pct),
300 ("Isp", engine.isp_s),
301 ] {
302 if let Some(value) = value {
303 check_writable(value, "optional .rse attribute", false)?;
304 attributes.push((name, value.to_string()));
305 }
306 }
307 out.push_str(" <engine");
308 for (name, value) in &attributes {
309 let _ = write!(out, " {name}=\"{value}\"");
310 }
311 out.push_str(">\n");
312 if let Some(comments) = &engine.comments {
313 let _ = writeln!(
314 out,
315 " <comments>{}</comments>",
316 xml_text(comments, false)?
317 );
318 }
319 out.push_str(" <data>\n");
320 let with_mass = engine.points.iter().filter(|p| p.mass_g.is_some()).count();
321 let with_cg = engine.points.iter().filter(|p| p.cg_mm.is_some()).count();
322 for (count, what) in [(with_mass, "m"), (with_cg, "cg")] {
323 if count != 0 && count != engine.points.len() {
324 return Err(MotorError::Inconsistent(format!(
325 "the .rse engine {:?} gives `{what}` on some points but not all",
326 engine.code
327 )));
328 }
329 }
330 let mut previous = 0.0;
331 for point in &engine.points {
332 check_writable(point.time_s, "time (s)", true)?;
333 check_writable(point.thrust_n, "thrust (N)", false)?;
334 if point.time_s < previous {
335 return Err(MotorError::Domain {
336 what: "time (s), which decreases",
337 value: point.time_s,
338 });
339 }
340 previous = point.time_s;
341 let _ = write!(
342 out,
343 " <eng-data t=\"{}\" f=\"{}\"",
344 point.time_s, point.thrust_n
345 );
346 if let Some(mass) = point.mass_g {
347 check_writable(mass, "point mass (g)", false)?;
348 let _ = write!(out, " m=\"{mass}\"");
349 }
350 if let Some(cg) = point.cg_mm {
351 check_writable(cg, "point CG (mm)", false)?;
352 let _ = write!(out, " cg=\"{cg}\"");
353 }
354 out.push_str("/>\n");
355 }
356 out.push_str(" </data>\n </engine>\n");
357 Ok(())
358}
359
360fn xml_text(value: &str, attribute: bool) -> Result<String, MotorError> {
364 let mut escaped = String::with_capacity(value.len());
365 for c in value.chars() {
366 match c {
367 '&' => escaped.push_str("&"),
368 '<' => escaped.push_str("<"),
369 '>' => escaped.push_str(">"),
370 '"' if attribute => escaped.push_str("""),
371 '\t' if attribute => escaped.push_str("	"),
372 '\n' if attribute => escaped.push_str(" "),
373 '\r' => escaped.push_str(" "),
374 '\t' | '\n' => escaped.push(c),
375 '\u{0}'..='\u{1f}' | '\u{fffe}' | '\u{ffff}' => {
377 return Err(MotorError::Inconsistent(format!(
378 "{value:?} holds a character XML 1.0 can't carry"
379 )));
380 }
381 _ => escaped.push(c),
382 }
383 }
384 Ok(escaped)
385}
386
387fn engine(
388 lines: &Lines,
389 node: Node<'_, '_>,
390 warnings: &mut Vec<ParseWarning>,
391) -> Result<RseEngine, MotorError> {
392 let line = lines.of(node);
393 for attribute in node.attributes() {
394 let name = attribute.name();
395 if !KNOWN.iter().any(|known| known.eq_ignore_ascii_case(name))
396 && !RENDERING
397 .iter()
398 .any(|known| known.eq_ignore_ascii_case(name))
399 {
400 warnings.push(ParseWarning::new(
401 line,
402 WarningKind::Dropped,
403 format!("unknown <engine> attribute `{name}` was left out, and {NOTHING_DEPENDS}"),
404 ));
405 }
406 }
407 let code = attr(node, &["code"]).ok_or_else(|| missing(line, "code"))?;
408 let manufacturer = match attr(node, &["mfg"]) {
409 Some(mfg) => mfg.to_owned(),
410 None => {
411 warnings.push(ParseWarning::new(
412 line,
413 WarningKind::Unusual,
414 format!("engine {code:?} has no `mfg`; read as empty"),
415 ));
416 String::new()
417 }
418 };
419 let required = |names: &[&'static str]| -> Result<f64, MotorError> {
420 let text = attr(node, names).ok_or_else(|| missing(line, names[0]))?;
421 number(text, names[0], line)
422 };
423 let optional = |name: &'static str| -> Result<Option<f64>, MotorError> {
424 attr(node, &[name])
425 .map(|text| number(text, name, line))
426 .transpose()
427 };
428 let diameter_mm = required(&["dia"])?;
429 let length_mm = required(&["len"])?;
430 check_dimensions(diameter_mm, length_mm).map_err(|e| syntax(line, e.to_string()))?;
431 let initial_mass_g = required(&["initWt", "initMass"])?;
432 let propellant_mass_g = required(&["propWt", "propMass"])?;
433 for (value, what) in [(initial_mass_g, "initWt"), (propellant_mass_g, "propWt")] {
434 if value < 0.0 {
435 return Err(syntax(line, format!("negative `{what}` {value}")));
436 }
437 }
438 if propellant_mass_g >= initial_mass_g && initial_mass_g > 0.0 {
439 warnings.push(ParseWarning::new(
440 line,
441 WarningKind::Unusual,
442 format!(
443 "engine {code:?}: propellant mass {propellant_mass_g} g is not below the loaded \
444 mass {initial_mass_g} g"
445 ),
446 ));
447 }
448 let mut flag = |name: &'static str| match attr(node, &[name]) {
449 None => None,
450 Some("1") => Some(true),
451 Some("0") => Some(false),
452 Some(other) => {
453 warnings.push(ParseWarning::new(
454 line,
455 WarningKind::Dropped,
456 format!(
457 "`{name}` is {other:?}, not 0 or 1; it was left out, and {NOTHING_DEPENDS}"
458 ),
459 ));
460 None
461 }
462 };
463 let auto_calc_mass = flag("auto-calc-mass");
464 let auto_calc_cg = flag("auto-calc-cg");
465
466 let mut comments = None;
467 let mut data = None;
468 for child in node.children().filter(Node::is_element) {
469 let name = child.tag_name().name();
470 let duplicate = match name {
471 "comments" => comments
472 .replace(
473 child
476 .descendants()
477 .filter(Node::is_text)
478 .filter_map(|text| text.text())
479 .collect::<String>(),
480 )
481 .is_some(),
482 "data" => data.replace(child).is_some(),
483 other => {
484 warnings.push(ParseWarning::new(
485 lines.of(child),
486 WarningKind::Dropped,
487 format!(
488 "unknown element <{other}> in an engine was left out, and \
489 {NOTHING_DEPENDS}"
490 ),
491 ));
492 false
493 }
494 };
495 if duplicate {
496 warnings.push(ParseWarning::new(
497 lines.of(child),
498 WarningKind::Dropped,
499 format!("engine {code:?} has more than one <{name}>; the last is read"),
500 ));
501 }
502 }
503 let data = data.ok_or_else(|| syntax(line, format!("engine {code:?} has no <data>")))?;
504 let points = points(lines, data, code, warnings)?;
505
506 let engine = RseEngine {
507 manufacturer,
508 code: code.to_owned(),
509 motor_type: attr(node, &["Type"]).map(str::to_owned),
510 diameter_mm,
511 length_mm,
512 initial_mass_g,
513 propellant_mass_g,
514 delays: attr(node, &["delays"]).map(str::to_owned),
515 auto_calc_mass,
516 auto_calc_cg,
517 average_thrust_n: optional("avgThrust")?,
518 peak_thrust_n: optional("peakThrust")?,
519 throat_diameter_mm: optional("throatDia")?,
520 exit_diameter_mm: optional("exitDia")?,
521 total_impulse_ns: optional("Itot")?,
522 burn_time_s: optional("burn-time")?,
523 mass_fraction_pct: optional("massFrac")?,
524 isp_s: optional("Isp")?,
525 comments,
526 points,
527 };
528 if let Some((last, peak)) = cut_off(engine.points.iter().map(|point| point.thrust_n)) {
530 return Err(syntax(
531 line,
532 format!(
533 "engine {:?} ends at {last} N, above half its peak thrust of {peak} N, so the \
534 file looks cut off. A curve ends at zero thrust",
535 engine.code
536 ),
537 ));
538 }
539 summary_warnings(&engine, line, warnings);
540 Ok(engine)
541}
542
543const KNOWN: [&str; 20] = [
545 "mfg",
546 "code",
547 "Type",
548 "dia",
549 "len",
550 "initWt",
551 "initMass",
552 "propWt",
553 "propMass",
554 "delays",
555 "auto-calc-mass",
556 "auto-calc-cg",
557 "avgThrust",
558 "peakThrust",
559 "throatDia",
560 "exitDia",
561 "Itot",
562 "burn-time",
563 "massFrac",
564 "Isp",
565];
566
567fn points(
568 lines: &Lines,
569 data: Node<'_, '_>,
570 code: &str,
571 warnings: &mut Vec<ParseWarning>,
572) -> Result<Vec<RsePoint>, MotorError> {
573 let mut points: Vec<RsePoint> = Vec::new();
574 for node in data.children().filter(Node::is_element) {
575 let line = lines.of(node);
576 if !(node.has_tag_name("eng-data") || node.has_tag_name("point")) {
577 warnings.push(ParseWarning::new(
578 line,
579 WarningKind::Dropped,
580 format!(
581 "unknown element <{}> in <data> was left out, and {NOTHING_DEPENDS}",
582 node.tag_name().name()
583 ),
584 ));
585 continue;
586 }
587 let get = |name: &'static str| -> Result<Option<f64>, MotorError> {
588 attr(node, &[name])
589 .map(|text| number(text, name, line))
590 .transpose()
591 };
592 let time_s = get("t")?.ok_or_else(|| missing(line, "t"))?;
593 let thrust_n = get("f")?.ok_or_else(|| missing(line, "f"))?;
594 if time_s < 0.0 {
595 return Err(syntax(line, format!("negative time {time_s}")));
596 }
597 if let Some(previous) = points.last()
598 && time_s < previous.time_s
599 {
600 return Err(syntax(
601 line,
602 format!(
603 "time {time_s} s is before the previous point's {} s",
604 previous.time_s
605 ),
606 ));
607 }
608 points.push(RsePoint {
609 time_s,
610 thrust_n,
611 mass_g: get("m")?,
612 cg_mm: get("cg")?,
613 });
614 }
615 let line = lines.of(data);
616 if points.len() < 2 {
617 return Err(syntax(
618 line,
619 format!("engine {code:?} needs at least two points"),
620 ));
621 }
622 let total = points.len();
623 let partial = |count: usize| count != 0 && count != total;
624 if partial(points.iter().filter(|p| p.mass_g.is_some()).count()) {
625 warnings.push(ParseWarning::new(
626 line,
627 WarningKind::Dropped,
628 format!(
629 "engine {code:?} gives `m` on only some points, so all were left out. {WORKED_OUT}"
630 ),
631 ));
632 points.iter_mut().for_each(|p| p.mass_g = None);
633 }
634 if partial(points.iter().filter(|p| p.cg_mm.is_some()).count()) {
635 warnings.push(ParseWarning::new(
636 line,
637 WarningKind::Dropped,
638 format!(
639 "engine {code:?} gives `cg` on only some points, so all were left out. {WORKED_OUT}"
640 ),
641 ));
642 points.iter_mut().for_each(|p| p.cg_mm = None);
643 }
644 Ok(points)
645}
646
647fn summary_warnings(engine: &RseEngine, line: usize, warnings: &mut Vec<ParseWarning>) {
650 let mut warn = |kind: WarningKind, message: String| {
651 warnings.push(ParseWarning::new(
652 line,
653 kind,
654 format!("engine {:?}: {message}", engine.code),
655 ));
656 };
657 for warning in engine.delays().warnings {
658 warn(warning.kind, warning.message);
659 }
660 if engine
661 .motor_type
662 .as_deref()
663 .is_some_and(|kind| kind.trim().eq_ignore_ascii_case("hybrid"))
664 {
665 warn(
666 WarningKind::Unusual,
667 "a hybrid motor: HPR Sim models solid motors only, and a `SolidMotor` built from this \
668 curve would be wrong"
669 .into(),
670 );
671 }
672 if let Some(last) = engine.points.last()
673 && last.thrust_n != 0.0
674 {
675 warn(
676 WarningKind::Unusual,
677 format!("the curve ends at {} N, not zero", last.thrust_n),
678 );
679 }
680 if engine.points.iter().any(|p| p.thrust_n < 0.0) {
681 warn(WarningKind::Unusual, "the curve has negative thrust".into());
682 return;
683 }
684 let Ok(curve) = engine.thrust_curve() else {
685 return;
686 };
687 for (given, computed, name) in [
688 (engine.total_impulse_ns, curve.total_impulse_ns(), "Itot"),
689 (engine.peak_thrust_n, curve.peak_thrust_n(), "peakThrust"),
690 ] {
691 if let Some(given) = given
692 && (given - computed).abs() > 0.01 * computed.abs()
693 {
694 warn(
695 WarningKind::Unusual,
696 format!("`{name}` {given} differs from the curve's {computed} by more than 1%"),
697 );
698 }
699 }
700}
701
702fn attr<'a>(node: Node<'a, '_>, names: &[&str]) -> Option<&'a str> {
704 names
705 .iter()
706 .find_map(|name| node.attribute(*name))
707 .or_else(|| {
708 node.attributes()
709 .find(|a| names.iter().any(|name| a.name().eq_ignore_ascii_case(name)))
710 .map(|a| a.value())
711 })
712}
713
714fn check_dimensions(diameter_mm: f64, length_mm: f64) -> Result<(), MotorError> {
715 for (value, what) in [(diameter_mm, "diameter (mm)"), (length_mm, "length (mm)")] {
716 if !(value.is_finite() && value > 0.0) {
717 return Err(MotorError::Domain { what, value });
718 }
719 }
720 Ok(())
721}
722
723fn number(text: &str, what: &'static str, line: usize) -> Result<f64, MotorError> {
724 finite(text, what).map_err(|_| syntax(line, format!("can't read `{what}` from {text:?}")))
725}
726
727fn missing(line: usize, what: &str) -> MotorError {
728 syntax(line, format!("missing the `{what}` attribute"))
729}
730
731fn syntax(line: usize, message: String) -> MotorError {
732 MotorError::Syntax {
733 format: FORMAT,
734 line,
735 message,
736 }
737}
738
739pub const MAX_ELEMENT_DEPTH: usize = 32;
747
748fn check_nesting(text: &str) -> Result<(), MotorError> {
756 let bytes = text.as_bytes();
757 let find = |from: usize, needle: &[u8]| {
758 bytes[from..]
759 .windows(needle.len())
760 .position(|window| window == needle)
761 .map_or(bytes.len(), |at| from + at + needle.len())
762 };
763 let mut depth = 0_usize;
764 let mut i = 0;
765 while let Some(offset) = bytes[i..].iter().position(|&b| b == b'<') {
766 let start = i + offset;
767 let rest = &bytes[start..];
768 i = if rest.starts_with(b"<!--") {
769 find(start + 4, b"-->")
770 } else if rest.starts_with(b"<![CDATA[") {
771 find(start + 9, b"]]>")
772 } else if rest.starts_with(b"<?") {
773 find(start + 2, b"?>")
774 } else if rest.starts_with(b"<!") || rest.starts_with(b"</") {
775 if rest[1] == b'/' {
776 depth = depth.saturating_sub(1);
777 }
778 find(start + 2, b">")
779 } else {
780 let mut quote = None;
781 let mut end = bytes.len();
782 let mut self_closing = false;
783 for (j, &b) in bytes.iter().enumerate().skip(start + 1) {
784 match (quote, b) {
785 (_, b'<') => {
786 end = j;
787 break;
788 }
789 (None, b'"' | b'\'') => quote = Some(b),
790 (Some(open), _) if b == open => quote = None,
791 (None, b'>') => {
792 self_closing = bytes[j - 1] == b'/';
793 end = j + 1;
794 break;
795 }
796 _ => {}
797 }
798 }
799 if !self_closing {
800 depth += 1;
801 if depth > MAX_ELEMENT_DEPTH {
802 let line = bytes[..start].iter().filter(|&&b| b == b'\n').count() + 1;
803 return Err(syntax(
804 line,
805 format!("elements nested more than {MAX_ELEMENT_DEPTH} deep"),
806 ));
807 }
808 }
809 end
810 };
811 if i >= bytes.len() {
812 break;
813 }
814 }
815 Ok(())
816}
817
818#[cfg(test)]
819pub(crate) mod tests {
820 use proptest::prelude::*;
821
822 use super::*;
823 use crate::delay::Delay;
824
825 const SAMPLE: &str = r#"<engine-database>
826 <engine-list>
827 <engine mfg=" Aerotech" code="H128W" Type="reloadable" dia="29." len="194." initWt="196.6"
828 propWt="90.6" delays="6,10,14" auto-calc-mass="1" auto-calc-cg="1" avgThrust="128."
829 peakThrust="150." throatDia="0." exitDia="0." Itot="10.2" burn-time="0.8" massFrac="46.1"
830 Isp="200." tDiv="10" tStep="-1." tFix="1" FDiv="10" FStep="-1." FFix="1" mDiv="10"
831 mStep="-1." mFix="1" cgDiv="10" cgStep="-1." cgFix="1">
832 <comments>Line one & two
833<![CDATA[raw & data]]></comments>
834 <data>
835 <eng-data t="0." f="0." m="90.6" cg="97."/>
836 <eng-data t="0.02" f="150." m="89.1" cg="97."/>
837 <eng-data t="0.1" f="100." m="80.2" cg="97."/>
838 <eng-data t="0.1" f="50." m="80.2" cg="97."/>
839 <eng-data t="0.2" f="0." m="0." cg="97."/>
840 </data>
841 </engine>
842 </engine-list>
843</engine-database>"#;
844
845 #[test]
846 fn deep_nesting_is_refused_before_the_xml_parser_recurses() {
847 let deep = |n: usize| format!("{}{}", "<a>".repeat(n), "</a>".repeat(n));
851 let result = parse(&deep(100_000));
852 assert!(
853 matches!(&result, Err(MotorError::Syntax { line: 1, message, .. })
854 if message.contains("nested")),
855 "{result:?}"
856 );
857
858 let body = SAMPLE.split_once('\n').unwrap().1;
861 let inner = body.strip_suffix("</engine-database>").unwrap();
862 let wrapped = |extra: usize| {
863 format!(
864 "<engine-database>{}\n{inner}{}</engine-database>",
865 "<!-- <x> --><x a='>'><y/>".repeat(extra),
866 "</x>".repeat(extra)
867 )
868 };
869 let at_limit = wrapped(MAX_ELEMENT_DEPTH - 4);
870 assert_eq!(parse(&at_limit).unwrap().value.engines.len(), 1);
871 let comments_line = at_limit
872 .lines()
873 .position(|l| l.contains("<comments>"))
874 .unwrap()
875 + 1;
876 assert!(matches!(
877 parse(&wrapped(MAX_ELEMENT_DEPTH - 3)),
878 Err(MotorError::Syntax { line, .. }) if line == comments_line
879 ));
880 let hidden = format!(
882 "<?xml version='1.0'?><!-- {0} --><engine-database><![CDATA[{0}]]><?pi {0}?>\n{body}",
883 "<a>".repeat(100)
884 );
885 assert_eq!(parse(&hidden).unwrap().value.engines.len(), 1);
886 }
887
888 #[test]
889 fn reads_the_observed_layout() {
890 let parsed = parse(SAMPLE).unwrap();
891 let engine = &parsed.value.engines[0];
892 assert_eq!(engine.manufacturer, " Aerotech");
893 assert_eq!(engine.code, "H128W");
894 assert_eq!(engine.motor_type.as_deref(), Some("reloadable"));
895 assert_eq!(engine.diameter_mm, 29.0);
896 assert_eq!(engine.initial_mass_g, 196.6);
897 assert_eq!(engine.auto_calc_mass, Some(true));
898 assert_eq!(engine.exit_diameter_mm, Some(0.0));
899 assert_eq!(
900 engine.comments.as_deref(),
901 Some("Line one & two\nraw & data")
902 );
903 assert_eq!(engine.points.len(), 5);
904 assert_eq!(engine.points[1].mass_g, Some(89.1));
905 assert_eq!(engine.points[4].cg_mm, Some(97.0));
906 assert_eq!(
907 engine.delays().delays,
908 [
909 Delay::Seconds(6.0),
910 Delay::Seconds(10.0),
911 Delay::Seconds(14.0)
912 ]
913 );
914 let curve = engine.thrust_curve().unwrap();
915 assert_eq!(curve.times_s()[3], 0.1);
916 assert_eq!(parsed.warnings.len(), 1, "{:?}", parsed.warnings);
918 assert_eq!(parsed.warnings[0].line, 3);
919 }
920
921 #[test]
922 fn reads_the_guides_names_and_nested_engines() {
923 let text = r#"<engine code="A1" mfg="X" type="single-use" dia="18" len="70" initMass="16"
924 propMass="3"><data><point t="0.1" f="2"/><point t="0.5" f="0"/></data></engine>"#;
925 let parsed = parse(text).unwrap();
926 let engine = &parsed.value.engines[0];
927 assert_eq!(engine.motor_type.as_deref(), Some("single-use"));
928 assert_eq!(engine.initial_mass_g, 16.0);
929 assert_eq!(engine.propellant_mass_g, 3.0);
930 assert_eq!(engine.points[0].mass_g, None);
931 assert!(parsed.warnings.is_empty(), "{:?}", parsed.warnings);
932 }
933
934 #[test]
935 fn rejects_malformed_files() {
936 let engine = |attrs: &str, points: &str| {
937 format!(
938 r#"<engine-database><engine-list><engine {attrs}><data>{points}</data></engine></engine-list></engine-database>"#
939 )
940 };
941 let good_attrs = r#"code="A" mfg="X" dia="18" len="70" initWt="16" propWt="3""#;
942 let good_points =
943 r#"<eng-data t="0" f="0"/><eng-data t="0.1" f="2"/><eng-data t="0.5" f="0"/>"#;
944 assert!(parse(&engine(good_attrs, good_points)).is_ok());
945 let bad = [
946 "".to_owned(),
947 "<engine-database/>".to_owned(),
948 "<engine code=\"A\"".to_owned(),
949 "<!DOCTYPE x [<!ENTITY e \"boom\">]><engine-database/>".to_owned(),
950 engine(
951 r#"mfg="X" dia="18" len="70" initWt="16" propWt="3""#,
952 good_points,
953 ),
954 engine(
955 r#"code="A" mfg="X" len="70" initWt="16" propWt="3""#,
956 good_points,
957 ),
958 engine(
959 r#"code="A" mfg="X" dia="0" len="70" initWt="16" propWt="3""#,
960 good_points,
961 ),
962 engine(
963 r#"code="A" mfg="X" dia="18" len="70" initWt="16" propWt="-3""#,
964 good_points,
965 ),
966 engine(
967 r#"code="A" mfg="X" dia="NaN" len="70" initWt="16" propWt="3""#,
968 good_points,
969 ),
970 engine(good_attrs, r#"<eng-data t="0" f="1"/>"#),
971 engine(good_attrs, r#"<eng-data t="0" f="1"/><eng-data t="0.1"/>"#),
972 engine(
973 good_attrs,
974 r#"<eng-data t="0.2" f="1"/><eng-data t="0.1" f="0"/>"#,
975 ),
976 engine(
977 good_attrs,
978 r#"<eng-data t="-0.1" f="1"/><eng-data t="0.1" f="0"/>"#,
979 ),
980 engine(
981 good_attrs,
982 r#"<eng-data t="0" f="inf"/><eng-data t="0.1" f="0"/>"#,
983 ),
984 ];
985 for text in &bad {
986 assert!(parse(text).is_err(), "{text}");
987 }
988 }
989
990 pub(crate) fn bits(file: &RseFile) -> Vec<Option<u64>> {
992 file.engines
993 .iter()
994 .flat_map(|e| {
995 [
996 Some(e.diameter_mm),
997 Some(e.length_mm),
998 Some(e.initial_mass_g),
999 Some(e.propellant_mass_g),
1000 e.average_thrust_n,
1001 e.peak_thrust_n,
1002 e.throat_diameter_mm,
1003 e.exit_diameter_mm,
1004 e.total_impulse_ns,
1005 e.burn_time_s,
1006 e.mass_fraction_pct,
1007 e.isp_s,
1008 ]
1009 .into_iter()
1010 .chain(
1011 e.points
1012 .iter()
1013 .flat_map(|p| [Some(p.time_s), Some(p.thrust_n), p.mass_g, p.cg_mm]),
1014 )
1015 .map(|value| value.map(f64::to_bits))
1016 .collect::<Vec<_>>()
1017 })
1018 .collect()
1019 }
1020
1021 #[test]
1022 fn comments_keep_only_their_text() {
1023 let text = r#"<engine code="A" mfg="X" dia="18" len="70" initWt="16" propWt="3">
1024<comments>keep<!-- editor note -->this<?pi x?><b>bold</b><b>a<i>b</i>c</b></comments>
1025<comments>second</comments>
1026<data><eng-data t="0" f="0"/><eng-data t="0.2" f="2"/><eng-data t="0.3" f="0"/></data>
1027<data><eng-data t="0" f="0"/><eng-data t="0.2" f="3"/><eng-data t="0.3" f="0"/></data>
1028<comments><engine code="B" mfg="X" dia="18" len="70" initWt="16" propWt="3"><data>
1029<eng-data t="0" f="0"/><eng-data t="0.2" f="2"/></data></engine></comments>
1030</engine>"#;
1031 let parsed = parse(text).unwrap();
1032 assert_eq!(
1033 parsed.value.engines.len(),
1034 1,
1035 "the nested engine is not read"
1036 );
1037 let engine = &parsed.value.engines[0];
1038 assert_eq!(engine.comments.as_deref(), Some("\n"));
1040 assert_eq!(engine.points[1].thrust_n, 3.0);
1041 let dropped: Vec<usize> = parsed
1042 .warnings
1043 .iter()
1044 .filter(|w| w.kind == WarningKind::Dropped)
1045 .map(|w| w.line)
1046 .collect();
1047 assert_eq!(dropped, [3, 5, 6, 6], "{:?}", parsed.warnings);
1048 let single = r#"<engine code="A" mfg="X" dia="18" len="70" initWt="16" propWt="3">
1049<comments>keep<!-- editor note -->this<?pi x?><b>bold</b><b>a<i>b</i>c</b></comments>
1050<data><eng-data t="0" f="0"/><eng-data t="0.2" f="2"/><eng-data t="0.3" f="0"/></data></engine>"#;
1051 let engine = &parse(single).unwrap().value.engines[0];
1052 assert_eq!(engine.comments.as_deref(), Some("keepthisboldabc"));
1053 }
1054
1055 #[test]
1056 fn large_files_read_in_linear_time() {
1057 let points: String = (0..500)
1060 .map(|i| {
1061 format!(
1062 "<eng-data t=\"{}\" f=\"{}\" m=\"1\" cg=\"35\"/>\n",
1063 f64::from(i) * 0.01,
1064 if i == 499 { 0.0 } else { 10.0 }
1065 )
1066 })
1067 .collect();
1068 let engine = format!(
1069 "<engine code=\"A\" mfg=\"X\" dia=\"18\" len=\"70\" initWt=\"16\" propWt=\"3\">\n<data>\n{points}</data></engine>\n"
1070 );
1071 let text = format!(
1072 "<engine-database><engine-list>\n{}</engine-list></engine-database>",
1073 engine.repeat(200)
1074 );
1075 let parsed = parse(&text).unwrap();
1076 assert_eq!(parsed.value.engines.len(), 200);
1077 let last = text.lines().count();
1078 assert!(parsed.warnings.iter().all(|w| w.line <= last));
1079 }
1080
1081 #[test]
1082 fn a_broken_engine_is_skipped_with_a_warning() {
1083 let text = r#"<engine-database><engine-list>
1084<engine code="A" mfg="X" dia="18" len="70" initWt="16" propWt="3"><data>
1085 <eng-data t="0" f="0"/><eng-data t="0.2" f="2"/><eng-data t="0.1" f="0"/></data></engine>
1086<engine code="B" mfg="X" dia="18" len="70" initWt="16" propWt="3"><data>
1087 <eng-data t="0" f="0"/><eng-data t="0.2" f="2"/><eng-data t="0.3" f="0"/></data></engine>
1088</engine-list></engine-database>"#;
1089 let parsed = parse(text).unwrap();
1090 assert_eq!(parsed.value.engines.len(), 1);
1091 assert_eq!(parsed.value.engines[0].code, "B");
1092 assert_eq!(parsed.warnings.len(), 1);
1093 assert_eq!(parsed.warnings[0].line, 3);
1094 assert_eq!(parsed.warnings[0].kind, WarningKind::Skipped);
1095 }
1096
1097 #[test]
1098 fn partial_mass_columns_are_dropped_with_a_warning() {
1099 let text = r#"<engine code="A" mfg="X" dia="18" len="70" initWt="16" propWt="3"><data>
1100 <eng-data t="0" f="0" m="3"/><eng-data t="0.1" f="2"/><eng-data t="0.5" f="0" m="0"/>
1101 </data></engine>"#;
1102 let parsed = parse(text).unwrap();
1103 assert!(
1104 parsed.value.engines[0]
1105 .points
1106 .iter()
1107 .all(|p| p.mass_g.is_none())
1108 );
1109 assert_eq!(parsed.warnings.len(), 1);
1110 }
1111
1112 #[test]
1113 fn a_hybrid_is_read_with_a_warning() {
1114 let hybrid = |kind: &str| {
1115 format!(
1116 r#"<engine code="H" mfg="X" Type="{kind}" dia="38" len="300" initWt="900" propWt="200"><data>
1117 <eng-data t="0" f="0"/><eng-data t="0.5" f="200"/><eng-data t="1" f="0"/>
1118 </data></engine>"#
1119 )
1120 };
1121 let parsed = parse(&hybrid(" Hybrid")).unwrap();
1122 assert_eq!(parsed.value.engines.len(), 1);
1123 assert!(matches!(
1124 parsed.warnings.as_slice(),
1125 [w] if w.kind == WarningKind::Unusual && w.message.contains("hybrid")
1126 ));
1127 assert!(parse(&hybrid("reloadable")).unwrap().warnings.is_empty());
1128 }
1129
1130 #[test]
1131 fn writes_what_it_reads() {
1132 let file = parse(SAMPLE).unwrap().value;
1133 let text = write(&file).unwrap();
1134 assert_eq!(parse(&text).unwrap().value, file);
1135 assert_eq!(write(&parse(&text).unwrap().value).unwrap(), text);
1136 }
1137
1138 #[test]
1142 fn the_first_line_names_the_program() {
1143 let file = parse(SAMPLE).unwrap().value;
1144 let text = write(&file).unwrap();
1145 let first = format!(
1146 "<!-- FusionSpace HPR {} · FS-ACHERNAR · SW · TOOL 001 -->\n<engine-database>\n",
1147 env!("CARGO_PKG_VERSION")
1148 );
1149 assert!(text.starts_with(&first), "{text}");
1150 assert!(text.contains(&hpr_core::tool::stamp()));
1151 let read = parse(&text).unwrap();
1152 let messages = |warnings: &[ParseWarning]| {
1154 warnings
1155 .iter()
1156 .map(|w| (w.kind, w.message.clone()))
1157 .collect::<Vec<_>>()
1158 };
1159 assert_eq!(
1160 messages(&read.warnings),
1161 messages(&parse(SAMPLE).unwrap().warnings)
1162 );
1163 assert_eq!(read.value, file);
1164 let again = write(&read.value).unwrap();
1165 assert_eq!(again, text);
1166 assert_eq!(again.matches("TOOL 001").count(), 1);
1167 assert!(!again.contains("TOOL 005"));
1168 for designation in ["FS · SW · TOOL 005", "FS-ACHERNAR · SW · TOOL 001"] {
1172 let old = text.replace(
1173 &hpr_core::tool::stamp(),
1174 &format!("hpr-sim {} · {designation}", env!("CARGO_PKG_VERSION")),
1175 );
1176 assert_ne!(old, text);
1177 assert_eq!(parse(&old).unwrap().value, file);
1178 assert_eq!(write(&parse(&old).unwrap().value).unwrap(), text);
1179 }
1180 }
1181
1182 #[test]
1184 fn stamp_is_a_comment_xml_can_hold() {
1185 let stamp = hpr_core::tool::stamp();
1186 assert!(!stamp.contains("--") && !stamp.ends_with('-'), "{stamp}");
1187 }
1188
1189 #[test]
1190 fn writer_refuses_what_it_cannot_represent() {
1191 let mut engine = parse(SAMPLE).unwrap().value.engines[0].clone();
1192 engine.points[1].mass_g = None;
1193 assert!(
1194 write(&RseFile {
1195 engines: vec![engine.clone()]
1196 })
1197 .is_err()
1198 );
1199 engine.points.iter_mut().for_each(|p| p.mass_g = None);
1200 assert!(
1201 write(&RseFile {
1202 engines: vec![engine.clone()]
1203 })
1204 .is_ok()
1205 );
1206 engine.code = "bell\u{7}".into();
1207 assert!(
1208 write(&RseFile {
1209 engines: vec![engine.clone()]
1210 })
1211 .is_err()
1212 );
1213 engine.code = "A".into();
1214 engine.points.truncate(1);
1215 assert!(
1216 write(&RseFile {
1217 engines: vec![engine]
1218 })
1219 .is_err()
1220 );
1221 assert!(write(&RseFile { engines: vec![] }).is_err());
1222 }
1223
1224 fn text(max: usize) -> impl Strategy<Value = String> {
1225 prop::collection::vec(
1226 prop_oneof![
1227 Just('&'),
1228 Just('<'),
1229 Just('>'),
1230 Just('"'),
1231 Just('\''),
1232 Just('\t'),
1233 Just('\n'),
1234 Just('\r'),
1235 Just(' '),
1236 Just('é'),
1237 Just(']'),
1238 proptest::char::range('a', 'z'),
1239 ],
1240 0..max,
1241 )
1242 .prop_map(|chars| chars.into_iter().collect())
1243 }
1244
1245 fn engines() -> impl Strategy<Value = RseEngine> {
1246 let number = || prop_oneof![Just(-0.0), -1e6..1e6f64];
1247 let option = move || prop::option::of(number());
1248 (
1249 (
1250 text(12),
1251 text(12),
1252 prop::option::of(text(8)),
1253 prop::option::of(text(8)),
1254 ),
1255 (1e-3..1e4f64, 1e-3..1e5f64, 0.0..1e5f64, 0.0..1e5f64),
1256 (
1257 prop::option::of(any::<bool>()),
1258 prop::option::of(any::<bool>()),
1259 ),
1260 (
1261 option(),
1262 option(),
1263 option(),
1264 option(),
1265 option(),
1266 option(),
1267 option(),
1268 option(),
1269 ),
1270 prop::option::of(text(40)),
1271 (any::<bool>(), any::<bool>()),
1272 prop::collection::vec((0.0..10.0f64, 0.0..1e5f64, number(), number()), 2..20),
1273 )
1274 .prop_map(
1275 |(strings, envelope, flags, summary, comments, columns, mut samples)| {
1276 samples.sort_by(|a, b| a.0.total_cmp(&b.0));
1277 if cut_off(samples.iter().map(|s| s.1)).is_some()
1280 && let Some(last) = samples.last_mut()
1281 {
1282 last.1 = 0.0;
1283 }
1284 RseEngine {
1285 manufacturer: strings.0,
1286 code: strings.1,
1287 motor_type: strings.2,
1288 delays: strings.3,
1289 diameter_mm: envelope.0,
1290 length_mm: envelope.1,
1291 initial_mass_g: envelope.2,
1292 propellant_mass_g: envelope.3,
1293 auto_calc_mass: flags.0,
1294 auto_calc_cg: flags.1,
1295 average_thrust_n: summary.0,
1296 peak_thrust_n: summary.1,
1297 throat_diameter_mm: summary.2,
1298 exit_diameter_mm: summary.3,
1299 total_impulse_ns: summary.4,
1300 burn_time_s: summary.5,
1301 mass_fraction_pct: summary.6,
1302 isp_s: summary.7,
1303 comments,
1304 points: samples
1305 .into_iter()
1306 .map(|(t, f, m, cg)| RsePoint {
1307 time_s: t,
1308 thrust_n: f,
1309 mass_g: columns.0.then_some(m),
1310 cg_mm: columns.1.then_some(cg),
1311 })
1312 .collect(),
1313 }
1314 },
1315 )
1316 }
1317
1318 proptest! {
1319 #[test]
1320 fn write_parse_round_trips_bit_for_bit(engines in prop::collection::vec(engines(), 1..4)) {
1321 let file = RseFile { engines };
1322 let written = write(&file).unwrap();
1323 let back = parse(&written).unwrap().value;
1324 prop_assert_eq!(&back, &file);
1325 prop_assert_eq!(bits(&back), bits(&file));
1326 }
1327 }
1328
1329 #[test]
1332 fn a_curve_cut_off_above_half_its_peak_is_refused() {
1333 let engine = |end: f64| {
1334 format!(
1335 r#"<engine-database><engine-list>
1336<engine code="G84" mfg="X" dia="24" len="228" initWt="172" propWt="77"><data>
1337 <eng-data t="0" f="0"/><eng-data t="0.1" f="100"/><eng-data t="0.4" f="{end}"/></data></engine>
1338</engine-list></engine-database>"#
1339 )
1340 };
1341 let Err(MotorError::Syntax { line, message, .. }) = parse(&engine(60.0)) else {
1342 panic!("a cut curve was read");
1343 };
1344 assert_eq!(line, 2);
1345 assert!(
1346 message.contains("ends at 60 N, above half its peak thrust of 100 N"),
1347 "{message}"
1348 );
1349 let parsed = parse(&engine(10.0)).unwrap();
1350 assert_eq!(parsed.value.engines.len(), 1);
1351 assert!(
1352 parsed
1353 .warnings
1354 .iter()
1355 .any(|w| w.kind == WarningKind::Unusual
1356 && w.message.contains("ends at 10 N, not zero")),
1357 "{:?}",
1358 parsed.warnings
1359 );
1360 let mut file = parsed.value;
1361 file.engines[0].points[2].thrust_n = 60.0;
1362 let Err(MotorError::Inconsistent(message)) = write(&file) else {
1363 panic!("a cut curve was written");
1364 };
1365 assert!(message.contains("ends at 60 N"), "{message}");
1366 }
1367}