Skip to main content

hpr_motor/
delay.rs

1//! Ejection delays: the time from burnout to the ejection charge, or none for a plugged motor.
2//!
3//! Motor files and catalogs write a motor's available delays as one string. The RASP spec gives
4//! "delays separated by dashes", with `0` for an ejection charge with no delay and `P` for plugged
5//! (`docs/format/eng.md`). Real files also use commas, a trailing `P`, and `100` or `1000` as
6//! plugged markers; checked against ThrustCurve.org's metadata, `100` and `1000` nearly always mean
7//! plugged, and so does `0` more often than not (counts in `docs/format/eng.md` and `rse.md`). So
8//! this reader:
9//!
10//! - splits on `-` and `,`, dropping empty pieces with a warning;
11//! - reads `P` (either case), `100` and `1000` as [`Delay::Plugged`];
12//! - reads `0` as [`Delay::ZeroOrPlugged`], with a warning, so that it can't become an ejection at
13//!   burnout without a decision;
14//! - reads other numbers as [`Delay::Seconds`].
15//!
16//! The raw string stays in the file model so writers reproduce it exactly; physics should prefer
17//! the catalog's delays.
18
19use serde::{Deserialize, Serialize};
20
21use crate::text::{NOTHING_DEPENDS, WarningKind};
22
23/// How a flight reads a listed delay of 0, and how to choose (#952): a motor file's delays are
24/// never flown. `hpr::Motor::from_eng`, `from_rse` and `from_catalog` leave the delay unset, and
25/// `hpr sim --motor` flies it so unless `--delay` sets it, so no motor charge fires, as for a
26/// plugged motor: `hpr::ork::recovery` deploys no device on an ejection charge it doesn't have,
27/// and a flight refuses a device set to fire on one (`hpr_sim::Trigger::MotorDelay`). A delay of
28/// 0 s (`hpr sim --delay 0`, `Motor::with_delay_s(0.0)`, Python's `delay_s=0`) fires the charge
29/// at burnout.
30pub(crate) const ZERO_FLOWN: &str = "A motor file's delays aren't flown: with none chosen, no \
31                                    motor charge fires, as if plugged. For a charge at burnout, \
32                                    choose a delay of 0 (`hpr sim --delay 0`, or `delay_s=0` in \
33                                    Python)";
34
35/// One available delay setting. Serialized with a `kind` tag and the seconds as `value`:
36/// `{"kind":"seconds","value":6.0}`, `{"kind":"plugged"}`.
37// Read back by hand, from exactly those objects ([`DelayVisitor`]).
38#[derive(Debug, Clone, Copy, PartialEq, Serialize, schemars::JsonSchema)]
39#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
40#[non_exhaustive]
41#[serde(deny_unknown_fields)]
42pub enum Delay {
43    /// The ejection charge fires this many seconds after burnout: positive, or zero where a file
44    /// says so plainly, as a `.ork` does for a charge at burnout (`hpr_io::ork`).
45    Seconds(f64),
46    /// No ejection charge: the forward closure is plugged.
47    Plugged,
48    /// A `0`: the RASP spec means an ejection charge at burnout, but most files mean plugged
49    /// (`docs/format/eng.md`). The user or the catalog has to settle which.
50    ZeroOrPlugged,
51}
52
53impl<'de> Deserialize<'de> for Delay {
54    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
55        deserializer.deserialize_map(DelayVisitor)
56    }
57}
58
59/// Reads a [`Delay`] from exactly the objects its JSON Schema takes: a `value` beside `plugged` or
60/// `zero_or_plugged`, even `null`, is refused, as is a `[kind, value]` array. serde's derived
61/// reader for an adjacently tagged enum takes both.
62struct DelayVisitor;
63
64impl<'de> serde::de::Visitor<'de> for DelayVisitor {
65    type Value = Delay;
66
67    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
68        formatter.write_str("a delay: an object with a \"kind\", and a \"value\" for \"seconds\"")
69    }
70
71    fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Delay, A::Error> {
72        use serde::de::Error;
73        #[derive(Deserialize)]
74        #[serde(rename_all = "snake_case")]
75        enum Key {
76            Kind,
77            Value,
78        }
79        #[derive(Deserialize)]
80        #[serde(rename_all = "snake_case")]
81        enum Kind {
82            Seconds,
83            Plugged,
84            ZeroOrPlugged,
85        }
86        // The value can come before the kind, so it is read as a number or `null` and judged once
87        // both are in: `Some(None)` is a `"value": null`.
88        let (mut kind, mut value): (Option<Kind>, Option<Option<f64>>) = (None, None);
89        while let Some(key) = map.next_key::<Key>()? {
90            match key {
91                Key::Kind if kind.is_some() => return Err(A::Error::duplicate_field("kind")),
92                Key::Kind => kind = Some(map.next_value()?),
93                Key::Value if value.is_some() => return Err(A::Error::duplicate_field("value")),
94                Key::Value => value = Some(map.next_value()?),
95            }
96        }
97        match (kind, value) {
98            (None, _) => Err(A::Error::missing_field("kind")),
99            (Some(Kind::Seconds), Some(Some(seconds))) => Ok(Delay::Seconds(seconds)),
100            (Some(Kind::Seconds), Some(None)) => Err(A::Error::invalid_type(
101                serde::de::Unexpected::Unit,
102                &"the seconds, a number",
103            )),
104            (Some(Kind::Seconds), None) => Err(A::Error::missing_field("value")),
105            (Some(Kind::Plugged | Kind::ZeroOrPlugged), Some(_)) => Err(A::Error::custom(
106                "a \"value\" is given, which only a \"seconds\" delay has",
107            )),
108            (Some(Kind::Plugged), None) => Ok(Delay::Plugged),
109            (Some(Kind::ZeroOrPlugged), None) => Ok(Delay::ZeroOrPlugged),
110        }
111    }
112}
113
114/// A delay string read into settings.
115#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
116pub struct DelayList {
117    /// The settings in the order written (some files list them longest first).
118    pub delays: Vec<Delay>,
119    /// Problems found while reading: an empty or unreadable piece ([`WarningKind::Dropped`], and
120    /// left out of `delays`), or an ambiguous `0` ([`WarningKind::Unusual`], kept as
121    /// [`Delay::ZeroOrPlugged`]).
122    pub warnings: Vec<DelayWarning>,
123}
124
125/// A problem found while reading a delay string.
126#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
127pub struct DelayWarning {
128    /// Whether a piece was left out.
129    pub kind: WarningKind,
130    /// What was found.
131    pub message: String,
132}
133
134impl DelayList {
135    /// Reads a delay string such as `6-10-14`, `5,8,11`, `P`, `6-10-14-P` or `1000`. Any number
136    /// equal to 100 or 1000 (`1000.` too) is a plugged marker.
137    pub fn parse(raw: &str) -> Self {
138        let mut delays = Vec::new();
139        let mut warnings = Vec::new();
140        let trimmed = raw.trim();
141        if trimmed.is_empty() {
142            return Self { delays, warnings };
143        }
144        for piece in trimmed.split(['-', ',']) {
145            let piece = piece.trim();
146            match piece {
147                "" => warnings.push(DelayWarning {
148                    kind: WarningKind::Dropped,
149                    message: format!(
150                        "an empty delay in {raw:?} was left out, and {NOTHING_DEPENDS}"
151                    ),
152                }),
153                "P" | "p" => delays.push(Delay::Plugged),
154                _ => match piece.parse::<f64>() {
155                    Ok(marker) if marker == 100.0 || marker == 1000.0 => {
156                        delays.push(Delay::Plugged)
157                    }
158                    Ok(0.0) => {
159                        warnings.push(DelayWarning {
160                            kind: WarningKind::Unusual,
161                            message: format!(
162                                "delay 0 in {raw:?} is ambiguous: the RASP spec means an ejection \
163                                 charge at burnout, but files mostly mean plugged. {ZERO_FLOWN}"
164                            ),
165                        });
166                        delays.push(Delay::ZeroOrPlugged);
167                    }
168                    Ok(seconds) if seconds.is_finite() && seconds > 0.0 => {
169                        delays.push(Delay::Seconds(seconds));
170                    }
171                    _ => warnings.push(DelayWarning {
172                        kind: WarningKind::Dropped,
173                        message: format!(
174                            "unreadable delay {piece:?} in {raw:?} was left out, and \
175                             {NOTHING_DEPENDS}"
176                        ),
177                    }),
178                },
179            }
180        }
181        Self { delays, warnings }
182    }
183
184    /// Whether any setting is plugged ([`Delay::Plugged`]; an ambiguous `0` doesn't count).
185    pub fn has_plugged(&self) -> bool {
186        self.delays.contains(&Delay::Plugged)
187    }
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193
194    #[test]
195    fn plain_lists_and_markers() {
196        let list = DelayList::parse("6-10-14");
197        assert_eq!(
198            list.delays,
199            [
200                Delay::Seconds(6.0),
201                Delay::Seconds(10.0),
202                Delay::Seconds(14.0)
203            ]
204        );
205        assert!(list.warnings.is_empty());
206        assert_eq!(DelayList::parse("P").delays, [Delay::Plugged]);
207        assert_eq!(DelayList::parse("1000.").delays, [Delay::Plugged]);
208        assert_eq!(DelayList::parse("100.0").delays, [Delay::Plugged]);
209        assert_eq!(DelayList::parse(" p ").delays, [Delay::Plugged]);
210        assert_eq!(
211            DelayList::parse("10,14,1000").delays,
212            [Delay::Seconds(10.0), Delay::Seconds(14.0), Delay::Plugged]
213        );
214        assert!(DelayList::parse("").delays.is_empty());
215        assert!(!DelayList::parse("6").has_plugged());
216    }
217
218    #[test]
219    fn serde_form_is_tagged() {
220        let delays = [Delay::Seconds(6.0), Delay::Plugged, Delay::ZeroOrPlugged];
221        let json = serde_json::to_string(&delays).unwrap();
222        assert_eq!(
223            json,
224            r#"[{"kind":"seconds","value":6.0},{"kind":"plugged"},{"kind":"zero_or_plugged"}]"#
225        );
226        assert_eq!(serde_json::from_str::<Vec<Delay>>(&json).unwrap(), delays);
227        // The value may come first.
228        assert_eq!(
229            serde_json::from_str::<Delay>(r#"{"value":4.5,"kind":"seconds"}"#).unwrap(),
230            Delay::Seconds(4.5)
231        );
232    }
233
234    /// Only the objects the JSON Schema takes are read (issue #253): serde's derived reader took
235    /// `"value": null` beside a unit kind, and a `[kind, value]` array.
236    #[test]
237    fn serde_form_is_read_as_the_schema_says() {
238        let refused = |json: &str| serde_json::from_str::<Delay>(json).unwrap_err().to_string();
239        for json in [
240            r#"{"kind":"plugged","value":null}"#,
241            r#"{"kind":"zero_or_plugged","value":null}"#,
242            r#"{"value":3.0,"kind":"plugged"}"#,
243        ] {
244            assert!(
245                refused(json).contains("which only a \"seconds\" delay has"),
246                "{json}: {}",
247                refused(json)
248            );
249        }
250        assert!(refused(r#"{"kind":"seconds","value":null}"#).contains("the seconds, a number"));
251        assert!(refused(r#"{"kind":"seconds"}"#).contains("missing field `value`"));
252        assert!(refused(r#"{"value":3.0}"#).contains("missing field `kind`"));
253        assert!(
254            refused(r#"{"kind":"plugged","kind":"plugged"}"#).contains("duplicate field `kind`")
255        );
256        assert!(
257            refused(r#"{"kind":"seconds","value":1.0,"value":2.0}"#)
258                .contains("duplicate field `value`")
259        );
260        assert!(refused(r#"{"kind":"plugged","x":0}"#).contains("unknown variant `x`"));
261        assert!(refused(r#"{"kind":"later"}"#).contains("unknown variant `later`"));
262        assert!(refused(r#"["plugged"]"#).contains("invalid type: sequence"));
263        assert!(refused(r#"["seconds", 6.0]"#).contains("invalid type: sequence"));
264    }
265
266    /// A listed 0 reads as [`Delay::ZeroOrPlugged`], and its warning says how a flight takes it,
267    /// with no charge until a delay is chosen, and how to choose a charge at burnout (#952). The
268    /// `hpr` crate's tests pin that flight.
269    #[test]
270    fn a_delay_of_0_says_how_it_is_flown_and_how_to_choose() {
271        let list = DelayList::parse("0-6");
272        assert_eq!(list.delays, [Delay::ZeroOrPlugged, Delay::Seconds(6.0)]);
273        let [warning] = &list.warnings[..] else {
274            panic!("one warning: {:?}", list.warnings);
275        };
276        assert_eq!(warning.kind, WarningKind::Unusual);
277        assert_eq!(
278            warning.message,
279            "delay 0 in \"0-6\" is ambiguous: the RASP spec means an ejection charge at burnout, \
280             but files mostly mean plugged. A motor file's delays aren't flown: with none \
281             chosen, no motor charge fires, as if plugged. For a charge at burnout, choose a \
282             delay of 0 (`hpr sim --delay 0`, or `delay_s=0` in Python)"
283        );
284    }
285
286    #[test]
287    fn malformed_pieces_are_dropped_with_warnings() {
288        let list = DelayList::parse("4-7-10,");
289        assert_eq!(list.delays.len(), 3);
290        assert_eq!(list.warnings.len(), 1);
291        let list = DelayList::parse("1-3--4");
292        assert_eq!(list.delays.len(), 3);
293        assert_eq!(list.warnings.len(), 1);
294        let list = DelayList::parse("-");
295        assert!(list.delays.is_empty());
296        assert_eq!(list.warnings.len(), 2);
297        let list = DelayList::parse("S-M-L");
298        assert!(list.delays.is_empty());
299        assert_eq!(list.warnings.len(), 3);
300        let list = DelayList::parse("0");
301        assert_eq!(list.delays, [Delay::ZeroOrPlugged]);
302        assert!(!list.has_plugged());
303        assert_eq!(list.warnings.len(), 1);
304        assert_eq!(list.warnings[0].kind, WarningKind::Unusual);
305        assert_eq!(DelayList::parse("0.0-6").delays[0], Delay::ZeroOrPlugged);
306        assert_eq!(DelayList::parse("x").warnings[0].kind, WarningKind::Dropped);
307    }
308}