dbc_parse/model.rs
1//! The parsed database model — nodes, messages, signals, value tables,
2//! attributes.
3
4use crate::bits;
5use crate::error::DbcError;
6use alloc::string::String;
7use alloc::vec::Vec;
8
9/// `2^n` for `n` in `0..=64` — `core` has no `f64::powi`.
10#[must_use]
11fn two_pow(n: u8) -> f64 {
12 if n == 64 {
13 // 2^64, exactly representable as a power of two.
14 18_446_744_073_709_551_616.0
15 } else {
16 // (1 << n) ≤ 2^63 — exactly representable as f64.
17 #[allow(clippy::cast_precision_loss)]
18 {
19 (1_u64 << n) as f64
20 }
21 }
22}
23
24/// `floor` — `core` has no `f64::floor`. Exact for finite inputs; values
25/// with magnitude ≥ 2^53 are integral by construction.
26#[must_use]
27fn floor(x: f64) -> f64 {
28 if !x.is_finite() || x.abs() >= 9_007_199_254_740_992.0 {
29 return x;
30 }
31 // |x| < 2^53 fits i64 exactly; the cast truncates toward zero.
32 #[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)]
33 let t = x as i64 as f64;
34 // Exact equality is the point: `t == x` detects already-integral values.
35 #[allow(clippy::float_cmp)]
36 if x >= 0.0 || t == x {
37 t
38 } else {
39 t - 1.0
40 }
41}
42
43/// Half-away-from-zero rounding — `core` has no `f64::round`.
44#[must_use]
45fn round_half_away(x: f64) -> f64 {
46 let floor = floor(x);
47 let diff = x - floor;
48 if diff > 0.5 {
49 floor + 1.0
50 } else if diff < 0.5 || x < 0.0 {
51 floor
52 } else {
53 floor + 1.0
54 }
55}
56
57/// Largest 11-bit standard identifier.
58pub const STANDARD_ID_MAX: u32 = 0x7FF;
59/// Largest 29-bit extended identifier.
60pub const EXTENDED_ID_MAX: u32 = 0x1FFF_FFFF;
61
62/// A CAN identifier: 11-bit (standard) or 29-bit (extended).
63///
64/// `dbc-parse` carries its own minimal `CanId` rather than depending on the
65/// estate's `can-core`: L0 crates have zero runtime estate dependencies
66/// (`docs/layers.md`, engineering-standards). The shape mirrors `can-core`
67/// so a future higher-layer bridge can convert with `match`.
68///
69/// The tuple variants are public, so — as in `can-core` — the crate's
70/// contract is defense in depth: the validating constructors reject
71/// out-of-range values and the parser never produces an out-of-range id.
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
73pub enum CanId {
74 /// 11-bit standard identifier, `0x000..=0x7FF` (a `u11` in a `u16`).
75 Standard(u16),
76 /// 29-bit extended identifier, `0x000..=0x1FFF_FFFF` (a `u29` in a
77 /// `u32`).
78 Extended(u32),
79}
80
81impl CanId {
82 /// Validates and wraps an 11-bit standard identifier.
83 ///
84 /// # Errors
85 ///
86 /// [`DbcError::InvalidId`] when `raw > 0x7FF`.
87 pub fn standard(raw: u16) -> Result<Self, DbcError> {
88 if u32::from(raw) > STANDARD_ID_MAX {
89 return Err(DbcError::InvalidId {
90 max: STANDARD_ID_MAX,
91 raw: u32::from(raw),
92 });
93 }
94 Ok(Self::Standard(raw))
95 }
96
97 /// Validates and wraps a 29-bit extended identifier.
98 ///
99 /// # Errors
100 ///
101 /// [`DbcError::InvalidId`] when `raw > 0x1FFF_FFFF`.
102 pub fn extended(raw: u32) -> Result<Self, DbcError> {
103 if raw > EXTENDED_ID_MAX {
104 return Err(DbcError::InvalidId {
105 max: EXTENDED_ID_MAX,
106 raw,
107 });
108 }
109 Ok(Self::Extended(raw))
110 }
111
112 /// Interprets a DBC `BO_` id word: bit 31 (`0x8000_0000`) marks an
113 /// extended frame and is stripped; the remaining 29 bits are the id.
114 /// A plain id that exceeds the 11-bit standard width is rejected —
115 /// the DBC format requires bit 31 for extended frames.
116 ///
117 /// # Errors
118 ///
119 /// [`DbcError::InvalidId`] for error/flag bits below bit 31 or an
120 /// over-wide standard id.
121 pub fn from_dbc_raw(raw: u32) -> Result<Self, DbcError> {
122 if raw & 0x8000_0000 != 0 {
123 Self::extended(raw & 0x1FFF_FFFF)
124 } else if raw > STANDARD_ID_MAX {
125 Err(DbcError::InvalidId {
126 max: STANDARD_ID_MAX,
127 raw,
128 })
129 } else {
130 // raw ≤ 0x7FF — no truncation.
131 #[allow(clippy::cast_possible_truncation)]
132 Ok(Self::Standard(raw as u16))
133 }
134 }
135
136 /// `true` for the 11-bit standard format.
137 #[must_use]
138 pub const fn is_standard(&self) -> bool {
139 matches!(self, Self::Standard(_))
140 }
141
142 /// The identifier value, widened to `u32`.
143 #[must_use]
144 pub const fn raw(&self) -> u32 {
145 match *self {
146 // u16 → u32 widening is lossless.
147 Self::Standard(v) => v as u32,
148 Self::Extended(v) => v,
149 }
150 }
151}
152
153/// A node declared in the `BU_` section.
154#[derive(Debug, Clone, PartialEq, Eq)]
155pub struct Node {
156 /// Node name, e.g. `PCM1`.
157 pub name: String,
158}
159
160/// Byte order of a signal's bit layout.
161#[derive(Debug, Clone, Copy, PartialEq, Eq)]
162pub enum ByteOrder {
163 /// Big-endian ("Motorola"): `start_bit` names the MSB, in the classic
164 /// sawtooth DBC numbering (`@0` in the grammar).
165 Motorola,
166 /// Little-endian ("Intel"): `start_bit` names the LSB, laid out linearly
167 /// ascending (`@1` in the grammar).
168 Intel,
169}
170
171/// Multiplexing role of a signal within its message.
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173pub enum MultiplexingInfo {
174 /// A plain signal, always present.
175 None,
176 /// The multiplexor switch (`M`): its value selects which multiplexed
177 /// signals are present in a frame.
178 Multiplexor,
179 /// A multiplexed signal (`m<N>`): present only when the message's
180 /// multiplexor equals `N`.
181 Value(i32),
182}
183
184/// One signal of a [`Message`] — its layout, scaling, and metadata.
185#[derive(Debug, Clone, PartialEq)]
186pub struct Signal {
187 /// Signal name, e.g. `Temperature`.
188 pub name: String,
189 /// Start bit, in DBC bit numbering: the MSB for [`ByteOrder::Motorola`],
190 /// the LSB for [`ByteOrder::Intel`] (see [`crate::bits`]). Up to 511 —
191 /// CAN FD layouts reach into byte 64.
192 pub start_bit: u16,
193 /// Signal width in bits (1–64).
194 pub bit_length: u8,
195 /// Bit layout order.
196 pub byte_order: ByteOrder,
197 /// Two's-complement signed interpretation of the raw bits.
198 pub is_signed: bool,
199 /// Physical value = `raw * scale + offset`.
200 pub scale: f64,
201 /// Physical value = `raw * scale + offset`.
202 pub offset: f64,
203 /// Declared physical minimum (from `[min|max]`).
204 pub min: f64,
205 /// Declared physical maximum (from `[min|max]`).
206 pub max: f64,
207 /// Unit string, e.g. `"degK"` (empty when the file carries `"-"` or `""`).
208 pub unit: String,
209 /// Receiving node names, in file order (`Vector__XXX` preserved as-is).
210 pub receivers: Vec<String>,
211 /// Multiplexing role within the message.
212 pub multiplexing_info: MultiplexingInfo,
213}
214
215impl Signal {
216 /// Decodes the signal's physical value from a CAN frame payload: the
217 /// raw bits are extracted per the layout, sign-extended when signed,
218 /// then scaled (`raw * scale + offset`).
219 ///
220 /// Total: bits beyond the buffer read as zero (partial payloads decode
221 /// as if zero-filled — see [`crate::bits::extract_raw`]).
222 #[must_use]
223 pub fn decode_raw(&self, data: &[u8]) -> f64 {
224 let raw = bits::extract_raw(self.start_bit, self.bit_length, self.byte_order, data);
225 // f64 is the API's value domain — precision loss for raws above
226 // 2^53 is inherent and documented.
227 #[allow(clippy::cast_precision_loss)]
228 let as_int = if self.is_signed {
229 bits::sign_extend(raw, self.bit_length) as f64
230 } else {
231 raw as f64
232 };
233 as_int * self.scale + self.offset
234 }
235
236 /// Encodes a physical value into a CAN frame payload: scaled back to
237 /// raw (`round((value - offset) / scale)`, half away from zero),
238 /// range- and width-checked, then written bit by bit.
239 ///
240 /// The `[min|max]` range is enforced only when `min < max` — files that
241 /// declare an empty range (`[0|0]`, as in `motohawk.dbc`'s `Enable`)
242 /// impose no constraint.
243 ///
244 /// # Errors
245 ///
246 /// [`DbcError::ValueOutOfRange`] for non-finite values or declared-range
247 /// violations, [`DbcError::RawOutOfRange`] when the scaled raw does not
248 /// fit the bit width, [`DbcError::BufferTooShort`] when the buffer
249 /// cannot hold the layout.
250 pub fn encode_raw(&self, data: &mut [u8], value: f64) -> Result<(), DbcError> {
251 if !value.is_finite() || (self.min < self.max && !(value >= self.min && value <= self.max))
252 {
253 return Err(DbcError::ValueOutOfRange {
254 value,
255 min: self.min,
256 max: self.max,
257 });
258 }
259 let raw = round_half_away((value - self.offset) / self.scale);
260 let width = self.bit_length;
261 let fits = if self.is_signed {
262 let half = two_pow(width - 1);
263 raw >= -half && raw < half
264 } else {
265 raw >= 0.0 && raw < two_pow(width)
266 };
267 // i64::MIN = −2^63 is a power of two — exact in f64.
268 #[allow(clippy::cast_precision_loss)]
269 let i64_min = i64::MIN as f64;
270 // Signed raws must land inside i64 for the two's-complement cast;
271 // unsigned raws are already bounded by `fits` (< 2^width ≤ 2^64).
272 let needs_i64 = self.is_signed && (raw < i64_min || raw >= two_pow(63));
273 if !fits || needs_i64 {
274 return Err(DbcError::RawOutOfRange {
275 raw,
276 bit_length: self.bit_length,
277 });
278 }
279 // In range per the checks above; two's complement for signed.
280 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
281 let raw_bits = if self.is_signed {
282 raw as i64 as u64
283 } else {
284 raw as u64
285 };
286 bits::insert_raw(
287 self.start_bit,
288 self.bit_length,
289 self.byte_order,
290 data,
291 raw_bits,
292 )
293 }
294}
295
296/// A CAN message declaration (`BO_`), with its signals (`SG_`).
297#[derive(Debug, Clone, PartialEq)]
298pub struct Message {
299 /// The message identifier.
300 pub id: CanId,
301 /// Message name, e.g. `ExampleMessage`.
302 pub name: String,
303 /// Declared payload length in bytes (the `dlc` column).
304 pub dlc: u8,
305 /// Transmitting node name (`Vector__XXX` when unspecified).
306 pub sender: String,
307 /// The message's signals, in file order.
308 pub signals: Vec<Signal>,
309}
310
311impl Message {
312 /// Decodes every applicable signal of the frame: `(signal, physical
313 /// value)` pairs, in file order.
314 ///
315 /// Multiplexed messages decode per the multiplexor: the switch signal
316 /// (`M`) and plain signals are always included; `m<N>` signals only
317 /// when the decoded switch equals `N`. Signals gated by *extended*
318 /// multiplexing ranges (`SG_MUL_VAL_`) are not filtered here — they
319 /// need the database-level ranges in [`Dbc::extended_multiplexing`].
320 #[must_use]
321 pub fn unpack(&self, data: &[u8]) -> Vec<(Signal, f64)> {
322 let selector = self
323 .signals
324 .iter()
325 .find(|signal| signal.multiplexing_info == MultiplexingInfo::Multiplexor)
326 .map(|switch| {
327 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
328 let raw = round_half_away(switch.decode_raw(data)) as i64;
329 raw
330 });
331 self.signals
332 .iter()
333 .filter(|signal| match (signal.multiplexing_info, selector) {
334 (MultiplexingInfo::Value(tag), Some(selected)) => i64::from(tag) == selected,
335 _ => true,
336 })
337 .map(|signal| (signal.clone(), signal.decode_raw(data)))
338 .collect()
339 }
340}
341
342/// A value table: raw value → label mappings from `VAL_` (message-scoped)
343/// or `VAL_TABLE_` (global, named).
344#[derive(Debug, Clone, PartialEq, Eq)]
345pub struct ValueTable {
346 /// Table name for `VAL_TABLE_` declarations; `None` for message-scoped
347 /// `VAL_` entries.
348 pub name: Option<String>,
349 /// Message id for `VAL_` declarations; `None` for `VAL_TABLE_`.
350 pub message_id: Option<u32>,
351 /// Signal name the table annotates (unused for `VAL_TABLE_`).
352 pub signal: String,
353 /// `(raw value, label)` pairs, in file order.
354 pub entries: Vec<(i64, String)>,
355}
356
357/// The object an attribute value attaches to (`BA_`).
358#[derive(Debug, Clone, PartialEq, Eq)]
359pub enum AttributeObject {
360 /// Database-level attribute (`BA_ "name" value;`).
361 Database,
362 /// Node-level (`BA_ "name" BU_ node value;`).
363 Node(String),
364 /// Message-level (`BA_ "name" BO_ id value;`).
365 Message(u32),
366 /// Signal-level (`BA_ "name" SG_ id signal value;`).
367 Signal {
368 /// Owning message id.
369 message_id: u32,
370 /// Signal name.
371 signal: String,
372 },
373}
374
375/// An attribute value as carried by `BA_` lines.
376#[derive(Debug, Clone, PartialEq)]
377pub enum AttributeValue {
378 /// Integer (or enum index) value.
379 Int(i64),
380 /// Float value.
381 Float(f64),
382 /// String (or enum label) value.
383 Str(String),
384}
385
386/// One `BA_` attribute assignment.
387#[derive(Debug, Clone, PartialEq)]
388pub struct Attribute {
389 /// Attribute name, e.g. `GenMsgCycleTime`.
390 pub name: String,
391 /// The object the value attaches to.
392 pub object: AttributeObject,
393 /// The assigned value.
394 pub value: AttributeValue,
395}
396
397/// An extended-multiplexing range set (`SG_MUL_VAL_`): a signal is present
398/// when its selector takes any value in any of the `(from, to)` inclusive
399/// ranges.
400#[derive(Debug, Clone, PartialEq, Eq)]
401pub struct ExtendedMux {
402 /// Owning message id.
403 pub message_id: u32,
404 /// The gated signal.
405 pub signal: String,
406 /// The selector signal (`Multiplexor` in the sample files).
407 pub selector: String,
408 /// Inclusive `(from, to)` value ranges, in file order.
409 pub ranges: Vec<(i32, i32)>,
410}
411
412/// A parsed DBC database.
413#[derive(Debug, Clone, PartialEq, Default)]
414pub struct Dbc {
415 /// `VERSION "..."` string, when present.
416 pub version: Option<String>,
417 /// Nodes from the `BU_` section.
418 pub nodes: Vec<Node>,
419 /// Messages (`BO_`) with their signals (`SG_`).
420 pub messages: Vec<Message>,
421 /// Value tables from `VAL_` and `VAL_TABLE_`.
422 pub value_tables: Vec<ValueTable>,
423 /// Attribute assignments from `BA_` (`BA_DEF_` schemas and
424 /// `BA_DEF_DEF_` defaults are validated-and-skipped, not retained).
425 pub attributes: Vec<Attribute>,
426 /// Extended-multiplexing range sets from `SG_MUL_VAL_`.
427 pub extended_multiplexing: Vec<ExtendedMux>,
428}
429
430impl Dbc {
431 /// Parses a DBC document — the primary entry point.
432 ///
433 /// # Errors
434 ///
435 /// [`DbcError::Syntax`] for malformed known constructs (with 1-based
436 /// line numbers), [`DbcError::InvalidId`] for unrepresentable message
437 /// ids. Unknown vendor keywords are skipped, never rejected.
438 #[allow(clippy::should_implement_trait)] // the format's verb, and the API
439 pub fn parse(input: &str) -> Result<Self, DbcError> {
440 crate::parser::parse(input)
441 }
442}