xz_crc32.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. * CRC32 using the polynomial from IEEE-802.3
  3. *
  4. * Authors: Lasse Collin <lasse.collin@tukaani.org>
  5. * Igor Pavlov <http://7-zip.org/>
  6. *
  7. * This file has been put into the public domain.
  8. * You can do whatever you want with this file.
  9. */
  10. /*
  11. * This is not the fastest implementation, but it is pretty compact.
  12. * The fastest versions of xz_crc32() on modern CPUs without hardware
  13. * accelerated CRC instruction are 3-5 times as fast as this version,
  14. * but they are bigger and use more memory for the lookup table.
  15. */
  16. #include "xz_private.h"
  17. /*
  18. * STATIC_RW_DATA is used in the pre-boot environment on some architectures.
  19. * See <linux/decompress/mm.h> for details.
  20. */
  21. #ifndef STATIC_RW_DATA
  22. # define STATIC_RW_DATA static
  23. #endif
  24. STATIC_RW_DATA uint32_t xz_crc32_table[256];
  25. XZ_EXTERN void xz_crc32_init(void)
  26. {
  27. const uint32_t poly = CRC32_POLY_LE;
  28. uint32_t i;
  29. uint32_t j;
  30. uint32_t r;
  31. for (i = 0; i < 256; ++i) {
  32. r = i;
  33. for (j = 0; j < 8; ++j)
  34. r = (r >> 1) ^ (poly & ~((r & 1) - 1));
  35. xz_crc32_table[i] = r;
  36. }
  37. return;
  38. }
  39. XZ_EXTERN uint32_t xz_crc32(const uint8_t *buf, size_t size, uint32_t crc)
  40. {
  41. crc = ~crc;
  42. while (size != 0) {
  43. crc = xz_crc32_table[*buf++ ^ (crc & 0xFF)] ^ (crc >> 8);
  44. --size;
  45. }
  46. return ~crc;
  47. }