blob: ecc5acefb1bdd72b151adc40c78b435e663eed8e [file] [log] [blame]
Jonny Svärd5adf5a62022-02-09 16:42:10 +01001/*
2 * Copyright (c) 2022 Arm Limited. All rights reserved.
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 *
6 * Licensed under the Apache License, Version 2.0 (the License); you may
7 * not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an AS IS BASIS, WITHOUT
14 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19#include <cstddef>
20#include <inttypes.h>
21
22namespace {
23
24class Crc {
25public:
26 constexpr Crc() : table() {
27 uint32_t poly = 0xedb88320;
28
29 for (uint32_t i = 0; i < 256; i++) {
30 uint32_t crc = i;
31
32 for (int j = 0; j < 8; j++) {
33 if (crc & 1) {
34 crc = poly ^ (crc >> 1);
35 } else {
36 crc >>= 1;
37 }
38 }
39
40 table[i] = crc;
41 }
42 }
43
44 uint32_t crc32(const void *data, const size_t length, uint32_t init = 0) const {
45 uint32_t crc = init ^ 0xffffffff;
46
47 const uint8_t *v = static_cast<const uint8_t *>(data);
48
49 for (size_t i = 0; i < length; i++) {
50 crc = table[(crc ^ v[i]) & 0xff] ^ (crc >> 8);
51 }
52
53 return crc ^ 0xffffffff;
54 }
55
56private:
57 uint32_t table[256];
58};
59} // namespace