Impl to_* and from_be_bytes function for transit type

This commit is contained in:
2026-03-22 17:39:46 +01:00
parent bcaf76de12
commit 5ab61e77d6
+26 -9
View File
@@ -53,6 +53,7 @@ pub enum U26Error {
InvalidCodeWord, InvalidCodeWord,
IncorrectibleError, IncorrectibleError,
Overflow, Overflow,
ChecksumError,
} }
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
@@ -122,7 +123,7 @@ impl TryFrom<u32> for Stored_U26 {
} }
} }
#[derive(Debug)] #[derive(Debug, PartialEq)]
/// this type is used for transmitting data, the concern here is protection against transmission errors which most likely occur /// this type is used for transmitting data, the concern here is protection against transmission errors which most likely occur
/// as burst errors effecting multiple bits, hemming codes would be a waist of space here so instead a 6 bit crc code is used /// as burst errors effecting multiple bits, hemming codes would be a waist of space here so instead a 6 bit crc code is used
/// ///
@@ -136,6 +137,21 @@ impl Transit_U26 {
let crc6 = calc_crc6(value); let crc6 = calc_crc6(value);
Self((value << 6) | (crc6 & 0x3F) as u32) Self((value << 6) | (crc6 & 0x3F) as u32)
} }
pub fn from_be_bytes(bytes: [u8; 4]) -> Result<Self, U26Error> {
let raw_val = u32::from_be_bytes(bytes);
let crc = (raw_val & 0x3F) as u8;
let val = raw_val >> 6;
if check_crc6(val, crc) {
Ok(Self(raw_val))
} else {
Err(U26Error::ChecksumError)
}
}
pub fn to_be_bytes(&self) -> [u8; 4] {
self.0.to_be_bytes()
}
} }
impl From<Transit_U26> for u32 { impl From<Transit_U26> for u32 {
@@ -459,20 +475,21 @@ mod base_type_tests {
#[test] #[test]
fn crc6_consistency() { fn crc6_consistency() {
// Test that same input always produces same output // Test that calc crc6 and check crc6 agree on validity
let data = 0x123456; let data = 0x123456;
let crc = calc_crc6(data); let crc = calc_crc6(data);
assert!(check_crc6(data, crc)) assert!(check_crc6(data, crc))
} }
#[test] #[test]
fn crc6_different_inputs_different_outputs() { fn transit_u26_to_from_bytes() {
// Test that different inputs produce different CRCs (with high probability) let data1 = Transit_U26::new(0x123456);
let data1 = 0x123456; // check that to from bytes conversion produces the same value
let data2 = 0x123457; let mut bytes = data1.to_be_bytes();
let crc1 = calc_crc6(data1); assert_eq!(data1, Transit_U26::from_be_bytes(bytes).unwrap());
let crc2 = calc_crc6(data2); // test that changed data leads to checksum error
assert_ne!(crc1, crc2); bytes[1] = 0x00;
assert!(Transit_U26::from_be_bytes(bytes).unwrap_err() == U26Error::ChecksumError)
} }
#[test] #[test]