Files
AVA2/shared/common/CRC32.cpp
T

150 lines
2.9 KiB
C++

#include "CRC32.h"
#include <cstdio>
#include <vector>
#include <sys/stat.h>
namespace
{
struct CrcTable
{
DWORD v[256];
CrcTable()
{
for (DWORD n = 0; n < 256; ++n)
{
DWORD c = n;
for (int k = 0; k < 8; ++k)
c = (c & 1) ? (0xEDB88320u ^ (c >> 1)) : (c >> 1);
v[n] = c;
}
}
};
const CrcTable s_crcTable;
}
#define CRCTable (s_crcTable.v)
#define DO1(buf, i) crc = CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8)
#define DO2(buf, i) DO1(buf, i); DO1(buf, i + 1);
#define DO4(buf, i) DO2(buf, i); DO2(buf, i + 2);
#define DO8(buf, i) DO4(buf, i); DO4(buf, i + 4);
#define DO16(buf, i) DO8(buf, i); DO8(buf, i + 8);
DWORD GetCRC32(const char * buf, size_t len)
{
DWORD crc = 0xffffffff;
if (len >= 16)
{
do
{
DO16(buf, 0);
buf += 16;
len -= 16;
} while (len >= 16);
}
if (len != 0)
{
do
{
DO1(buf, 0);
++buf;
--len;
} while (len > 0);
}
crc ^= 0xffffffff;
return crc;
}
#ifndef UPPER
#define UPPER(c) (((c)>='a' && (c) <= 'z') ? ((c)+('A'-'a')) : (c))
#endif
#define DO1CI(buf, i) crc = CRCTable[(crc ^ UPPER(buf[i])) & 0xff] ^ (crc >> 8)
#define DO2CI(buf, i) DO1CI(buf, i); DO1CI(buf, i + 1);
#define DO4CI(buf, i) DO2CI(buf, i); DO2CI(buf, i + 2);
#define DO8CI(buf, i) DO4CI(buf, i); DO4CI(buf, i + 4);
#define DO16CI(buf, i) DO8CI(buf, i); DO8CI(buf, i + 8);
DWORD GetCaseCRC32(const char * buf, size_t len)
{
DWORD crc = 0xffffffff;
if (16 <= len)
{
do
{
DO16CI(buf, 0);
buf += 16;
len -= 16;
} while (len >= 16);
}
if (0 != len)
{
do
{
DO1CI(buf, 0);
++buf;
--len;
} while (len > 0);
}
crc ^= 0xffffffff;
return crc;
}
DWORD GetHFILECRC32(HANDLE hFile)
{
FILE* fp = static_cast<FILE*>(hFile);
struct stat info{};
if (!fp || fstat(fileno(fp), &info) != 0 || !S_ISREG(info.st_mode))
return 0;
const long pos = std::ftell(fp);
if (pos < 0 || std::fseek(fp, 0, SEEK_END) != 0)
return 0;
const long size = std::ftell(fp);
if (size < 0 || std::fseek(fp, 0, SEEK_SET) != 0)
{
std::fseek(fp, pos, SEEK_SET);
return 0;
}
std::vector<char> data(size > 0 ? size : 0);
const size_t got = data.empty() ? 0 : std::fread(data.data(), 1, data.size(), fp);
std::fseek(fp, pos, SEEK_SET);
if (got != data.size() || data.empty())
return 0;
return GetCRC32(data.data(), data.size());
}
DWORD GetFileCRC32(const char* c_szFileName)
{
FILE* fp = std::fopen(c_szFileName, "rb");
if (!fp)
return 0;
DWORD dwRetCRC32=GetHFILECRC32(fp);
std::fclose(fp);
return dwRetCRC32;
}
DWORD GetFileSize(const char* c_szFileName)
{
FILE* fp = std::fopen(c_szFileName, "rb");
if (!fp)
return 0;
std::fseek(fp, 0, SEEK_END);
const long size = std::ftell(fp);
std::fclose(fp);
return size < 0 ? 0 : static_cast<DWORD>(size);
}