1use serde::{Deserialize, Serialize};
20
21use crate::text::{NOTHING_DEPENDS, WarningKind};
22
23pub(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#[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 Seconds(f64),
46 Plugged,
48 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
59struct 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 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
116pub struct DelayList {
117 pub delays: Vec<Delay>,
119 pub warnings: Vec<DelayWarning>,
123}
124
125#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
127pub struct DelayWarning {
128 pub kind: WarningKind,
130 pub message: String,
132}
133
134impl DelayList {
135 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 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 assert_eq!(
229 serde_json::from_str::<Delay>(r#"{"value":4.5,"kind":"seconds"}"#).unwrap(),
230 Delay::Seconds(4.5)
231 );
232 }
233
234 #[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 #[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}