Skip to content

Commit

Permalink
refactor checksum code
Browse files Browse the repository at this point in the history
  • Loading branch information
dmitrystu committed Feb 1, 2020
1 parent dfed5d3 commit 30f74db
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 19 deletions.
6 changes: 2 additions & 4 deletions inc/checksum.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,9 @@
extern "C" {
#endif

#include "config.h"

const char *checksum_name;
size_t append_checksum(void *data, uint32_t len);
size_t validate_checksum(const void *data, uint32_t len);
size_t append_checksum(void *data, size_t len);
size_t validate_checksum(const void *data, size_t len);

#if defined(__cplusplus)
}
Expand Down
33 changes: 18 additions & 15 deletions src/checksum.c
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ static checksum_t table[0x100];

static void init_checksum(checksum_t *checksum) {
for (int j = 0; j < 256; j++) {
uint64_t cs = j;
checksum_t cs = j;
for (int i = 0; i < 8; i++) {
if (cs & 0x01) {
cs = (cs >> 1) ^ CRC_POLY;
Expand Down Expand Up @@ -116,7 +116,17 @@ static void update_checksum(checksum_t *cs, uint8_t data) { }
static void init_checksum(checksum_t *cs) { *cs = 0; }
#endif

size_t append_checksum(void *data, uint32_t len) {
static int __memcmp(const void *a, const void *b, size_t len) {
while(len--) {
int res = *(const int8_t*)a++ - *(const int8_t*)b++;
if (res != 0) {
return res;
}
}
return 0;
}

size_t append_checksum(void *data, size_t len) {
checksum_t cs;
uint8_t *buf = data;
init_checksum(&cs);
Expand All @@ -128,22 +138,15 @@ size_t append_checksum(void *data, uint32_t len) {
return sizeof(checksum_t);
}

size_t validate_checksum(const void *data, uint32_t len) {
checksum_t cs, tcs;
size_t validate_checksum(const void *data, size_t len) {
checksum_t cs;
const uint8_t *buf = data;
init_checksum(&cs);
memcpy(&tcs, buf, sizeof(checksum_t));
while(1) {
if (cs == tcs) return (size_t)(buf - (uint8_t *)data);
if (sizeof(checksum_t) >= len--) break;
update_checksum(&cs, (uint8_t)(tcs & 0xFF));
tcs = (tcs & ~0xFF) | buf[sizeof(checksum_t)];
tcs = (tcs >> 8) | (tcs << (8 * sizeof(checksum_t) - 8));
while (sizeof(checksum_t) < len--) {
if (__memcmp(&cs, buf, sizeof(checksum_t)) == 0) {
return (size_t)(buf - (uint8_t *)data);
}
buf++;
// if (!memcmp((void*)buf, &cs, sizeof(checksum_t))) {
// return (size_t)(buf - (uint8_t *)data);
// }
// update_checksum(&cs, *buf++);
}
return 0;
}
Expand Down

0 comments on commit 30f74db

Please sign in to comment.