Samuel Huang | 06f1ae9 | 2018-03-13 18:19:34 +0000 | [diff] [blame] | 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 | |
| 5 | #include "components/zucchini/crc32.h" |
| 6 | |
| 7 | #include <array> |
| 8 | |
Hans Wennborg | 5a340be | 2020-04-28 11:06:24 +0000 | [diff] [blame] | 9 | #include "base/check_op.h" |
Samuel Huang | 06f1ae9 | 2018-03-13 18:19:34 +0000 | [diff] [blame] | 10 | |
| 11 | namespace zucchini { |
| 12 | |
| 13 | namespace { |
| 14 | |
| 15 | std::array<uint32_t, 256> MakeCrc32Table() { |
| 16 | constexpr uint32_t kCrc32Poly = 0xEDB88320; |
| 17 | |
| 18 | std::array<uint32_t, 256> crc32Table; |
| 19 | for (uint32_t i = 0; i < 256; ++i) { |
| 20 | uint32_t r = i; |
| 21 | for (int j = 0; j < 8; ++j) |
| 22 | r = (r >> 1) ^ (kCrc32Poly & ~((r & 1) - 1)); |
| 23 | crc32Table[i] = r; |
| 24 | } |
| 25 | return crc32Table; |
| 26 | } |
| 27 | |
| 28 | } // namespace |
| 29 | |
| 30 | // Minimalistic CRC-32 implementation for Zucchini usage. Adapted from LZMA SDK |
| 31 | // (found at third_party/lzma_sdk/7zCrc.c), which is public domain. |
| 32 | uint32_t CalculateCrc32(const uint8_t* first, const uint8_t* last) { |
| 33 | DCHECK_GE(last, first); |
| 34 | |
| 35 | static const std::array<uint32_t, 256> kCrc32Table = MakeCrc32Table(); |
| 36 | |
| 37 | uint32_t ret = 0xFFFFFFFF; |
| 38 | for (; first != last; ++first) |
| 39 | ret = kCrc32Table[(ret ^ *first) & 0xFF] ^ (ret >> 8); |
| 40 | return ret ^ 0xFFFFFFFF; |
| 41 | } |
| 42 | |
| 43 | } // namespace zucchini |