temporal_control/dispatch/encoding/crc32.rs
1//! CRC-32/ISO-HDLC, table-driven, with the table built at compile time.
2
3/// Reflected generator polynomial `0x04C11DB7` of CRC-32/ISO-HDLC.
4const POLYNOMIAL: u32 = 0xEDB8_8320;
5
6/// Remainder of every byte value, for byte-at-a-time processing.
7const TABLE: [u32; 256] = table();
8
9/// Builds [`TABLE`].
10const fn table() -> [u32; 256] {
11 let mut table = [0u32; 256];
12 let mut byte = 0u32;
13
14 while byte < 256 {
15 let mut crc = byte;
16 let mut bit = 0;
17
18 while bit < 8 {
19 crc = if crc & 1 == 0 {
20 crc >> 1
21 } else {
22 (crc >> 1) ^ POLYNOMIAL
23 };
24 bit += 1;
25 }
26
27 table[byte as usize] = crc;
28 byte += 1;
29 }
30
31 table
32}
33
34/// CRC-32/ISO-HDLC of `bytes`, the checksum of zlib, PNG and Ethernet.
35///
36/// Parameters: polynomial `0x04C11DB7` (reflected `0xEDB88320`), initial value and final XOR
37/// `0xFFFFFFFF`, input and output reflected. Check value: `crc32(b"123456789") ==
38/// 0xCBF4_3926`. Detects every error burst of up to 32 bits, in particular every single-bit
39/// error.
40///
41/// # Examples
42///
43/// ```
44/// use temporal_control::dispatch::encoding::crc32;
45///
46/// assert_eq!(crc32(b"123456789"), 0xCBF4_3926);
47/// assert_eq!(crc32(b""), 0);
48/// ```
49#[must_use]
50pub fn crc32(bytes: &[u8]) -> u32 {
51 !bytes.iter().fold(!0u32, |crc, &b| {
52 TABLE[usize::from(crc.to_le_bytes()[0] ^ b)] ^ (crc >> 8)
53 })
54}