bxcan/id.rs
1//! CAN Identifiers.
2
3/// Standard 11-bit CAN Identifier (`0..=0x7FF`).
4#[derive(Debug, Copy, Clone, Eq, PartialEq)]
5pub struct StandardId(u16);
6
7impl StandardId {
8 /// CAN ID `0`, the highest priority.
9 pub const ZERO: Self = Self(0);
10
11 /// CAN ID `0x7FF`, the lowest priority.
12 pub const MAX: Self = Self(0x7FF);
13
14 /// Tries to create a `StandardId` from a raw 16-bit integer.
15 ///
16 /// This will return `None` if `raw` is out of range of an 11-bit integer (`> 0x7FF`).
17 #[inline]
18 pub const fn new(raw: u16) -> Option<Self> {
19 if raw <= 0x7FF {
20 Some(Self(raw))
21 } else {
22 None
23 }
24 }
25
26 /// Creates a new `StandardId` without checking if it is inside the valid range.
27 ///
28 /// # Safety
29 ///
30 /// The caller must ensure that `raw` is in the valid range, otherwise the behavior is
31 /// undefined.
32 #[inline]
33 pub const unsafe fn new_unchecked(raw: u16) -> Self {
34 Self(raw)
35 }
36
37 /// Returns this CAN Identifier as a raw 16-bit integer.
38 #[inline]
39 pub fn as_raw(&self) -> u16 {
40 self.0
41 }
42}
43
44/// Extended 29-bit CAN Identifier (`0..=1FFF_FFFF`).
45#[derive(Debug, Copy, Clone, Eq, PartialEq)]
46pub struct ExtendedId(u32);
47
48impl ExtendedId {
49 /// CAN ID `0`, the highest priority.
50 pub const ZERO: Self = Self(0);
51
52 /// CAN ID `0x1FFFFFFF`, the lowest priority.
53 pub const MAX: Self = Self(0x1FFF_FFFF);
54
55 /// Tries to create a `ExtendedId` from a raw 32-bit integer.
56 ///
57 /// This will return `None` if `raw` is out of range of an 29-bit integer (`> 0x1FFF_FFFF`).
58 #[inline]
59 pub const fn new(raw: u32) -> Option<Self> {
60 if raw <= 0x1FFF_FFFF {
61 Some(Self(raw))
62 } else {
63 None
64 }
65 }
66
67 /// Creates a new `ExtendedId` without checking if it is inside the valid range.
68 ///
69 /// # Safety
70 ///
71 /// The caller must ensure that `raw` is in the valid range, otherwise the behavior is
72 /// undefined.
73 #[inline]
74 pub const unsafe fn new_unchecked(raw: u32) -> Self {
75 Self(raw)
76 }
77
78 /// Returns this CAN Identifier as a raw 32-bit integer.
79 #[inline]
80 pub fn as_raw(&self) -> u32 {
81 self.0
82 }
83
84 /// Returns the Base ID part of this extended identifier.
85 pub fn standard_id(&self) -> StandardId {
86 // ID-28 to ID-18
87 StandardId((self.0 >> 18) as u16)
88 }
89}
90
91/// A CAN Identifier (standard or extended).
92#[derive(Debug, Copy, Clone, Eq, PartialEq)]
93pub enum Id {
94 /// Standard 11-bit Identifier (`0..=0x7FF`).
95 Standard(StandardId),
96
97 /// Extended 29-bit Identifier (`0..=0x1FFF_FFFF`).
98 Extended(ExtendedId),
99}
100
101impl From<StandardId> for Id {
102 #[inline]
103 fn from(id: StandardId) -> Self {
104 Id::Standard(id)
105 }
106}
107
108impl From<ExtendedId> for Id {
109 #[inline]
110 fn from(id: ExtendedId) -> Self {
111 Id::Extended(id)
112 }
113}