crc/
crc16.rs

1use crate::table::crc16_table;
2use crate::util::crc16;
3use crate::*;
4use crc_catalog::Algorithm;
5
6impl<const L: usize> Crc<u16, Table<L>>
7where
8    Table<L>: private::Sealed,
9{
10    pub const fn new(algorithm: &'static Algorithm<u16>) -> Self {
11        Self {
12            algorithm,
13            data: crc16_table(algorithm.width, algorithm.poly, algorithm.refin),
14        }
15    }
16
17    pub const fn checksum(&self, bytes: &[u8]) -> u16 {
18        let mut crc = init(self.algorithm, self.algorithm.init);
19        crc = self.update(crc, bytes);
20        finalize(self.algorithm, crc)
21    }
22
23    const fn update(&self, crc: u16, bytes: &[u8]) -> u16 {
24        update_table(crc, self.algorithm, &self.data, bytes)
25    }
26
27    pub const fn digest(&self) -> Digest<u16, Table<L>> {
28        self.digest_with_initial(self.algorithm.init)
29    }
30
31    /// Construct a `Digest` with a given initial value.
32    ///
33    /// This overrides the initial value specified by the algorithm.
34    /// The effects of the algorithm's properties `refin` and `width`
35    /// are applied to the custom initial value.
36    pub const fn digest_with_initial(&self, initial: u16) -> Digest<u16, Table<L>> {
37        let value = init(self.algorithm, initial);
38        Digest::new(self, value)
39    }
40
41    pub const fn table(&self) -> &<Table<L> as Implementation>::Data<u16> {
42        &self.data
43    }
44}
45
46impl<'a, const L: usize> Digest<'a, u16, Table<L>>
47where
48    Table<L>: private::Sealed,
49{
50    const fn new(crc: &'a Crc<u16, Table<L>>, value: u16) -> Self {
51        Digest { crc, value }
52    }
53
54    pub fn update(&mut self, bytes: &[u8]) {
55        self.value = self.crc.update(self.value, bytes);
56    }
57
58    pub const fn finalize(self) -> u16 {
59        finalize(self.crc.algorithm, self.value)
60    }
61}
62
63const fn init(algorithm: &Algorithm<u16>, initial: u16) -> u16 {
64    if algorithm.refin {
65        initial.reverse_bits() >> (16u8 - algorithm.width)
66    } else {
67        initial << (16u8 - algorithm.width)
68    }
69}
70
71const fn finalize(algorithm: &Algorithm<u16>, mut crc: u16) -> u16 {
72    if algorithm.refin ^ algorithm.refout {
73        crc = crc.reverse_bits();
74    }
75    if !algorithm.refout {
76        crc >>= 16u8 - algorithm.width;
77    }
78    crc ^ algorithm.xorout
79}
80
81const fn update_table<const L: usize>(
82    mut crc: u16,
83    algorithm: &Algorithm<u16>,
84    table: &[[u16; 256]; L],
85    bytes: &[u8],
86) -> u16 {
87    let len = bytes.len();
88    let mut i = 0;
89    let reflect = algorithm.refin;
90
91    // Process 16 bytes at a time when L=16
92    if L == 16 {
93        while i + 16 <= len {
94            if reflect {
95                let current0 = bytes[i] ^ (crc as u8);
96                let current1 = bytes[i + 1] ^ ((crc >> 8) as u8);
97
98                crc = table[0][bytes[i + 15] as usize]
99                    ^ table[1][bytes[i + 14] as usize]
100                    ^ table[2][bytes[i + 13] as usize]
101                    ^ table[3][bytes[i + 12] as usize]
102                    ^ table[4][bytes[i + 11] as usize]
103                    ^ table[5][bytes[i + 10] as usize]
104                    ^ table[6][bytes[i + 9] as usize]
105                    ^ table[7][bytes[i + 8] as usize]
106                    ^ table[8][bytes[i + 7] as usize]
107                    ^ table[9][bytes[i + 6] as usize]
108                    ^ table[10][bytes[i + 5] as usize]
109                    ^ table[11][bytes[i + 4] as usize]
110                    ^ table[12][bytes[i + 3] as usize]
111                    ^ table[13][bytes[i + 2] as usize]
112                    ^ table[14][current1 as usize]
113                    ^ table[15][current0 as usize];
114            } else {
115                let current0 = bytes[i] ^ ((crc >> 8) as u8);
116                let current1 = bytes[i + 1] ^ (crc as u8);
117
118                crc = table[0][bytes[i + 15] as usize]
119                    ^ table[1][bytes[i + 14] as usize]
120                    ^ table[2][bytes[i + 13] as usize]
121                    ^ table[3][bytes[i + 12] as usize]
122                    ^ table[4][bytes[i + 11] as usize]
123                    ^ table[5][bytes[i + 10] as usize]
124                    ^ table[6][bytes[i + 9] as usize]
125                    ^ table[7][bytes[i + 8] as usize]
126                    ^ table[8][bytes[i + 7] as usize]
127                    ^ table[9][bytes[i + 6] as usize]
128                    ^ table[10][bytes[i + 5] as usize]
129                    ^ table[11][bytes[i + 4] as usize]
130                    ^ table[12][bytes[i + 3] as usize]
131                    ^ table[13][bytes[i + 2] as usize]
132                    ^ table[14][current1 as usize]
133                    ^ table[15][current0 as usize];
134            }
135            i += 16;
136        }
137    }
138
139    // Process remaining bytes one at a time using the table (for L=1 and L=16)
140    if L > 0 {
141        if reflect {
142            while i < len {
143                let table_index = ((crc ^ bytes[i] as u16) & 0xFF) as usize;
144                crc = table[0][table_index] ^ (crc >> 8);
145                i += 1;
146            }
147        } else {
148            while i < len {
149                let table_index = (((crc >> 8) ^ bytes[i] as u16) & 0xFF) as usize;
150                crc = table[0][table_index] ^ (crc << 8);
151                i += 1;
152            }
153        }
154    } else {
155        // This section is for NoTable case (L=0)
156        let poly = if reflect {
157            let poly = algorithm.poly.reverse_bits();
158            poly >> (16u8 - algorithm.width)
159        } else {
160            algorithm.poly << (16u8 - algorithm.width)
161        };
162
163        if reflect {
164            while i < len {
165                let to_crc = (crc ^ bytes[i] as u16) & 0xFF;
166                crc = crc16(poly, reflect, to_crc) ^ (crc >> 8);
167                i += 1;
168            }
169        } else {
170            while i < len {
171                let to_crc = ((crc >> 8) ^ bytes[i] as u16) & 0xFF;
172                crc = crc16(poly, reflect, to_crc) ^ (crc << 8);
173                i += 1;
174            }
175        }
176    }
177
178    crc
179}
180
181#[cfg(test)]
182mod test {
183    use crate::*;
184    use crc_catalog::{Algorithm, CRC_16_IBM_SDLC};
185
186    /// Test this optimized version against the well known implementation to ensure correctness
187    #[test]
188    fn correctness() {
189        let data: &[&str] = &[
190            "",
191            "1",
192            "1234",
193            "123456789",
194            "0123456789ABCDE",
195            "01234567890ABCDEFGHIJK",
196            "01234567890ABCDEFGHIJK01234567890ABCDEFGHIJK01234567890ABCDEFGHIJK01234567890ABCDEFGHIJK01234567890ABCDEFGHIJK01234567890ABCDEFGHIJK01234567890ABCDEFGHIJK01234567890ABCDEFGHIJK01234567890ABCDEFGHIJK01234567890ABCDEFGHIJK01234567890ABCDEFGHIJK01234567890ABCDEFGHIJK",
197        ];
198
199        pub const CRC_16_IBM_SDLC_NONREFLEX: Algorithm<u16> = Algorithm {
200            width: 16,
201            poly: 0x1021,
202            init: 0xffff,
203            refin: false,
204            refout: true,
205            xorout: 0xffff,
206            check: 0x906e,
207            residue: 0xf0b8,
208        };
209
210        let algs_to_test = [&CRC_16_IBM_SDLC, &CRC_16_IBM_SDLC_NONREFLEX];
211
212        for alg in algs_to_test {
213            for data in data {
214                let crc_slice16 = Crc::<u16, Table<16>>::new(alg);
215                let crc_nolookup = Crc::<u16, NoTable>::new(alg);
216                let expected = Crc::<u16, Table<1>>::new(alg).checksum(data.as_bytes());
217
218                // Check that doing all at once works as expected
219                assert_eq!(crc_slice16.checksum(data.as_bytes()), expected);
220                assert_eq!(crc_nolookup.checksum(data.as_bytes()), expected);
221
222                let mut digest = crc_slice16.digest();
223                digest.update(data.as_bytes());
224                assert_eq!(digest.finalize(), expected);
225
226                let mut digest = crc_nolookup.digest();
227                digest.update(data.as_bytes());
228                assert_eq!(digest.finalize(), expected);
229
230                // Check that we didn't break updating from multiple sources
231                if data.len() > 2 {
232                    let data = data.as_bytes();
233                    let data1 = &data[..data.len() / 2];
234                    let data2 = &data[data.len() / 2..];
235                    let mut digest = crc_slice16.digest();
236                    digest.update(data1);
237                    digest.update(data2);
238                    assert_eq!(digest.finalize(), expected);
239                    let mut digest = crc_nolookup.digest();
240                    digest.update(data1);
241                    digest.update(data2);
242                    assert_eq!(digest.finalize(), expected);
243                }
244            }
245        }
246    }
247}