Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032 #ifndef CRC32CheckSum_INCLUDE_ONCE
00033 #define CRC32CheckSum_INCLUDE_ONCE
00034
00035 #include <vlCore/VirtualFile.hpp>
00036
00037 namespace vl
00038 {
00042 class CRC32CheckSum
00043 {
00044
00045 static const int CHUNK_SIZE = 128*1024;
00046
00047 public:
00049 CRC32CheckSum() { crc32_init(); }
00050
00051 unsigned int compute(const void* buf, int length)
00052 {
00053 const unsigned char* buffer = (const unsigned char*)buf;
00054 unsigned int mCRC32 = 0xffffffff;
00055 while(length--)
00056 mCRC32 = (mCRC32 >> 8) ^ crc32_table[(mCRC32 & 0xFF) ^ *buffer++];
00057 return mCRC32 ^ 0xffffffff;
00058 }
00059
00060 unsigned int compute(VirtualFile* stream)
00061 {
00062 std::vector<unsigned char> buffer;
00063 buffer.resize(CHUNK_SIZE);
00064 unsigned char *ptr = &buffer.front();
00065 startCRC32();
00066
00067 for( int length = (int)stream->read(ptr, CHUNK_SIZE); length; length = (int)stream->read(ptr, CHUNK_SIZE) )
00068 continueCRC32(ptr,length);
00069
00070 return finalizeCRC32();
00071 }
00072
00073 void startCRC32() { mCRC32 = 0xffffffff; }
00074 unsigned int finalizeCRC32() { return mCRC32 ^ 0xffffffff; }
00075 void continueCRC32(unsigned char* ptr, int length)
00076 {
00077 while(length--)
00078 mCRC32 = (mCRC32 >> 8) ^ crc32_table[(mCRC32 & 0xFF) ^ *ptr++];
00079 }
00080
00081 protected:
00082 void crc32_init()
00083 {
00084 mCRC32 = 0;
00085 unsigned int ulPolynomial = 0x04c11db7;
00086 for(int i = 0; i <= 0xFF; i++)
00087 {
00088 crc32_table[i]=reflect(i, 8) << 24;
00089 for (int j = 0; j < 8; j++)
00090 crc32_table[i] = (crc32_table[i] << 1) ^ (crc32_table[i] & (1 << 31) ? ulPolynomial : 0);
00091 crc32_table[i] = reflect(crc32_table[i], 32);
00092 }
00093 }
00094
00095 unsigned int reflect(unsigned int val, char ch)
00096 {
00097 unsigned int refl = 0;
00098 for(int i = 1; i < (ch + 1); i++)
00099 {
00100 if(val & 1)
00101 refl |= 1 << (ch - i);
00102 val >>= 1;
00103 }
00104 return refl;
00105 }
00106
00107 protected:
00108 unsigned int mCRC32;
00109 unsigned int crc32_table[256];
00110 };
00111 }
00112
00113 #endif