1use std::borrow::Cow;
4
5use xtce_model::{
6 BooleanExpr, Calibrator, CompareOp, Comparison, ComparisonValue, Condition, ContainerId,
7 DataEncoding, DiscreteLookup, EntryKind, FloatCoding, IntegerCoding, LocationReference,
8 MatchCriteria, Operand, ParamId, ParameterType, SizeSpec, StringDelimiter, TypeKind, XtceDb,
9};
10
11use crate::bits::{
12 BitCursor, ones_complement, sign_magnitude, swap_byte_order, twos_complement,
13 twos_complement_unmasked,
14};
15use crate::calibrate::{self, CalibrationInput};
16use crate::charset;
17use crate::error::DecodeError;
18use crate::value::{DecodedPacket, EngValue, ParameterValue, RawValue};
19
20const MAX_CONTAINER_DEPTH: usize = 64;
26
27#[derive(Clone, Copy)]
31pub struct Decoder<'db> {
32 db: &'db XtceDb,
33 root: ContainerId,
34 capacity_hint: usize,
40}
41
42impl<'db> Decoder<'db> {
43 pub fn new(db: &'db XtceDb) -> Result<Self, DecodeError> {
50 let root = db
51 .default_root_container()
52 .ok_or_else(|| DecodeError::AmbiguousRoot {
53 candidates: db.root_containers().len(),
54 })?;
55 Ok(Self::rooted(db, root))
56 }
57
58 pub fn with_root(db: &'db XtceDb, name: &str) -> Result<Self, DecodeError> {
64 let root = db
65 .find_container(name)
66 .ok_or_else(|| DecodeError::NoSuchContainer {
67 name: name.to_owned(),
68 })?;
69 Ok(Self::rooted(db, root))
70 }
71
72 fn rooted(db: &'db XtceDb, root: ContainerId) -> Self {
73 Self {
74 db,
75 root,
76 capacity_hint: longest_path_entries(db, root),
77 }
78 }
79
80 #[must_use]
82 pub fn db(&self) -> &'db XtceDb {
83 self.db
84 }
85
86 #[must_use]
88 pub fn root(&self) -> ContainerId {
89 self.root
90 }
91
92 pub fn decode<'p>(&self, data: &'p [u8]) -> Result<DecodedPacket<'db, 'p>, DecodeError> {
103 let mut packet = DecodedPacket::with_capacity(self.db, data, self.root, self.capacity_hint);
104 self.decode_into(&mut packet, data)?;
105 Ok(packet)
106 }
107
108 pub fn decode_into<'p>(
133 &self,
134 packet: &mut DecodedPacket<'db, 'p>,
135 data: &'p [u8],
136 ) -> Result<(), DecodeError> {
137 packet.reset(data, self.root);
138 let mut cursor = BitCursor::new(data);
139 let mut current = self.root;
140
141 loop {
142 self.decode_container(current, &mut cursor, packet, 0)?;
143
144 let container = self
145 .db
146 .container(current)
147 .ok_or_else(|| DecodeError::dangling_container(current))?;
148
149 let mut matched: Option<ContainerId> = None;
150 let mut extra: Vec<ContainerId> = Vec::new();
151 for &inheritor in &container.inheritors {
152 if self.inheritor_matches(inheritor, packet)? {
153 match matched {
154 None => matched = Some(inheritor),
155 Some(_) => extra.push(inheritor),
156 }
157 }
158 }
159
160 if !extra.is_empty() {
161 let mut candidates: Vec<ContainerId> = matched.into_iter().collect();
162 candidates.extend(extra);
163 return Err(DecodeError::AmbiguousPacket {
164 container: self.container_name(current),
165 candidates: candidates
166 .into_iter()
167 .map(|id| self.container_name(id))
168 .collect(),
169 });
170 }
171
172 if let Some(next) = matched {
173 current = next;
174 } else {
175 if container.is_abstract {
176 return Err(DecodeError::UnrecognizedPacket {
177 container: self.container_name(current),
178 candidates: container
179 .inheritors
180 .iter()
181 .map(|&id| self.container_name(id))
182 .collect(),
183 });
184 }
185 break;
186 }
187 }
188
189 packet.set_container(current);
190 packet.set_bits_consumed(cursor.position());
191 Ok(())
192 }
193
194 #[must_use]
196 pub fn new_packet<'p>(&self, data: &'p [u8]) -> DecodedPacket<'db, 'p> {
197 DecodedPacket::with_capacity(self.db, data, self.root, self.capacity_hint)
198 }
199
200 fn decode_container<'p>(
205 &self,
206 id: ContainerId,
207 cursor: &mut BitCursor<'p>,
208 packet: &mut DecodedPacket<'db, 'p>,
209 depth: usize,
210 ) -> Result<(), DecodeError> {
211 if depth > MAX_CONTAINER_DEPTH {
212 return Err(DecodeError::Unsupported {
213 element: "ContainerRefEntry".to_owned(),
214 context: format!(
215 "{} (nesting exceeded {MAX_CONTAINER_DEPTH} levels; the entry list is probably cyclic)",
216 self.container_name(id)
217 ),
218 });
219 }
220
221 let container_start = cursor.position();
222 for entry in self.db.container_entries(id) {
223 if let Some(location) = entry.location {
224 let base = match location.reference {
225 LocationReference::PreviousEntry => cursor.position(),
226 LocationReference::ContainerStart => container_start,
227 LocationReference::ContainerEnd | LocationReference::NextEntry => {
228 return Err(DecodeError::Unsupported {
229 element: "LocationInContainerInBits".to_owned(),
230 context: format!(
231 "{} (referenceLocation containerEnd/nextEntry needs a size this \
232 decoder does not know until the container is finished)",
233 self.container_name(id)
234 ),
235 });
236 }
237 };
238 let target = i64::try_from(base).unwrap_or(i64::MAX) + location.offset_in_bits;
239 cursor.seek(usize::try_from(target).unwrap_or(0));
240 }
241
242 for _ in 0..entry.repeat.unwrap_or(1) {
243 match entry.kind {
244 EntryKind::Parameter(parameter) => {
245 self.decode_parameter(parameter, cursor, packet)?;
246 }
247 EntryKind::Container(child) => {
248 self.decode_container(child, cursor, packet, depth + 1)?;
249 }
250 EntryKind::FixedValue { size_in_bits, .. } => {
256 cursor
257 .skip(size_in_bits as usize)
258 .map_err(|error| DecodeError::Bits {
259 parameter: format!(
260 "<FixedValueEntry> in {}",
261 self.container_name(id)
262 ),
263 source: error,
264 })?;
265 }
266 EntryKind::Unsupported { element } => {
267 return Err(DecodeError::Unsupported {
268 element: self.db.name(element).to_owned(),
269 context: format!("entry list of {}", self.container_name(id)),
270 });
271 }
272 }
273 }
274 }
275 Ok(())
276 }
277
278 fn decode_parameter<'p>(
279 &self,
280 id: ParamId,
281 cursor: &mut BitCursor<'p>,
282 packet: &mut DecodedPacket<'db, 'p>,
283 ) -> Result<(), DecodeError> {
284 let parameter = self
285 .db
286 .parameter(id)
287 .ok_or_else(|| DecodeError::dangling_parameter(id))?;
288 let name = self.db.name(parameter.name);
289 let ty = self
290 .db
291 .parameter_type(parameter.type_id)
292 .ok_or(DecodeError::DanglingIndex {
293 what: "parameter type",
294 })?;
295
296 let bit_offset = cursor.position();
297 let (raw, eng) = self.decode_value(ty, name, cursor, packet)?;
298 packet.insert(ParameterValue {
299 parameter: id,
300 raw,
301 eng,
302 bit_offset,
303 bit_width: cursor.position().saturating_sub(bit_offset),
304 });
305 Ok(())
306 }
307
308 fn decode_value<'p>(
309 &self,
310 ty: &'db ParameterType,
311 name: &'db str,
312 cursor: &mut BitCursor<'p>,
313 packet: &DecodedPacket<'db, 'p>,
314 ) -> Result<(RawValue<'p>, EngValue<'db, 'p>), DecodeError> {
315 if let TypeKind::Unsupported { element } = ty.kind {
316 return Err(DecodeError::Unsupported {
317 element: self.db.name(element).to_owned(),
318 context: format!("parameter {name}"),
319 });
320 }
321
322 if matches!(ty.kind, TypeKind::String) {
327 let raw = self.read_string_raw(ty, name, cursor, packet)?;
328 let RawValue::Bytes(buffer) = raw else {
329 return Err(DecodeError::DanglingIndex {
330 what: "string buffer",
331 });
332 };
333 let text = match &buffer {
334 Cow::Borrowed(slice) => Self::decode_string(ty, name, slice)?,
335 Cow::Owned(owned) => Cow::Owned(Self::decode_string(ty, name, owned)?.into_owned()),
338 };
339 return Ok((RawValue::Bytes(buffer), EngValue::Text(text)));
340 }
341
342 let raw = self.read_raw(ty, name, cursor, packet)?;
343
344 match &ty.kind {
348 TypeKind::Enumerated(list) => {
349 let value = raw
350 .as_i128()
351 .ok_or_else(|| DecodeError::UnknownEnumeration {
352 parameter: name.to_owned(),
353 value: 0,
354 })?;
355 let label =
356 list.label_for(value)
357 .ok_or_else(|| DecodeError::UnknownEnumeration {
358 parameter: name.to_owned(),
359 value,
360 })?;
361 return Ok((raw, EngValue::Label(self.db.name(label))));
362 }
363 TypeKind::Boolean { .. } => {
364 let truthy = match &raw {
365 RawValue::Unsigned(value) => *value != 0,
366 RawValue::Signed(value) => *value != 0,
367 RawValue::Float(value) => *value != 0.0,
368 RawValue::Bytes(bytes) => !bytes.is_empty(),
369 };
370 return Ok((raw, EngValue::Bool(truthy)));
371 }
372 _ => {}
373 }
374
375 let eng = self.calibrate(ty, name, &raw, packet)?;
376 Ok((raw, eng))
377 }
378
379 fn calibrate<'p>(
381 &self,
382 ty: &'db ParameterType,
383 name: &'db str,
384 raw: &RawValue<'p>,
385 packet: &DecodedPacket<'db, 'p>,
386 ) -> Result<EngValue<'db, 'p>, DecodeError> {
387 let input = match raw {
388 RawValue::Unsigned(value) => CalibrationInput::Integer(i128::from(*value)),
389 RawValue::Signed(value) => CalibrationInput::Integer(i128::from(*value)),
390 RawValue::Float(value) => CalibrationInput::Float(*value),
391 RawValue::Bytes(bytes) => return Ok(EngValue::Bytes(bytes.clone())),
394 };
395
396 for context in ty.encoding.context_calibrators() {
397 let mut all = true;
398 for criteria in &context.criteria {
399 if !self.evaluate(criteria, packet, Some(raw), name)? {
400 all = false;
401 break;
402 }
403 }
404 if all {
405 return Ok(EngValue::Float(self.run_calibrator(
406 &context.calibrator,
407 input,
408 name,
409 )?));
410 }
411 }
412
413 if let Some(calibrator) = ty.encoding.default_calibrator() {
414 return Ok(EngValue::Float(
415 self.run_calibrator(calibrator, input, name)?,
416 ));
417 }
418
419 Ok(match raw {
420 RawValue::Unsigned(value) => EngValue::Unsigned(*value),
421 RawValue::Signed(value) => EngValue::Signed(*value),
422 RawValue::Float(value) => EngValue::Float(*value),
423 RawValue::Bytes(bytes) => EngValue::Bytes(bytes.clone()),
424 })
425 }
426
427 fn run_calibrator(
428 &self,
429 calibrator: &Calibrator,
430 input: CalibrationInput,
431 name: &str,
432 ) -> Result<f64, DecodeError> {
433 if let Calibrator::Unsupported { element } = calibrator {
434 return Err(DecodeError::Unsupported {
435 element: self.db.name(*element).to_owned(),
436 context: format!("calibrator for {name}"),
437 });
438 }
439 calibrate::apply(calibrator, input).map_err(|error| DecodeError::Calibration {
440 parameter: name.to_owned(),
441 reason: error.to_string(),
442 })
443 }
444
445 fn read_raw<'p>(
446 &self,
447 ty: &'db ParameterType,
448 name: &'db str,
449 cursor: &mut BitCursor<'p>,
450 packet: &DecodedPacket<'db, 'p>,
451 ) -> Result<RawValue<'p>, DecodeError> {
452 match &ty.encoding {
453 DataEncoding::Integer(encoding) => {
454 let width = encoding.size_in_bits;
455 let mut bits = cursor
456 .read_uint(width)
457 .map_err(|source| DecodeError::Bits {
458 parameter: name.to_owned(),
459 source,
460 })?;
461 let swapped = encoding.byte_order == xtce_model::ByteOrder::LeastSignificantFirst;
462 if swapped {
463 bits = swap_byte_order(bits, width);
464 }
465 Ok(match encoding.coding {
466 IntegerCoding::Unsigned => RawValue::Unsigned(bits),
467 IntegerCoding::TwosComplement if swapped => {
472 RawValue::Signed(twos_complement_unmasked(bits, width).ok_or_else(
473 || DecodeError::Unsupported {
474 element: "IntegerDataEncoding".to_owned(),
475 context: format!(
476 "{name}: a {width}-bit little-endian two's-complement \
477 field can hold a value wider than an i64"
478 ),
479 },
480 )?)
481 }
482 IntegerCoding::TwosComplement => RawValue::Signed(twos_complement(bits, width)),
483 IntegerCoding::SignMagnitude => RawValue::Signed(sign_magnitude(bits, width)),
484 IntegerCoding::OnesComplement => RawValue::Signed(ones_complement(bits, width)),
485 })
486 }
487
488 DataEncoding::Float(encoding) => {
489 let width = encoding.size_in_bits;
490 let mut bits = cursor
491 .read_uint(width)
492 .map_err(|source| DecodeError::Bits {
493 parameter: name.to_owned(),
494 source,
495 })?;
496 if encoding.byte_order == xtce_model::ByteOrder::LeastSignificantFirst {
497 bits = swap_byte_order(bits, width);
498 }
499 let value = match encoding.coding {
500 FloatCoding::Ieee754 => {
501 ieee754(bits, width).ok_or_else(|| DecodeError::Unsupported {
502 element: "FloatDataEncoding".to_owned(),
503 context: format!("{name}: IEEE-754 at {width} bits"),
504 })?
505 }
506 FloatCoding::MilStd1750A if width != 32 => {
513 return Err(DecodeError::Unsupported {
514 element: "FloatDataEncoding".to_owned(),
515 context: format!("{name}: MIL-STD-1750A at {width} bits, not 32"),
516 });
517 }
518 FloatCoding::MilStd1750A => mil_std_1750a(bits),
519 };
520 Ok(RawValue::Float(value))
521 }
522
523 DataEncoding::Binary(encoding) => {
524 let width = self.resolve_size(&encoding.size, packet, name)?;
525 let bytes = cursor
526 .read_bytes(width)
527 .map_err(|source| DecodeError::Bits {
528 parameter: name.to_owned(),
529 source,
530 })?;
531 Ok(RawValue::Bytes(bytes))
532 }
533
534 DataEncoding::String(_) => self.read_string_raw(ty, name, cursor, packet),
535
536 DataEncoding::None => Err(DecodeError::Unsupported {
537 element: "DataEncoding".to_owned(),
538 context: format!("{name} has no data encoding"),
539 }),
540 }
541 }
542
543 fn read_string_raw<'p>(
544 &self,
545 ty: &'db ParameterType,
546 name: &'db str,
547 cursor: &mut BitCursor<'p>,
548 packet: &DecodedPacket<'db, 'p>,
549 ) -> Result<RawValue<'p>, DecodeError> {
550 let DataEncoding::String(encoding) = &ty.encoding else {
551 return Err(DecodeError::DanglingIndex {
552 what: "string encoding",
553 });
554 };
555 let width = self.resolve_size(&encoding.raw_size, packet, name)?;
556 let bytes = cursor
559 .read_bytes_left_aligned(width)
560 .map_err(|source| DecodeError::Bits {
561 parameter: name.to_owned(),
562 source,
563 })?;
564 Ok(RawValue::Bytes(bytes))
565 }
566
567 fn decode_string<'p>(
569 ty: &ParameterType,
570 name: &str,
571 buffer: &'p [u8],
572 ) -> Result<Cow<'p, str>, DecodeError> {
573 let DataEncoding::String(encoding) = &ty.encoding else {
574 return Ok(Cow::Borrowed(""));
575 };
576
577 let text_bytes: Cow<'p, [u8]> = match &encoding.delimiter {
578 StringDelimiter::WholeBuffer => Cow::Borrowed(buffer),
579 StringDelimiter::TerminationChar(terminator) => {
580 let end = find_subslice(buffer, terminator).ok_or_else(|| {
583 DecodeError::UnterminatedString {
584 parameter: name.to_owned(),
585 bytes: buffer.len(),
586 }
587 })?;
588 Cow::Borrowed(buffer.get(..end).unwrap_or_default())
589 }
590 StringDelimiter::LeadingSize { size_in_bits } => {
591 let mut prefix = BitCursor::new(buffer);
592 let length_bits =
593 prefix
594 .read_uint(*size_in_bits)
595 .map_err(|source| DecodeError::Bits {
596 parameter: name.to_owned(),
597 source,
598 })?;
599 if length_bits % 8 != 0 {
600 return Err(DecodeError::BadFieldSize {
601 parameter: name.to_owned(),
602 bits: i64::try_from(length_bits).unwrap_or(i64::MAX),
603 });
604 }
605 prefix
608 .read_bytes(usize::try_from(length_bits).unwrap_or(0))
609 .map_err(|source| DecodeError::Bits {
610 parameter: name.to_owned(),
611 source,
612 })?
613 }
614 };
615
616 let invalid = |len: usize| DecodeError::InvalidText {
617 parameter: name.to_owned(),
618 charset: charset::name(encoding.charset),
619 bytes: len,
620 };
621
622 match text_bytes {
623 Cow::Borrowed(slice) => charset::decode(slice, encoding.charset, encoding.byte_order)
624 .map_err(|_| invalid(slice.len())),
625 Cow::Owned(owned) => charset::decode(&owned, encoding.charset, encoding.byte_order)
626 .map(|text| Cow::Owned(text.into_owned()))
627 .map_err(|_| invalid(owned.len())),
628 }
629 }
630
631 fn resolve_size<'p>(
632 &self,
633 spec: &SizeSpec,
634 packet: &DecodedPacket<'db, 'p>,
635 name: &str,
636 ) -> Result<usize, DecodeError> {
637 let bits: i64 = match spec {
638 SizeSpec::Fixed(bits) => i64::from(*bits),
639
640 SizeSpec::Dynamic {
641 parameter,
642 use_calibrated,
643 adjustment,
644 } => {
645 let value =
646 packet
647 .get(*parameter)
648 .ok_or_else(|| DecodeError::ParameterNotYetDecoded {
649 context: "dynamic field size",
650 parameter: self.parameter_name(*parameter),
651 })?;
652 let integral = if *use_calibrated {
653 value.eng.as_i128()
654 } else {
655 value.raw.as_i128()
656 };
657 if let (Some(exact), None) = (integral, adjustment) {
660 i64::try_from(exact).unwrap_or(i64::MAX)
661 } else {
662 {
663 let numeric = if *use_calibrated {
664 value.eng.as_f64()
665 } else {
666 value.raw.as_f64()
667 }
668 .ok_or_else(|| DecodeError::BadFieldSize {
669 parameter: name.to_owned(),
670 bits: 0,
671 })?;
672 let adjusted = adjustment.map_or(numeric, |a| a.apply(numeric));
673 adjusted as i64
675 }
676 }
677 }
678
679 SizeSpec::DiscreteLookup(lookups) => self.discrete_lookup(lookups, packet, name)?,
680
681 SizeSpec::Unsupported { element } => {
682 return Err(DecodeError::Unsupported {
683 element: self.db.name(*element).to_owned(),
684 context: format!("size of {name}"),
685 });
686 }
687 };
688
689 usize::try_from(bits).map_err(|_| DecodeError::BadFieldSize {
690 parameter: name.to_owned(),
691 bits,
692 })
693 }
694
695 fn discrete_lookup<'p>(
696 &self,
697 lookups: &[DiscreteLookup],
698 packet: &DecodedPacket<'db, 'p>,
699 name: &str,
700 ) -> Result<i64, DecodeError> {
701 for lookup in lookups {
702 let mut all = true;
703 for criteria in &lookup.criteria {
704 if !self.evaluate(criteria, packet, None, name)? {
705 all = false;
706 break;
707 }
708 }
709 if all {
710 return Ok(lookup.value);
711 }
712 }
713 Err(DecodeError::NoDiscreteLookupMatch {
714 parameter: name.to_owned(),
715 })
716 }
717
718 fn inheritor_matches(
721 &self,
722 id: ContainerId,
723 packet: &DecodedPacket<'db, '_>,
724 ) -> Result<bool, DecodeError> {
725 let container = self
726 .db
727 .container(id)
728 .ok_or_else(|| DecodeError::dangling_container(id))?;
729 for criteria in &container.restriction {
733 if !self.evaluate(criteria, packet, None, self.db.name(container.name))? {
734 return Ok(false);
735 }
736 }
737 Ok(true)
738 }
739
740 fn evaluate(
746 &self,
747 criteria: &MatchCriteria,
748 packet: &DecodedPacket<'db, '_>,
749 current: Option<&RawValue<'_>>,
750 context: &str,
751 ) -> Result<bool, DecodeError> {
752 match criteria {
753 MatchCriteria::Comparison(comparison) => {
754 self.evaluate_comparison(comparison, packet, current)
755 }
756 MatchCriteria::Boolean(expr) => self.evaluate_boolean(expr, packet),
757 MatchCriteria::Unsupported { element } => Err(DecodeError::Unsupported {
758 element: self.db.name(*element).to_owned(),
759 context: format!("match criteria of {context}"),
760 }),
761 }
762 }
763
764 fn evaluate_comparison(
765 &self,
766 comparison: &Comparison,
767 packet: &DecodedPacket<'db, '_>,
768 current: Option<&RawValue<'_>>,
769 ) -> Result<bool, DecodeError> {
770 let literal_text = self.db.name(comparison.value.text);
771 let operator = comparison.operator;
772
773 let outcome = match packet.get(comparison.parameter) {
774 Some(value) => {
775 let scalar = if comparison.use_calibrated {
776 Scalar::from_eng(&value.eng)
777 } else {
778 Scalar::from_raw(&value.raw)
779 };
780 test_literal(scalar, operator, &comparison.value, literal_text)
781 }
782 None => match current {
786 Some(raw) => test_literal(
787 Scalar::from_raw(raw),
788 operator,
789 &comparison.value,
790 literal_text,
791 ),
792 None => {
793 return Err(DecodeError::ParameterNotYetDecoded {
794 context: "comparison",
795 parameter: self.parameter_name(comparison.parameter),
796 });
797 }
798 },
799 };
800
801 outcome.map_err(|failure| DecodeError::IncomparableValue {
802 parameter: self.parameter_name(comparison.parameter),
803 value_kind: failure.value_kind,
804 literal: literal_text.to_owned(),
805 })
806 }
807
808 fn evaluate_boolean(
809 &self,
810 expr: &BooleanExpr,
811 packet: &DecodedPacket<'db, '_>,
812 ) -> Result<bool, DecodeError> {
813 match expr {
814 BooleanExpr::Condition(condition) => self.evaluate_condition(condition, packet),
815 BooleanExpr::And(children) => {
816 for child in children {
817 if !self.evaluate_boolean(child, packet)? {
818 return Ok(false);
819 }
820 }
821 Ok(true)
822 }
823 BooleanExpr::Or(children) => {
824 for child in children {
825 if self.evaluate_boolean(child, packet)? {
826 return Ok(true);
827 }
828 }
829 Ok(false)
830 }
831 }
832 }
833
834 fn evaluate_condition(
835 &self,
836 condition: &Condition,
837 packet: &DecodedPacket<'db, '_>,
838 ) -> Result<bool, DecodeError> {
839 let left = self.operand_value(condition.left, packet)?;
840
841 let outcome = match condition.right {
842 Operand::Literal(literal) => test_literal(
844 left,
845 condition.operator,
846 &literal,
847 self.db.name(literal.text),
848 ),
849 Operand::Parameter { .. } => test_scalars(
850 left,
851 condition.operator,
852 self.operand_value(condition.right, packet)?,
853 ),
854 };
855
856 outcome.map_err(|failure| DecodeError::IncomparableValue {
857 parameter: self.operand_name(condition.left),
858 value_kind: failure.value_kind,
859 literal: self.operand_name(condition.right),
860 })
861 }
862
863 fn operand_value<'v>(
865 &self,
866 operand: Operand,
867 packet: &'v DecodedPacket<'db, '_>,
868 ) -> Result<Scalar<'v>, DecodeError>
869 where
870 'db: 'v,
871 {
872 match operand {
873 Operand::Parameter {
874 parameter,
875 use_calibrated,
876 } => {
877 let value =
878 packet
879 .get(parameter)
880 .ok_or_else(|| DecodeError::ParameterNotYetDecoded {
881 context: "condition",
882 parameter: self.parameter_name(parameter),
883 })?;
884 Ok(if use_calibrated {
885 Scalar::from_eng(&value.eng)
886 } else {
887 Scalar::from_raw(&value.raw)
888 })
889 }
890 Operand::Literal(literal) => Ok(Scalar::Text(self.db.name(literal.text))),
891 }
892 }
893
894 fn operand_name(&self, operand: Operand) -> String {
896 match operand {
897 Operand::Parameter { parameter, .. } => self.parameter_name(parameter),
898 Operand::Literal(literal) => format!("{:?}", self.db.name(literal.text)),
899 }
900 }
901
902 fn container_name(&self, id: ContainerId) -> String {
903 self.db
904 .container(id)
905 .map_or_else(|| "?".to_owned(), |c| self.db.name(c.name).to_owned())
906 }
907
908 fn parameter_name(&self, id: ParamId) -> String {
909 self.db
910 .parameter(id)
911 .map_or_else(|| "?".to_owned(), |p| self.db.name(p.name).to_owned())
912 }
913}
914
915fn longest_path_entries(db: &XtceDb, root: ContainerId) -> usize {
917 let mut expanded: Vec<Option<usize>> = vec![None; db.containers().len()];
918 let mut deepest: Vec<Option<usize>> = vec![None; db.containers().len()];
919 walk(db, root, 0, &mut expanded, &mut deepest)
920}
921
922fn own_entries(db: &XtceDb, id: ContainerId, depth: usize, memo: &mut Vec<Option<usize>>) -> usize {
924 if depth > MAX_CONTAINER_DEPTH {
925 return 0;
926 }
927 if let Some(Some(cached)) = memo.get(id.index()) {
928 return *cached;
929 }
930 if let Some(slot) = memo.get_mut(id.index()) {
932 *slot = Some(0);
933 }
934 let total = db
935 .container_entries(id)
936 .iter()
937 .map(|entry| {
938 let repeat = entry.repeat.unwrap_or(1) as usize;
939 match entry.kind {
940 EntryKind::Container(child) => own_entries(db, child, depth + 1, memo) * repeat,
941 _ => repeat,
942 }
943 })
944 .sum();
945 if let Some(slot) = memo.get_mut(id.index()) {
946 *slot = Some(total);
947 }
948 total
949}
950
951fn walk(
953 db: &XtceDb,
954 id: ContainerId,
955 depth: usize,
956 expanded: &mut Vec<Option<usize>>,
957 deepest: &mut Vec<Option<usize>>,
958) -> usize {
959 if depth > MAX_CONTAINER_DEPTH {
960 return 0;
961 }
962 if let Some(Some(cached)) = deepest.get(id.index()) {
963 return *cached;
964 }
965 if let Some(slot) = deepest.get_mut(id.index()) {
966 *slot = Some(0);
967 }
968 let here = own_entries(db, id, 0, expanded);
969 let below = db.container(id).map_or(0, |container| {
970 container
971 .inheritors
972 .iter()
973 .map(|&child| walk(db, child, depth + 1, expanded, deepest))
974 .max()
975 .unwrap_or(0)
976 });
977 let total = here + below;
978 if let Some(slot) = deepest.get_mut(id.index()) {
979 *slot = Some(total);
980 }
981 total
982}
983
984#[derive(Clone, Copy, Debug)]
990enum Scalar<'a> {
991 Integer(i128),
992 Float(f64),
993 Text(&'a str),
994 Opaque(&'static str),
996}
997
998impl<'a> Scalar<'a> {
999 fn from_raw(raw: &'a RawValue<'_>) -> Self {
1000 match raw {
1001 RawValue::Unsigned(value) => Self::Integer(i128::from(*value)),
1002 RawValue::Signed(value) => Self::Integer(i128::from(*value)),
1003 RawValue::Float(value) => Self::Float(*value),
1004 RawValue::Bytes(_) => Self::Opaque("binary"),
1005 }
1006 }
1007
1008 fn from_eng(eng: &'a EngValue<'_, '_>) -> Self {
1009 match eng {
1010 EngValue::Unsigned(value) => Self::Integer(i128::from(*value)),
1011 EngValue::Signed(value) => Self::Integer(i128::from(*value)),
1012 EngValue::Bool(value) => Self::Integer(i128::from(*value)),
1013 EngValue::Float(value) => Self::Float(*value),
1014 EngValue::Label(text) => Self::Text(text),
1015 EngValue::Text(text) => Self::Text(text.as_ref()),
1016 EngValue::Bytes(_) => Self::Opaque("binary"),
1017 }
1018 }
1019
1020 const fn kind(self) -> &'static str {
1021 match self {
1022 Self::Integer(_) => "integer",
1023 Self::Float(_) => "float",
1024 Self::Text(_) => "text",
1025 Self::Opaque(kind) => kind,
1026 }
1027 }
1028}
1029
1030#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1035struct Incomparable {
1036 value_kind: &'static str,
1037}
1038
1039const fn unordered(operator: CompareOp) -> bool {
1045 matches!(operator, CompareOp::NotEqual)
1046}
1047
1048fn test_literal(
1055 value: Scalar<'_>,
1056 operator: CompareOp,
1057 literal: &ComparisonValue,
1058 text: &str,
1059) -> Result<bool, Incomparable> {
1060 let incomparable = Incomparable {
1061 value_kind: value.kind(),
1062 };
1063 match value {
1064 Scalar::Integer(left) => match literal.as_int {
1065 Some(right) => Ok(operator.matches(left.cmp(&right))),
1066 None => Err(incomparable),
1067 },
1068 Scalar::Float(left) => match literal.as_float {
1069 Some(right) => Ok(ordering(operator, left.partial_cmp(&right))),
1070 None => Err(incomparable),
1071 },
1072 Scalar::Text(left) => Ok(operator.matches(left.cmp(text))),
1073 Scalar::Opaque(_) => Err(incomparable),
1074 }
1075}
1076
1077fn test_scalars(
1079 left: Scalar<'_>,
1080 operator: CompareOp,
1081 right: Scalar<'_>,
1082) -> Result<bool, Incomparable> {
1083 match (left, right) {
1084 (Scalar::Integer(a), Scalar::Integer(b)) => Ok(operator.matches(a.cmp(&b))),
1085 (Scalar::Float(a), Scalar::Float(b)) => Ok(ordering(operator, a.partial_cmp(&b))),
1086 (Scalar::Integer(a), Scalar::Float(b)) => {
1087 Ok(ordering(operator, (a as f64).partial_cmp(&b)))
1088 }
1089 (Scalar::Float(a), Scalar::Integer(b)) => {
1090 Ok(ordering(operator, a.partial_cmp(&(b as f64))))
1091 }
1092 (Scalar::Text(a), Scalar::Text(b)) => Ok(operator.matches(a.cmp(b))),
1093 _ => match operator {
1097 CompareOp::Equal => Ok(false),
1098 CompareOp::NotEqual => Ok(true),
1099 _ => Err(Incomparable {
1100 value_kind: left.kind(),
1101 }),
1102 },
1103 }
1104}
1105
1106fn ordering(operator: CompareOp, ordering: Option<std::cmp::Ordering>) -> bool {
1108 match ordering {
1109 Some(ordering) => operator.matches(ordering),
1110 None => unordered(operator),
1111 }
1112}
1113
1114fn ieee754(bits: u64, width: u32) -> Option<f64> {
1116 match width {
1117 16 => Some(f64::from(half_to_f32(bits as u16))),
1118 32 => Some(f64::from(f32::from_bits(bits as u32))),
1119 64 => Some(f64::from_bits(bits)),
1120 _ => None,
1121 }
1122}
1123
1124fn half_to_f32(bits: u16) -> f32 {
1132 let sign = u32::from(bits >> 15) << 31;
1133 let exponent = u32::from((bits >> 10) & 0x1F);
1134 let fraction = u32::from(bits & 0x03FF);
1135
1136 match exponent {
1137 0 if fraction == 0 => f32::from_bits(sign),
1138 0 => {
1139 let shift = fraction.leading_zeros() - 21;
1143 let exponent = 113 - shift;
1144 let fraction = (fraction << shift) & 0x03FF;
1145 f32::from_bits(sign | (exponent << 23) | (fraction << 13))
1146 }
1147 0x1F => f32::from_bits(sign | 0x7F80_0000 | (fraction << 13)),
1148 _ => f32::from_bits(sign | ((exponent + 127 - 15) << 23) | (fraction << 13)),
1149 }
1150}
1151
1152fn mil_std_1750a(bits: u64) -> f64 {
1157 let word = bits as u32;
1158 let exponent = twos_complement(u64::from(word & 0xFF), 8);
1159 let mantissa = twos_complement(u64::from((word >> 8) & 0x00FF_FFFF), 24);
1160 (mantissa as f64) * 2f64.powi(i32::try_from(exponent).unwrap_or(0) - 23)
1161}
1162
1163fn find_subslice(haystack: &[u8], needle: &[u8]) -> Option<usize> {
1164 if needle.is_empty() {
1165 return Some(0);
1166 }
1167 haystack
1168 .windows(needle.len())
1169 .position(|window| window == needle)
1170}
1171
1172#[cfg(test)]
1173mod tests {
1174 use super::*;
1175 use xtce_model::NameId;
1176
1177 fn half_reference(bits: u16) -> f64 {
1182 let sign = if bits >> 15 == 1 { -1.0 } else { 1.0 };
1183 let exponent = i32::from((bits >> 10) & 0x1F);
1184 let fraction = f64::from(bits & 0x03FF);
1185 match exponent {
1186 0 => sign * fraction * 2f64.powi(-24),
1187 0x1F => {
1188 if fraction == 0.0 {
1189 sign * f64::INFINITY
1190 } else {
1191 f64::NAN
1192 }
1193 }
1194 _ => sign * (1.0 + fraction / 1024.0) * 2f64.powi(exponent - 15),
1195 }
1196 }
1197
1198 #[test]
1199 fn half_precision_matches_the_ieee_definition_for_every_encoding() {
1200 for bits in 0u16..=u16::MAX {
1202 let got = f64::from(half_to_f32(bits));
1203 let want = half_reference(bits);
1204 if want.is_nan() {
1205 assert!(got.is_nan(), "bits {bits:#06x}: expected NaN, got {got}");
1206 } else {
1207 assert_eq!(got.to_bits(), want.to_bits(), "bits {bits:#06x}");
1208 }
1209 }
1210 }
1211
1212 #[test]
1213 fn half_precision_subnormals() {
1214 assert_eq!(f64::from(half_to_f32(0x0001)), 2f64.powi(-24));
1217 assert_eq!(f64::from(half_to_f32(0x0002)), 2f64.powi(-23));
1218 assert_eq!(f64::from(half_to_f32(0x03FF)), 1023.0 * 2f64.powi(-24));
1219 assert_eq!(f64::from(half_to_f32(0x0400)), 2f64.powi(-14));
1221 assert_eq!(f64::from(half_to_f32(0x8001)), -(2f64.powi(-24)));
1222 }
1223
1224 #[test]
1225 fn half_precision_specials() {
1226 assert_eq!(f64::from(half_to_f32(0x0000)), 0.0);
1227 assert!(f64::from(half_to_f32(0x8000)).is_sign_negative());
1228 assert_eq!(f64::from(half_to_f32(0x3C00)), 1.0);
1229 assert_eq!(f64::from(half_to_f32(0xC000)), -2.0);
1230 assert!(f64::from(half_to_f32(0x7C00)).is_infinite());
1231 assert!(f64::from(half_to_f32(0xFC00)).is_infinite());
1232 assert!(f64::from(half_to_f32(0x7E00)).is_nan());
1233 }
1234
1235 #[test]
1236 fn mil_std_1750a_reference_values() {
1237 assert_eq!(mil_std_1750a(0x4000_0000), 0.5);
1239 assert_eq!(mil_std_1750a(0x4000_0001), 1.0);
1240 assert_eq!(mil_std_1750a(0x4000_0004), 8.0);
1241 assert_eq!(mil_std_1750a(0x8000_0000), -1.0);
1242 assert_eq!(mil_std_1750a(0x0000_0000), 0.0);
1243 assert_eq!(mil_std_1750a(0xBFFF_FFFF), -0.250_000_059_604_644_8);
1245 assert_eq!(mil_std_1750a(0x8000_0080), -2f64.powi(-128));
1247 assert_eq!(mil_std_1750a(0x4000_007F), 0.5 * 2f64.powi(127));
1248 }
1249
1250 fn literal(text: &str) -> ComparisonValue {
1251 ComparisonValue::new(NameId::ZERO, text)
1252 }
1253
1254 #[test]
1255 fn nan_is_unordered_exactly_as_python_treats_it() {
1256 use CompareOp::{Equal, Greater, GreaterOrEqual, Less, LessOrEqual, NotEqual};
1257 let nan = Scalar::Float(f64::NAN);
1258
1259 for (operator, expected) in [
1262 (Equal, false),
1263 (NotEqual, true),
1264 (Less, false),
1265 (LessOrEqual, false),
1266 (Greater, false),
1267 (GreaterOrEqual, false),
1268 ] {
1269 assert_eq!(
1270 test_literal(nan, operator, &literal("0"), "0"),
1271 Ok(expected),
1272 "{operator:?} against a literal"
1273 );
1274 assert_eq!(
1275 test_scalars(nan, operator, Scalar::Float(f64::NAN)),
1276 Ok(expected),
1277 "{operator:?} against another NaN"
1278 );
1279 assert_eq!(
1280 test_scalars(nan, operator, Scalar::Integer(0)),
1281 Ok(expected),
1282 "{operator:?} against an integer"
1283 );
1284 }
1285 }
1286
1287 #[test]
1288 fn negative_zero_equals_zero() {
1289 assert_eq!(
1291 test_literal(
1292 Scalar::Float(-0.0),
1293 CompareOp::Equal,
1294 &literal("0.0"),
1295 "0.0"
1296 ),
1297 Ok(true)
1298 );
1299 assert_eq!(
1300 test_scalars(Scalar::Float(-0.0), CompareOp::Equal, Scalar::Float(0.0)),
1301 Ok(true)
1302 );
1303 }
1304
1305 #[test]
1306 fn literals_are_coerced_to_the_value_they_meet() {
1307 assert_eq!(
1308 test_literal(Scalar::Integer(11), CompareOp::Equal, &literal("11"), "11"),
1309 Ok(true)
1310 );
1311 assert!(
1314 test_literal(Scalar::Integer(3), CompareOp::Equal, &literal("3.5"), "3.5").is_err()
1315 );
1316 assert_eq!(
1318 test_literal(Scalar::Float(3.0), CompareOp::Equal, &literal("3"), "3"),
1319 Ok(true)
1320 );
1321 assert_eq!(
1323 test_literal(Scalar::Text("ON"), CompareOp::Equal, &literal("ON"), "ON"),
1324 Ok(true)
1325 );
1326 assert_eq!(
1327 test_literal(Scalar::Text("OFF"), CompareOp::Less, &literal("ON"), "ON"),
1328 Ok(true)
1329 );
1330 assert!(
1332 test_literal(
1333 Scalar::Opaque("binary"),
1334 CompareOp::Equal,
1335 &literal("0"),
1336 "0"
1337 )
1338 .is_err()
1339 );
1340 }
1341
1342 #[test]
1343 fn text_against_a_number_follows_python() {
1344 let text = Scalar::Text("ON");
1346 let number = Scalar::Integer(5);
1347 assert_eq!(test_scalars(text, CompareOp::Equal, number), Ok(false));
1348 assert_eq!(test_scalars(text, CompareOp::NotEqual, number), Ok(true));
1349 assert!(test_scalars(text, CompareOp::Less, number).is_err());
1350 assert!(test_scalars(number, CompareOp::Greater, text).is_err());
1351 }
1352
1353 #[test]
1354 fn operators_over_an_ordering() {
1355 use std::cmp::Ordering::{Equal, Greater, Less};
1356 assert!(CompareOp::Equal.matches(Equal));
1357 assert!(!CompareOp::Equal.matches(Less));
1358 assert!(CompareOp::NotEqual.matches(Less));
1359 assert!(CompareOp::NotEqual.matches(Greater));
1360 assert!(!CompareOp::NotEqual.matches(Equal));
1361 assert!(CompareOp::LessOrEqual.matches(Equal));
1362 assert!(CompareOp::GreaterOrEqual.matches(Equal));
1363 assert!(!CompareOp::Greater.matches(Equal));
1364 }
1365}