Add CRC-32 function

This commit is contained in:
Dietrich Epp 2022-04-10 03:37:14 -04:00
parent 2f644a8674
commit 75f1908690
4 changed files with 85 additions and 0 deletions

View File

@ -4,10 +4,12 @@ load("//bazel:copts.bzl", "COPTS")
cc_library( cc_library(
name = "lib", name = "lib",
srcs = [ srcs = [
"crc32.c",
"toolbox.c", "toolbox.c",
"util.c", "util.c",
], ],
hdrs = [ hdrs = [
"crc32.h",
"defs.h", "defs.h",
"endian.h", "endian.h",
"util.h", "util.h",
@ -44,3 +46,15 @@ cc_test(
":test", ":test",
], ],
) )
cc_test(
name = "crc32_test",
size = "small",
srcs = [
"crc32_test.c",
],
copts = COPTS,
deps = [
":lib",
],
)

40
lib/crc32.c Normal file
View File

@ -0,0 +1,40 @@
#include "lib/crc32.h"
static int gCRCInitted;
static UInt32 gCRCTable[256];
static void CRC32Init(void)
{
int i, j;
UInt32 v, u;
for (i = 0; i < 256; i++) {
v = i;
for (j = 0; j < 8; j++) {
u = v;
v >>= 1;
if (u & 1) {
v ^= 0xedb88320;
}
}
gCRCTable[i] = v;
}
gCRCInitted = 1;
}
UInt32 CRC32Update(UInt32 crc, const void *ptr, Size size)
{
const UInt8 *p, *e;
if (!gCRCInitted) {
CRC32Init();
}
crc = ~crc;
p = ptr;
e = p + size;
while (p < e) {
crc = (crc >> 8) ^ gCRCTable[(crc & 0xff) ^ *p++];
}
return ~crc;
}

9
lib/crc32.h Normal file
View File

@ -0,0 +1,9 @@
#ifndef CRC32_H
#define CRC32_H
#include "lib/defs.h"
/* Incrementally calculate a CRC32. This is the same CRC32 used by Gzip. */
UInt32 CRC32Update(UInt32 crc, const void *ptr, Size size);
#endif

22
lib/crc32_test.c Normal file
View File

@ -0,0 +1,22 @@
#include "lib/crc32.h"
#include <stdio.h>
static const char kTest[9] = {'1', '2', '3', '4', '5', '6', '7', '8', '9'};
int main(int argc, char **argv)
{
UInt32 expect;
UInt32 val;
(void)argc;
(void)argv;
expect = 0xcbf43926;
val = CRC32Update(0, kTest, sizeof(kTest));
if (val != expect) {
fprintf(stderr, "Error: CRC = 0x%08x, expect 0x%08x\n", val, expect);
return 1;
}
return 0;
}