Skip to main content

cal_model/
project.rs

1//! The calibration project: an A2L description plus an optional DBC
2//! database, resolved into addressable, convertible, limit-checked
3//! parameters.
4//!
5//! # What the L1 substrates do and do not hand over
6//!
7//! [`a2l_parse`] gives the *declaration* — addresses, limits, record
8//! layouts, COMPU_METHODs — and [`dbc_parse`] gives the *bus layout*.
9//! `cal-model` owns everything between those two and the wire: resolving
10//! every reference the description makes, evaluating and inverting
11//! conversions, checking limits, coding deposits into bytes, and pairing
12//! characteristics with signals by name.
13//!
14//! # Reference resolution is strict
15//!
16//! A CHARACTERISTIC whose `COMPU_METHOD` or `RECORD_LAYOUT` is not declared
17//! in its module is a [`CalError::Unsupported`], not a silently defaulted
18//! one. A conversion that cannot be resolved is worse than no conversion:
19//! the ECU would be written with values the calibration engineer never saw.
20//! A `TABLE` conversion resolves once its `COMPU_TAB_REF` points are
21//! registered ([`register_table`](Self::register_table)).
22
23use crate::conversion::CompuMethod;
24use crate::error::CalError;
25use crate::model::{CharKind, Characteristic, Measurement, Module};
26use crate::signal::SignalBinding;
27use a2l_parse::{A2lProject, DataType};
28use dbc_parse::Dbc;
29use std::cmp::Ordering;
30use std::collections::BTreeMap;
31use std::path::Path;
32
33/// A calibration project: an A2L description, optionally bound to a DBC
34/// database.
35#[derive(Debug, Clone, PartialEq)]
36pub struct CalibrationProject {
37    a2l: A2lProject,
38    modules: Vec<Module>,
39    dbc: Option<Dbc>,
40    tables: BTreeMap<String, Vec<(f64, f64)>>,
41    bindings: BTreeMap<String, BTreeMap<String, SignalBinding>>,
42    measurement_bindings: BTreeMap<String, BTreeMap<String, SignalBinding>>,
43    deposit_byte_order: xcp_core::ByteOrder,
44}
45
46impl CalibrationProject {
47    /// Parse an A2L description and resolve every reference it makes.
48    ///
49    /// # Errors
50    ///
51    /// [`CalError::A2l`] for a malformed file,
52    /// [`CalError::Unsupported`] when a characteristic or measurement
53    /// references a `COMPU_METHOD` or `RECORD_LAYOUT` its module does not
54    /// declare.
55    pub fn from_a2l(text: &str) -> Result<Self, CalError> {
56        Self::from_parsed(A2lProject::parse(text)?)
57    }
58
59    /// Read and resolve an A2L description from disk.
60    ///
61    /// # Errors
62    ///
63    /// [`CalError::Io`] when the file cannot be read, otherwise as
64    /// [`from_a2l`](Self::from_a2l).
65    pub fn from_a2l_file(path: &Path) -> Result<Self, CalError> {
66        let text = std::fs::read_to_string(path).map_err(|err| CalError::Io {
67            path: path.display().to_string(),
68            detail: err.to_string(),
69        })?;
70        Self::from_a2l(&text)
71    }
72
73    /// Resolve an already-parsed A2L project.
74    ///
75    /// # Errors
76    ///
77    /// [`CalError::Unsupported`] as in [`from_a2l`](Self::from_a2l).
78    pub fn from_parsed(a2l: A2lProject) -> Result<Self, CalError> {
79        let mut modules = Vec::with_capacity(a2l.modules.len());
80        for a2l_module in &a2l.modules {
81            let mut characteristics = Vec::with_capacity(a2l_module.characteristics.len());
82            for raw in &a2l_module.characteristics {
83                let layout = a2l_module
84                    .record_layout_by_name(&raw.deposit)
85                    .ok_or_else(|| CalError::Unsupported {
86                        subject: format!("characteristic `{}`", raw.name),
87                        reason: format!(
88                            "RECORD_LAYOUT `{}` is not declared in module `{}`",
89                            raw.deposit, a2l_module.name
90                        ),
91                    })?;
92                let fnc = layout.fnc_values.ok_or_else(|| CalError::Unsupported {
93                    subject: format!("characteristic `{}`", raw.name),
94                    reason: format!(
95                        "RECORD_LAYOUT `{}` declares no FNC_VALUES, so the deposit datatype is unknown",
96                        raw.deposit
97                    ),
98                })?;
99                let method = a2l_module
100                    .compu_method_by_name(&raw.conversion)
101                    .ok_or_else(|| CalError::Unsupported {
102                        subject: format!("characteristic `{}`", raw.name),
103                        reason: format!(
104                            "COMPU_METHOD `{}` is not declared in module `{}`",
105                            raw.conversion, a2l_module.name
106                        ),
107                    })?;
108                characteristics.push(Characteristic {
109                    name: raw.name.clone(),
110                    kind: CharKind::from_char_type(raw.r#type),
111                    address: raw.address,
112                    deposit: raw.deposit.clone(),
113                    deposit_position: fnc.position,
114                    datatype: fnc.datatype,
115                    elements: 1,
116                    conversion: CompuMethod::from_a2l(method),
117                    lower_limit: raw.lower_limit,
118                    upper_limit: raw.upper_limit,
119                    max_diff: raw.max_diff,
120                });
121            }
122            let mut measurements = Vec::with_capacity(a2l_module.measurements.len());
123            for raw in &a2l_module.measurements {
124                let method = a2l_module
125                    .compu_method_by_name(&raw.conversion)
126                    .ok_or_else(|| CalError::Unsupported {
127                        subject: format!("measurement `{}`", raw.name),
128                        reason: format!(
129                            "COMPU_METHOD `{}` is not declared in module `{}`",
130                            raw.conversion, a2l_module.name
131                        ),
132                    })?;
133                measurements.push(Measurement {
134                    name: raw.name.clone(),
135                    address: raw.address,
136                    conversion: CompuMethod::from_a2l(method),
137                    datatype: raw.datatype,
138                });
139            }
140            modules.push(Module {
141                name: a2l_module.name.clone(),
142                characteristics,
143                measurements,
144            });
145        }
146        Ok(Self {
147            a2l,
148            modules,
149            dbc: None,
150            tables: BTreeMap::new(),
151            bindings: BTreeMap::new(),
152            measurement_bindings: BTreeMap::new(),
153            deposit_byte_order: xcp_core::ByteOrder::Intel,
154        })
155    }
156
157    /// The A2L `PROJECT` name.
158    #[must_use]
159    pub fn project_name(&self) -> &str {
160        &self.a2l.project
161    }
162
163    /// The underlying parsed description, for callers that need the record
164    /// layouts and compu methods this layer resolved away.
165    #[must_use]
166    pub const fn a2l(&self) -> &A2lProject {
167        &self.a2l
168    }
169
170    /// The attached DBC database, when one has been attached.
171    #[must_use]
172    pub const fn dbc(&self) -> Option<&Dbc> {
173        self.dbc.as_ref()
174    }
175
176    /// Every module, in declaration order.
177    pub fn modules(&self) -> impl Iterator<Item = &Module> {
178        self.modules.iter()
179    }
180
181    /// The module named `name`.
182    ///
183    /// # Errors
184    ///
185    /// [`CalError::UnknownModule`] when no such module exists.
186    pub fn module(&self, name: &str) -> Result<&Module, CalError> {
187        self.modules
188            .iter()
189            .find(|m| m.name == name)
190            .ok_or_else(|| CalError::UnknownModule(name.to_string()))
191    }
192
193    /// Module names, in declaration order.
194    pub fn module_names(&self) -> impl Iterator<Item = &str> {
195        self.modules.iter().map(|m| m.name.as_str())
196    }
197
198    /// The characteristic `name` in module `module`.
199    ///
200    /// # Errors
201    ///
202    /// [`CalError::UnknownModule`] or [`CalError::UnknownCharacteristic`].
203    pub fn characteristic(&self, module: &str, name: &str) -> Result<&Characteristic, CalError> {
204        self.module(module)?
205            .characteristic(name)
206            .ok_or_else(|| CalError::UnknownCharacteristic(qualified(module, name)))
207    }
208
209    /// The measurement `name` in module `module`.
210    ///
211    /// # Errors
212    ///
213    /// [`CalError::UnknownModule`] or [`CalError::UnknownCharacteristic`].
214    pub fn measurement(&self, module: &str, name: &str) -> Result<&Measurement, CalError> {
215        self.module(module)?
216            .measurement(name)
217            .ok_or_else(|| CalError::UnknownCharacteristic(qualified(module, name)))
218    }
219
220    /// Declare how many elements a curve/map/value-block deposits.
221    ///
222    /// `a2l_parse` deliberately does not retain the ASAP2 `NUMBER` keyword
223    /// (nor `NO_AXIS_PTS`, which lives in the `AXIS_DESCR` blocks it
224    /// skips), so the element count of a multi-element characteristic is
225    /// not in the parsed model. Rather than guess — a wrong count reads the
226    /// wrong number of bytes out of ECU memory — the count is declared here,
227    /// next to the datatype it multiplies.
228    ///
229    /// # Errors
230    ///
231    /// [`CalError::UnknownModule`] or [`CalError::UnknownCharacteristic`].
232    pub fn declare_elements(
233        &mut self,
234        module: &str,
235        name: &str,
236        elements: usize,
237    ) -> Result<(), CalError> {
238        let target = self
239            .modules
240            .iter_mut()
241            .find(|m| m.name == module)
242            .ok_or_else(|| CalError::UnknownModule(module.to_string()))?
243            .characteristics
244            .iter_mut()
245            .find(|c| c.name == name)
246            .ok_or_else(|| CalError::UnknownCharacteristic(qualified(module, name)))?;
247        target.elements = elements;
248        Ok(())
249    }
250
251    /// Register the `(raw, physical)` points of an A2L `COMPU_TAB`.
252    ///
253    /// Points must be non-empty and strictly ascending by raw value — the
254    /// order the format specifies, and the order [`Curve`](crate::Curve)
255    /// and [`CompuMethod::apply`] rely on.
256    ///
257    /// # Errors
258    ///
259    /// [`CalError::Unsupported`] when the point list is empty or not
260    /// strictly ascending.
261    pub fn register_table(&mut self, name: &str, points: Vec<(f64, f64)>) -> Result<(), CalError> {
262        if points.is_empty() {
263            return Err(CalError::Unsupported {
264                subject: format!("COMPU_TAB `{name}`"),
265                reason: "a table needs at least one point".to_string(),
266            });
267        }
268        // Slice destructuring rather than indexing — `windows(2)` always
269        // yields exactly two elements — and `partial_cmp` rather than a
270        // negated `<`, so a NaN raw is visibly incomparable rather than
271        // silently "not ascending".
272        if points.windows(2).any(|pair| match pair {
273            [first, second] => !matches!(first.0.partial_cmp(&second.0), Some(Ordering::Less)),
274            _ => true,
275        }) {
276            return Err(CalError::Unsupported {
277                subject: format!("COMPU_TAB `{name}`"),
278                reason: "points must be strictly ascending by raw value".to_string(),
279            });
280        }
281        self.tables.insert(name.to_string(), points);
282        Ok(())
283    }
284
285    /// The points registered for `name`.
286    #[must_use]
287    pub fn table(&self, name: &str) -> Option<&[(f64, f64)]> {
288        self.tables.get(name).map(Vec::as_slice)
289    }
290
291    /// Every registered table, by `COMPU_TAB` name.
292    #[must_use]
293    pub const fn tables(&self) -> &BTreeMap<String, Vec<(f64, f64)>> {
294        &self.tables
295    }
296
297    /// The byte order used to code multi-byte deposit elements.
298    ///
299    /// XCP slaves advertise their byte order in the CONNECT response; the
300    /// default is Intel (little-endian), matching `xcp_core`'s default.
301    #[must_use]
302    pub const fn deposit_byte_order(&self) -> xcp_core::ByteOrder {
303        self.deposit_byte_order
304    }
305
306    /// Set the byte order used to code multi-byte deposit elements.
307    pub fn set_deposit_byte_order(&mut self, order: xcp_core::ByteOrder) {
308        self.deposit_byte_order = order;
309    }
310
311    /// Bind the project's characteristics to the signals of `dbc`.
312    ///
313    /// A characteristic binds to the first signal whose name matches it —
314    /// exactly first, then ASCII-case-insensitively, because DBC signal
315    /// names are conventionally upper-case while A2L names are lower-case.
316    /// Bindings replace any previous attachment. Characteristics with no
317    /// same-named signal are simply left unbound;
318    /// [`require_signal_binding`](Self::require_signal_binding) is where
319    /// that becomes a typed error.
320    ///
321    /// # Errors
322    ///
323    /// [`CalError::Unsupported`] when a matched signal's layout cannot be
324    /// bit-coded (a width outside `1..=64`, or a start bit beyond the DBC
325    /// range). The database is left unattached.
326    pub fn attach_dbc(&mut self, dbc: Dbc) -> Result<(), CalError> {
327        let mut bindings: BTreeMap<String, BTreeMap<String, SignalBinding>> = BTreeMap::new();
328        let mut measurement_bindings: BTreeMap<String, BTreeMap<String, SignalBinding>> =
329            BTreeMap::new();
330        for module in &self.modules {
331            let mut per_module = BTreeMap::new();
332            for characteristic in &module.characteristics {
333                if let Some((can_id, signal)) = find_signal(&dbc, &characteristic.name) {
334                    let binding = validate_binding(&characteristic.name, can_id, signal)?;
335                    per_module.insert(characteristic.name.clone(), binding);
336                }
337            }
338            let mut per_measurement = BTreeMap::new();
339            for measurement in &module.measurements {
340                if let Some((can_id, signal)) = find_signal(&dbc, &measurement.name) {
341                    let binding = validate_binding(&measurement.name, can_id, signal)?;
342                    per_measurement.insert(measurement.name.clone(), binding);
343                }
344            }
345            bindings.insert(module.name.clone(), per_module);
346            measurement_bindings.insert(module.name.clone(), per_measurement);
347        }
348        self.bindings = bindings;
349        self.measurement_bindings = measurement_bindings;
350        self.dbc = Some(dbc);
351        Ok(())
352    }
353
354    /// Parse a DBC document and bind it (the common case).
355    ///
356    /// # Errors
357    ///
358    /// [`CalError::Dbc`] for a malformed database, otherwise as
359    /// [`attach_dbc`](Self::attach_dbc).
360    pub fn attach_dbc_text(&mut self, text: &str) -> Result<(), CalError> {
361        self.attach_dbc(Dbc::parse(text)?)
362    }
363
364    /// The CAN signal bound to `characteristic` in `module`, when one is.
365    #[must_use]
366    pub fn signal_for_characteristic(
367        &self,
368        module: &str,
369        char_name: &str,
370    ) -> Option<&SignalBinding> {
371        self.bindings.get(module)?.get(char_name)
372    }
373
374    /// Every binding in `module`, ordered by characteristic name.
375    #[must_use]
376    pub fn signal_bindings(&self, module: &str) -> Vec<&SignalBinding> {
377        self.bindings
378            .get(module)
379            .map(|m| m.values().collect())
380            .unwrap_or_default()
381    }
382
383    /// The CAN signal bound to measurement `name` in `module`, when one is.
384    ///
385    /// Measurements bind exactly like characteristics do — a bench tool
386    /// watching `engine_speed` on the bus wants the same layout it gets for
387    /// a calibratable.
388    #[must_use]
389    pub fn signal_for_measurement(
390        &self,
391        module: &str,
392        measurement: &str,
393    ) -> Option<&SignalBinding> {
394        self.measurement_bindings.get(module)?.get(measurement)
395    }
396
397    /// Every measurement binding in `module`, ordered by measurement name.
398    #[must_use]
399    pub fn measurement_bindings(&self, module: &str) -> Vec<&SignalBinding> {
400        self.measurement_bindings
401            .get(module)
402            .map(|m| m.values().collect())
403            .unwrap_or_default()
404    }
405
406    /// The CAN signal bound to measurement `name` in `module`.
407    ///
408    /// # Errors
409    ///
410    /// [`CalError::UnknownModule`], [`CalError::UnknownCharacteristic`], or
411    /// [`CalError::NoSignalBinding`].
412    pub fn require_measurement_binding(
413        &self,
414        module: &str,
415        measurement: &str,
416    ) -> Result<&SignalBinding, CalError> {
417        self.measurement(module, measurement)?;
418        self.signal_for_measurement(module, measurement)
419            .ok_or_else(|| CalError::NoSignalBinding(qualified(module, measurement)))
420    }
421
422    /// The CAN signal bound to `characteristic` in `module`.
423    ///
424    /// # Errors
425    ///
426    /// [`CalError::UnknownModule`], [`CalError::UnknownCharacteristic`],
427    /// or [`CalError::NoSignalBinding`] when no DBC is attached or no
428    /// signal matches.
429    pub fn require_signal_binding(
430        &self,
431        module: &str,
432        char_name: &str,
433    ) -> Result<&SignalBinding, CalError> {
434        self.characteristic(module, char_name)?;
435        self.signal_for_characteristic(module, char_name)
436            .ok_or_else(|| CalError::NoSignalBinding(qualified(module, char_name)))
437    }
438
439    /// Resolve a characteristic's conversion, filling a `TABLE` method's
440    /// points from the registered tables.
441    ///
442    /// # Errors
443    ///
444    /// [`CalError::Unsupported`] when a `TABLE` conversion has no points
445    /// and no registered `COMPU_TAB_REF`.
446    pub fn resolved_conversion(
447        &self,
448        characteristic: &Characteristic,
449    ) -> Result<CompuMethod, CalError> {
450        characteristic.conversion.resolved(&self.tables)
451    }
452
453    /// Raw value → physical value, through the A2L `COMPU_METHOD`.
454    ///
455    /// `raw` is the memory **bit pattern**: for a signed datatype the low
456    /// `element_bits` bits are sign-extended, so `-1 °C` in an `SBYTE`
457    /// characteristic is `0xFF`.
458    ///
459    /// # Errors
460    ///
461    /// [`CalError::UnknownModule`], [`CalError::UnknownCharacteristic`],
462    /// or [`CalError::Unsupported`] for an unresolvable conversion.
463    pub fn to_physical(&self, module: &str, name: &str, raw: u64) -> Result<f64, CalError> {
464        let characteristic = self.characteristic(module, name)?;
465        let conversion = self.resolved_conversion(characteristic)?;
466        Ok(conversion.apply(characteristic.raw_value(raw)))
467    }
468
469    /// Physical value → raw value, inverting the A2L `COMPU_METHOD`.
470    ///
471    /// The value is limit-checked first, then inverted against the deposit's
472    /// raw bounds, then rounded to the nearest integer the datatype holds.
473    /// The result is the memory **bit pattern** (two's complement for
474    /// signed datatypes).
475    ///
476    /// # Errors
477    ///
478    /// [`CalError::LimitViolation`] when the physical value is outside the
479    /// A2L limits, [`CalError::OutOfBounds`] when the deposit cannot
480    /// represent it, [`CalError::Unsupported`] for a non-invertible or
481    /// unresolvable conversion, plus the lookup errors.
482    pub fn to_raw(&self, module: &str, name: &str, physical: f64) -> Result<u64, CalError> {
483        let characteristic = self.characteristic(module, name)?;
484        self.check_physical_limits(characteristic, physical)?;
485        let conversion = self.resolved_conversion(characteristic)?;
486        let (value_min, value_max) = characteristic.value_bounds();
487        let value = conversion.invert(&characteristic.name, physical, value_min, value_max)?;
488        let rounded = value.round();
489        let bounded = if rounded < value_min {
490            value_min
491        } else if rounded > value_max {
492            value_max
493        } else {
494            rounded
495        };
496        Ok(characteristic.raw_bits(bounded))
497    }
498
499    /// Check a physical value against the A2L limits of a characteristic.
500    ///
501    /// # Errors
502    ///
503    /// [`CalError::LimitViolation`] carrying the characteristic name, the
504    /// offending value, and both limits.
505    pub fn check_physical_limits(
506        &self,
507        characteristic: &Characteristic,
508        physical: f64,
509    ) -> Result<(), CalError> {
510        if characteristic.within_limits(physical) {
511            return Ok(());
512        }
513        Err(CalError::LimitViolation {
514            name: characteristic.name.clone(),
515            value: physical,
516            lower: characteristic.lower_limit,
517            upper: characteristic.upper_limit,
518        })
519    }
520
521    /// Check a raw value against the A2L limits: convert, then check.
522    ///
523    /// # Errors
524    ///
525    /// [`CalError::LimitViolation`] carrying the characteristic name, the
526    /// **physical** value the raw produced, and both limits.
527    pub fn check_limits(&self, module: &str, name: &str, raw: u64) -> Result<(), CalError> {
528        let physical = self.to_physical(module, name, raw)?;
529        let characteristic = self.characteristic(module, name)?;
530        self.check_physical_limits(characteristic, physical)
531    }
532
533    /// Locate a characteristic by name across every module, returning the
534    /// module name too. First declaration wins.
535    ///
536    /// # Errors
537    ///
538    /// [`CalError::UnknownCharacteristic`] when no module declares it.
539    pub fn locate(&self, name: &str) -> Result<(&str, &Characteristic), CalError> {
540        self.modules
541            .iter()
542            .find_map(|module| {
543                module
544                    .characteristic(name)
545                    .map(|characteristic| (module.name.as_str(), characteristic))
546            })
547            .ok_or_else(|| CalError::UnknownCharacteristic(name.to_string()))
548    }
549
550    /// Decode a deposit payload into one raw bit pattern per element.
551    ///
552    /// # Errors
553    ///
554    /// [`CalError::Unsupported`] when the datatype is IEEE-754 (a float
555    /// deposit carries a value, not a bit pattern) or when `data` is shorter
556    /// than the declared deposit.
557    pub fn read_raw(
558        &self,
559        characteristic: &Characteristic,
560        data: &[u8],
561    ) -> Result<Vec<u64>, CalError> {
562        require_integer_datatype(characteristic)?;
563        let size = characteristic.datatype.size_bytes();
564        // The whole deposit record, reserved bytes ahead of the value array
565        // included — the same span `write_raw` produces.
566        let needed = usize::from(characteristic.deposit_position) + characteristic.elements * size;
567        if data.len() < needed {
568            return Err(CalError::Unsupported {
569                subject: format!("characteristic `{}`", characteristic.name),
570                reason: format!(
571                    "deposit needs {needed} bytes ({} element(s) · {size} byte(s) at position {}) but the payload carries {}",
572                    characteristic.elements,
573                    characteristic.deposit_position,
574                    data.len()
575                ),
576            });
577        }
578        let mut raws = Vec::with_capacity(characteristic.elements);
579        for index in 0..characteristic.elements {
580            let start = usize::from(characteristic.deposit_position) + index * size;
581            let end = start + size;
582            let slice = data.get(start..end).ok_or_else(|| CalError::Unsupported {
583                subject: format!("characteristic `{}`", characteristic.name),
584                reason: format!(
585                    "deposit needs {end} bytes but the payload carries {}",
586                    data.len()
587                ),
588            })?;
589            raws.push(decode_element(slice, self.deposit_byte_order));
590        }
591        Ok(raws)
592    }
593
594    /// Encode one raw bit pattern per element into a deposit payload.
595    ///
596    /// The payload is `deposit_position + elements · element width` bytes
597    /// long, so the bytes before `FNC_VALUES POSITION` are present and zero
598    /// — an ECU that ignores them is unaffected, and one that does not is
599    /// told exactly what the layout is.
600    ///
601    /// # Errors
602    ///
603    /// [`CalError::Unsupported`] when the datatype is IEEE-754, when the
604    /// element count overflows the deposit size, or when the deposit exceeds
605    /// one XCP UPLOAD (255 bytes).
606    pub fn write_raw(
607        &self,
608        characteristic: &Characteristic,
609        raws: &[u64],
610    ) -> Result<Vec<u8>, CalError> {
611        require_integer_datatype(characteristic)?;
612        let size = characteristic.datatype.size_bytes();
613        let leading = usize::from(characteristic.deposit_position);
614        let needed = leading
615            .checked_add(
616                raws.len()
617                    .checked_mul(size)
618                    .ok_or_else(|| CalError::Unsupported {
619                        subject: format!("characteristic `{}`", characteristic.name),
620                        reason: "element count overflows the deposit size".to_string(),
621                    })?,
622            )
623            .ok_or_else(|| CalError::Unsupported {
624                subject: format!("characteristic `{}`", characteristic.name),
625                reason: "deposit size overflows".to_string(),
626            })?;
627        if needed > usize::from(u8::MAX) {
628            return Err(CalError::Unsupported {
629                subject: format!("characteristic `{}`", characteristic.name),
630                reason: format!("deposit of {needed} bytes exceeds one XCP UPLOAD"),
631            });
632        }
633        let mut data = vec![0_u8; needed];
634        for (index, &raw) in raws.iter().enumerate() {
635            let value = characteristic.raw_value(raw);
636            let start = leading + index * size;
637            if let Some(slot) = data.get_mut(start..start + size) {
638                encode_element(slot, value, self.deposit_byte_order);
639            }
640        }
641        Ok(data)
642    }
643
644    /// The physical values of one raw value list.
645    ///
646    /// # Errors
647    ///
648    /// [`CalError::Unsupported`] for an unresolvable conversion.
649    pub fn physical_values(
650        &self,
651        characteristic: &Characteristic,
652        raws: &[u64],
653    ) -> Result<Vec<f64>, CalError> {
654        let conversion = self.resolved_conversion(characteristic)?;
655        Ok(raws
656            .iter()
657            .map(|&raw| conversion.apply(characteristic.raw_value(raw)))
658            .collect())
659    }
660}
661
662/// Reject IEEE-754 deposits: they carry a value, not a bit pattern, and
663/// every raw/physical contract in this crate is stated over bit patterns.
664fn require_integer_datatype(characteristic: &Characteristic) -> Result<(), CalError> {
665    match characteristic.datatype {
666        DataType::Float32 | DataType::Float64 => Err(CalError::Unsupported {
667            subject: format!("characteristic `{}`", characteristic.name),
668            reason: format!(
669                "{} deposits are IEEE-754 values, not integer bit patterns",
670                characteristic.datatype.keyword()
671            ),
672        }),
673        _ => Ok(()),
674    }
675}
676
677/// Turn a matched DBC signal into a binding, refusing a layout that cannot
678/// be bit-coded.
679fn validate_binding(
680    name: &str,
681    can_id: u32,
682    signal: &dbc_parse::Signal,
683) -> Result<SignalBinding, CalError> {
684    if signal.bit_length == 0 || signal.bit_length > 64 || signal.start_bit > 511 {
685        return Err(CalError::Unsupported {
686            subject: format!("signal `{}`", signal.name),
687            reason: format!(
688                "layout start_bit {} length {} is outside the DBC range (start <= 511, length 1..=64)",
689                signal.start_bit, signal.bit_length
690            ),
691        });
692    }
693    Ok(SignalBinding::from_signal(name, can_id, signal))
694}
695
696/// The first signal named `name` in `dbc` (exact, then case-insensitive),
697/// with its message id.
698fn find_signal<'a>(dbc: &'a Dbc, name: &str) -> Option<(u32, &'a dbc_parse::Signal)> {
699    for message in &dbc.messages {
700        for signal in &message.signals {
701            if signal.name == name {
702                return Some((message.id.raw(), signal));
703            }
704        }
705    }
706    for message in &dbc.messages {
707        for signal in &message.signals {
708            if signal.name.eq_ignore_ascii_case(name) {
709                return Some((message.id.raw(), signal));
710            }
711        }
712    }
713    None
714}
715
716/// `module.characteristic`, the qualified form used in error payloads.
717fn qualified(module: &str, name: &str) -> String {
718    format!("{module}.{name}")
719}
720
721/// Assemble `bytes` into a raw value.
722fn decode_element(bytes: &[u8], order: xcp_core::ByteOrder) -> u64 {
723    let len = bytes.len();
724    let mut value = 0_u64;
725    for (index, &byte) in bytes.iter().enumerate() {
726        let shift = match order {
727            xcp_core::ByteOrder::Intel => index * 8,
728            xcp_core::ByteOrder::Motorola => (len - 1 - index) * 8,
729        };
730        value |= u64::from(byte) << shift;
731    }
732    value
733}
734
735/// Scatter a numeric value into `bytes`.
736fn encode_element(bytes: &mut [u8], value: f64, order: xcp_core::ByteOrder) {
737    #[allow(clippy::cast_possible_wrap)]
738    let bits = value as i64 as u64;
739    let len = bytes.len();
740    for (index, slot) in bytes.iter_mut().enumerate() {
741        let shift = match order {
742            xcp_core::ByteOrder::Intel => index * 8,
743            xcp_core::ByteOrder::Motorola => (len - 1 - index) * 8,
744        };
745        #[allow(clippy::cast_possible_truncation)]
746        {
747            *slot = ((bits >> shift) & 0xFF) as u8;
748        }
749    }
750}