Skip to content

Commit bcdca45

Browse files
committed
Manually implement Ord according to CAN bus arbitration rules
1 parent fd280d5 commit bcdca45

File tree

1 file changed

+41
-1
lines changed

1 file changed

+41
-1
lines changed

src/can/id.rs

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ impl ExtendedId {
8585
}
8686

8787
/// A CAN Identifier (standard or extended).
88-
#[derive(Debug, Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)]
88+
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
8989
pub enum Id {
9090
/// Standard 11-bit Identifier (`0..=0x7FF`).
9191
Standard(StandardId),
@@ -94,6 +94,30 @@ pub enum Id {
9494
Extended(ExtendedId),
9595
}
9696

97+
impl Ord for Id {
98+
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
99+
let split_id = |id: &Id| {
100+
let (standard_id_part, ide_bit, extended_id_part) = match id {
101+
Id::Standard(StandardId(x)) => (*x, 0, 0),
102+
Id::Extended(x) => (
103+
x.standard_id().0,
104+
1,
105+
x.0 & ((1 << 18) - 1), // Bit ID-17 to ID-0
106+
),
107+
};
108+
(standard_id_part, ide_bit, extended_id_part)
109+
};
110+
111+
split_id(self).cmp(&split_id(other))
112+
}
113+
}
114+
115+
impl PartialOrd for Id {
116+
fn partial_cmp(&self, other: &Id) -> Option<core::cmp::Ordering> {
117+
Some(self.cmp(other))
118+
}
119+
}
120+
97121
impl From<StandardId> for Id {
98122
#[inline]
99123
fn from(id: StandardId) -> Self {
@@ -157,4 +181,20 @@ mod tests {
157181
StandardId::new((ExtendedId::MAX.0 >> 18) as u16)
158182
);
159183
}
184+
185+
#[test]
186+
fn cmp_standard() {
187+
assert!(StandardId::MAX < StandardId::ZERO);
188+
}
189+
190+
#[test]
191+
fn cmp_extended() {
192+
assert!(ExtendedId::MAX < ExtendedId::ZERO);
193+
}
194+
195+
#[test]
196+
fn cmp_id() {
197+
assert!(Id::Standard(StandardId::MAX) < Id::Standard(StandardId::ZERO));
198+
assert!(Id::Extended(ExtendedId::MAX) < Id::Extended(ExtendedId::ZERO));
199+
}
160200
}

0 commit comments

Comments
 (0)