Repo of no-std crates for my personal embedded projects
at main 851 B view raw
1/// Calculate the CRC8 checksum. 2/// 3/// Implementation based on the reference implementation by Sensirion. 4#[inline] 5pub(crate) const fn crc8(data: &[u8]) -> u8 { 6 const CRC8_POLYNOMIAL: u8 = 0x31; 7 let mut crc: u8 = u8::MAX; 8 let mut i = 0; 9 10 while i < data.len() { 11 crc ^= data[i]; 12 i += 1; 13 14 let mut c = 0; 15 while c < 8 { 16 c += 1; 17 if (crc & 0x80) > 0 { 18 crc = (crc << 1) ^ CRC8_POLYNOMIAL; 19 } else { 20 crc <<= 1; 21 } 22 } 23 } 24 25 crc 26} 27 28#[cfg(test)] 29mod tests { 30 use super::*; 31 32 /// Test the crc8 function against the test value provided in the 33 /// SHTC3 datasheet (section 5.10). 34 #[test] 35 fn crc8_test_value() { 36 assert_eq!(crc8(&[0x00]), 0xac); 37 assert_eq!(crc8(&[0xbe, 0xef]), 0x92); 38 } 39}