1 /*
2 * Copyright (C) 2021 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "chpp/crc.h"
18
19 #include <stddef.h>
20 #include <stdint.h>
21
chppCrc32(uint32_t crc,const uint8_t * buf,size_t len)22 uint32_t chppCrc32(uint32_t crc, const uint8_t *buf, size_t len) {
23 // This lookup table (LUT) consumes 16 * 4 = 64 bytes. Other implementations
24 // exist with a larger LUT, with a LUT calculated on the fly, or without using
25 // a LUT altogether.
26 static const uint32_t crc32LookupTable[] = {
27 0x00000000, 0x1DB71064, 0x3B6E20C8, 0x26D930AC, 0x76DC4190, 0x6B6B51F4,
28 0x4DB26158, 0x5005713C, 0xEDB88320, 0xF00F9344, 0xD6D6A3E8, 0xCB61B38C,
29 0x9B64C2B0, 0x86D3D2D4, 0xA00AE278, 0xBDBDF21C};
30
31 crc = ~crc;
32 for (size_t i = 0; i < len; i++) {
33 crc = crc32LookupTable[(crc ^ buf[i]) & 0x0F] ^ (crc >> 4);
34 crc = crc32LookupTable[(crc ^ (buf[i] >> 4)) & 0x0F] ^ (crc >> 4);
35 }
36 crc = ~crc;
37
38 return crc;
39 }
40