1use crate::error::CanError;
22use crate::id::{CanId, CAN_EFF_MASK, CAN_ERR_FLAG, CAN_RTR_FLAG};
23use alloc::vec::Vec;
24
25pub const CLASSIC_MAX_LEN: usize = 8;
27pub const FD_MAX_LEN: usize = 64;
29pub const CLASSIC_FRAME_SIZE: usize = 16;
31pub const FD_FRAME_SIZE: usize = 72;
33
34pub const FD_DLC_TO_LEN: [usize; 16] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 16, 20, 24, 32, 48, 64];
37
38pub 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
50pub fn len_to_dlc(len: usize) -> Result<u8, CanError> {
58 for (dlc, table_len) in FD_DLC_TO_LEN.iter().enumerate() {
60 if *table_len == len {
61 #[allow(clippy::cast_possible_truncation)]
63 return Ok(dlc as u8);
64 }
65 }
66 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#[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 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 #[allow(clippy::cast_possible_truncation)]
127 Self::from_parts(id, data, data.len() as u8, false, false, false, false)
128 }
129
130 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 pub fn remote(id: CanId, dlc: u8) -> Result<Self, CanError> {
152 Self::from_parts(id, &[], dlc, true, false, false, false)
153 }
154
155 #[allow(clippy::fn_params_excessive_bools)] 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 return Err(CanError::RemoteFrameWithData);
184 }
185 } else if is_fd {
189 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 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 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 #[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 #[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 #[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); out.push(0); 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 #[must_use]
313 pub const fn id(&self) -> CanId {
314 self.id
315 }
316
317 #[must_use]
319 pub const fn data(&self) -> &'a [u8] {
320 self.data
321 }
322
323 #[must_use]
325 pub const fn dlc(&self) -> u8 {
326 self.dlc
327 }
328
329 #[must_use]
331 pub const fn is_remote(&self) -> bool {
332 self.is_remote
333 }
334
335 #[must_use]
337 pub const fn is_fd(&self) -> bool {
338 self.is_fd
339 }
340
341 #[must_use]
346 pub const fn brs(&self) -> bool {
347 self.brs
348 }
349
350 #[must_use]
353 pub const fn error_state_indicator(&self) -> bool {
354 self.error_state_indicator
355 }
356}
357
358fn 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
375fn 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 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 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
423fn parse_fd(buf: &[u8], raw: u32) -> Result<CanFrame<'_>, CanError> {
425 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 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 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
480fn 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 #![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 #[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 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 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 buf[7] = 5; 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]; 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); assert_eq!(bytes[5], 0x01); 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 assert_eq!(
619 CanFrame::parse(&[0u8; 15]),
620 Err(CanError::BufferTooShort { need: 16, have: 15 })
621 );
622 assert_eq!(
624 CanFrame::parse(&[0u8; 17]),
625 Err(CanError::DataTooLong { max: 16, got: 17 })
626 );
627 let mut buf = [0u8; 16];
629 buf[4] = 9;
630 assert_eq!(CanFrame::parse(&buf), Err(CanError::InvalidDlc(9)));
631 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 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 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 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 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 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 assert_eq!(
681 CanFrame::new(id, &nine),
682 Err(CanError::DataTooLong { max: 8, got: 9 })
683 );
684 assert_eq!(
686 CanFrame::fd(id, &nine, false, false),
687 Err(CanError::DataTooLong { max: 8, got: 9 })
688 );
689 assert_eq!(
691 CanFrame::from_parts(id, &[], 0, false, false, true, false),
692 Err(CanError::FdBrsOnClassic)
693 );
694 assert_eq!(
696 CanFrame::from_parts(id, &[], 0, false, false, false, true),
697 Err(CanError::FdBrsOnClassic)
698 );
699 assert_eq!(
701 CanFrame::from_parts(id, &[1], 1, true, false, false, false),
702 Err(CanError::RemoteFrameWithData)
703 );
704 assert_eq!(
706 CanFrame::from_parts(id, &[], 0, true, true, false, false),
707 Err(CanError::RemoteFrameWithData)
708 );
709 assert_eq!(CanFrame::remote(id, 16), Err(CanError::InvalidDlc(16)));
711 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 assert_eq!(
721 CanFrame::from_parts(id, &[], 16, false, false, false, false),
722 Err(CanError::InvalidDlc(16))
723 );
724 assert_eq!(
726 CanFrame::from_parts(id, &[1, 2], 3, false, false, false, false),
727 Err(CanError::InvalidDlc(3))
728 );
729 assert_eq!(
731 CanFrame::from_parts(id, &[1, 2], 1, false, true, false, false),
732 Err(CanError::InvalidDlc(1))
733 );
734 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 #[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}