From 5ab61e77d64d82d0e43c9b0bb046eac0959e3378 Mon Sep 17 00:00:00 2001 From: ju6ge Date: Thu, 19 Mar 2026 20:37:39 +0100 Subject: [PATCH] Impl to_* and from_be_bytes function for transit type --- lib-bms-protocol/src/types.rs | 35 ++++++++++++++++++++++++++--------- 1 file changed, 26 insertions(+), 9 deletions(-) diff --git a/lib-bms-protocol/src/types.rs b/lib-bms-protocol/src/types.rs index 31ee68e..79d558d 100644 --- a/lib-bms-protocol/src/types.rs +++ b/lib-bms-protocol/src/types.rs @@ -53,6 +53,7 @@ pub enum U26Error { InvalidCodeWord, IncorrectibleError, Overflow, + ChecksumError, } #[derive(Debug, PartialEq)] @@ -122,7 +123,7 @@ impl TryFrom 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 /// 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); Self((value << 6) | (crc6 & 0x3F) as u32) } + + pub fn from_be_bytes(bytes: [u8; 4]) -> Result { + 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 for u32 { @@ -459,20 +475,21 @@ mod base_type_tests { #[test] 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 crc = calc_crc6(data); assert!(check_crc6(data, crc)) } #[test] - fn crc6_different_inputs_different_outputs() { - // Test that different inputs produce different CRCs (with high probability) - let data1 = 0x123456; - let data2 = 0x123457; - let crc1 = calc_crc6(data1); - let crc2 = calc_crc6(data2); - assert_ne!(crc1, crc2); + fn transit_u26_to_from_bytes() { + let data1 = Transit_U26::new(0x123456); + // check that to from bytes conversion produces the same value + let mut bytes = data1.to_be_bytes(); + assert_eq!(data1, Transit_U26::from_be_bytes(bytes).unwrap()); + // test that changed data leads to checksum error + bytes[1] = 0x00; + assert!(Transit_U26::from_be_bytes(bytes).unwrap_err() == U26Error::ChecksumError) } #[test]