|
| 1 | +#include "crc_macros.h" |
1 | 2 | #include <stdint.h> |
2 | | -#include <stdlib.h> |
3 | 3 |
|
4 | 4 | #define GENPOLY 4129 |
5 | 5 |
|
6 | 6 | static uint16_t CRCTable[256]; |
7 | 7 |
|
8 | | -static void crc_init(void) { |
9 | | - uint16_t crc = 0x8000; |
10 | | - for (unsigned int i = 1; i < 256; i <<= 1) { |
11 | | - crc = (crc << 1) ^ (crc & 0x8000 ? GENPOLY : 0); |
12 | | - for (unsigned int j = 0; j < i; j++) |
13 | | - CRCTable[i + j] = crc ^ CRCTable[j]; |
14 | | - } |
15 | | -} |
| 8 | +static void crc_init(void) { CRCINIT_BE(uint16_t, CRCTable, GENPOLY); } |
16 | 9 |
|
17 | 10 | // This table-lookup should be equivalent to the code emitted when optimizing |
18 | 11 | // CRC with HashRecognize. This function itself will be untouched by |
19 | 12 | // HashRecognize. |
20 | 13 | static uint16_t crc_table(uint16_t crc_initval, uint16_t data) { |
21 | 14 | uint16_t crc = crc_initval; |
22 | | - |
23 | | - if (CRCTable[255] == 0) |
24 | | - crc_init(); |
25 | | - |
26 | | - for (size_t i = 0; i < 2; ++i) { |
27 | | - uint8_t pos = (crc ^ (data << (i << 3))) >> 8; |
28 | | - crc = (crc << 8) ^ CRCTable[pos]; |
29 | | - } |
30 | | - |
| 15 | + CRCTABLE_BE(uint16_t, CRCTable, crc_init, crc, data); |
31 | 16 | return crc; |
32 | 17 | } |
33 | 18 |
|
34 | 19 | static uint16_t crc_loop(uint16_t crc_initval, uint16_t data) { |
35 | 20 | uint16_t crc = crc_initval; |
36 | 21 |
|
37 | 22 | // This loop will be optimized by HashRecognize. |
38 | | - for (size_t i = 0; i < 16; ++i) { |
39 | | - uint16_t xor_crc_data = crc ^ data; |
40 | | - uint16_t crc_shl = crc << 1; |
41 | | - crc = (xor_crc_data & 0x8000) ? (crc_shl ^ GENPOLY) : crc_shl; |
42 | | - data <<= 1; |
43 | | - } |
| 23 | + CRCLOOP_BE(uint16_t, GENPOLY, crc, data); |
44 | 24 | return crc; |
45 | 25 | } |
46 | 26 |
|
47 | 27 | int main() { |
48 | | - // These are random hand-picked values. |
49 | | - static const uint16_t crc_initval[8] = {0, 129, 11, 255, 16, 4129, 16384, 1}; |
50 | | - static const uint16_t data[8] = {0, 1, 11, 16, 129, 255, 4129, 16384}; |
51 | | - for (size_t i = 0; i < 8; ++i) { |
52 | | - uint16_t actual = crc_loop(crc_initval[i], data[i]); |
53 | | - uint16_t expected = crc_table(crc_initval[i], data[i]); |
54 | | - if (actual != expected) |
55 | | - return 1; |
56 | | - } |
57 | | - return 0; |
| 28 | + int res = 0; |
| 29 | + VERIFY_RESULT(crc_table, crc_loop, res); |
| 30 | + return res; |
58 | 31 | } |
0 commit comments