MassBuilderSaveTool/src/Utilities/Crc32.h

63 lines
1.8 KiB
C++

#pragma once
// MassBuilderSaveTool
// Copyright (C) 2021-2022 Guillaume Jacquemin
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <Corrade/Containers/ArrayView.h>
#include <Corrade/Containers/StaticArray.h>
#include <Magnum/Types.h>
using namespace Corrade;
using namespace Magnum;
struct Crc32 {
static const Containers::StaticArray<256, UnsignedInt> table;
static auto update(UnsignedInt initial, Containers::ArrayView<const void> data) -> UnsignedInt {
UnsignedInt c = initial ^ 0xFFFFFFFF;
auto u = Containers::arrayCast<const UnsignedByte>(data);
for(std::size_t i = 0; i < data.size(); ++i) {
c = table[(c ^ u[i]) & 0xFF] ^ (c >> 8);
}
return c ^ 0xFFFFFFFF;
}
};
const Containers::StaticArray<256, UnsignedInt> Crc32::table = []{
UnsignedInt polynomial = 0xEDB88320u;
Containers::StaticArray<256, UnsignedInt> temp{ValueInit};
for(UnsignedInt i = 0; i < 256; i++) {
UnsignedInt c = i;
for(std::size_t j = 0; j < 8; j++) {
if(c & 1) {
c = polynomial ^ (c >> 1);
}
else {
c >>= 1;
}
}
temp[i] = c;
}
return temp;
}();