]> mj.ucw.cz Git - libucw.git/blob - ucw/crc.h
ABI: Symbol renames for libucw and libcharset
[libucw.git] / ucw / crc.h
1 /*
2  *      CRC32 (Castagnoli 1993)
3  *
4  *      Based on Michael E. Kounavis and Frank L. Berry: A Systematic Approach
5  *      to Building High Performance Software-based CRC Generators
6  *      (Proceedings of the 10th IEEE Symposium on Computers and Communications 2005)
7  *
8  *      Includes code from http://sourceforge.net/projects/slicing-by-8/,
9  *      which carried the following copyright notice:
10  *
11  *      Copyright (c) 2004-2006 Intel Corporation - All Rights Reserved
12  *
13  *      This software program is licensed subject to the BSD License,
14  *      available at http://www.opensource.org/licenses/bsd-license.html
15  *
16  *      Adapted for LibUCW by Martin Mares <mj@ucw.cz> in 2012.
17  */
18
19 #ifndef _UCW_CRC_H
20 #define _UCW_CRC_H
21
22 #ifdef CONFIG_UCW_CLEAN_ABI
23 #define crc32_hash_buffer ucw_crc32_hash_buffer
24 #define crc32_init ucw_crc32_init
25 #endif
26
27 /**
28  * Internal CRC calculator context.
29  * You should use it just as an opaque handle only.
30  */
31 typedef struct crc32_context {
32   u32 state;
33   void (*update_func)(struct crc32_context *ctx, const byte *buf, uns len);
34 } crc32_context;
35
36 /**
37  * Initialize new calculation of CRC in a given context.
38  * @crc_mode selects which algorithm should be used.
39  **/
40 void crc32_init(crc32_context *ctx, uns crc_mode);
41
42 /**
43  * Algorithm used for CRC calculation. The algorithms differ by the amount
44  * of precomputed tables they use. Bigger tables imply faster calculation
45  * at the cost of an increased cache footprint.
46  **/
47 enum crc_mode {
48   CRC_MODE_DEFAULT,             /* Default algorithm (4K table) */
49   CRC_MODE_SMALL,               /* Optimize for small data (1K table) */
50   CRC_MODE_BIG,                 /* Optimize for large data (8K table) */
51   CRC_MODE_MAX,
52 };
53
54 /** Feed @len bytes starting at @buf to the CRC calculator. **/
55 static inline void crc32_update(crc32_context *ctx, const byte *buf, uns len)
56 {
57   ctx->update_func(ctx, buf, len);
58 }
59
60 /** Finish calculation and return the CRC value. **/
61 static inline u32 crc32_final(crc32_context *ctx)
62 {
63   return ctx->state ^ 0xffffffff;
64 }
65
66 /**
67  * A convenience one-shot function for CRC.
68  * It is equivalent to this snippet of code:
69  *
70  *  crc32_context ctx;
71  *  crc32_init(&ctx, CRC_MODE_DEFAULT);
72  *  crc32_update(&ctx, buf, len);
73  *  return crc32_final(&ctx);
74  */
75 u32 crc32_hash_buffer(const byte *buf, uns len);
76
77 #endif