1 /// Implementation of CRC32 digester.
2 module tern.digest.crc32;
3 
4 import tern.serialization;
5 import tern.digest;
6 
7 /**
8  * Implementation of CRC32 digester.
9  *
10  * CRC32 (Cyclic Redundancy Check 32) is a widely used error-detecting code algorithm that
11  * produces a 32-bit (4-byte) hash value. It is commonly used in network communications, storage 
12  * systems, and other applications where data integrity is crucial.
13  *
14  * Example:
15  * ```d
16  * import tern.digest.crc;
17  *
18  * ubyte[] data = [1, 2, 3, 4, 5];
19  * auto hashValue = CRC32.hash(data);
20  * ```
21  */
22 public static @digester class CRC32
23 {
24 public:
25 static:
26 pure:
27     const uint[256] crcTable;
28 
29     shared static this()
30     {
31         uint[256] _crcTable;
32         uint poly =  0xEDB88320;
33         for (uint i =  0; i <  256; ++i) 
34         {
35             uint crc = i;
36             for (uint j =  0; j <  8; ++j) 
37             {
38                 if (crc &  1)
39                     crc = (crc >>  1) ^ poly;
40                 else
41                     crc = crc >>  1;
42             }
43             _crcTable[i] = crc;
44         }
45         crcTable = _crcTable;
46     }
47 
48     /**
49      * Computes the CRC32 hash digest of the given data.
50      *
51      * Params:
52      *  data = The input byte array for which the CRC32 hash is to be computed.
53      *
54      * Returns:
55      *  A byte array representing the computed CRC32 hash digest.
56      */
57     ubyte[] hash(const(ubyte[]) data) 
58     {
59         uint crc =  0xFFFFFFFF;
60         foreach (ubyte octet; data)
61             crc = crcTable[(crc ^ octet) &  0xFF] ^ (crc >>  8);
62         return (~crc).serialize!true(); 
63     }
64 }