Skip to main content

xtce_decode/
value.rs

1//! Decoded parameter values.
2//!
3//! XTCE separates the *raw* value — the bits as they appear in the packet, interpreted only
4//! as far as the data encoding says — from the *engineering* value, which is the raw value
5//! after calibration or enumeration lookup. Keeping both is not redundancy: a `Comparison`
6//! in a restriction criterion may test either one, and differential testing against another
7//! implementation is only meaningful if both are compared.
8
9use std::borrow::Cow;
10use std::fmt;
11
12use xtce_model::{ContainerId, ParamId, XtceDb, intern::FxHashMap};
13
14/// A value exactly as encoded in the packet.
15#[derive(Clone, Debug, PartialEq)]
16pub enum RawValue<'p> {
17    /// An unsigned integer field.
18    Unsigned(u64),
19    /// A signed integer field.
20    Signed(i64),
21    /// A float field.
22    Float(f64),
23    /// A binary or string field. Borrowed from the packet when the read was byte-aligned.
24    Bytes(Cow<'p, [u8]>),
25}
26
27/// A value after calibration, enumeration lookup or text decoding.
28#[derive(Clone, Debug, PartialEq)]
29pub enum EngValue<'db, 'p> {
30    /// An uncalibrated unsigned integer.
31    Unsigned(u64),
32    /// An uncalibrated signed integer.
33    Signed(i64),
34    /// A float, either encoded as one or produced by a calibrator.
35    Float(f64),
36    /// A boolean parameter's value.
37    Bool(bool),
38    /// An enumeration label, borrowed from the definition.
39    Label(&'db str),
40    /// Text decoded from the packet.
41    Text(Cow<'p, str>),
42    /// Binary data.
43    Bytes(Cow<'p, [u8]>),
44}
45
46impl RawValue<'_> {
47    /// The value as an integer, when it is one.
48    #[must_use]
49    pub fn as_i128(&self) -> Option<i128> {
50        match self {
51            Self::Unsigned(value) => Some(i128::from(*value)),
52            Self::Signed(value) => Some(i128::from(*value)),
53            Self::Float(_) | Self::Bytes(_) => None,
54        }
55    }
56
57    /// The value as a float, when it is numeric.
58    #[must_use]
59    pub fn as_f64(&self) -> Option<f64> {
60        match self {
61            Self::Unsigned(value) => Some(*value as f64),
62            Self::Signed(value) => Some(*value as f64),
63            Self::Float(value) => Some(*value),
64            Self::Bytes(_) => None,
65        }
66    }
67}
68
69impl EngValue<'_, '_> {
70    /// The value as an integer, when it is one.
71    ///
72    /// Booleans convert to 0 and 1, matching XTCE's definition of a boolean as a restricted
73    /// enumeration over an integer encoding.
74    #[must_use]
75    pub fn as_i128(&self) -> Option<i128> {
76        match self {
77            Self::Unsigned(value) => Some(i128::from(*value)),
78            Self::Signed(value) => Some(i128::from(*value)),
79            Self::Bool(value) => Some(i128::from(*value)),
80            Self::Float(_) | Self::Label(_) | Self::Text(_) | Self::Bytes(_) => None,
81        }
82    }
83
84    /// The value as a float, when it is numeric.
85    #[must_use]
86    pub fn as_f64(&self) -> Option<f64> {
87        match self {
88            Self::Unsigned(value) => Some(*value as f64),
89            Self::Signed(value) => Some(*value as f64),
90            Self::Float(value) => Some(*value),
91            Self::Bool(value) => Some(f64::from(u8::from(*value))),
92            Self::Label(_) | Self::Text(_) | Self::Bytes(_) => None,
93        }
94    }
95
96    /// The value as text, when it is textual.
97    #[must_use]
98    pub fn as_str(&self) -> Option<&str> {
99        match self {
100            Self::Label(text) => Some(text),
101            Self::Text(text) => Some(text),
102            _ => None,
103        }
104    }
105}
106
107impl fmt::Display for RawValue<'_> {
108    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109        match self {
110            Self::Unsigned(value) => write!(f, "{value}"),
111            Self::Signed(value) => write!(f, "{value}"),
112            Self::Float(value) => write!(f, "{value}"),
113            Self::Bytes(bytes) => write_hex(f, bytes),
114        }
115    }
116}
117
118impl fmt::Display for EngValue<'_, '_> {
119    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120        match self {
121            Self::Unsigned(value) => write!(f, "{value}"),
122            Self::Signed(value) => write!(f, "{value}"),
123            Self::Float(value) => write!(f, "{value}"),
124            Self::Bool(value) => write!(f, "{value}"),
125            Self::Label(text) => write!(f, "{text}"),
126            Self::Text(text) => write!(f, "{text}"),
127            Self::Bytes(bytes) => write_hex(f, bytes),
128        }
129    }
130}
131
132fn write_hex(f: &mut fmt::Formatter<'_>, bytes: &[u8]) -> fmt::Result {
133    const PREVIEW: usize = 16;
134    for byte in bytes.iter().take(PREVIEW) {
135        write!(f, "{byte:02x}")?;
136    }
137    if bytes.len() > PREVIEW {
138        write!(f, "… ({} bytes)", bytes.len())?;
139    }
140    Ok(())
141}
142
143/// One decoded parameter: which parameter, and both of its values.
144#[derive(Clone, Debug)]
145pub struct ParameterValue<'db, 'p> {
146    /// The parameter this value belongs to.
147    pub parameter: ParamId,
148    /// The bits as they appeared in the packet.
149    pub raw: RawValue<'p>,
150    /// The value after calibration or lookup.
151    pub eng: EngValue<'db, 'p>,
152    /// Bit offset of the field within the packet.
153    pub bit_offset: usize,
154    /// Width of the field, in bits.
155    pub bit_width: usize,
156}
157
158/// The result of decoding one packet.
159///
160/// Values are kept in decode order. If a parameter is decoded more than once — which an
161/// entry list can do — the later value replaces the earlier one in place, so the packet
162/// reads as a map with stable ordering, exactly as the reference implementation's dict does.
163pub struct DecodedPacket<'db, 'p> {
164    db: &'db XtceDb,
165    data: &'p [u8],
166    values: Vec<ParameterValue<'db, 'p>>,
167    slots: FxHashMap<ParamId, u32>,
168    container: ContainerId,
169    bits_consumed: usize,
170}
171
172impl<'db, 'p> DecodedPacket<'db, 'p> {
173    pub(crate) fn with_capacity(
174        db: &'db XtceDb,
175        data: &'p [u8],
176        container: ContainerId,
177        capacity: usize,
178    ) -> Self {
179        Self {
180            db,
181            data,
182            values: Vec::with_capacity(capacity),
183            slots: FxHashMap::with_capacity_and_hasher(
184                capacity,
185                std::hash::BuildHasherDefault::default(),
186            ),
187            container,
188            bits_consumed: 0,
189        }
190    }
191
192    /// Empties the packet for reuse, keeping its allocations.
193    ///
194    /// This is what makes [`crate::Decoder::decode_into`] allocation-free after the first
195    /// packet: decoding a stream otherwise allocates a `Vec` and a table per packet, and a
196    /// large container regrows both several times on the way.
197    pub(crate) fn reset(&mut self, data: &'p [u8], container: ContainerId) {
198        self.values.clear();
199        self.slots.clear();
200        self.data = data;
201        self.container = container;
202        self.bits_consumed = 0;
203    }
204
205    pub(crate) fn insert(&mut self, value: ParameterValue<'db, 'p>) {
206        if let Some(index) = self.slots.get(&value.parameter).copied() {
207            if let Some(slot) = self.values.get_mut(index as usize) {
208                *slot = value;
209            }
210        } else {
211            let index = u32::try_from(self.values.len()).unwrap_or(u32::MAX);
212            self.slots.insert(value.parameter, index);
213            self.values.push(value);
214        }
215    }
216
217    pub(crate) fn set_container(&mut self, container: ContainerId) {
218        self.container = container;
219    }
220
221    pub(crate) fn set_bits_consumed(&mut self, bits: usize) {
222        self.bits_consumed = bits;
223    }
224
225    /// The database this packet was decoded against.
226    #[must_use]
227    pub fn db(&self) -> &'db XtceDb {
228        self.db
229    }
230
231    /// The packet bytes.
232    #[must_use]
233    pub fn data(&self) -> &'p [u8] {
234        self.data
235    }
236
237    /// The most derived container that matched.
238    #[must_use]
239    pub fn container(&self) -> ContainerId {
240        self.container
241    }
242
243    /// Bits consumed by the entry lists that ran.
244    #[must_use]
245    pub fn bits_consumed(&self) -> usize {
246        self.bits_consumed
247    }
248
249    /// Bits in the packet that no entry claimed.
250    ///
251    /// Non-zero is not an error — the reference implementation only warns — but it usually
252    /// means the definition and the packet disagree, so it is worth surfacing.
253    #[must_use]
254    pub fn trailing_bits(&self) -> isize {
255        self.data.len() as isize * 8 - self.bits_consumed as isize
256    }
257
258    /// Decoded values, in decode order.
259    #[must_use]
260    pub fn values(&self) -> &[ParameterValue<'db, 'p>] {
261        &self.values
262    }
263
264    /// Number of decoded parameters.
265    #[must_use]
266    pub fn len(&self) -> usize {
267        self.values.len()
268    }
269
270    /// Whether nothing was decoded.
271    #[must_use]
272    pub fn is_empty(&self) -> bool {
273        self.values.is_empty()
274    }
275
276    /// A decoded value by parameter id.
277    #[must_use]
278    pub fn get(&self, parameter: ParamId) -> Option<&ParameterValue<'db, 'p>> {
279        let index = self.slots.get(&parameter).copied()?;
280        self.values.get(index as usize)
281    }
282
283    /// A decoded value by parameter name.
284    #[must_use]
285    pub fn get_by_name(&self, name: &str) -> Option<&ParameterValue<'db, 'p>> {
286        self.get(self.db.find_parameter(name)?)
287    }
288
289    /// Iterates `(name, value)` pairs in decode order.
290    pub fn iter_named(&self) -> impl Iterator<Item = (&'db str, &ParameterValue<'db, 'p>)> {
291        self.values.iter().map(move |value| {
292            let name = self
293                .db
294                .parameter(value.parameter)
295                .map_or("?", |parameter| self.db.name(parameter.name));
296            (name, value)
297        })
298    }
299}
300
301impl fmt::Debug for DecodedPacket<'_, '_> {
302    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
303        f.debug_struct("DecodedPacket")
304            .field("container", &self.container)
305            .field("values", &self.values.len())
306            .field("bits_consumed", &self.bits_consumed)
307            .finish_non_exhaustive()
308    }
309}