blob: fb504fda9eb390bc66e387f03d1fab82e56e7687 [file]
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "formats/png/crc.h"
#include <array>
#include <cstdint>
#include "absl/strings/string_view.h"
namespace credentio {
namespace {
// Precomputed CRC-32 table (IEEE 802.3 polynomial: 0xedb88320)
constexpr std::array<uint32_t, 256> MakeCrcTable() {
std::array<uint32_t, 256> table = {};
for (uint32_t i = 0; i < 256; ++i) {
uint32_t c = i;
for (int j = 0; j < 8; ++j) {
if (c & 1) {
c = 0xedb88320L ^ (c >> 1);
} else {
c = c >> 1;
}
}
table[i] = c;
}
return table;
}
static constexpr std::array<uint32_t, 256> kCrcTable = MakeCrcTable();
uint32_t UpdateCrc(uint32_t crc, absl::string_view data) {
uint32_t c = crc;
for (char byte : data) {
c = kCrcTable[(c ^ static_cast<uint8_t>(byte)) & 0xff] ^ (c >> 8);
}
return c;
}
} // namespace
uint32_t PngChunkCrc(absl::string_view type, absl::string_view data) {
uint32_t crc = 0xffffffffL;
crc = UpdateCrc(crc, type);
crc = UpdateCrc(crc, data);
return crc ^ 0xffffffffL;
}
} // namespace credentio