Skip to main content

xtce_model/
types.rs

1//! Parameter types, data encodings and calibrators.
2
3use crate::ids::{ParamId, TypeId};
4use crate::intern::NameId;
5
6/// A `<xtce:*ParameterType>` definition.
7#[derive(Clone, Debug)]
8pub struct ParameterType {
9    /// Type name as written, e.g. `MSN__PARAM_Type`.
10    pub name: NameId,
11    /// Fully qualified name, e.g. `/Root/MSN__PARAM_Type`.
12    pub qualified_name: NameId,
13    /// The space system that owns this definition.
14    pub space_system: crate::ids::SpaceSystemId,
15    /// Engineering units, if declared. XTCE permits compound units, hence a list.
16    pub units: Vec<NameId>,
17    /// What kind of value this type produces.
18    pub kind: TypeKind,
19    /// How the value is laid out in the packet.
20    pub encoding: DataEncoding,
21}
22
23impl ParameterType {
24    /// Number of bits this type occupies, when that is fixed at load time.
25    ///
26    /// `None` means the width depends on packet content — a dynamically sized binary or
27    /// string field — and can only be known while decoding.
28    #[must_use]
29    pub fn fixed_size_in_bits(&self) -> Option<u32> {
30        self.encoding.fixed_size_in_bits()
31    }
32}
33
34/// The semantic family of a parameter type.
35#[derive(Clone, Debug)]
36pub enum TypeKind {
37    /// `IntegerParameterType`.
38    Integer,
39    /// `FloatParameterType`.
40    Float,
41    /// `StringParameterType`.
42    String,
43    /// `BinaryParameterType`.
44    Binary,
45    /// `BooleanParameterType`.
46    ///
47    /// XTCE calls this "a restricted form of enumeration", and the reference
48    /// implementation derives truthiness from the *raw* value, ignoring the label
49    /// attributes. The labels are kept here so callers can render them; see
50    /// [`crate::XtceDb::boolean_label`].
51    Boolean {
52        /// Label for the false value, from `zeroStringValue`.
53        zero_label: Option<NameId>,
54        /// Label for the true value, from `oneStringValue`.
55        one_label: Option<NameId>,
56    },
57    /// `EnumeratedParameterType`.
58    Enumerated(EnumerationList),
59    /// `AbsoluteTimeParameterType`.
60    AbsoluteTime {
61        /// `ReferenceTime/Epoch`, verbatim.
62        epoch: Option<NameId>,
63        /// `ReferenceTime/OffsetFrom/@parameterRef`, resolved.
64        offset_from: Option<ParamId>,
65    },
66    /// `RelativeTimeParameterType`.
67    RelativeTime,
68    /// `AggregateParameterType`: a record, "analogous to a C-struct".
69    ///
70    /// Like an array, a parameter of this type never reaches a decoder: the container entry
71    /// naming it is expanded at load time into one synthetic parameter per member. XTCE says
72    /// the members are "ordered and contiguous … (packed)" and addressed "by the dot syntax
73    /// similar to C such as `P.voltage`", so that is what the expansion produces.
74    Aggregate {
75        /// Members in document order, which is the order they occupy in the packet.
76        members: Vec<AggregateMember>,
77    },
78    /// `ArrayParameterType`: a repetition of one element type.
79    ///
80    /// A parameter of this type never reaches a decoder. The container entry that names it is
81    /// expanded at load time into one synthetic parameter per index, each of the element
82    /// type, so everything downstream sees ordinary fields — see `XtceDb::array_element_of`.
83    /// The type is kept because `xtce info` reports it and because the expansion needs it.
84    Array {
85        /// The type each element has.
86        element: TypeId,
87        /// One entry per dimension, outermost first. XTCE writes `Array[1st][2nd][last]` and
88        /// says the last dimension varies fastest, so the layout is row-major.
89        dimensions: Vec<ArrayDimension>,
90    },
91    /// A parameter type this crate models structurally but cannot decode.
92    ///
93    /// Loading succeeds; decoding a parameter of this type reports
94    /// `XtceError::Unsupported` naming the element below.
95    Unsupported {
96        /// The element name that put this type out of scope.
97        element: NameId,
98    },
99}
100
101impl TypeKind {
102    /// A short, stable name for reporting, e.g. in `xtce info`.
103    #[must_use]
104    pub const fn label(&self) -> &'static str {
105        match self {
106            Self::Integer => "integer",
107            Self::Float => "float",
108            Self::String => "string",
109            Self::Binary => "binary",
110            Self::Boolean { .. } => "boolean",
111            Self::Enumerated(_) => "enumerated",
112            Self::AbsoluteTime { .. } => "absolute-time",
113            Self::RelativeTime => "relative-time",
114            Self::Array { .. } => "array",
115            Self::Aggregate { .. } => "aggregate",
116            Self::Unsupported { .. } => "unsupported",
117        }
118    }
119}
120
121/// One `<xtce:Member>` of an aggregate.
122#[derive(Clone, Copy, Debug)]
123pub struct AggregateMember {
124    /// The member's name, which becomes the part after the dot.
125    pub name: NameId,
126    /// The type the member has.
127    pub type_id: TypeId,
128}
129
130/// One `<xtce:Dimension>` of an array, as a pair of inclusive zero-based indices.
131///
132/// XTCE 1.2 §4.3.2.4.2: "For partial entries of an array, the starting and ending index for
133/// each dimension … Indexes are zero based." Both ends are inclusive, so a dimension of
134/// `0..=4` has five elements.
135#[derive(Clone, Copy, Debug, PartialEq, Eq)]
136pub struct ArrayDimension {
137    /// `StartingIndex`, zero-based and inclusive.
138    pub start: i64,
139    /// `EndingIndex`, zero-based and inclusive.
140    pub end: i64,
141}
142
143impl ArrayDimension {
144    /// How many elements the dimension spans, or `None` if it runs backwards.
145    #[must_use]
146    pub fn len(&self) -> Option<usize> {
147        // `try_from` rather than a cast: the sign is exactly what makes a backwards
148        // dimension unusable, so losing it here would turn one into a plausible length.
149        let span = self.end.checked_sub(self.start)?;
150        usize::try_from(span).ok()?.checked_add(1)
151    }
152
153    /// Whether the dimension spans nothing, which XTCE cannot express but a file can say.
154    #[must_use]
155    pub fn is_empty(&self) -> bool {
156        self.len().is_none()
157    }
158}
159
160/// The `<xtce:EnumerationList>` of an enumerated parameter type.
161///
162/// Entries are stored sorted by `value` so that lookup is a binary search rather than a
163/// linear scan; enumerations in real databases reach several hundred entries.
164#[derive(Clone, Debug, Default)]
165pub struct EnumerationList {
166    entries: Vec<Enumeration>,
167}
168
169/// One `<xtce:Enumeration>`.
170#[derive(Clone, Copy, Debug)]
171pub struct Enumeration {
172    /// The raw encoded value this label applies to.
173    pub value: i128,
174    /// Inclusive upper bound, from `maxValue`; equal to `value` for a point entry.
175    pub max_value: i128,
176    /// The label.
177    pub label: NameId,
178}
179
180impl EnumerationList {
181    /// Builds a list from unsorted entries.
182    #[must_use]
183    pub fn new(mut entries: Vec<Enumeration>) -> Self {
184        entries.sort_unstable_by_key(|entry| entry.value);
185        Self { entries }
186    }
187
188    /// All entries, ordered by value.
189    #[must_use]
190    pub fn entries(&self) -> &[Enumeration] {
191        &self.entries
192    }
193
194    /// The label covering `value`, if any.
195    ///
196    /// Ranged entries (`maxValue`) are honoured, so a value inside `value..=max_value`
197    /// matches.
198    #[must_use]
199    pub fn label_for(&self, value: i128) -> Option<NameId> {
200        // `partition_point` finds the last entry whose `value` is <= the query; ranged
201        // entries then need only that one bound check.
202        let idx = self.entries.partition_point(|entry| entry.value <= value);
203        let candidate = self.entries.get(idx.checked_sub(1)?)?;
204        (value <= candidate.max_value).then_some(candidate.label)
205    }
206}
207
208/// Byte order of a multi-byte encoded value.
209#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
210pub enum ByteOrder {
211    /// `mostSignificantByteFirst` — big-endian, the CCSDS default.
212    #[default]
213    MostSignificantFirst,
214    /// `leastSignificantByteFirst` — little-endian.
215    LeastSignificantFirst,
216}
217
218/// How a value is laid out in the packet.
219#[derive(Clone, Debug)]
220pub enum DataEncoding {
221    /// `<xtce:IntegerDataEncoding>`.
222    Integer(IntegerEncoding),
223    /// `<xtce:FloatDataEncoding>`.
224    Float(FloatEncoding),
225    /// `<xtce:StringDataEncoding>`.
226    String(StringEncoding),
227    /// `<xtce:BinaryDataEncoding>`.
228    Binary(BinaryEncoding),
229    /// No usable encoding was found under the parameter type.
230    None,
231}
232
233impl DataEncoding {
234    /// Width in bits when fixed at load time.
235    #[must_use]
236    pub fn fixed_size_in_bits(&self) -> Option<u32> {
237        match self {
238            Self::Integer(encoding) => Some(encoding.size_in_bits),
239            Self::Float(encoding) => Some(encoding.size_in_bits),
240            Self::String(encoding) => encoding.raw_size.fixed(),
241            Self::Binary(encoding) => encoding.size.fixed(),
242            Self::None => None,
243        }
244    }
245
246    /// The default calibrator, if the encoding supports calibration and declares one.
247    #[must_use]
248    pub fn default_calibrator(&self) -> Option<&Calibrator> {
249        match self {
250            Self::Integer(encoding) => encoding.default_calibrator.as_ref(),
251            Self::Float(encoding) => encoding.default_calibrator.as_ref(),
252            Self::String(_) | Self::Binary(_) | Self::None => None,
253        }
254    }
255
256    /// Context calibrators, in document order.
257    #[must_use]
258    pub fn context_calibrators(&self) -> &[ContextCalibrator] {
259        match self {
260            Self::Integer(encoding) => &encoding.context_calibrators,
261            Self::Float(encoding) => &encoding.context_calibrators,
262            Self::String(_) | Self::Binary(_) | Self::None => &[],
263        }
264    }
265}
266
267/// Integer encodings defined by XTCE 4.3.2.2.5.6.2.
268#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
269pub enum IntegerCoding {
270    /// `unsigned`.
271    #[default]
272    Unsigned,
273    /// `twosComplement`, plus the misspelling `twosCompliment` and the informal `signed`,
274    /// both of which occur in shipped mission databases and are accepted by the reference
275    /// implementation.
276    TwosComplement,
277    /// `signMagnitude`: the top bit is the sign, the rest is magnitude.
278    SignMagnitude,
279    /// `onesComplement`.
280    OnesComplement,
281}
282
283/// `<xtce:IntegerDataEncoding>`.
284#[derive(Clone, Debug)]
285pub struct IntegerEncoding {
286    /// Field width in bits, 1..=64.
287    pub size_in_bits: u32,
288    /// How the bits map to an integer.
289    pub coding: IntegerCoding,
290    /// Byte order for widths above one byte.
291    pub byte_order: ByteOrder,
292    /// Calibrator applied when no context calibrator matches.
293    pub default_calibrator: Option<Calibrator>,
294    /// Conditional calibrators, evaluated in document order.
295    pub context_calibrators: Vec<ContextCalibrator>,
296}
297
298/// Float encodings.
299#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
300pub enum FloatCoding {
301    /// `IEEE754` / `IEEE754_1985`, at 16, 32 or 64 bits.
302    #[default]
303    Ieee754,
304    /// `MILSTD_1750A`, always 32 bits.
305    MilStd1750A,
306}
307
308/// `<xtce:FloatDataEncoding>`.
309#[derive(Clone, Debug)]
310pub struct FloatEncoding {
311    /// Field width in bits.
312    pub size_in_bits: u32,
313    /// Which float format the bits are in.
314    pub coding: FloatCoding,
315    /// Byte order.
316    pub byte_order: ByteOrder,
317    /// Calibrator applied when no context calibrator matches.
318    pub default_calibrator: Option<Calibrator>,
319    /// Conditional calibrators, evaluated in document order.
320    pub context_calibrators: Vec<ContextCalibrator>,
321}
322
323/// Character sets XTCE allows for string data.
324#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
325pub enum Charset {
326    /// `UTF-8`, the XTCE default.
327    #[default]
328    Utf8,
329    /// `US-ASCII`.
330    UsAscii,
331    /// `ISO-8859-1` (Latin-1).
332    Iso8859_1,
333    /// `Windows-1252`.
334    Windows1252,
335    /// `UTF-16`, `UTF-16BE` or `UTF-16LE`; endianness is carried separately.
336    Utf16,
337    /// `UTF-32`, `UTF-32BE` or `UTF-32LE`.
338    Utf32,
339}
340
341impl Charset {
342    /// Bytes per code unit.
343    #[must_use]
344    pub const fn code_unit_bytes(self) -> usize {
345        match self {
346            Self::Utf8 | Self::UsAscii | Self::Iso8859_1 | Self::Windows1252 => 1,
347            Self::Utf16 => 2,
348            Self::Utf32 => 4,
349        }
350    }
351}
352
353/// How the *derived* string is delimited inside its raw buffer.
354#[derive(Clone, Debug, Default)]
355pub enum StringDelimiter {
356    /// The whole raw buffer is the string.
357    #[default]
358    WholeBuffer,
359    /// The string ends at the first occurrence of these bytes.
360    TerminationChar(Vec<u8>),
361    /// The buffer starts with an integer of this many bits giving the string length in bits.
362    LeadingSize {
363        /// Width of the length prefix, in bits.
364        size_in_bits: u32,
365    },
366}
367
368/// `<xtce:StringDataEncoding>`.
369#[derive(Clone, Debug)]
370pub struct StringEncoding {
371    /// Character set of the decoded text.
372    pub charset: Charset,
373    /// Byte order, relevant for UTF-16 and UTF-32.
374    pub byte_order: ByteOrder,
375    /// Size of the raw buffer, including any terminator or length prefix.
376    pub raw_size: SizeSpec,
377    /// How to find the string inside the raw buffer.
378    pub delimiter: StringDelimiter,
379}
380
381/// `<xtce:BinaryDataEncoding>`.
382#[derive(Clone, Debug)]
383pub struct BinaryEncoding {
384    /// Size of the binary field.
385    pub size: SizeSpec,
386}
387
388/// How a variable-width field's size is determined.
389#[derive(Clone, Debug)]
390pub enum SizeSpec {
391    /// A literal bit count from `SizeInBits/FixedValue`.
392    Fixed(u32),
393    /// A bit count read from another parameter, per `SizeInBits/DynamicValue`.
394    Dynamic {
395        /// The parameter holding the size.
396        parameter: ParamId,
397        /// Whether to read its calibrated or raw value.
398        use_calibrated: bool,
399        /// Optional `slope`/`intercept` conversion, typically bytes to bits.
400        adjustment: Option<LinearAdjustment>,
401    },
402    /// A bit count chosen by the first matching entry of a `DiscreteLookupList`.
403    DiscreteLookup(Vec<DiscreteLookup>),
404    /// The size could not be modelled; decoding such a field reports the element below.
405    Unsupported {
406        /// The element that put the size out of scope.
407        element: NameId,
408    },
409}
410
411impl SizeSpec {
412    /// The bit count, when it is fixed at load time.
413    #[must_use]
414    pub const fn fixed(&self) -> Option<u32> {
415        match self {
416            Self::Fixed(bits) => Some(*bits),
417            _ => None,
418        }
419    }
420}
421
422/// `<xtce:LinearAdjustment>`: `slope * x + intercept`.
423#[derive(Clone, Copy, Debug)]
424pub struct LinearAdjustment {
425    /// Multiplier.
426    pub slope: f64,
427    /// Additive term.
428    pub intercept: f64,
429}
430
431impl LinearAdjustment {
432    /// Applies the adjustment.
433    #[must_use]
434    pub fn apply(self, value: f64) -> f64 {
435        self.slope * value + self.intercept
436    }
437}
438
439/// One `<xtce:DiscreteLookup>`: a value returned when all its criteria hold.
440#[derive(Clone, Debug)]
441pub struct DiscreteLookup {
442    /// Criteria that must all hold.
443    pub criteria: Vec<crate::containers::MatchCriteria>,
444    /// The value produced when they do.
445    pub value: i64,
446}
447
448/// A calibrator converting a raw encoded value into an engineering value.
449#[derive(Clone, Debug)]
450pub enum Calibrator {
451    /// `<xtce:PolynomialCalibrator>`.
452    ///
453    /// Terms are kept in document order, not sorted by exponent: floating-point addition is
454    /// not associative, and the differential tests compare against a reference that
455    /// accumulates in document order.
456    Polynomial(Vec<PolynomialTerm>),
457    /// `<xtce:SplineCalibrator>`.
458    Spline(Spline),
459    /// A calibrator kind outside this crate's scope, e.g. `MathOperationCalibrator`.
460    Unsupported {
461        /// The element that put the calibrator out of scope.
462        element: NameId,
463    },
464}
465
466/// One `<xtce:Term>` of a polynomial calibrator.
467#[derive(Clone, Copy, Debug)]
468pub struct PolynomialTerm {
469    /// Multiplier.
470    pub coefficient: f64,
471    /// Power of the raw value.
472    pub exponent: i32,
473}
474
475/// `<xtce:SplineCalibrator>`.
476#[derive(Clone, Debug)]
477pub struct Spline {
478    /// 0 for nearest-lower-point, 1 for linear interpolation.
479    pub order: u8,
480    /// Points sorted by raw value.
481    pub points: Vec<SplinePoint>,
482    /// Whether queries outside the point range are extrapolated instead of rejected.
483    pub extrapolate: bool,
484}
485
486/// One `<xtce:SplinePoint>`.
487#[derive(Clone, Copy, Debug)]
488pub struct SplinePoint {
489    /// Raw value.
490    pub raw: f64,
491    /// Calibrated value.
492    pub calibrated: f64,
493}
494
495/// `<xtce:ContextCalibrator>`: a calibrator gated on other parameter values.
496#[derive(Clone, Debug)]
497pub struct ContextCalibrator {
498    /// Criteria that must all hold for this calibrator to apply.
499    pub criteria: Vec<crate::containers::MatchCriteria>,
500    /// The calibrator to apply.
501    pub calibrator: Calibrator,
502}
503
504/// A `<xtce:Parameter>` definition.
505#[derive(Clone, Debug)]
506pub struct Parameter {
507    /// Parameter name as written.
508    pub name: NameId,
509    /// Fully qualified name.
510    pub qualified_name: NameId,
511    /// The space system that owns this definition.
512    pub space_system: crate::ids::SpaceSystemId,
513    /// The parameter's type.
514    pub type_id: TypeId,
515    /// `shortDescription`, if present.
516    pub short_description: Option<NameId>,
517    /// `<LongDescription>`, if present.
518    pub long_description: Option<NameId>,
519    /// `initialValue`, verbatim, if present.
520    pub initial_value: Option<NameId>,
521}