crc32.cc 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // Copyright 2017 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "components/zucchini/crc32.h"
  5. #include <array>
  6. #include "base/check_op.h"
  7. namespace zucchini {
  8. namespace {
  9. std::array<uint32_t, 256> MakeCrc32Table() {
  10. constexpr uint32_t kCrc32Poly = 0xEDB88320;
  11. std::array<uint32_t, 256> crc32Table;
  12. for (uint32_t i = 0; i < 256; ++i) {
  13. uint32_t r = i;
  14. for (int j = 0; j < 8; ++j)
  15. r = (r >> 1) ^ (kCrc32Poly & ~((r & 1) - 1));
  16. crc32Table[i] = r;
  17. }
  18. return crc32Table;
  19. }
  20. } // namespace
  21. // Minimalistic CRC-32 implementation for Zucchini usage. Adapted from LZMA SDK
  22. // (found at third_party/lzma_sdk/C/7zCrc.c), which is public domain.
  23. uint32_t CalculateCrc32(const uint8_t* first, const uint8_t* last) {
  24. DCHECK_GE(last, first);
  25. static const std::array<uint32_t, 256> kCrc32Table = MakeCrc32Table();
  26. uint32_t ret = 0xFFFFFFFF;
  27. for (; first != last; ++first)
  28. ret = kCrc32Table[(ret ^ *first) & 0xFF] ^ (ret >> 8);
  29. return ret ^ 0xFFFFFFFF;
  30. }
  31. } // namespace zucchini