mirror of
https://github.com/depp/syncfiles.git
synced 2024-11-28 12:51:05 +00:00
Add CRC-32 function
This commit is contained in:
parent
2f644a8674
commit
75f1908690
@ -4,10 +4,12 @@ load("//bazel:copts.bzl", "COPTS")
|
||||
cc_library(
|
||||
name = "lib",
|
||||
srcs = [
|
||||
"crc32.c",
|
||||
"toolbox.c",
|
||||
"util.c",
|
||||
],
|
||||
hdrs = [
|
||||
"crc32.h",
|
||||
"defs.h",
|
||||
"endian.h",
|
||||
"util.h",
|
||||
@ -44,3 +46,15 @@ cc_test(
|
||||
":test",
|
||||
],
|
||||
)
|
||||
|
||||
cc_test(
|
||||
name = "crc32_test",
|
||||
size = "small",
|
||||
srcs = [
|
||||
"crc32_test.c",
|
||||
],
|
||||
copts = COPTS,
|
||||
deps = [
|
||||
":lib",
|
||||
],
|
||||
)
|
||||
|
40
lib/crc32.c
Normal file
40
lib/crc32.c
Normal 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
9
lib/crc32.h
Normal 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
22
lib/crc32_test.c
Normal 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;
|
||||
}
|
Loading…
Reference in New Issue
Block a user