File Coverage

crc32.c
Criterion Covered Total %
statement 26 26 100.0
branch 8 8 100.0
condition n/a
subroutine n/a
pod n/a
total 34 34 100.0


line stmt bran cond sub pod time code
1             /*
2             * crc32.c - IEEE 802.3 reflected CRC-32 implementation.
3             *
4             * Table-driven, computed lazily on first use. Table holds 256 entries
5             * = 1 KiB of static data. Polynomial 0xEDB88320.
6             */
7              
8             #include "crc32.h"
9              
10             static uint32_t crc32_table[256];
11             static int crc32_table_built = 0;
12              
13             static void
14 5           crc32_build_table(void)
15             {
16             uint32_t c;
17             int i, j;
18 1285 100         for (i = 0; i < 256; i++) {
19 1280           c = (uint32_t)i;
20 11520 100         for (j = 0; j < 8; j++) {
21 10240           c = (c & 1u) ? (0xEDB88320u ^ (c >> 1)) : (c >> 1);
22             }
23 1280           crc32_table[i] = c;
24             }
25 5           crc32_table_built = 1;
26 5           }
27              
28             void
29 10           crc32_init(crc32_ctx_t *ctx)
30             {
31 10 100         if (!crc32_table_built) crc32_build_table();
32 10           ctx->state = 0xFFFFFFFFu;
33 10           }
34              
35             void
36 11           crc32_update(crc32_ctx_t *ctx, const void *data, size_t len)
37             {
38 11           const unsigned char *p = (const unsigned char *)data;
39 11           uint32_t c = ctx->state;
40             size_t i;
41 622913 100         for (i = 0; i < len; i++) {
42 622902           c = crc32_table[(c ^ p[i]) & 0xFFu] ^ (c >> 8);
43             }
44 11           ctx->state = c;
45 11           }
46              
47             void
48 10           crc32_final(crc32_ctx_t *ctx, unsigned char out[CRC32_DIGEST_SIZE])
49             {
50 10           uint32_t c = ctx->state ^ 0xFFFFFFFFu;
51             /* Big-endian output: matches the conventional "0xCBF43926" reading
52             * for the "123456789" test vector. */
53 10           out[0] = (unsigned char)((c >> 24) & 0xFFu);
54 10           out[1] = (unsigned char)((c >> 16) & 0xFFu);
55 10           out[2] = (unsigned char)((c >> 8) & 0xFFu);
56 10           out[3] = (unsigned char)( c & 0xFFu);
57 10           }