Skip to main content

can_core/
frame.rs

1//! CAN frames — classic CAN 2.0 and CAN FD, in `SocketCAN` wire format.
2//!
3//! [`CanFrame`] is a **zero-copy view**: `parse` borrows the payload region
4//! straight out of the input buffer (no copy, no allocation), and `to_bytes`
5//! writes the `SocketCAN` `struct can_frame` (16 bytes) or `struct canfd_frame`
6//! (72 bytes) layout back into a fresh `Vec<u8>`.
7//!
8//! # DLC ↔ payload-length mapping
9//!
10//! Classic CAN (DLC 0–8): the DLC *is* the payload length in bytes.
11//! CAN FD (DLC 0–15): the DLC is an index into the mapping table
12//! `0,1,2,3,4,5,6,7,8,12,16,20,24,32,48,64` — DLC 9–15 encode payloads of
13//! 12–64 bytes. Lengths that are not table entries (9–11, 13–15, … bytes)
14//! are not encodable and rejected with [`CanError::DataTooLong`].
15//!
16//! # Totality
17//!
18//! `parse` never panics: every buffer access is bounds-checked and every
19//! malformed input resolves to a typed [`CanError`].
20
21use crate::error::CanError;
22use crate::id::{CanId, CAN_EFF_MASK, CAN_ERR_FLAG, CAN_RTR_FLAG};
23use alloc::vec::Vec;
24
25/// Largest classic CAN 2.0 payload.
26pub const CLASSIC_MAX_LEN: usize = 8;
27/// Largest CAN FD payload.
28pub const FD_MAX_LEN: usize = 64;
29/// Size of `struct can_frame` — the `SocketCAN` classic wire format.
30pub const CLASSIC_FRAME_SIZE: usize = 16;
31/// Size of `struct canfd_frame` — the `SocketCAN` CAN FD wire format.
32pub const FD_FRAME_SIZE: usize = 72;
33
34/// DLC (0–15) → CAN FD payload length in bytes. The first nine entries also
35/// serve classic CAN, where the DLC equals the length directly.
36pub const FD_DLC_TO_LEN: [usize; 16] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 16, 20, 24, 32, 48, 64];
37
38/// Maps a DLC (0–15) to its CAN FD payload length.
39///
40/// # Errors
41///
42/// [`CanError::InvalidDlc`] when `dlc > 15`.
43pub fn dlc_to_len(dlc: u8) -> Result<usize, CanError> {
44    FD_DLC_TO_LEN
45        .get(usize::from(dlc))
46        .copied()
47        .ok_or(CanError::InvalidDlc(dlc))
48}
49
50/// Maps a CAN FD payload length to its DLC.
51///
52/// # Errors
53///
54/// [`CanError::DataTooLong`] when `len` exceeds 64 bytes or is not a
55/// DLC-representable length (9–11, 13–15, 17–19, …); `max` then reports the
56/// largest length that *would* fit.
57pub fn len_to_dlc(len: usize) -> Result<u8, CanError> {
58    // Linear scan of a 16-entry table: the first hit is the unique entry.
59    for (dlc, table_len) in FD_DLC_TO_LEN.iter().enumerate() {
60        if *table_len == len {
61            // dlc < FD_DLC_TO_LEN.len() == 16 by construction — no truncation.
62            #[allow(clippy::cast_possible_truncation)]
63            return Ok(dlc as u8);
64        }
65    }
66    // Not a table entry: report the largest length that would fit.
67    let max = FD_DLC_TO_LEN
68        .iter()
69        .rev()
70        .find(|candidate| **candidate <= len)
71        .copied()
72        .unwrap_or(0);
73    Err(CanError::DataTooLong { max, got: len })
74}
75
76/// A CAN 2.0 or CAN FD frame — a borrowed, zero-copy view over a payload.
77///
78/// Construct with [`CanFrame::new`] (classic data), [`CanFrame::fd`] (CAN FD
79/// data), [`CanFrame::remote`] (classic RTR), or the fully explicit
80/// [`CanFrame::from_parts`]; parse from `SocketCAN` bytes with
81/// [`CanFrame::parse`]; serialize with [`CanFrame::to_bytes`].
82///
83/// ```
84/// use can_core::{CanFrame, CanId};
85///
86/// let id = CanId::standard(0x123).unwrap();
87/// let payload = [0xDE, 0xAD, 0xBE, 0xEF];
88/// let frame = CanFrame::new(id, &payload).unwrap();
89///
90/// let bytes = frame.to_bytes();
91/// assert_eq!(bytes.len(), 16); // struct can_frame
92/// assert_eq!(&bytes[8..12], &payload);
93///
94/// let reparsed = CanFrame::parse(&bytes).unwrap();
95/// assert_eq!(frame, reparsed);
96/// ```
97// The CAN frame format carries exactly these flag bits (RTR, FD, BRS,
98// ESI) — the bool count is the domain, not a design smell.
99#[allow(clippy::struct_excessive_bools)]
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub struct CanFrame<'a> {
102    id: CanId,
103    data: &'a [u8],
104    dlc: u8,
105    is_remote: bool,
106    is_fd: bool,
107    brs: bool,
108    error_state_indicator: bool,
109}
110
111impl<'a> CanFrame<'a> {
112    /// Builds a classic CAN 2.0 data frame; the DLC is the payload length.
113    ///
114    /// # Errors
115    ///
116    /// [`CanError::DataTooLong`] for payloads over 8 bytes, and
117    /// [`CanError::InvalidIdLength`] for an out-of-range id.
118    pub fn new(id: CanId, data: &'a [u8]) -> Result<Self, CanError> {
119        if data.len() > CLASSIC_MAX_LEN {
120            return Err(CanError::DataTooLong {
121                max: CLASSIC_MAX_LEN,
122                got: data.len(),
123            });
124        }
125        // len ≤ 8 by the check above — no truncation.
126        #[allow(clippy::cast_possible_truncation)]
127        Self::from_parts(id, data, data.len() as u8, false, false, false, false)
128    }
129
130    /// Builds a CAN FD data frame.
131    ///
132    /// # Errors
133    ///
134    /// [`CanError::DataTooLong`] for payloads that are not
135    /// DLC-representable (or exceed 64 bytes), and
136    /// [`CanError::InvalidIdLength`] for an out-of-range id.
137    pub fn fd(id: CanId, data: &'a [u8], brs: bool, esi: bool) -> Result<Self, CanError> {
138        let dlc = len_to_dlc(data.len())?;
139        Self::from_parts(id, data, dlc, false, true, brs, esi)
140    }
141
142    /// Builds a classic remote-transmission-request frame: no payload, a
143    /// DLC of `dlc` (the requested length). DLC 9–15 models the legacy
144    /// SocketCAN refinement (`len8_dlc`) for remote frames requesting more
145    /// than 8 bytes.
146    ///
147    /// # Errors
148    ///
149    /// [`CanError::InvalidDlc`] when `dlc > 15`, [`CanError::InvalidIdLength`]
150    /// for an out-of-range id.
151    pub fn remote(id: CanId, dlc: u8) -> Result<Self, CanError> {
152        Self::from_parts(id, &[], dlc, true, false, false, false)
153    }
154
155    /// Fully explicit constructor — every field is validated.
156    ///
157    /// # Errors
158    ///
159    /// All [`CanError`] variants are reachable, depending on the field
160    /// combination: id range, payload/DLC consistency, FD-vs-classic flag
161    /// constraints, and the remote-frame rules (remote frames carry no data;
162    /// CAN FD frames cannot be remote).
163    #[allow(clippy::fn_params_excessive_bools)] // the format's four flag bits
164    pub fn from_parts(
165        id: CanId,
166        data: &'a [u8],
167        dlc: u8,
168        is_remote: bool,
169        is_fd: bool,
170        brs: bool,
171        error_state_indicator: bool,
172    ) -> Result<Self, CanError> {
173        validate_id(id)?;
174        if dlc > 15 {
175            return Err(CanError::InvalidDlc(dlc));
176        }
177        if is_remote {
178            if !data.is_empty() {
179                return Err(CanError::RemoteFrameWithData);
180            }
181            if is_fd {
182                // CAN FD abolished remote frames (ISO 11898-1).
183                return Err(CanError::RemoteFrameWithData);
184            }
185            // Remote frames carry no payload. DLC 9–15 is the legacy
186            // SocketCAN refinement (len8_dlc) — a classic remote frame
187            // requesting more than 8 bytes.
188        } else if is_fd {
189            // BRS/ESI are legal on FD frames — no constraint beyond the
190            // payload/DLC consistency check.
191            let expected = len_to_dlc(data.len())?;
192            if expected != dlc {
193                return Err(CanError::InvalidDlc(dlc));
194            }
195        } else {
196            if data.len() > CLASSIC_MAX_LEN {
197                return Err(CanError::DataTooLong {
198                    max: CLASSIC_MAX_LEN,
199                    got: data.len(),
200                });
201            }
202            if brs || error_state_indicator {
203                return Err(CanError::FdBrsOnClassic);
204            }
205            // Classic: DLC == payload length, or the refined legacy form —
206            // an 8-byte payload carrying DLC 9–15 (as kernels report for
207            // adapters that transmit such frames).
208            let refined = data.len() == CLASSIC_MAX_LEN && (9..=15).contains(&dlc);
209            if usize::from(dlc) != data.len() && !refined {
210                return Err(CanError::InvalidDlc(dlc));
211            }
212        }
213        Ok(Self {
214            id,
215            data,
216            dlc,
217            is_remote,
218            is_fd,
219            brs,
220            error_state_indicator,
221        })
222    }
223
224    /// Parses one frame in `SocketCAN` wire format: exactly 16 bytes
225    /// (`struct can_frame`, classic) or exactly 72 bytes (`struct
226    /// canfd_frame`, CAN FD). The payload borrows from `buf`.
227    ///
228    /// # Errors
229    ///
230    /// [`CanError::BufferTooShort`] under 16 bytes,
231    /// [`CanError::DataTooLong`] above 16 bytes when not exactly 72,
232    /// [`CanError::InvalidIdLength`] for error-flagged or over-wide id
233    /// words, [`CanError::InvalidDlc`] for out-of-range length bytes, and
234    /// [`CanError::RemoteFrameWithData`] for an RTR flag inside an FD frame.
235    pub fn parse(buf: &'a [u8]) -> Result<Self, CanError> {
236        if buf.len() < CLASSIC_FRAME_SIZE {
237            return Err(CanError::BufferTooShort {
238                need: CLASSIC_FRAME_SIZE,
239                have: buf.len(),
240            });
241        }
242        let Some(word_bytes) = buf.get(0..4) else {
243            return Err(CanError::BufferTooShort {
244                need: 4,
245                have: buf.len(),
246            });
247        };
248        let mut word = [0u8; 4];
249        word.copy_from_slice(word_bytes);
250        let raw = u32::from_le_bytes(word);
251
252        match buf.len() {
253            CLASSIC_FRAME_SIZE => parse_classic(buf, raw),
254            FD_FRAME_SIZE => parse_fd(buf, raw),
255            _ => Err(CanError::DataTooLong {
256                max: CLASSIC_FRAME_SIZE,
257                got: buf.len(),
258            }),
259        }
260    }
261
262    /// Serializes to the `SocketCAN` wire format: 16 bytes for classic frames
263    /// (with the RTR flag for remote frames), 72 bytes for CAN FD frames
264    /// (BRS/ESI in the flags byte).
265    #[must_use]
266    pub fn to_bytes(&self) -> Vec<u8> {
267        let mut word = self.id.to_raw_socketcan();
268        if self.is_remote {
269            word |= CAN_RTR_FLAG;
270        }
271        if self.is_fd {
272            let mut out = Vec::with_capacity(FD_FRAME_SIZE);
273            out.extend_from_slice(&word.to_le_bytes());
274            // len (0..=64), flags (BRS = 0x01, ESI = 0x02), two reserved
275            // bytes, then the payload. Invariant: len ≤ 64.
276            #[allow(clippy::cast_possible_truncation)]
277            out.push(self.data.len() as u8);
278            out.push(u8::from(self.brs) | (u8::from(self.error_state_indicator) << 1));
279            out.push(0);
280            out.push(0);
281            out.extend_from_slice(self.data);
282            out.resize(FD_FRAME_SIZE, 0);
283            out
284        } else {
285            let mut out = Vec::with_capacity(CLASSIC_FRAME_SIZE);
286            out.extend_from_slice(&word.to_le_bytes());
287            // Length byte: the requested length for RTR frames (capped at
288            // 8 — a refined DLC 9–15 rides in len8_dlc), else the payload
289            // length. Invariant: ≤ 8 either way.
290            #[allow(clippy::cast_possible_truncation)]
291            let len = if self.is_remote {
292                self.dlc.min(CLASSIC_MAX_LEN as u8)
293            } else {
294                self.data.len() as u8
295            };
296            out.push(len);
297            out.push(0); // __pad
298            out.push(0); // __res0
299                         // len8_dlc: the precise DLC, refining the length byte exactly
300                         // when it lies in 9..=15 (classic 8-byte payloads, and legacy
301                         // RTR frames requesting more than 8 bytes).
302            out.push(self.dlc);
303            if !self.is_remote {
304                out.extend_from_slice(self.data);
305            }
306            out.resize(CLASSIC_FRAME_SIZE, 0);
307            out
308        }
309    }
310
311    /// The frame's identifier.
312    #[must_use]
313    pub const fn id(&self) -> CanId {
314        self.id
315    }
316
317    /// The payload — empty for remote frames.
318    #[must_use]
319    pub const fn data(&self) -> &'a [u8] {
320        self.data
321    }
322
323    /// The Data Length Code (0–8 classic, 0–15 CAN FD).
324    #[must_use]
325    pub const fn dlc(&self) -> u8 {
326        self.dlc
327    }
328
329    /// `true` for remote-transmission-request frames.
330    #[must_use]
331    pub const fn is_remote(&self) -> bool {
332        self.is_remote
333    }
334
335    /// `true` for CAN FD frames.
336    #[must_use]
337    pub const fn is_fd(&self) -> bool {
338        self.is_fd
339    }
340
341    /// Bit-rate switch: the FD arbitration phase runs at the nominal rate,
342    /// the data phase at a faster rate. Meaningful only when [`is_fd`].
343    ///
344    /// [`is_fd`]: Self::is_fd
345    #[must_use]
346    pub const fn brs(&self) -> bool {
347        self.brs
348    }
349
350    /// Error state indicator (FD only): the transmitter's error-counter
351    /// state, carried transparently for network error bookkeeping.
352    #[must_use]
353    pub const fn error_state_indicator(&self) -> bool {
354        self.error_state_indicator
355    }
356}
357
358/// Validates an id handed to a public constructor.
359fn validate_id(id: CanId) -> Result<(), CanError> {
360    match id {
361        CanId::Standard(v) if u32::from(v) > crate::id::STANDARD_ID_MAX => {
362            Err(CanError::InvalidIdLength {
363                max: crate::id::STANDARD_ID_MAX,
364                got: u32::from(v),
365            })
366        }
367        CanId::Extended(v) if v > crate::id::EXTENDED_ID_MAX => Err(CanError::InvalidIdLength {
368            max: crate::id::EXTENDED_ID_MAX,
369            got: v,
370        }),
371        _ => Ok(()),
372    }
373}
374
375/// Parses a 16-byte `struct can_frame`.
376fn parse_classic(buf: &[u8], raw: u32) -> Result<CanFrame<'_>, CanError> {
377    let id = CanId::from_raw_socketcan(raw)?;
378    let is_remote = raw & CAN_RTR_FLAG != 0;
379
380    let Some(&len_byte) = buf.get(4) else {
381        return Err(CanError::BufferTooShort {
382            need: 5,
383            have: buf.len(),
384        });
385    };
386    // The classic length byte is a true length (0..=8); kernels emit the
387    // refined DLC separately in len8_dlc.
388    if usize::from(len_byte) > CLASSIC_MAX_LEN {
389        return Err(CanError::InvalidDlc(len_byte));
390    }
391    let len = usize::from(len_byte);
392
393    // len8_dlc (byte 7): when the length byte is 8 and len8_dlc carries a
394    // refined DLC 9–15 (kernels surface legacy "DLC > 8" classic frames —
395    // data or remote — this way), it refines the DLC; otherwise it is
396    // ignored. The payload stays at 8 bytes — classic CAN cannot carry
397    // more.
398    let dlc = match buf.get(7) {
399        Some(&dlc8) if len == CLASSIC_MAX_LEN && (9..=15).contains(&dlc8) => dlc8,
400        _ => len_byte,
401    };
402
403    let data = if is_remote {
404        &[]
405    } else {
406        buf.get(8..8 + len).ok_or(CanError::BufferTooShort {
407            need: 8 + len,
408            have: buf.len(),
409        })?
410    };
411
412    Ok(CanFrame {
413        id,
414        data,
415        dlc,
416        is_remote,
417        is_fd: false,
418        brs: false,
419        error_state_indicator: false,
420    })
421}
422
423/// Parses a 72-byte `struct canfd_frame`.
424fn parse_fd(buf: &[u8], raw: u32) -> Result<CanFrame<'_>, CanError> {
425    // CAN FD abolished remote frames and error frames: neither flag may
426    // appear in an FD id word.
427    if raw & CAN_RTR_FLAG != 0 {
428        return Err(CanError::RemoteFrameWithData);
429    }
430    if raw & CAN_ERR_FLAG != 0 {
431        return Err(CanError::InvalidIdLength {
432            max: CAN_EFF_MASK,
433            got: raw,
434        });
435    }
436    let id = CanId::from_raw_socketcan(raw)?;
437
438    let Some(&len_byte) = buf.get(4) else {
439        return Err(CanError::BufferTooShort {
440            need: 5,
441            have: buf.len(),
442        });
443    };
444    if usize::from(len_byte) > FD_MAX_LEN {
445        return Err(CanError::DataTooLong {
446            max: FD_MAX_LEN,
447            got: usize::from(len_byte),
448        });
449    }
450    let len = usize::from(len_byte);
451    let Ok(dlc) = len_to_dlc(len) else {
452        // Not a DLC-representable FD length (9–11, 13–15, …).
453        return Err(CanError::DataTooLong {
454            max: largest_fd_len_below(len),
455            got: len,
456        });
457    };
458
459    let flags = buf.get(5).copied().unwrap_or(0);
460    let brs = flags & 0x01 != 0;
461    let error_state_indicator = flags & 0x02 != 0;
462    // Remaining flag bits are reserved by the kernel ABI; ignored.
463
464    let data = buf.get(8..8 + len).ok_or(CanError::BufferTooShort {
465        need: 8 + len,
466        have: buf.len(),
467    })?;
468
469    Ok(CanFrame {
470        id,
471        data,
472        dlc,
473        is_remote: false,
474        is_fd: true,
475        brs,
476        error_state_indicator,
477    })
478}
479
480/// Largest DLC-representable FD length `<= len` (0 when none).
481fn largest_fd_len_below(len: usize) -> usize {
482    FD_DLC_TO_LEN
483        .iter()
484        .rev()
485        .find(|candidate| **candidate <= len)
486        .copied()
487        .unwrap_or(0)
488}
489
490#[cfg(test)]
491mod tests {
492    // Tests exercise edge values and index fixed-size buffers directly:
493    // unwrap/expect/indexing are lifted at test scope by design.
494    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
495    use super::*;
496    use crate::id::{CAN_EFF_FLAG, CAN_SFF_MASK};
497
498    #[test]
499    fn dlc_table_is_complete_and_monotone() {
500        assert_eq!(FD_DLC_TO_LEN.len(), 16);
501        assert_eq!(FD_DLC_TO_LEN[0], 0);
502        assert_eq!(FD_DLC_TO_LEN[8], 8);
503        assert_eq!(FD_DLC_TO_LEN[15], 64);
504        for window in FD_DLC_TO_LEN.windows(2) {
505            assert!(window[0] < window[1], "table must be strictly increasing");
506        }
507        for (dlc, len) in FD_DLC_TO_LEN.iter().enumerate() {
508            // dlc < 16 by construction — no truncation.
509            #[allow(clippy::cast_possible_truncation)]
510            let dlc = dlc as u8;
511            assert_eq!(dlc_to_len(dlc), Ok(*len));
512            assert_eq!(len_to_dlc(*len), Ok(dlc));
513        }
514    }
515
516    #[test]
517    fn dlc_errors() {
518        assert_eq!(dlc_to_len(16), Err(CanError::InvalidDlc(16)));
519        assert_eq!(
520            len_to_dlc(11),
521            Err(CanError::DataTooLong { max: 8, got: 11 })
522        );
523        assert_eq!(
524            len_to_dlc(13),
525            Err(CanError::DataTooLong { max: 12, got: 13 })
526        );
527        assert_eq!(
528            len_to_dlc(65),
529            Err(CanError::DataTooLong { max: 64, got: 65 })
530        );
531    }
532
533    #[test]
534    fn classic_wire_layout() {
535        let id = CanId::standard(0x123).unwrap();
536        let frame = CanFrame::new(id, &[1, 2, 3]).unwrap();
537        let bytes = frame.to_bytes();
538        assert_eq!(bytes.len(), 16);
539        assert_eq!(&bytes[0..4], &0x123_u32.to_le_bytes());
540        assert_eq!(bytes[4], 3);
541        assert_eq!(&bytes[8..11], &[1, 2, 3]);
542    }
543
544    #[test]
545    fn classic_len8_dlc_refinement() {
546        // len == 8 with len8_dlc == 12: a refined DLC 12 on an 8-byte
547        // classic payload (legacy "DLC > 8" frames from real adapters).
548        let mut buf = [0u8; 16];
549        buf[0..4].copy_from_slice(&0x456_u32.to_le_bytes());
550        buf[4] = 8;
551        buf[7] = 12;
552        let frame = CanFrame::parse(&buf).unwrap();
553        assert_eq!(frame.dlc(), 12);
554        assert_eq!(frame.data().len(), 8);
555        // The refined frame is constructible and round-trips byte-exactly.
556        let payload = buf.get(8..16).unwrap();
557        let rebuilt = CanFrame::from_parts(
558            CanId::standard(0x456).unwrap(),
559            payload,
560            12,
561            false,
562            false,
563            false,
564            false,
565        )
566        .unwrap();
567        assert_eq!(rebuilt, frame);
568        let out = frame.to_bytes();
569        assert_eq!(out, buf);
570        // Refined forms below DLC 9 or on shorter payloads are ignored:
571        buf[7] = 5; // len8_dlc <= 8 carries no refinement
572        assert_eq!(CanFrame::parse(&buf).unwrap().dlc(), 8);
573        buf[4] = 3;
574        buf[7] = 12;
575        assert_eq!(CanFrame::parse(&buf).unwrap().dlc(), 3);
576    }
577
578    #[test]
579    fn fd_wire_layout() {
580        let id = CanId::extended(0x18FF_0102).unwrap();
581        let payload = [7u8; 12]; // DLC 9
582        let frame = CanFrame::fd(id, &payload, true, false).unwrap();
583        assert_eq!(frame.dlc(), 9);
584        let bytes = frame.to_bytes();
585        assert_eq!(bytes.len(), 72);
586        assert_eq!(
587            &bytes[0..4],
588            &(0x18FF_0102_u32 | CAN_EFF_FLAG).to_le_bytes()
589        );
590        assert_eq!(bytes[4], 12); // true length byte
591        assert_eq!(bytes[5], 0x01); // BRS
592        assert_eq!(&bytes[8..20], &payload);
593
594        let reparsed = CanFrame::parse(&bytes).unwrap();
595        assert!(reparsed.is_fd());
596        assert!(reparsed.brs());
597        assert!(!reparsed.error_state_indicator());
598        assert_eq!(frame, reparsed);
599    }
600
601    #[test]
602    fn fd_all_lengths_roundtrip() {
603        let id = CanId::standard(0x7FF).unwrap();
604        for dlc in 0_u8..=15 {
605            let len = dlc_to_len(dlc).unwrap();
606            let payload = [0xAB_u8; 64];
607            let frame = CanFrame::fd(id, &payload[..len], false, false).unwrap();
608            let bytes = frame.to_bytes();
609            let reparsed = CanFrame::parse(&bytes).unwrap();
610            assert_eq!(reparsed, frame);
611            assert_eq!(reparsed.dlc(), dlc);
612        }
613    }
614
615    #[test]
616    fn parse_errors() {
617        // Too short:
618        assert_eq!(
619            CanFrame::parse(&[0u8; 15]),
620            Err(CanError::BufferTooShort { need: 16, have: 15 })
621        );
622        // Wrong total size:
623        assert_eq!(
624            CanFrame::parse(&[0u8; 17]),
625            Err(CanError::DataTooLong { max: 16, got: 17 })
626        );
627        // Classic length byte > 8:
628        let mut buf = [0u8; 16];
629        buf[4] = 9;
630        assert_eq!(CanFrame::parse(&buf), Err(CanError::InvalidDlc(9)));
631        // Error-frame class:
632        let mut err_buf = [0u8; 16];
633        err_buf[0..4].copy_from_slice(&(CAN_ERR_FLAG | 0x123).to_le_bytes());
634        assert!(matches!(
635            CanFrame::parse(&err_buf),
636            Err(CanError::InvalidIdLength { .. })
637        ));
638        // Standard-classic id with bits above 0x7FF:
639        let mut wide = [0u8; 16];
640        wide[0..4].copy_from_slice(&0x1234_u32.to_le_bytes());
641        assert!(matches!(
642            CanFrame::parse(&wide),
643            Err(CanError::InvalidIdLength {
644                max: CAN_SFF_MASK,
645                ..
646            })
647        ));
648        // RTR flag inside an FD-sized frame:
649        let mut fd_rtr = [0u8; 72];
650        fd_rtr[0..4].copy_from_slice(&(CAN_EFF_FLAG | CAN_RTR_FLAG | 0x123).to_le_bytes());
651        assert_eq!(CanFrame::parse(&fd_rtr), Err(CanError::RemoteFrameWithData));
652        // FD length byte not DLC-representable:
653        let mut fd_bad = [0u8; 72];
654        fd_bad[4] = 11;
655        assert_eq!(
656            CanFrame::parse(&fd_bad),
657            Err(CanError::DataTooLong { max: 8, got: 11 })
658        );
659        // FD length byte > 64:
660        let mut fd_huge = [0u8; 72];
661        fd_huge[4] = 65;
662        assert_eq!(
663            CanFrame::parse(&fd_huge),
664            Err(CanError::DataTooLong { max: 64, got: 65 })
665        );
666        // ESI flag survives the round trip:
667        let mut fd_esi = [0u8; 72];
668        fd_esi[4] = 8;
669        fd_esi[5] = 0x02;
670        let esi = CanFrame::parse(&fd_esi).unwrap();
671        assert!(esi.error_state_indicator());
672        assert!(!esi.brs());
673    }
674
675    #[test]
676    fn constructor_errors() {
677        let id = CanId::standard(0x123).unwrap();
678        let nine = [0u8; 9];
679        // Classic with 9 bytes:
680        assert_eq!(
681            CanFrame::new(id, &nine),
682            Err(CanError::DataTooLong { max: 8, got: 9 })
683        );
684        // FD with a non-representable length:
685        assert_eq!(
686            CanFrame::fd(id, &nine, false, false),
687            Err(CanError::DataTooLong { max: 8, got: 9 })
688        );
689        // BRS on a classic frame:
690        assert_eq!(
691            CanFrame::from_parts(id, &[], 0, false, false, true, false),
692            Err(CanError::FdBrsOnClassic)
693        );
694        // ESI on a classic frame:
695        assert_eq!(
696            CanFrame::from_parts(id, &[], 0, false, false, false, true),
697            Err(CanError::FdBrsOnClassic)
698        );
699        // Remote frame with data:
700        assert_eq!(
701            CanFrame::from_parts(id, &[1], 1, true, false, false, false),
702            Err(CanError::RemoteFrameWithData)
703        );
704        // FD remote frame:
705        assert_eq!(
706            CanFrame::from_parts(id, &[], 0, true, true, false, false),
707            Err(CanError::RemoteFrameWithData)
708        );
709        // Remote DLC > 15:
710        assert_eq!(CanFrame::remote(id, 16), Err(CanError::InvalidDlc(16)));
711        // Refined remote DLC (legacy len8_dlc): serializes as len 8 +
712        // len8_dlc 12, and round-trips.
713        let refined = CanFrame::remote(id, 12).unwrap();
714        assert_eq!(refined.dlc(), 12);
715        let bytes = refined.to_bytes();
716        assert_eq!(bytes[4], 8);
717        assert_eq!(bytes[7], 12);
718        assert_eq!(CanFrame::parse(&bytes), Ok(refined));
719        // DLC > 15:
720        assert_eq!(
721            CanFrame::from_parts(id, &[], 16, false, false, false, false),
722            Err(CanError::InvalidDlc(16))
723        );
724        // Classic DLC inconsistent with the payload length:
725        assert_eq!(
726            CanFrame::from_parts(id, &[1, 2], 3, false, false, false, false),
727            Err(CanError::InvalidDlc(3))
728        );
729        // FD DLC inconsistent with the payload length:
730        assert_eq!(
731            CanFrame::from_parts(id, &[1, 2], 1, false, true, false, false),
732            Err(CanError::InvalidDlc(1))
733        );
734        // Out-of-range id via a hand-built enum value (defense in depth):
735        assert_eq!(
736            CanFrame::from_parts(CanId::Standard(0xFFFF), &[], 0, false, false, false, false),
737            Err(CanError::InvalidIdLength {
738                max: 0x7FF,
739                got: 0xFFFF
740            })
741        );
742    }
743
744    #[test]
745    fn remote_frame_wire_roundtrip() {
746        let id = CanId::extended(0x0123_4567).unwrap();
747        let frame = CanFrame::remote(id, 3).unwrap();
748        assert!(frame.is_remote());
749        assert_eq!(frame.data(), &[]);
750        let bytes = frame.to_bytes();
751        assert_eq!(
752            &bytes[0..4],
753            &(0x0123_4567_u32 | CAN_EFF_FLAG | CAN_RTR_FLAG).to_le_bytes()
754        );
755        assert_eq!(bytes[4], 3);
756        let reparsed = CanFrame::parse(&bytes).unwrap();
757        assert_eq!(frame, reparsed);
758        assert_eq!(reparsed.dlc(), 3);
759    }
760
761    /// Accessor coverage — every getter is pinned once.
762    #[test]
763    fn accessors() {
764        let id = CanId::standard(0x123).unwrap();
765        let frame = CanFrame::new(id, &[1]).unwrap();
766        assert_eq!(frame.id(), id);
767        assert_eq!(frame.data(), &[1]);
768        assert_eq!(frame.dlc(), 1);
769        assert!(!frame.is_remote());
770        assert!(!frame.is_fd());
771        assert!(!frame.brs());
772        assert!(!frame.error_state_indicator());
773    }
774}