]> git.bts.cx Git - sun.git/blob - runtime/src/sun/tree/crc32.h
Initial commit
[sun.git] / runtime / src / sun / tree / crc32.h
1 #ifndef SUN_TREE_CRC32_H
2 #define SUN_TREE_CRC32_H
3
4 #include <stdint.h>
5
6 #ifdef __cplusplus
7 extern "C" {
8 #endif
9
10 // Taken from here: https://web.archive.org/web/20190108202303/http://www.hackersdelight.org/hdcodetxt/crc.c.txt
11 // Licence: https://web.archive.org/web/20190716204559/http://www.hackersdelight.org/permissions.htm
12 // See also: https://stackoverflow.com/a/21001712
13 // FIXME: Look into https://gist.github.com/badboy/6267743
14
15 uint32_t crc32c(char *message) {
16 int i, j;
17 uint32_t byte, crc, mask;
18 static uint32_t table[256];
19
20 /* Set up the table, if necessary. */
21
22 if (table[1] == 0) {
23 for (byte = 0; byte <= 255; byte++) {
24 crc = byte;
25 for (j = 7; j >= 0; j--) { // Do eight times.
26 mask = -(crc & 1);
27 crc = (crc >> 1) ^ (0xEDB88320 & mask);
28 }
29 table[byte] = crc;
30 }
31 }
32
33 /* Through with table setup, now calculate the CRC. */
34
35 i = 0;
36 crc = 0xFFFFFFFF;
37 while ((byte = message[i]) != 0) {
38 crc = (crc >> 8) ^ table[(crc ^ byte) & 0xFF];
39 i = i + 1;
40 }
41 return ~crc;
42 }
43
44 #ifdef __cplusplus
45 }
46 #endif
47
48 #endif