added "permission obtained from John Erickson <jerickson@ddj.com> ...."
[samba.git] / source / lib / crc32.c
1 /* 
2  * Dr Dobb's Journal: http://www.ddj.com/ftp/1992/1992.05/crcman.zip
3  *
4  * Copyright Mark R. Nelson 1992
5  *
6  * This code used by permission of J Erickson <jerickson@ddj.com>
7  * Tues 6th October 1998.  Copyright acknowledged above, as agreed.
8  *
9  */
10
11 #include "includes.h"
12
13 #define CRC32_POLYNOMIAL     0xEDB88320L
14
15 /*****************************************************************
16  Instead of performing a straightforward calculation of the 32 bit
17  CRC using a series of logical operations, this program uses the
18  faster table lookup method.  This routine is called once when the
19  program starts up to build the table which will be used later
20  when calculating the CRC values.
21  *****************************************************************/
22
23 static uint32 CRCTable[256];
24
25 void crc32_build_table(void)
26 {
27         int i;
28         int j;
29         uint32 crc;
30
31         for ( i = 0; i <= 255 ; i++ )
32         {
33                 crc = i;
34                 for ( j = 8 ; j > 0; j-- )
35                 {
36                         if ( crc & 1 )
37                         {
38                                 crc = ( crc >> 1 ) ^ CRC32_POLYNOMIAL;
39                         }
40                         else
41                         {
42                                 crc >>= 1;
43                         }
44                 }
45                 CRCTable[ i ] = crc;
46         }
47 }
48
49 /*****************************************************************
50  This routine calculates the CRC for a block of data using the
51  table lookup method. 
52  *****************************************************************/
53
54 uint32 crc32_calc_buffer( uint32 count, uchar *buffer)
55 {
56         uchar *p;
57         uint32 crc;
58
59         p = buffer;
60         crc = 0xffffffff;
61
62         while ( count-- != 0 )
63         {
64                 uint32 temp1;
65                 uint32 temp2;
66
67                 temp1 = ( crc >> 8 ) & 0x00FFFFFFL;
68                 temp2 = CRCTable[ ( (int) crc ^ *p++ ) & 0xff ];
69                 crc = temp1 ^ temp2;
70         }
71         return crc;
72 }
73