Files
Library/include/Void/Storage/Crc32c.hpp

84 lines
2.1 KiB
C++

#pragma once
#include <array>
#include <cstddef>
#include <cstdint>
#include <span>
#include <string_view>
namespace Void::Storage
{
namespace detail
{
[[nodiscard]] constexpr std::array<std::uint32_t, 256>
make_crc32c_table() noexcept
{
// Reflected Castagnoli polynomial (normal 0x1EDC6F41, reflected 0x82F63B78).
constexpr std::uint32_t kPoly = 0x82F63B78u;
std::array<std::uint32_t, 256> table{};
for (std::uint32_t i = 0; i < 256; ++i) {
std::uint32_t c = i;
for (int k = 0; k < 8; ++k) {
c = (c & 1u) ? (kPoly ^ (c >> 1)) : (c >> 1);
}
table[i] = c;
}
return table;
}
inline constexpr auto kCrc32cTable = make_crc32c_table();
} // namespace detail
inline constexpr std::uint32_t kCrc32cInitial = 0xFFFFFFFFu;
[[nodiscard]] constexpr std::uint32_t crc32c_init() noexcept
{
return kCrc32cInitial;
}
[[nodiscard]] constexpr std::uint32_t crc32c_update(
std::uint32_t state,
std::span<const std::byte> data) noexcept
{
for (const auto b : data) {
const auto idx =
(state ^ static_cast<std::uint32_t>(std::to_integer<unsigned char>(b))) &
0xFFu;
state = detail::kCrc32cTable[idx] ^ (state >> 8);
}
return state;
}
[[nodiscard]] constexpr std::uint32_t crc32c_update(
std::uint32_t state,
std::string_view text) noexcept
{
for (const unsigned char c : text) {
state = detail::kCrc32cTable[(state ^ c) & 0xFFu] ^ (state >> 8);
}
return state;
}
[[nodiscard]] constexpr std::uint32_t crc32c_finalize(std::uint32_t state) noexcept
{
return state ^ 0xFFFFFFFFu;
}
[[nodiscard]] constexpr std::uint32_t crc32c(
std::span<const std::byte> data) noexcept
{
return crc32c_finalize(crc32c_update(crc32c_init(), data));
}
[[nodiscard]] constexpr std::uint32_t crc32c(std::string_view text) noexcept
{
return crc32c_finalize(crc32c_update(crc32c_init(), text));
}
static_assert(crc32c(std::string_view{"123456789"}) == 0xE3069283u,
"CRC32C golden vector mismatch");
static_assert(crc32c(std::string_view{""}) == 0u,
"CRC32C empty vector mismatch");
} // namespace Void::Storage