crc32hash.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // This file is part of Desktop App Toolkit,
  2. // a set of libraries for developing nice desktop applications.
  3. //
  4. // For license and copyright information please follow this link:
  5. // https://github.com/desktop-app/legal/blob/master/LEGAL
  6. //
  7. #include "base/crc32hash.h"
  8. namespace base {
  9. namespace {
  10. class Crc32Table {
  11. public:
  12. Crc32Table() {
  13. auto poly = std::uint32_t(0x04c11db7);
  14. for (auto i = 0; i != 256; ++i) {
  15. _data[i] = reflect(i, 8) << 24;
  16. for (auto j = 0; j != 8; ++j) {
  17. _data[i] = (_data[i] << 1) ^ (_data[i] & (1 << 31) ? poly : 0);
  18. }
  19. _data[i] = reflect(_data[i], 32);
  20. }
  21. }
  22. std::uint32_t operator[](int index) const {
  23. return _data[index];
  24. }
  25. private:
  26. std::uint32_t reflect(std::uint32_t val, char ch) {
  27. auto result = std::uint32_t(0);
  28. for (int i = 1; i < (ch + 1); ++i) {
  29. if (val & 1) {
  30. result |= 1 << (ch - i);
  31. }
  32. val >>= 1;
  33. }
  34. return result;
  35. }
  36. std::uint32_t _data[256];
  37. };
  38. } // namespace
  39. std::int32_t crc32(const void *data, int len) {
  40. static const auto kTable = Crc32Table();
  41. const auto buffer = static_cast<const std::uint8_t*>(data);
  42. auto crc = std::uint32_t(0xffffffff);
  43. for (auto i = 0; i != len; ++i) {
  44. crc = (crc >> 8) ^ kTable[(crc & 0xFF) ^ buffer[i]];
  45. }
  46. return static_cast<std::int32_t>(crc ^ 0xffffffff);
  47. }
  48. } // namespace base