| 1 | /// The polynomial used for the crc32 lookup table. |
| 2 | /// |
| 3 | /// See also https://en.wikipedia.org/wiki/Cyclic_redundancy_check#Polynomial_representations |
| 4 | const POLYNOMIAL: u32 = 0x04C11DB7; |
| 5 | |
| 6 | /// Most implementations (ethernet, zlib) use the reflected version of this polynomial. |
| 7 | const _: () = assert!(POLYNOMIAL.reverse_bits() == 0xEDB88320); |
| 8 | |
| 9 | /// Lookup table to speed up crc32 checksum calculation. |
| 10 | /// |
| 11 | /// The original C implementation notes: |
| 12 | /// |
| 13 | /// > I think this is an implementation of the AUTODIN-II, |
| 14 | /// > Ethernet & FDDI 32-bit CRC standard. Vaguely derived |
| 15 | /// > from code by Rob Warnock, in Section 51 of the |
| 16 | /// > comp.compression FAQ. |
| 17 | pub(crate) static BZ2_CRC32TABLE: [u32; 256] = generate_crc32_table(POLYNOMIAL); |
| 18 | |
| 19 | /// Generate the crc32 lookup table. |
| 20 | /// |
| 21 | /// Note that contrary to most material you'll find on the internet, we're using the non-reflected |
| 22 | /// polynomial, which impacts some of the logic (e.g. we bitwise and with 0x80000000 instead of 0x1). |
| 23 | /// |
| 24 | /// This [article] has some excellent additional detail on how crc works, and how to make it fast. |
| 25 | /// |
| 26 | /// [article]: https://create.stephan-brumme.com/crc32/ |
| 27 | const fn generate_crc32_table(polynomial: u32) -> [u32; 256] { |
| 28 | let mut table = [0u32; 256]; |
| 29 | |
| 30 | let mut i = 0; |
| 31 | while i < 256 { |
| 32 | let mut crc = (i as u32) << 24; |
| 33 | |
| 34 | let mut j = 0; |
| 35 | while j < 8 { |
| 36 | if (crc & 0x80000000) != 0 { |
| 37 | crc = (crc << 1) ^ polynomial; |
| 38 | } else { |
| 39 | crc <<= 1; |
| 40 | } |
| 41 | |
| 42 | j += 1; |
| 43 | } |
| 44 | |
| 45 | table[i] = crc; |
| 46 | |
| 47 | i += 1; |
| 48 | } |
| 49 | |
| 50 | table |
| 51 | } |