#include "CyclicRedundancyChecker.h"

void CyclicRedundancyChecker::createTable()
{
    unsigned long c{0};
    for (int n = 0; n < 256; n++)
    {
        c = (unsigned long) n;
        for (int k = 0; k < 8; k++)
        {
            if (c & 1)
            {
                c = 0xedb88320L ^ (c >> 1);
            }
            else
            {
                c = c >> 1;
            }
        }
        mTable[n] = c;
    }
    mTableComputed = true;
}

void CyclicRedundancyChecker::addValue(unsigned char val)
{
    if (!mTableComputed)
    {
        createTable();
    }
    mLastValue = mTable[(mLastValue ^ val) & 0xff] ^ (mLastValue >> 8);
}

uint32_t CyclicRedundancyChecker::getChecksum() const
{
    return mLastValue ^ 0xffffffffL;
}

void CyclicRedundancyChecker::reset()
{
    mLastValue = 0xffffffffL;
}
