Skip to main content

predsync_core/
crc.rs

1//! CRC-16/IBM-SDLC, the frame checksum used by predsync.
2
3const CRC_INIT: u16 = 0xFFFF;
4const CRC_XOROUT: u16 = 0xFFFF;
5const CRC_POLY_REFLECTED: u16 = 0x8408;
6
7const fn build_crc_table() -> [u16; 256] {
8    let mut table = [0u16; 256];
9    let mut i = 0usize;
10    while i < 256 {
11        let mut crc = i as u16;
12        let mut bit = 0usize;
13        while bit < 8 {
14            crc = if crc & 1 != 0 {
15                (crc >> 1) ^ CRC_POLY_REFLECTED
16            } else {
17                crc >> 1
18            };
19            bit += 1;
20        }
21        table[i] = crc;
22        i += 1;
23    }
24    table
25}
26
27const CRC_TABLE: [u16; 256] = build_crc_table();
28
29/// CRC-16/IBM-SDLC (X.25): reflected polynomial 0x1021, init and xorout 0xFFFF.
30pub fn crc16(data: &[u8]) -> u16 {
31    let mut crc = CRC_INIT;
32    for &byte in data {
33        crc = (crc >> 8) ^ CRC_TABLE[(crc ^ u16::from(byte)) as usize & 0xFF];
34    }
35    crc ^ CRC_XOROUT
36}
37
38#[cfg(test)]
39mod tests {
40    use super::*;
41
42    #[test]
43    fn crc16_check_value_906e() {
44        assert_eq!(crc16(b"123456789"), 0x906E);
45    }
46
47    #[test]
48    fn crc16_empty() {
49        assert_eq!(crc16(b""), 0x0000);
50    }
51
52    #[test]
53    fn crc16_matches_reference_vectors() {
54        let cases: &[(&[u8], u16)] = &[
55            (b"", 0x0000),
56            (b"123456789", 0x906E),
57            (b"\x00", 0xF078),
58            (b"hello", 0x34BD),
59            (&[0, 0, 0, 7], 0x8861),
60            (b"\x00\x00\x00\x03\x02\x00hi", 0xF29B),
61        ];
62        for (data, expected) in cases {
63            assert_eq!(crc16(data), *expected, "data {data:02x?}");
64        }
65    }
66}