Crate crc8_rs[−][src]
A no_std library for doing 8-bit cyclic redundancy checks. This is mostly meant for embedded hardware, but it can be used in a std environment as well. This uses const generics from Rust 15.1 which is available in stable from Match 25th, 2021, before then you will have to use the Rust beta.
Usage
Inserting and verifying corrupting byte arrays.
use crc8::{ verify_crc8, insert_crc8 }; const GENERATOR_POLYNOMIAL: u8 = 0xD5; // We add an empty byte at the end for the CRC let msg = b"Hello World!\0"; let msg = insert_crc8(&msg, GENERATOR_POLYNOMIAL); // Will verify just fine! assert!(verify_crc8(&msg, GENERATOR_POLYNOMIAL)); let corrupted_msg = { let mut tmp_msg = msg; tmp_msg[1] = b'a'; tmp_msg }; // The message is now corrupted and thus it can't verify the integrity! assert!(!verify_crc8(&corrupted_msg, GENERATOR_POLYNOMIAL));
Adding a CRC to custom Packet struct
use crc8::{ fetch_crc8, verify_crc8, concat_byte_arrays }; const GENERATOR_POLYNOMIAL: u8 = 0xD5; // We can declare our packets ourselves struct Packet { header: u8, content: [u8; 14], crc: u8, } impl Packet { fn new(header: u8, content: [u8; 14]) -> Packet { let mut pkt = Packet { header, content, crc: 0, }; pkt.crc = GENERATOR_POLYNOMIAL ^ fetch_crc8( &pkt.to_bytes(), GENERATOR_POLYNOMIAL ); pkt } fn to_bytes(&self) -> [u8; 16] { concat_byte_arrays::<16, 15, 1>( concat_byte_arrays::<15, 1, 14>([self.header], self.content), [self.crc] ) } } assert!(verify_crc8( &Packet::new(b'H', *b"ello everyone!").to_bytes(), GENERATOR_POLYNOMIAL) );
License
Licensed under a MIT license.
Functions
concat_byte_arrays | Concatenate two byte arrays into one byte array with compile time validation. |
fetch_crc8 | Generate Cyclic Redundancy Check for a given bytes array given a certain generator polynomial. |
insert_crc8 | Insert CRC on the last byte of a bytes array so that it can be verified. |
verify_crc8 | Verify the integrity of the bytes array. |