| 1 |
#ifndef CRC16_HH |
| 2 |
#define CRC16_HH |
| 3 |
|
| 4 |
#include "narrow.hh" |
| 5 |
#include "xrange.hh" |
| 6 |
#include <array> |
| 7 |
#include <cstddef> |
| 8 |
#include <cstdint> |
| 9 |
#include <initializer_list> |
| 10 |
#include <span> |
| 11 |
|
| 12 |
namespace openmsx { |
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
class CRC16 |
| 19 |
{ |
| 20 |
public: |
| 21 |
|
| 22 |
|
| 23 |
explicit constexpr CRC16(uint16_t initialCRC = 0xffff) |
| 24 |
: crc(initialCRC) |
| 25 |
{ |
| 26 |
} |
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
constexpr void init(uint16_t initialCRC) |
| 31 |
{ |
| 32 |
crc = initialCRC; |
| 33 |
} |
| 34 |
|
| 35 |
constexpr void init(std::initializer_list<uint8_t> list) |
| 36 |
{ |
| 37 |
crc = 0xffff; |
| 38 |
for (const auto& val : list) { |
| 39 |
update(val); |
| 40 |
} |
| 41 |
} |
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
constexpr void update(uint8_t value) |
| 46 |
{ |
| 47 |
|
| 48 |
crc = uint16_t((crc << 8) ^ tab[0][(crc >> 8) ^ value]); |
| 49 |
} |
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
constexpr void update(std::span<const uint8_t> data) |
| 55 |
{ |
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
unsigned c = crc; |
| 67 |
|
| 68 |
|
| 69 |
while (data.size() >= 8) { |
| 70 |
c = tab[7][data[0] ^ (c >> 8)] ^ |
| 71 |
tab[6][data[1] ^ (c & 255)] ^ |
| 72 |
tab[5][data[2]] ^ |
| 73 |
tab[4][data[3]] ^ |
| 74 |
tab[3][data[4]] ^ |
| 75 |
tab[2][data[5]] ^ |
| 76 |
tab[1][data[6]] ^ |
| 77 |
tab[0][data[7]]; |
| 78 |
data = data.subspan(8); |
| 79 |
} |
| 80 |
|
| 81 |
for (auto d : data) { |
| 82 |
c = uint16_t(c << 8) ^ tab[0][(c >> 8) ^ d]; |
| 83 |
} |
| 84 |
crc = uint16_t(c); |
| 85 |
} |
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
[[nodiscard]] constexpr uint16_t getValue() const |
| 90 |
{ |
| 91 |
return crc; |
| 92 |
} |
| 93 |
|
| 94 |
private: |
| 95 |
static constexpr auto tab = [] { |
| 96 |
std::array<std::array<uint16_t, 0x100>, 8> result = {}; |
| 97 |
for (auto i : xrange(0x100)) { |
| 98 |
auto x = uint16_t(i << 8); |
| 99 |
repeat(8, [&] { |
| 100 |
x = narrow_cast<uint16_t>((x << 1) ^ ((x & 0x8000) ? 0x1021 : 0)); |
| 101 |
}); |
| 102 |
result[0][i] = x; |
| 103 |
} |
| 104 |
for (auto i : xrange(0x100)) { |
| 105 |
uint16_t c = result[0][i]; |
| 106 |
for (auto j : xrange(1, 8)) { |
| 107 |
c = narrow_cast<uint16_t>(result[0][c >> 8] ^ (c << 8)); |
| 108 |
result[j][i] = c; |
| 109 |
} |
| 110 |
} |
| 111 |
return result; |
| 112 |
}(); |
| 113 |
|
| 114 |
uint16_t crc; |
| 115 |
}; |
| 116 |
|
| 117 |
} |
| 118 |
|
| 119 |
#endif |