crc/
crc32.rs

1use crate::table::crc32_table;
2use crate::util::crc32;
3use crate::*;
4use crc_catalog::Algorithm;
5
6impl<const L: usize> Crc<u32, Table<L>>
7where
8    Table<L>: private::Sealed,
9{
10    pub const fn new(algorithm: &'static Algorithm<u32>) -> Self {
11        Self {
12            algorithm,
13            data: crc32_table(algorithm.width, algorithm.poly, algorithm.refin),
14        }
15    }
16
17    pub const fn checksum(&self, bytes: &[u8]) -> u32 {
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: u32, bytes: &[u8]) -> u32 {
24        update_table(crc, self.algorithm, &self.data, bytes)
25    }
26
27    pub const fn digest(&self) -> Digest<u32, 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: u32) -> Digest<u32, 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<u32> {
42        &self.data
43    }
44}
45
46impl<'a, const L: usize> Digest<'a, u32, Table<L>>
47where
48    Table<L>: private::Sealed,
49{
50    const fn new(crc: &'a Crc<u32, Table<L>>, value: u32) -> 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) -> u32 {
59        finalize(self.crc.algorithm, self.value)
60    }
61}
62
63const fn init(algorithm: &Algorithm<u32>, initial: u32) -> u32 {
64    if algorithm.refin {
65        initial.reverse_bits() >> (32u8 - algorithm.width)
66    } else {
67        initial << (32u8 - algorithm.width)
68    }
69}
70
71const fn finalize(algorithm: &Algorithm<u32>, mut crc: u32) -> u32 {
72    if algorithm.refin ^ algorithm.refout {
73        crc = crc.reverse_bits();
74    }
75    if !algorithm.refout {
76        crc >>= 32u8 - algorithm.width;
77    }
78    crc ^ algorithm.xorout
79}
80
81const fn update_table<const L: usize>(
82    mut crc: u32,
83    algorithm: &Algorithm<u32>,
84    table: &[[u32; 256]; L],
85    bytes: &[u8],
86) -> u32 {
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                // XOR the first 4 bytes with the current CRC value
96                let mut current_slice = [0u8; 4];
97                current_slice[0] = bytes[i] ^ (crc as u8);
98                current_slice[1] = bytes[i + 1] ^ ((crc >> 8) as u8);
99                current_slice[2] = bytes[i + 2] ^ ((crc >> 16) as u8);
100                current_slice[3] = bytes[i + 3] ^ ((crc >> 24) as u8);
101
102                crc = table[0][bytes[i + 15] as usize]
103                    ^ table[1][bytes[i + 14] as usize]
104                    ^ table[2][bytes[i + 13] as usize]
105                    ^ table[3][bytes[i + 12] as usize]
106                    ^ table[4][bytes[i + 11] as usize]
107                    ^ table[5][bytes[i + 10] as usize]
108                    ^ table[6][bytes[i + 9] as usize]
109                    ^ table[7][bytes[i + 8] as usize]
110                    ^ table[8][bytes[i + 7] as usize]
111                    ^ table[9][bytes[i + 6] as usize]
112                    ^ table[10][bytes[i + 5] as usize]
113                    ^ table[11][bytes[i + 4] as usize]
114                    ^ table[12][current_slice[3] as usize]
115                    ^ table[13][current_slice[2] as usize]
116                    ^ table[14][current_slice[1] as usize]
117                    ^ table[15][current_slice[0] as usize];
118            } else {
119                // For non-reflected CRC32
120                let mut current_slice = [0u8; 4];
121                current_slice[0] = bytes[i] ^ ((crc >> 24) as u8);
122                current_slice[1] = bytes[i + 1] ^ ((crc >> 16) as u8);
123                current_slice[2] = bytes[i + 2] ^ ((crc >> 8) as u8);
124                current_slice[3] = bytes[i + 3] ^ (crc as u8);
125
126                crc = table[0][bytes[i + 15] as usize]
127                    ^ table[1][bytes[i + 14] as usize]
128                    ^ table[2][bytes[i + 13] as usize]
129                    ^ table[3][bytes[i + 12] as usize]
130                    ^ table[4][bytes[i + 11] as usize]
131                    ^ table[5][bytes[i + 10] as usize]
132                    ^ table[6][bytes[i + 9] as usize]
133                    ^ table[7][bytes[i + 8] as usize]
134                    ^ table[8][bytes[i + 7] as usize]
135                    ^ table[9][bytes[i + 6] as usize]
136                    ^ table[10][bytes[i + 5] as usize]
137                    ^ table[11][bytes[i + 4] as usize]
138                    ^ table[12][current_slice[3] as usize]
139                    ^ table[13][current_slice[2] as usize]
140                    ^ table[14][current_slice[1] as usize]
141                    ^ table[15][current_slice[0] as usize];
142            }
143            i += 16;
144        }
145    }
146
147    // Process remaining bytes one at a time using the table (for L=1 and L=16)
148    if L > 0 {
149        if reflect {
150            while i < len {
151                let table_index = ((crc ^ bytes[i] as u32) & 0xFF) as usize;
152                crc = table[0][table_index] ^ (crc >> 8);
153                i += 1;
154            }
155        } else {
156            while i < len {
157                let table_index = (((crc >> 24) ^ bytes[i] as u32) & 0xFF) as usize;
158                crc = table[0][table_index] ^ (crc << 8);
159                i += 1;
160            }
161        }
162    } else {
163        // This section is for NoTable case (L=0)
164        let poly = if reflect {
165            let poly = algorithm.poly.reverse_bits();
166            poly >> (32u8 - algorithm.width)
167        } else {
168            algorithm.poly << (32u8 - algorithm.width)
169        };
170
171        if reflect {
172            while i < len {
173                let to_crc = (crc ^ bytes[i] as u32) & 0xFF;
174                crc = crc32(poly, reflect, to_crc) ^ (crc >> 8);
175                i += 1;
176            }
177        } else {
178            while i < len {
179                let to_crc = ((crc >> 24) ^ bytes[i] as u32) & 0xFF;
180                crc = crc32(poly, reflect, to_crc) ^ (crc << 8);
181                i += 1;
182            }
183        }
184    }
185
186    crc
187}
188
189#[cfg(test)]
190mod test {
191    use crate::*;
192    use crc_catalog::{Algorithm, CRC_32_ISCSI};
193
194    /// Test this optimized version against the well known implementation to ensure correctness
195    #[test]
196    fn correctness() {
197        let data: &[&str] = &[
198            "",
199            "1",
200            "1234",
201            "123456789",
202            "0123456789ABCDE",
203            "01234567890ABCDEFGHIJK",
204            "01234567890ABCDEFGHIJK01234567890ABCDEFGHIJK01234567890ABCDEFGHIJK01234567890ABCDEFGHIJK01234567890ABCDEFGHIJK01234567890ABCDEFGHIJK01234567890ABCDEFGHIJK01234567890ABCDEFGHIJK01234567890ABCDEFGHIJK01234567890ABCDEFGHIJK01234567890ABCDEFGHIJK01234567890ABCDEFGHIJK",
205        ];
206
207        pub const CRC_32_ISCSI_NONREFLEX: Algorithm<u32> = Algorithm {
208            width: 32,
209            poly: 0x1edc6f41,
210            init: 0xffffffff,
211            // This is the only flag that affects the optimized code path
212            refin: false,
213            refout: true,
214            xorout: 0xffffffff,
215            check: 0xe3069283,
216            residue: 0xb798b438,
217        };
218
219        let algs_to_test = [&CRC_32_ISCSI, &CRC_32_ISCSI_NONREFLEX];
220
221        for alg in algs_to_test {
222            for data in data {
223                let crc_slice16 = Crc::<u32, Table<16>>::new(alg);
224                let crc_nolookup = Crc::<u32, NoTable>::new(alg);
225                let expected = Crc::<u32, Table<1>>::new(alg).checksum(data.as_bytes());
226
227                // Check that doing all at once works as expected
228                assert_eq!(crc_slice16.checksum(data.as_bytes()), expected);
229                assert_eq!(crc_nolookup.checksum(data.as_bytes()), expected);
230
231                let mut digest = crc_slice16.digest();
232                digest.update(data.as_bytes());
233                assert_eq!(digest.finalize(), expected);
234
235                let mut digest = crc_nolookup.digest();
236                digest.update(data.as_bytes());
237                assert_eq!(digest.finalize(), expected);
238
239                // Check that we didn't break updating from multiple sources
240                if data.len() > 2 {
241                    let data = data.as_bytes();
242                    let data1 = &data[..data.len() / 2];
243                    let data2 = &data[data.len() / 2..];
244                    let mut digest = crc_slice16.digest();
245                    digest.update(data1);
246                    digest.update(data2);
247                    assert_eq!(digest.finalize(), expected);
248                    let mut digest = crc_nolookup.digest();
249                    digest.update(data1);
250                    digest.update(data2);
251                    assert_eq!(digest.finalize(), expected);
252                }
253            }
254        }
255    }
256}