Public Functions
calculateCRCTable()
1
2//-----------------------------------------------------------------------------
3// Copyright (c) 2012 GarageGames, LLC
4//
5// Permission is hereby granted, free of charge, to any person obtaining a copy
6// of this software and associated documentation files (the "Software"), to
7// deal in the Software without restriction, including without limitation the
8// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
9// sell copies of the Software, and to permit persons to whom the Software is
10// furnished to do so, subject to the following conditions:
11//
12// The above copyright notice and this permission notice shall be included in
13// all copies or substantial portions of the Software.
14//
15// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21// IN THE SOFTWARE.
22//-----------------------------------------------------------------------------
23
24#include "core/crc.h"
25
26#include "core/stream/stream.h"
27
28//-----------------------------------------------------------------------------
29// simple crc function - generates lookup table on first call
30
31static U32 crcTable[256];
32static bool crcTableValid;
33
34static void calculateCRCTable()
35{
36 U32 val;
37
38 for(S32 i = 0; i < 256; i++)
39 {
40 val = i;
41 for(S32 j = 0; j < 8; j++)
42 {
43 if(val & 0x01)
44 val = 0xedb88320 ^ (val >> 1);
45 else
46 val = val >> 1;
47 }
48 crcTable[i] = val;
49 }
50
51 crcTableValid = true;
52}
53
54
55//-----------------------------------------------------------------------------
56
57U32 CRC::calculateCRC(const void * buffer, S32 len, U32 crcVal )
58{
59 // check if need to generate the crc table
60 if(!crcTableValid)
61 calculateCRCTable();
62
63 // now calculate the crc
64 char * buf = (char*)buffer;
65 for(S32 i = 0; i < len; i++)
66 crcVal = crcTable[(crcVal ^ buf[i]) & 0xff] ^ (crcVal >> 8);
67 return(crcVal);
68}
69
70U32 CRC::calculateCRCStream(Stream *stream, U32 crcVal )
71{
72 // check if need to generate the crc table
73 if(!crcTableValid)
74 calculateCRCTable();
75
76 // now calculate the crc
77 stream->setPosition(0);
78 S32 len = stream->getStreamSize();
79 U8 buf[4096];
80
81 S32 segCount = (len + 4095) / 4096;
82
83 for(S32 j = 0; j < segCount; j++)
84 {
85 S32 slen = getMin(4096, len - (j * 4096));
86 stream->read(slen, buf);
87 crcVal = CRC::calculateCRC(buf, slen, crcVal);
88 }
89 stream->setPosition(0);
90 return(crcVal);
91}
92