MassBuilderSaveTool/src/Utilities/Crc32.cpp
Guillaume Jacquemin 53c58ba979
Switch to C++17.
Also change namespace definitions to nested ones.
2024-07-14 16:28:17 +02:00

56 lines
1.6 KiB
C++

// MassBuilderSaveTool
// Copyright (C) 2021-2024 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 "Crc32.h"
namespace mbst::Utilities {
std::uint32_t
crc32(std::uint32_t initial, Containers::ArrayView<const void> data) {
static const auto table = []{
std::uint32_t polynomial = 0xEDB88320u;
Containers::StaticArray<256, std::uint32_t> temp{ValueInit};
for(std::uint32_t i = 0; i < 256; i++) {
std::uint32_t 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;
}();
std::uint32_t c = initial ^ 0xFFFFFFFF;
auto u = Containers::arrayCast<const std::uint8_t>(data);
for(std::size_t i = 0; i < data.size(); ++i) {
c = table[(c ^ u[i]) & 0xFF] ^ (c >> 8);
}
return c ^ 0xFFFFFFFF;
}
}