1use crate::types::ParameterValue;
30use heapless::{String, Vec};
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum LaunchTextError {
35 EmptyList,
41 MixedList,
44 DoesNotFit,
47 Malformed,
49}
50
51#[derive(Clone, Copy, PartialEq, Eq)]
52enum Kind {
53 Bool,
54 Integer,
55 Double,
56 String,
57}
58
59fn boolean(t: &str) -> Option<bool> {
60 match t {
61 "true" | "True" | "TRUE" => Some(true),
62 "false" | "False" | "FALSE" => Some(false),
63 _ => None,
64 }
65}
66
67fn kind_of_unquoted(t: &str) -> Kind {
68 if boolean(t).is_some() {
69 Kind::Bool
70 } else if t.parse::<i64>().is_ok() {
71 Kind::Integer
72 } else if t.parse::<f64>().is_ok() {
73 Kind::Double
74 } else {
75 Kind::String
76 }
77}
78
79#[derive(Clone, Copy)]
81enum Element<'a> {
82 Plain(&'a str),
84 Single(&'a str),
86 Double(&'a str),
88}
89
90impl Element<'_> {
91 fn kind(self) -> Kind {
92 match self {
93 Element::Plain(t) => kind_of_unquoted(t),
94 Element::Single(_) | Element::Double(_) => Kind::String,
95 }
96 }
97}
98
99fn for_each_element<'a>(
102 inner: &'a str,
103 mut f: impl FnMut(Element<'a>) -> Result<(), LaunchTextError>,
104) -> Result<usize, LaunchTextError> {
105 let bytes = inner.as_bytes();
106 let mut i = 0;
107 let mut n = 0;
108 let skip_ws = |i: &mut usize| {
109 while *i < bytes.len() && bytes[*i].is_ascii_whitespace() {
110 *i += 1;
111 }
112 };
113 skip_ws(&mut i);
114 if i == bytes.len() {
115 return Ok(0);
116 }
117 loop {
118 skip_ws(&mut i);
119 let element = match bytes.get(i) {
120 Some(b'\'') => {
121 let start = i + 1;
122 let mut j = start;
123 loop {
124 match bytes.get(j) {
125 None => return Err(LaunchTextError::Malformed),
126 Some(b'\'') if bytes.get(j + 1) == Some(&b'\'') => j += 2,
127 Some(b'\'') => break,
128 Some(_) => j += 1,
129 }
130 }
131 i = j + 1;
132 Element::Single(&inner[start..j])
133 }
134 Some(b'"') => {
135 let start = i + 1;
136 let mut j = start;
137 loop {
138 match bytes.get(j) {
139 None => return Err(LaunchTextError::Malformed),
140 Some(b'\\') => j += 2,
141 Some(b'"') => break,
142 Some(_) => j += 1,
143 }
144 }
145 i = j + 1;
146 Element::Double(&inner[start..j])
147 }
148 _ => {
149 let start = i;
150 while i < bytes.len() && bytes[i] != b',' {
151 i += 1;
152 }
153 Element::Plain(inner[start..i].trim())
154 }
155 };
156 f(element)?;
157 n += 1;
158 skip_ws(&mut i);
159 match bytes.get(i) {
160 None => return Ok(n),
161 Some(b',') => {
162 i += 1;
163 skip_ws(&mut i);
165 if i == bytes.len() {
166 return Ok(n);
167 }
168 }
169 Some(_) => return Err(LaunchTextError::Malformed),
170 }
171 }
172}
173
174fn push_single_quoted<const N: usize>(out: &mut String<N>, body: &str) -> bool {
176 let mut rest = body;
177 while let Some(at) = rest.find("''") {
178 if out.push_str(&rest[..=at]).is_err() {
179 return false;
180 }
181 rest = &rest[at + 2..];
182 }
183 out.push_str(rest).is_ok()
184}
185
186fn list_body(text: &str) -> Option<&str> {
187 text.strip_prefix('[')?.strip_suffix(']')
188}
189
190fn single_quoted_body(text: &str) -> Option<&str> {
191 let body = text.strip_prefix('\'')?.strip_suffix('\'')?;
192 let mut rest = body;
194 while let Some(at) = rest.find('\'') {
195 if rest.as_bytes().get(at + 1) != Some(&b'\'') {
196 return None;
197 }
198 rest = &rest[at + 2..];
199 }
200 Some(body)
201}
202
203fn list_kind(inner: &str) -> Result<(Kind, usize), LaunchTextError> {
207 let mut kind: Option<Kind> = None;
208 let n = for_each_element(inner, |e| {
209 let k = e.kind();
210 match kind {
211 None => kind = Some(k),
212 Some(seen) if seen != k => return Err(LaunchTextError::MixedList),
213 Some(_) => {}
214 }
215 Ok(())
216 })?;
217 match kind {
218 Some(kind) => Ok((kind, n)),
219 None => Err(LaunchTextError::EmptyList),
220 }
221}
222
223#[derive(Debug, Clone, Copy, PartialEq, Eq)]
225pub enum LaunchTextType {
226 Bool,
227 Integer,
228 Double,
229 String,
230 BoolArray,
231 IntegerArray,
232 DoubleArray,
233 StringArray,
234}
235
236pub fn launch_text_extent(text: &str) -> Result<(usize, usize), LaunchTextError> {
254 let text = text.trim();
255 let Some(inner) = list_body(text) else {
256 let longest = match launch_text_type(text)? {
257 LaunchTextType::String => single_quoted_body(text).unwrap_or(text).len(),
258 _ => 0,
259 };
260 return Ok((1, longest));
261 };
262 let mut longest = 0;
263 let n = for_each_element(inner, |e| {
264 if let Element::Plain(t) | Element::Single(t) | Element::Double(t) = e
265 && e.kind() == Kind::String
266 {
267 longest = longest.max(t.len());
268 }
269 Ok(())
270 })?;
271 Ok((n, longest))
272}
273
274pub fn launch_text_type(text: &str) -> Result<LaunchTextType, LaunchTextError> {
275 if let Some(inner) = list_body(text.trim()) {
276 let (kind, _) = list_kind(inner)?;
277 return Ok(match kind {
278 Kind::Bool => LaunchTextType::BoolArray,
279 Kind::Integer => LaunchTextType::IntegerArray,
280 Kind::Double => LaunchTextType::DoubleArray,
281 Kind::String => LaunchTextType::StringArray,
282 });
283 }
284 if single_quoted_body(text).is_some() {
285 return Ok(LaunchTextType::String);
286 }
287 Ok(match kind_of_unquoted(text) {
288 Kind::Bool => LaunchTextType::Bool,
289 Kind::Integer => LaunchTextType::Integer,
290 Kind::Double => LaunchTextType::Double,
291 Kind::String => LaunchTextType::String,
292 })
293}
294
295impl ParameterValue {
296 pub fn assign_launch_text(&mut self, text: &str) -> Result<(), LaunchTextError> {
303 if let Some(inner) = list_body(text.trim()) {
304 return self.assign_flow_list(inner);
305 }
306 if let Some(body) = single_quoted_body(text) {
307 if !matches!(self, Self::String(_)) {
308 *self = Self::String(String::new());
309 }
310 return match self {
311 Self::String(s) => {
312 s.clear();
313 if push_single_quoted(s, body) {
314 Ok(())
315 } else {
316 Err(LaunchTextError::DoesNotFit)
317 }
318 }
319 _ => Err(LaunchTextError::DoesNotFit),
320 };
321 }
322 if let Some(b) = boolean(text) {
323 *self = Self::Bool(b);
324 } else if let Ok(i) = text.parse::<i64>() {
325 *self = Self::Integer(i);
326 } else if let Ok(d) = text.parse::<f64>() {
327 *self = Self::Double(d);
328 } else if !self.assign_string(text) {
329 return Err(LaunchTextError::DoesNotFit);
330 }
331 Ok(())
332 }
333
334 fn assign_flow_list(&mut self, inner: &str) -> Result<(), LaunchTextError> {
335 let (kind, n) = list_kind(inner)?;
337 let cap = if kind == Kind::String {
339 crate::types::MAX_STRING_ARRAY_LEN
340 } else {
341 crate::types::MAX_ARRAY_LEN
342 };
343 if n > cap {
344 return Err(LaunchTextError::DoesNotFit);
345 }
346 *self = match kind {
348 Kind::Bool => Self::BoolArray(Vec::new()),
349 Kind::Integer => Self::IntegerArray(Vec::new()),
350 Kind::Double => Self::DoubleArray(Vec::new()),
351 Kind::String => Self::StringArray(Vec::new()),
352 };
353 let full = LaunchTextError::DoesNotFit;
354 for_each_element(inner, |e| {
355 let pushed = match (&mut *self, e) {
356 (Self::BoolArray(v), Element::Plain(t)) => {
357 v.push(boolean(t).unwrap_or(false)).is_ok()
358 }
359 (Self::IntegerArray(v), Element::Plain(t)) => {
360 v.push(t.parse::<i64>().unwrap_or(0)).is_ok()
361 }
362 (Self::DoubleArray(v), Element::Plain(t)) => {
363 v.push(t.parse::<f64>().unwrap_or(0.0)).is_ok()
364 }
365 (Self::StringArray(v), e) => {
366 let mut s = String::new();
367 let ok = match e {
368 Element::Plain(t) | Element::Double(t) => s.push_str(t).is_ok(),
369 Element::Single(t) => push_single_quoted(&mut s, t),
370 };
371 ok && v.push(s).is_ok()
372 }
373 _ => false,
374 };
375 if pushed { Ok(()) } else { Err(full) }
376 })?;
377 Ok(())
378 }
379}
380
381#[cfg(test)]
382mod tests {
383
384 #[test]
387 fn a_seeds_extent_is_its_element_count_and_longest_string() {
388 assert_eq!(launch_text_extent("[left, '5', 'a, b']"), Ok((3, 4)));
389 assert_eq!(launch_text_extent("[40.0, 50.0, 60.0]"), Ok((3, 0)));
390 assert_eq!(launch_text_extent("[true, false]"), Ok((2, 0)));
391 assert_eq!(launch_text_extent("hello"), Ok((1, 5)));
392 assert_eq!(launch_text_extent("'quoted'"), Ok((1, 6)));
393 assert_eq!(launch_text_extent("250"), Ok((1, 0)));
394 }
395
396 use super::*;
397
398 fn read(text: &str) -> Result<ParameterValue, LaunchTextError> {
399 let mut v = ParameterValue::NotSet;
400 v.assign_launch_text(text).map(|()| v)
401 }
402
403 #[test]
406 fn the_type_reader_agrees_with_the_value_reader() {
407 let corpus = [
408 "true",
409 "FALSE",
410 "42",
411 "-7",
412 "1.0",
413 "1e3",
414 "hello",
415 "",
416 "40.0,50.0",
417 "'1.0'",
418 "'[a]'",
419 "'it''s'",
420 "''",
421 "'a' 'b'",
422 "[true, false]",
423 "[1, 2, 3]",
424 "[1.5, 2.5]",
425 "[a, b]",
426 "['x', y]",
427 "[1, 2.5]",
428 "[]",
429 "[1, a]",
430 "['broken]",
431 " [1, 2] ",
432 ];
433 for text in corpus {
434 let ty = launch_text_type(text);
435 match read(text) {
436 Ok(v) => {
437 let want = match v {
438 ParameterValue::Bool(_) => LaunchTextType::Bool,
439 ParameterValue::Integer(_) => LaunchTextType::Integer,
440 ParameterValue::Double(_) => LaunchTextType::Double,
441 ParameterValue::String(_) => LaunchTextType::String,
442 ParameterValue::BoolArray(_) => LaunchTextType::BoolArray,
443 ParameterValue::IntegerArray(_) => LaunchTextType::IntegerArray,
444 ParameterValue::DoubleArray(_) => LaunchTextType::DoubleArray,
445 ParameterValue::StringArray(_) => LaunchTextType::StringArray,
446 other => panic!("{text:?}: unexpected {other:?}"),
447 };
448 assert_eq!(ty, Ok(want), "{text:?}");
449 }
450 Err(LaunchTextError::DoesNotFit) => {
451 assert!(ty.is_ok(), "{text:?}: a capacity is not a type error")
452 }
453 Err(e) => assert_eq!(ty, Err(e), "{text:?}"),
454 }
455 }
456 extern crate std;
458 let long = std::format!("[{}]", std::vec!["1"; 4096].join(", "));
459 assert_eq!(launch_text_type(&long), Ok(LaunchTextType::IntegerArray));
460 }
461
462 #[test]
463 fn scalars_keep_the_inference_they_had() {
464 assert!(matches!(read("true"), Ok(ParameterValue::Bool(true))));
465 assert!(matches!(read("FALSE"), Ok(ParameterValue::Bool(false))));
466 assert!(matches!(read("42"), Ok(ParameterValue::Integer(42))));
467 assert!(matches!(read("1.0"), Ok(ParameterValue::Double(d)) if d == 1.0));
468 assert!(matches!(read("hello"), Ok(ParameterValue::String(s)) if s == "hello"));
469 assert!(matches!(read(""), Ok(ParameterValue::String(s)) if s.is_empty()));
470 assert!(matches!(read("40.0,50.0"), Ok(ParameterValue::String(s)) if s == "40.0,50.0"));
472 }
473
474 #[test]
475 fn a_quoted_text_is_a_string() {
476 assert!(matches!(read("'1.0'"), Ok(ParameterValue::String(s)) if s == "1.0"));
477 assert!(matches!(read("'[a]'"), Ok(ParameterValue::String(s)) if s == "[a]"));
478 assert!(matches!(read("'it''s'"), Ok(ParameterValue::String(s)) if s == "it's"));
479 assert!(matches!(read("''"), Ok(ParameterValue::String(s)) if s.is_empty()));
480 assert!(matches!(read("'a' 'b'"), Ok(ParameterValue::String(s)) if s == "'a' 'b'"));
482 }
483
484 #[test]
485 fn a_double_list_is_a_double_array() {
486 match read("[40.0, 50.0, 60.0]") {
487 Ok(ParameterValue::DoubleArray(v)) => assert_eq!(v.as_slice(), &[40.0, 50.0, 60.0]),
488 other => panic!("{other:?}"),
489 }
490 match read("[1.5]") {
491 Ok(ParameterValue::DoubleArray(v)) => assert_eq!(v.as_slice(), &[1.5]),
492 other => panic!("one element is still a list: {other:?}"),
493 }
494 }
495
496 #[test]
497 fn integer_bool_and_string_lists() {
498 match read("[1, -2, 3]") {
499 Ok(ParameterValue::IntegerArray(v)) => assert_eq!(v.as_slice(), &[1, -2, 3]),
500 other => panic!("{other:?}"),
501 }
502 match read("[true, False]") {
503 Ok(ParameterValue::BoolArray(v)) => assert_eq!(v.as_slice(), &[true, false]),
504 other => panic!("{other:?}"),
505 }
506 match read("[a, '5', 'x, y', 'it''s', \"q\"]") {
507 Ok(ParameterValue::StringArray(v)) => {
508 let got: std::vec::Vec<&str> = v.iter().map(|s| s.as_str()).collect();
509 assert_eq!(got, ["a", "5", "x, y", "it's", "q"]);
510 }
511 other => panic!("{other:?}"),
512 }
513 }
514
515 #[test]
516 fn empty_and_mixed_lists_have_no_value() {
517 assert_eq!(read("[]").unwrap_err(), LaunchTextError::EmptyList);
518 assert_eq!(read("[ ]").unwrap_err(), LaunchTextError::EmptyList);
519 assert_eq!(read("[1, 2.5]").unwrap_err(), LaunchTextError::MixedList);
520 assert_eq!(read("[1, a]").unwrap_err(), LaunchTextError::MixedList);
521 assert_eq!(read("['1', 1]").unwrap_err(), LaunchTextError::MixedList);
522 match read("[a, b,]") {
523 Ok(ParameterValue::StringArray(v)) => assert_eq!(v.len(), 2),
524 other => panic!("a trailing comma adds no element: {other:?}"),
525 }
526 assert_eq!(read("['a]").unwrap_err(), LaunchTextError::Malformed);
527 assert_eq!(read("['a' b]").unwrap_err(), LaunchTextError::Malformed);
528 }
529
530 #[test]
531 fn a_list_past_the_capacity_is_refused_not_cut() {
532 let mut t = std::string::String::from("[");
533 for i in 0..=crate::types::MAX_ARRAY_LEN {
534 if i > 0 {
535 t.push_str(", ");
536 }
537 t.push('1');
538 }
539 t.push(']');
540 assert_eq!(read(&t).unwrap_err(), LaunchTextError::DoesNotFit);
541 }
542}