Skip to main content

xtce_model/
containers.rs

1//! Sequence containers, entry lists and the match criteria that select between them.
2
3use crate::ids::{ContainerId, MetaCommandId, ParamId, SpaceSystemId, Span};
4use crate::intern::NameId;
5
6/// A `<xtce:SequenceContainer>`.
7#[derive(Clone, Debug)]
8pub struct Container {
9    /// Container name as written.
10    pub name: NameId,
11    /// Fully qualified name.
12    pub qualified_name: NameId,
13    /// The space system that owns this definition.
14    pub space_system: SpaceSystemId,
15    /// `abstract="true"`: the container may not be the final match for a packet.
16    pub is_abstract: bool,
17    /// The container this one extends, from `<BaseContainer containerRef=..>`.
18    pub base: Option<ContainerId>,
19    /// Whether this container came from `<CommandMetaData>` rather than the telemetry half.
20    ///
21    /// True for a `MetaCommand`'s own `<CommandContainer>` *and* for a shared one in a
22    /// `<CommandContainerSet>`. It is what root selection needs: a telecommand is not a packet
23    /// to decode by default, whoever owns it.
24    pub is_command: bool,
25    /// The telecommand this container packs, when it is a `<CommandContainer>`.
26    ///
27    /// `None` for a telemetry container — and also for a shared one in a
28    /// `<CommandContainerSet>`, which is a telecommand's packaging but belongs to no single
29    /// command. [`Self::is_command`] is the question to ask about the half of the document
30    /// a container came from; this one is the question about ownership.
31    pub command: Option<MetaCommandId>,
32    /// Criteria under which this container specialises [`Self::base`]. All must hold.
33    pub restriction: Vec<MatchCriteria>,
34    /// This container's own entries, as a span of [`crate::XtceDb::entries`].
35    ///
36    /// Entries live in one shared arena so that decoding a container walks a contiguous
37    /// slice rather than chasing a per-container `Vec`.
38    pub entries: Span,
39    /// Containers that name this one as their base, in document order.
40    ///
41    /// Filled during resolution. Decoding descends this list, which is the direction the
42    /// reference implementation walks and the direction packets are actually discriminated.
43    pub inheritors: Vec<ContainerId>,
44    /// `shortDescription`, if present.
45    pub short_description: Option<NameId>,
46    /// `<LongDescription>`, if present.
47    pub long_description: Option<NameId>,
48}
49
50/// One element of an `<xtce:EntryList>`.
51#[derive(Clone, Copy, Debug)]
52pub struct Entry {
53    /// What the entry contributes.
54    pub kind: EntryKind,
55    /// Explicit placement, from `<LocationInContainerInBits>`.
56    ///
57    /// `None` means "immediately after the previous entry", which is the XTCE default and
58    /// covers every entry in the bundled test data.
59    pub location: Option<Location>,
60    /// Fixed repetition count, from `<RepeatEntry><Count><FixedValue>`.
61    pub repeat: Option<u32>,
62}
63
64/// What an entry contributes to a container.
65#[derive(Clone, Copy, Debug)]
66pub enum EntryKind {
67    /// `<ParameterRefEntry>`: one parameter.
68    Parameter(ParamId),
69    /// `<ContainerRefEntry>`: the referenced container's entries, inline.
70    Container(ContainerId),
71    /// `<FixedValueEntry>`: bits the definition fixes, carrying no parameter.
72    ///
73    /// Only a command container may have one. It is how a telecommand carries its sync
74    /// pattern and the header bits the ground does not get to choose — the bits are in the
75    /// packet, they are not anybody's value, and nothing reports them.
76    FixedValue {
77        /// The entry's `name`, if it has one. Optional in the schema, and for diagnostics
78        /// only: nothing resolves a reference to it.
79        name: Option<NameId>,
80        /// The bytes, as a span of [`crate::XtceDb::fixed_values`].
81        ///
82        /// `binaryValue` is `hexBinary`, so this is what it decodes to. Stored in a shared
83        /// arena because an entry is `Copy` and cannot own a `Vec`.
84        value: Span,
85        /// How many of those bits the entry occupies, from `sizeInBits`.
86        ///
87        /// May be fewer than the bytes hold, and may be more: XTCE does not require the two
88        /// to agree, so the width is the entry's and the bytes are the value.
89        size_in_bits: u32,
90    },
91    /// An entry kind outside this crate's scope, e.g. `<IndirectParameterRefEntry>`.
92    ///
93    /// Present so the container's shape is preserved; decoding one reports
94    /// `XtceError::Unsupported`.
95    Unsupported {
96        /// The element that put the entry out of scope.
97        element: NameId,
98    },
99}
100
101/// `<xtce:LocationInContainerInBits>`.
102#[derive(Clone, Copy, Debug)]
103pub struct Location {
104    /// What the offset is measured from.
105    pub reference: LocationReference,
106    /// Signed bit offset from the reference point.
107    pub offset_in_bits: i64,
108}
109
110/// The anchor of a [`Location`].
111#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
112pub enum LocationReference {
113    /// End of the previous entry — the XTCE default.
114    #[default]
115    PreviousEntry,
116    /// Start of the containing container.
117    ContainerStart,
118    /// End of the containing container.
119    ContainerEnd,
120    /// Start of the next entry.
121    NextEntry,
122}
123
124/// Comparison operators usable in match criteria.
125#[derive(Clone, Copy, PartialEq, Eq, Debug)]
126pub enum CompareOp {
127    /// `==` / `eq`
128    Equal,
129    /// `!=` / `neq`
130    NotEqual,
131    /// `<` / `lt`
132    Less,
133    /// `<=` / `leq`
134    LessOrEqual,
135    /// `>` / `gt`
136    Greater,
137    /// `>=` / `geq`
138    GreaterOrEqual,
139}
140
141impl CompareOp {
142    /// Parses the XML spelling of an operator.
143    ///
144    /// XTCE mandates entity-escaped forms (`&gt;`), but shipped databases also use the
145    /// bash-style words, and an XML parser hands back the unescaped character. All three
146    /// spellings are accepted, matching the reference implementation.
147    #[must_use]
148    pub fn parse(text: &str) -> Option<Self> {
149        Some(match text {
150            "==" | "eq" => Self::Equal,
151            "!=" | "neq" => Self::NotEqual,
152            "<" | "lt" | "&lt;" => Self::Less,
153            "<=" | "leq" | "&lt;=" => Self::LessOrEqual,
154            ">" | "gt" | "&gt;" => Self::Greater,
155            ">=" | "geq" | "&gt;=" => Self::GreaterOrEqual,
156            _ => return None,
157        })
158    }
159
160    /// Applies the operator to an [`Ordering`](std::cmp::Ordering).
161    #[must_use]
162    pub const fn matches(self, ordering: std::cmp::Ordering) -> bool {
163        use std::cmp::Ordering::{Equal, Greater, Less};
164        matches!(
165            (self, ordering),
166            (Self::Equal, Equal)
167                | (Self::NotEqual, Less | Greater)
168                | (Self::Less, Less)
169                | (Self::LessOrEqual, Less | Equal)
170                | (Self::Greater, Greater)
171                | (Self::GreaterOrEqual, Greater | Equal)
172        )
173    }
174}
175
176/// A condition on previously decoded parameter values.
177#[derive(Clone, Debug)]
178pub enum MatchCriteria {
179    /// `<xtce:Comparison>`: one parameter against a literal.
180    Comparison(Comparison),
181    /// `<xtce:BooleanExpression>`: a tree of conditions.
182    Boolean(BooleanExpr),
183    /// A criterion kind outside this crate's scope, e.g. `<CustomAlgorithm>`.
184    ///
185    /// Evaluating one reports `XtceError::Unsupported` rather than silently matching or
186    /// failing, so an out-of-scope discriminator can never quietly select the wrong
187    /// container.
188    Unsupported {
189        /// The element that put the criterion out of scope.
190        element: NameId,
191    },
192}
193
194/// A comparison literal, pre-coerced at load time.
195///
196/// XTCE does not type the `value` attribute of a `<Comparison>`, and the reference
197/// implementation resolves that by coercing the literal to `type(parsed_value)` on every
198/// evaluation — so an enumerated parameter compares as text and an integer one as a number.
199/// Which of those applies cannot be known from the schema alone, because a calibrator turns
200/// an integer-encoded parameter into a float.
201///
202/// Rather than predict it, every reading that could apply is computed once here, at load
203/// time. Evaluation then picks the one matching the value it actually got, and never parses
204/// inside the packet loop.
205#[derive(Clone, Copy, Debug)]
206pub struct ComparisonValue {
207    /// The literal exactly as written, for error messages and text comparisons.
208    pub text: NameId,
209    /// The literal read as an integer, if it is one.
210    pub as_int: Option<i128>,
211    /// The literal read as a float, if it is one.
212    pub as_float: Option<f64>,
213}
214
215impl ComparisonValue {
216    /// Pre-coerces a literal.
217    #[must_use]
218    pub fn new(text: NameId, literal: &str) -> Self {
219        let literal = literal.trim();
220        Self {
221            text,
222            as_int: literal.parse::<i128>().ok(),
223            as_float: literal.parse::<f64>().ok(),
224        }
225    }
226}
227
228/// `<xtce:Comparison>`.
229#[derive(Clone, Copy, Debug)]
230pub struct Comparison {
231    /// Parameter being tested.
232    pub parameter: ParamId,
233    /// Operator.
234    pub operator: CompareOp,
235    /// Required value, pre-coerced to every reading that could apply.
236    pub value: ComparisonValue,
237    /// Whether to test the calibrated or the raw value.
238    pub use_calibrated: bool,
239}
240
241/// `<xtce:BooleanExpression>`.
242#[derive(Clone, Debug)]
243pub enum BooleanExpr {
244    /// A single `<Condition>`.
245    Condition(Condition),
246    /// `<ANDedConditions>`: true when every child is true.
247    And(Vec<BooleanExpr>),
248    /// `<ORedConditions>`: true when any child is true.
249    Or(Vec<BooleanExpr>),
250}
251
252/// `<xtce:Condition>`: two operands and an operator.
253#[derive(Clone, Copy, Debug)]
254pub struct Condition {
255    /// Left-hand side; always a parameter reference per the schema.
256    pub left: Operand,
257    /// Operator.
258    pub operator: CompareOp,
259    /// Right-hand side; a parameter reference or a literal `<Value>`.
260    pub right: Operand,
261}
262
263/// One side of a [`Condition`].
264#[derive(Clone, Copy, Debug)]
265pub enum Operand {
266    /// `<ParameterInstanceRef>`.
267    Parameter {
268        /// The referenced parameter.
269        parameter: ParamId,
270        /// Whether to read its calibrated or raw value.
271        use_calibrated: bool,
272    },
273    /// `<Value>`, pre-coerced against whatever the other operand turns out to be.
274    Literal(ComparisonValue),
275}
276
277/// A `<xtce:SpaceSystem>` node.
278#[derive(Clone, Debug)]
279pub struct SpaceSystem {
280    /// Name as written.
281    pub name: NameId,
282    /// Fully qualified path, e.g. `/Root/Payload`. The root is `/Root`.
283    pub qualified_name: NameId,
284    /// Enclosing space system, if any.
285    pub parent: Option<SpaceSystemId>,
286    /// Nested space systems, in document order.
287    pub children: Vec<SpaceSystemId>,
288}