blob: 1c45dfeb9a9823e81f31fda4d26f59a30d3484e2 [file] [log] [blame]
Samuel Huang06f1ae92018-03-13 18:19:34 +00001// 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 Wennborg5a340be2020-04-28 11:06:24 +00009#include "base/check_op.h"
Samuel Huang06f1ae92018-03-13 18:19:34 +000010
11namespace zucchini {
12
13namespace {
14
15std::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.
32uint32_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