#include <string.h>
#include <limits.h>
#include "crcmodel.h"
#if defined(_LITTLE_ENDIAN)
#define sws(x) (((x >> 8) & 0x00ff) | ((x << 8) & 0xff00))
#define swl(x) (sws(x >> 16) | (sws(x) << 16))
#define swap_short(x) (x = sws(x))
#define swap_long(x) (x = swl(x))
#else
#define sws(x) (x)
#define swl(x) (x)
#define swap_short(x) (x = sws(x))
#define swap_long(x) (x = swl(x))
#endif
unsigned char
compute_crc8(unsigned char *bytes, int length)
{
cm_t crc_mdl;
p_cm_t p_crc;
int i;
unsigned char aCRC;
p_crc = &crc_mdl;
p_crc->cm_width = 8;
p_crc->cm_poly = 0x107;
p_crc->cm_init = 0;
p_crc->cm_refin = TRUE;
p_crc->cm_refot = TRUE;
p_crc->cm_xorot = 0;
cm_ini(p_crc);
for (i = 0; i < length; i++) {
cm_nxt(p_crc, bytes[i]);
}
aCRC = (unsigned char)cm_crc(p_crc);
return (aCRC);
}
uint32_t
compute_crc32(unsigned char *bytes, int length)
{
cm_t crc_mdl;
p_cm_t p_crc;
int i;
uint32_t aCRC;
p_crc = &crc_mdl;
p_crc->cm_width = 32;
p_crc->cm_poly = 0x04c11db7;
p_crc->cm_init = 0xffffffff;
p_crc->cm_refin = TRUE;
p_crc->cm_refot = TRUE;
p_crc->cm_xorot = 0xffffffff;
cm_ini(p_crc);
for (i = 0; i < length; i++) {
cm_nxt(p_crc, bytes[i]);
}
aCRC = (uint32_t)cm_crc(p_crc);
return (aCRC);
}
#define UINT32_T_MAX 0xFFFFFFFF
uint32_t
compute_checksum32(unsigned char *bytes, int length)
{
uint32_t regval = 0;
int i, j, k;
uint32_t next4bytes;
unsigned char tailbytes[4] = { 0x00, 0x00, 0x00, 0x00 };
for (i = 0; i < length-4; i += 4) {
(void) memcpy(&next4bytes, &(bytes[i]), 4);
swap_long(next4bytes);
if (next4bytes > UINT32_T_MAX - regval) {
next4bytes -= UINT32_T_MAX - regval;
regval = 0;
}
regval += next4bytes;
}
for (j = length-1, k = 3; j >= i; j--, k--) {
tailbytes[k] = bytes[j];
}
(void) memcpy(&next4bytes, tailbytes, 4);
swap_long(next4bytes);
if (next4bytes > UINT32_T_MAX - regval) {
next4bytes -= UINT32_T_MAX - regval;
regval = 0;
}
regval += next4bytes;
return ((uint32_t)regval);
}