crcmod-1.7/0000755000175000017500000000000011411642620012205 5ustar rlbrlb00000000000000crcmod-1.7/setup.py0000644000175000017500000000367711411635253013740 0ustar rlbrlb00000000000000from distutils.core import setup from distutils.extension import Extension import sys,os if sys.version_info[0] == 2: base_dir = 'python2' elif sys.version_info[0] == 3: base_dir = 'python3' setup_dict = dict( name='crcmod', version='1.7', description='CRC Generator', author='Ray Buvel', author_email='rlbuvel@gmail.com', url='http://crcmod.sourceforge.net/', download_url='http://sourceforge.net/projects/crcmod', packages=['crcmod'], package_dir={ 'crcmod' : os.path.join(base_dir,'crcmod'), }, ext_modules=[ Extension('crcmod._crcfunext', [os.path.join(base_dir,'src/_crcfunext.c'), ], ), ], long_description=open('README').read(), license="MIT", classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: Education', 'Intended Audience :: End Users/Desktop', 'Intended Audience :: Information Technology', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: C', 'Programming Language :: C++', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.4', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.1', 'Topic :: Communications', 'Topic :: Scientific/Engineering :: Interface Engine/Protocol Translator', 'Topic :: Scientific/Engineering :: Mathematics', 'Topic :: Utilities', ], ) try: setup(**setup_dict) except KeyboardInterrupt: raise except: # If there are any compilation errors or there are no build tools available # for the extension module, delete the extension module and try to install # the pure Python version. del setup_dict['ext_modules'] setup(**setup_dict) crcmod-1.7/python2/0000755000175000017500000000000011411642620013610 5ustar rlbrlb00000000000000crcmod-1.7/python2/src/0000755000175000017500000000000011411642620014377 5ustar rlbrlb00000000000000crcmod-1.7/python2/src/_crcfunext.c0000644000175000017500000003313011411635253016707 0ustar rlbrlb00000000000000//----------------------------------------------------------------------------- // Low level CRC functions for use by crcmod. This version is the C // implementation that corresponds to the Python module _crcfunpy. This module // will be used by crcmod if it is built for the target platform. Otherwise, // the Python module is used. // // Copyright (c) 2004 Raymond L. Buvel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- // Force Py_ssize_t to be used for s# conversions. #define PY_SSIZE_T_CLEAN #include // Make compatible with previous Python versions #if PY_VERSION_HEX < 0x02050000 typedef int Py_ssize_t; #define PY_SSIZE_T_MAX INT_MAX #define PY_SSIZE_T_MIN INT_MIN #endif // Note: the type declarations are set up to work on 32-bit platforms using the // GNU C compiler. They will need to be adjusted for other platforms. In // particular, the Microsoft Windows compiler uses _int64 instead of long long. // Define a few types to make it easier to port to other platforms. typedef unsigned char UINT8; typedef unsigned short UINT16; typedef unsigned int UINT32; typedef unsigned long long UINT64; // Define some macros for the data format strings. The INPUT strings are for // decoding the input parameters to the function which are (data, crc, table). // Note: these format strings use codes that are new in Python 2.3 so it would // be necessary to rewrite the code for versions earlier than 2.3. #define INPUT8 "s#Bs#" #define INPUT16 "s#Hs#" #define INPUT32 "s#Is#" #define INPUT64 "s#Ks#" // Define some macros that extract the specified byte from an integral value in // what should be a platform independent manner. #define BYTE0(x) ((UINT8)(x)) #define BYTE1(x) ((UINT8)((x) >> 8)) #define BYTE2(x) ((UINT8)((x) >> 16)) #define BYTE3(x) ((UINT8)((x) >> 24)) #define BYTE7(x) ((UINT8)((x) >> 56)) //----------------------------------------------------------------------------- // Compute a 8-bit crc over the input data. // Inputs: // data - string containing the data // crc - unsigned integer containing the initial crc // table - string containing the 8-bit table corresponding to the generator // polynomial. // Returns: // crc - unsigned integer containing the resulting crc static PyObject* _crc8(PyObject* self, PyObject* args) { UINT8 crc; UINT8* data; Py_ssize_t dataLen; UINT8* table; Py_ssize_t tableLen; if (!PyArg_ParseTuple(args, INPUT8, &data, &dataLen, &crc, &table, &tableLen)) { return NULL; } if (tableLen != 256) { PyErr_SetString(PyExc_ValueError, "invalid CRC table"); return NULL; } while (dataLen--) { crc = table[*data ^ crc]; data++; } return PyInt_FromLong((long)crc); } //----------------------------------------------------------------------------- // Compute a 8-bit crc over the input data. The data stream is bit reversed // during the computation. // Inputs: // data - string containing the data // crc - unsigned integer containing the initial crc // table - string containing the 8-bit table corresponding to the generator // polynomial. // Returns: // crc - unsigned integer containing the resulting crc static PyObject* _crc8r(PyObject* self, PyObject* args) { UINT8 crc; UINT8* data; Py_ssize_t dataLen; UINT8* table; Py_ssize_t tableLen; if (!PyArg_ParseTuple(args, INPUT8, &data, &dataLen, &crc, &table, &tableLen)) { return NULL; } if (tableLen != 256) { PyErr_SetString(PyExc_ValueError, "invalid CRC table"); return NULL; } while (dataLen--) { crc = table[*data ^ crc]; data++; } return PyInt_FromLong((long)crc); } //----------------------------------------------------------------------------- // Compute a 16-bit crc over the input data. // Inputs: // data - string containing the data // crc - unsigned integer containing the initial crc // table - string containing the 16-bit table corresponding to the generator // polynomial. // Returns: // crc - unsigned integer containing the resulting crc static PyObject* _crc16(PyObject* self, PyObject* args) { UINT16 crc; UINT8* data; Py_ssize_t dataLen; UINT16* table; Py_ssize_t tableLen; if (!PyArg_ParseTuple(args, INPUT16, &data, &dataLen, &crc, &table, &tableLen)) { return NULL; } if (tableLen != 256*2) { PyErr_SetString(PyExc_ValueError, "invalid CRC table"); return NULL; } while (dataLen--) { crc = table[*data ^ BYTE1(crc)] ^ (crc << 8); data++; } return PyInt_FromLong((long)crc); } //----------------------------------------------------------------------------- // Compute a 16-bit crc over the input data. The data stream is bit reversed // during the computation. // Inputs: // data - string containing the data // crc - unsigned integer containing the initial crc // table - string containing the 16-bit table corresponding to the generator // polynomial. // Returns: // crc - unsigned integer containing the resulting crc static PyObject* _crc16r(PyObject* self, PyObject* args) { UINT16 crc; UINT8* data; Py_ssize_t dataLen; UINT16* table; Py_ssize_t tableLen; if (!PyArg_ParseTuple(args, INPUT16, &data, &dataLen, &crc, &table, &tableLen)) { return NULL; } if (tableLen != 256*2) { PyErr_SetString(PyExc_ValueError, "invalid CRC table"); return NULL; } while (dataLen--) { crc = table[*data ^ BYTE0(crc)] ^ (crc >> 8); data++; } return PyInt_FromLong((long)crc); } //----------------------------------------------------------------------------- // Compute a 24-bit crc over the input data. // Inputs: // data - string containing the data // crc - unsigned integer containing the initial crc // table - string containing the 24-bit table corresponding to the generator // polynomial. // Returns: // crc - unsigned integer containing the resulting crc static PyObject* _crc24(PyObject* self, PyObject* args) { UINT32 crc; UINT8* data; Py_ssize_t dataLen; UINT32* table; Py_ssize_t tableLen; if (!PyArg_ParseTuple(args, INPUT32, &data, &dataLen, &crc, &table, &tableLen)) { return NULL; } if (tableLen != 256*4) { PyErr_SetString(PyExc_ValueError, "invalid CRC table"); return NULL; } while (dataLen--) { crc = table[*data ^ BYTE2(crc)] ^ (crc << 8); data++; } return PyInt_FromLong((long)(crc & 0xFFFFFFU)); } //----------------------------------------------------------------------------- // Compute a 24-bit crc over the input data. The data stream is bit reversed // during the computation. // Inputs: // data - string containing the data // crc - unsigned integer containing the initial crc // table - string containing the 24-bit table corresponding to the generator // polynomial. // Returns: // crc - unsigned integer containing the resulting crc static PyObject* _crc24r(PyObject* self, PyObject* args) { UINT32 crc; UINT8* data; Py_ssize_t dataLen; UINT32* table; Py_ssize_t tableLen; if (!PyArg_ParseTuple(args, INPUT32, &data, &dataLen, &crc, &table, &tableLen)) { return NULL; } if (tableLen != 256*4) { PyErr_SetString(PyExc_ValueError, "invalid CRC table"); return NULL; } crc = crc & 0xFFFFFFU; while (dataLen--) { crc = table[*data ^ BYTE0(crc)] ^ (crc >> 8); data++; } return PyInt_FromLong((long)crc); } //----------------------------------------------------------------------------- // Compute a 32-bit crc over the input data. // Inputs: // data - string containing the data // crc - unsigned integer containing the initial crc // table - string containing the 32-bit table corresponding to the generator // polynomial. // Returns: // crc - unsigned integer containing the resulting crc static PyObject* _crc32(PyObject* self, PyObject* args) { UINT32 crc; UINT8* data; Py_ssize_t dataLen; UINT32* table; Py_ssize_t tableLen; if (!PyArg_ParseTuple(args, INPUT32, &data, &dataLen, &crc, &table, &tableLen)) { return NULL; } if (tableLen != 256*4) { PyErr_SetString(PyExc_ValueError, "invalid CRC table"); return NULL; } while (dataLen--) { crc = table[*data ^ BYTE3(crc)] ^ (crc << 8); data++; } return PyLong_FromUnsignedLong(crc); } //----------------------------------------------------------------------------- // Compute a 32-bit crc over the input data. The data stream is bit reversed // during the computation. // Inputs: // data - string containing the data // crc - unsigned integer containing the initial crc // table - string containing the 32-bit table corresponding to the generator // polynomial. // Returns: // crc - unsigned integer containing the resulting crc static PyObject* _crc32r(PyObject* self, PyObject* args) { UINT32 crc; UINT8* data; Py_ssize_t dataLen; UINT32* table; Py_ssize_t tableLen; if (!PyArg_ParseTuple(args, INPUT32, &data, &dataLen, &crc, &table, &tableLen)) { return NULL; } if (tableLen != 256*4) { PyErr_SetString(PyExc_ValueError, "invalid CRC table"); return NULL; } while (dataLen--) { crc = table[*data ^ BYTE0(crc)] ^ (crc >> 8); data++; } return PyLong_FromUnsignedLong(crc); } //----------------------------------------------------------------------------- // Compute a 64-bit crc over the input data. // Inputs: // data - string containing the data // crc - unsigned integer containing the initial crc // table - string containing the 64-bit table corresponding to the generator // polynomial. // Returns: // crc - unsigned integer containing the resulting crc static PyObject* _crc64(PyObject* self, PyObject* args) { UINT64 crc; UINT8* data; Py_ssize_t dataLen; UINT64* table; Py_ssize_t tableLen; if (!PyArg_ParseTuple(args, INPUT64, &data, &dataLen, &crc, &table, &tableLen)) { return NULL; } if (tableLen != 256*8) { PyErr_SetString(PyExc_ValueError, "invalid CRC table"); return NULL; } while (dataLen--) { crc = table[*data ^ BYTE7(crc)] ^ (crc << 8); data++; } return PyLong_FromUnsignedLongLong(crc); } //----------------------------------------------------------------------------- // Compute a 64-bit crc over the input data. The data stream is bit reversed // during the computation. // Inputs: // data - string containing the data // crc - unsigned integer containing the initial crc // table - string containing the 64-bit table corresponding to the generator // polynomial. // Returns: // crc - unsigned integer containing the resulting crc static PyObject* _crc64r(PyObject* self, PyObject* args) { UINT64 crc; UINT8* data; Py_ssize_t dataLen; UINT64* table; Py_ssize_t tableLen; if (!PyArg_ParseTuple(args, INPUT64, &data, &dataLen, &crc, &table, &tableLen)) { return NULL; } if (tableLen != 256*8) { PyErr_SetString(PyExc_ValueError, "invalid CRC table"); return NULL; } while (dataLen--) { crc = table[*data ^ BYTE0(crc)] ^ (crc >> 8); data++; } return PyLong_FromUnsignedLongLong(crc); } //----------------------------------------------------------------------------- static PyMethodDef methodTable[] = { {"_crc8", _crc8, METH_VARARGS}, {"_crc8r", _crc8r, METH_VARARGS}, {"_crc16", _crc16, METH_VARARGS}, {"_crc16r", _crc16r, METH_VARARGS}, {"_crc24", _crc24, METH_VARARGS}, {"_crc24r", _crc24r, METH_VARARGS}, {"_crc32", _crc32, METH_VARARGS}, {"_crc32r", _crc32r, METH_VARARGS}, {"_crc64", _crc64, METH_VARARGS}, {"_crc64r", _crc64r, METH_VARARGS}, {NULL, NULL} }; //----------------------------------------------------------------------------- void init_crcfunext(void) { PyObject *m; if ((sizeof(UINT8) != 1) || (sizeof(UINT16) != 2) || (sizeof(UINT32) != 4) || (sizeof(UINT64) != 8)) { Py_FatalError("crcfunext: One of the data types is invalid"); } m = Py_InitModule("_crcfunext", methodTable); } crcmod-1.7/python2/crcmod/0000755000175000017500000000000011411642620015057 5ustar rlbrlb00000000000000crcmod-1.7/python2/crcmod/crcmod.py0000644000175000017500000004130411411635253016706 0ustar rlbrlb00000000000000#----------------------------------------------------------------------------- # Copyright (c) 2010 Raymond L. Buvel # Copyright (c) 2010 Craig McQueen # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. #----------------------------------------------------------------------------- '''crcmod is a Python module for gererating objects that compute the Cyclic Redundancy Check. Any 8, 16, 24, 32, or 64 bit polynomial can be used. The following are the public components of this module. Crc -- a class that creates instances providing the same interface as the md5 and sha modules in the Python standard library. These instances also provide a method for generating a C/C++ function to compute the CRC. mkCrcFun -- create a Python function to compute the CRC using the specified polynomial and initial value. This provides a much simpler interface if all you need is a function for CRC calculation. ''' __all__ = '''mkCrcFun Crc '''.split() # Select the appropriate set of low-level CRC functions for this installation. # If the extension module was not built, drop back to the Python implementation # even though it is significantly slower. try: import _crcfunext as _crcfun _usingExtension = True except ImportError: import _crcfunpy as _crcfun _usingExtension = False import sys, struct #----------------------------------------------------------------------------- class Crc: '''Compute a Cyclic Redundancy Check (CRC) using the specified polynomial. Instances of this class have the same interface as the md5 and sha modules in the Python standard library. See the documentation for these modules for examples of how to use a Crc instance. The string representation of a Crc instance identifies the polynomial, initial value, XOR out value, and the current CRC value. The print statement can be used to output this information. If you need to generate a C/C++ function for use in another application, use the generateCode method. If you need to generate code for another language, subclass Crc and override the generateCode method. The following are the parameters supplied to the constructor. poly -- The generator polynomial to use in calculating the CRC. The value is specified as a Python integer or long integer. The bits in this integer are the coefficients of the polynomial. The only polynomials allowed are those that generate 8, 16, 24, 32, or 64 bit CRCs. initCrc -- Initial value used to start the CRC calculation. This initial value should be the initial shift register value XORed with the final XOR value. That is equivalent to the CRC result the algorithm should return for a zero-length string. Defaults to all bits set because that starting value will take leading zero bytes into account. Starting with zero will ignore all leading zero bytes. rev -- A flag that selects a bit reversed algorithm when True. Defaults to True because the bit reversed algorithms are more efficient. xorOut -- Final value to XOR with the calculated CRC value. Used by some CRC algorithms. Defaults to zero. ''' def __init__(self, poly, initCrc=~0L, rev=True, xorOut=0, initialize=True): if not initialize: # Don't want to perform the initialization when using new or copy # to create a new instance. return (sizeBits, initCrc, xorOut) = _verifyParams(poly, initCrc, xorOut) self.digest_size = sizeBits//8 self.initCrc = initCrc self.xorOut = xorOut self.poly = poly self.reverse = rev (crcfun, table) = _mkCrcFun(poly, sizeBits, initCrc, rev, xorOut) self._crc = crcfun self.table = table self.crcValue = self.initCrc def __str__(self): lst = [] lst.append('poly = 0x%X' % self.poly) lst.append('reverse = %s' % self.reverse) fmt = '0x%%0%dX' % (self.digest_size*2) lst.append('initCrc = %s' % (fmt % self.initCrc)) lst.append('xorOut = %s' % (fmt % self.xorOut)) lst.append('crcValue = %s' % (fmt % self.crcValue)) return '\n'.join(lst) def new(self, arg=None): '''Create a new instance of the Crc class initialized to the same values as the original instance. The current CRC is set to the initial value. If a string is provided in the optional arg parameter, it is passed to the update method. ''' n = Crc(poly=None, initialize=False) n._crc = self._crc n.digest_size = self.digest_size n.initCrc = self.initCrc n.xorOut = self.xorOut n.table = self.table n.crcValue = self.initCrc n.reverse = self.reverse n.poly = self.poly if arg is not None: n.update(arg) return n def copy(self): '''Create a new instance of the Crc class initialized to the same values as the original instance. The current CRC is set to the current value. This allows multiple CRC calculations using a common initial string. ''' c = self.new() c.crcValue = self.crcValue return c def update(self, data): '''Update the current CRC value using the string specified as the data parameter. ''' self.crcValue = self._crc(data, self.crcValue) def digest(self): '''Return the current CRC value as a string of bytes. The length of this string is specified in the digest_size attribute. ''' n = self.digest_size crc = self.crcValue lst = [] while n > 0: lst.append(chr(crc & 0xFF)) crc = crc >> 8 n -= 1 lst.reverse() return ''.join(lst) def hexdigest(self): '''Return the current CRC value as a string of hex digits. The length of this string is twice the digest_size attribute. ''' n = self.digest_size crc = self.crcValue lst = [] while n > 0: lst.append('%02X' % (crc & 0xFF)) crc = crc >> 8 n -= 1 lst.reverse() return ''.join(lst) def generateCode(self, functionName, out, dataType=None, crcType=None): '''Generate a C/C++ function. functionName -- String specifying the name of the function. out -- An open file-like object with a write method. This specifies where the generated code is written. dataType -- An optional parameter specifying the data type of the input data to the function. Defaults to UINT8. crcType -- An optional parameter specifying the data type of the CRC value. Defaults to one of UINT8, UINT16, UINT32, or UINT64 depending on the size of the CRC value. ''' if dataType is None: dataType = 'UINT8' if crcType is None: size = 8*self.digest_size if size == 24: size = 32 crcType = 'UINT%d' % size if self.digest_size == 1: # Both 8-bit CRC algorithms are the same crcAlgor = 'table[*data ^ (%s)crc]' elif self.reverse: # The bit reverse algorithms are all the same except for the data # type of the crc variable which is specified elsewhere. crcAlgor = 'table[*data ^ (%s)crc] ^ (crc >> 8)' else: # The forward CRC algorithms larger than 8 bits have an extra shift # operation to get the high byte. shift = 8*(self.digest_size - 1) crcAlgor = 'table[*data ^ (%%s)(crc >> %d)] ^ (crc << 8)' % shift fmt = '0x%%0%dX' % (2*self.digest_size) if self.digest_size <= 4: fmt = fmt + 'U,' else: # Need the long long type identifier to keep gcc from complaining. fmt = fmt + 'ULL,' # Select the number of entries per row in the output code. n = {1:8, 2:8, 3:4, 4:4, 8:2}[self.digest_size] lst = [] for i, val in enumerate(self.table): if (i % n) == 0: lst.append('\n ') lst.append(fmt % val) poly = 'polynomial: 0x%X' % self.poly if self.reverse: poly = poly + ', bit reverse algorithm' if self.xorOut: # Need to remove the comma from the format. preCondition = '\n crc = crc ^ %s;' % (fmt[:-1] % self.xorOut) postCondition = preCondition else: preCondition = '' postCondition = '' if self.digest_size == 3: # The 24-bit CRC needs to be conditioned so that only 24-bits are # used from the 32-bit variable. if self.reverse: preCondition += '\n crc = crc & 0xFFFFFFU;' else: postCondition += '\n crc = crc & 0xFFFFFFU;' parms = { 'dataType' : dataType, 'crcType' : crcType, 'name' : functionName, 'crcAlgor' : crcAlgor % dataType, 'crcTable' : ''.join(lst), 'poly' : poly, 'preCondition' : preCondition, 'postCondition' : postCondition, } out.write(_codeTemplate % parms) #----------------------------------------------------------------------------- def mkCrcFun(poly, initCrc=~0L, rev=True, xorOut=0): '''Return a function that computes the CRC using the specified polynomial. poly -- integer representation of the generator polynomial initCrc -- default initial CRC value rev -- when true, indicates that the data is processed bit reversed. xorOut -- the final XOR value The returned function has the following user interface def crcfun(data, crc=initCrc): ''' # First we must verify the params (sizeBits, initCrc, xorOut) = _verifyParams(poly, initCrc, xorOut) # Make the function (and table), return the function return _mkCrcFun(poly, sizeBits, initCrc, rev, xorOut)[0] #----------------------------------------------------------------------------- # Naming convention: # All function names ending with r are bit reverse variants of the ones # without the r. #----------------------------------------------------------------------------- # Check the polynomial to make sure that it is acceptable and return the number # of bits in the CRC. def _verifyPoly(poly): msg = 'The degree of the polynomial must be 8, 16, 24, 32 or 64' poly = long(poly) # Use a common representation for all operations for n in (8,16,24,32,64): low = 1L<> 1 if ((1L<> 1) ^ poly else: crc = crc >> 1 mask = (1L< 0) { crc = %(crcAlgor)s; data++; len--; }%(postCondition)s return crc; } ''' crcmod-1.7/python2/crcmod/predefined.py0000644000175000017500000002260011411635253017542 0ustar rlbrlb00000000000000#----------------------------------------------------------------------------- # Copyright (c) 2010 Craig McQueen # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. #----------------------------------------------------------------------------- ''' crcmod.predefined defines some well-known CRC algorithms. To use it, e.g.: import crcmod.predefined crc32func = crcmod.predefined.mkPredefinedCrcFun("crc-32") crc32class = crcmod.predefined.PredefinedCrc("crc-32") crcmod.predefined.Crc is an alias for crcmod.predefined.PredefinedCrc But if doing 'from crc.predefined import *', only PredefinedCrc is imported. ''' # local imports import crcmod __all__ = [ 'PredefinedCrc', 'mkPredefinedCrcFun', ] REVERSE = True NON_REVERSE = False # The following table defines the parameters of well-known CRC algorithms. # The "Check" value is the CRC for the ASCII byte sequence "123456789". It # can be used for unit tests. _crc_definitions_table = [ # Name Identifier-name, Poly Reverse Init-value XOR-out Check [ 'crc-8', 'Crc8', 0x107, NON_REVERSE, 0x00, 0x00, 0xF4, ], [ 'crc-8-darc', 'Crc8Darc', 0x139, REVERSE, 0x00, 0x00, 0x15, ], [ 'crc-8-i-code', 'Crc8ICode', 0x11D, NON_REVERSE, 0xFD, 0x00, 0x7E, ], [ 'crc-8-itu', 'Crc8Itu', 0x107, NON_REVERSE, 0x55, 0x55, 0xA1, ], [ 'crc-8-maxim', 'Crc8Maxim', 0x131, REVERSE, 0x00, 0x00, 0xA1, ], [ 'crc-8-rohc', 'Crc8Rohc', 0x107, REVERSE, 0xFF, 0x00, 0xD0, ], [ 'crc-8-wcdma', 'Crc8Wcdma', 0x19B, REVERSE, 0x00, 0x00, 0x25, ], [ 'crc-16', 'Crc16', 0x18005, REVERSE, 0x0000, 0x0000, 0xBB3D, ], [ 'crc-16-buypass', 'Crc16Buypass', 0x18005, NON_REVERSE, 0x0000, 0x0000, 0xFEE8, ], [ 'crc-16-dds-110', 'Crc16Dds110', 0x18005, NON_REVERSE, 0x800D, 0x0000, 0x9ECF, ], [ 'crc-16-dect', 'Crc16Dect', 0x10589, NON_REVERSE, 0x0001, 0x0001, 0x007E, ], [ 'crc-16-dnp', 'Crc16Dnp', 0x13D65, REVERSE, 0xFFFF, 0xFFFF, 0xEA82, ], [ 'crc-16-en-13757', 'Crc16En13757', 0x13D65, NON_REVERSE, 0xFFFF, 0xFFFF, 0xC2B7, ], [ 'crc-16-genibus', 'Crc16Genibus', 0x11021, NON_REVERSE, 0x0000, 0xFFFF, 0xD64E, ], [ 'crc-16-maxim', 'Crc16Maxim', 0x18005, REVERSE, 0xFFFF, 0xFFFF, 0x44C2, ], [ 'crc-16-mcrf4xx', 'Crc16Mcrf4xx', 0x11021, REVERSE, 0xFFFF, 0x0000, 0x6F91, ], [ 'crc-16-riello', 'Crc16Riello', 0x11021, REVERSE, 0x554D, 0x0000, 0x63D0, ], [ 'crc-16-t10-dif', 'Crc16T10Dif', 0x18BB7, NON_REVERSE, 0x0000, 0x0000, 0xD0DB, ], [ 'crc-16-teledisk', 'Crc16Teledisk', 0x1A097, NON_REVERSE, 0x0000, 0x0000, 0x0FB3, ], [ 'crc-16-usb', 'Crc16Usb', 0x18005, REVERSE, 0x0000, 0xFFFF, 0xB4C8, ], [ 'x-25', 'CrcX25', 0x11021, REVERSE, 0x0000, 0xFFFF, 0x906E, ], [ 'xmodem', 'CrcXmodem', 0x11021, NON_REVERSE, 0x0000, 0x0000, 0x31C3, ], [ 'modbus', 'CrcModbus', 0x18005, REVERSE, 0xFFFF, 0x0000, 0x4B37, ], # Note definitions of CCITT are disputable. See: # http://homepages.tesco.net/~rainstorm/crc-catalogue.htm # http://web.archive.org/web/20071229021252/http://www.joegeluso.com/software/articles/ccitt.htm [ 'kermit', 'CrcKermit', 0x11021, REVERSE, 0x0000, 0x0000, 0x2189, ], [ 'crc-ccitt-false', 'CrcCcittFalse', 0x11021, NON_REVERSE, 0xFFFF, 0x0000, 0x29B1, ], [ 'crc-aug-ccitt', 'CrcAugCcitt', 0x11021, NON_REVERSE, 0x1D0F, 0x0000, 0xE5CC, ], [ 'crc-24', 'Crc24', 0x1864CFB, NON_REVERSE, 0xB704CE, 0x000000, 0x21CF02, ], [ 'crc-24-flexray-a', 'Crc24FlexrayA', 0x15D6DCB, NON_REVERSE, 0xFEDCBA, 0x000000, 0x7979BD, ], [ 'crc-24-flexray-b', 'Crc24FlexrayB', 0x15D6DCB, NON_REVERSE, 0xABCDEF, 0x000000, 0x1F23B8, ], [ 'crc-32', 'Crc32', 0x104C11DB7, REVERSE, 0x00000000, 0xFFFFFFFF, 0xCBF43926, ], [ 'crc-32-bzip2', 'Crc32Bzip2', 0x104C11DB7, NON_REVERSE, 0x00000000, 0xFFFFFFFF, 0xFC891918, ], [ 'crc-32c', 'Crc32C', 0x11EDC6F41, REVERSE, 0x00000000, 0xFFFFFFFF, 0xE3069283, ], [ 'crc-32d', 'Crc32D', 0x1A833982B, REVERSE, 0x00000000, 0xFFFFFFFF, 0x87315576, ], [ 'crc-32-mpeg', 'Crc32Mpeg', 0x104C11DB7, NON_REVERSE, 0xFFFFFFFF, 0x00000000, 0x0376E6E7, ], [ 'posix', 'CrcPosix', 0x104C11DB7, NON_REVERSE, 0xFFFFFFFF, 0xFFFFFFFF, 0x765E7680, ], [ 'crc-32q', 'Crc32Q', 0x1814141AB, NON_REVERSE, 0x00000000, 0x00000000, 0x3010BF7F, ], [ 'jamcrc', 'CrcJamCrc', 0x104C11DB7, REVERSE, 0xFFFFFFFF, 0x00000000, 0x340BC6D9, ], [ 'xfer', 'CrcXfer', 0x1000000AF, NON_REVERSE, 0x00000000, 0x00000000, 0xBD0BE338, ], # 64-bit # Name Identifier-name, Poly Reverse Init-value XOR-out Check [ 'crc-64', 'Crc64', 0x1000000000000001B, REVERSE, 0x0000000000000000, 0x0000000000000000, 0x46A5A9388A5BEFFE, ], [ 'crc-64-we', 'Crc64We', 0x142F0E1EBA9EA3693, NON_REVERSE, 0x0000000000000000, 0xFFFFFFFFFFFFFFFF, 0x62EC59E3F1A4F00A, ], [ 'crc-64-jones', 'Crc64Jones', 0x1AD93D23594C935A9, REVERSE, 0xFFFFFFFFFFFFFFFF, 0x0000000000000000, 0xCAA717168609F281, ], ] def _simplify_name(name): """ Reduce CRC definition name to a simplified form: * lowercase * dashes removed * spaces removed * any initial "CRC" string removed """ name = name.lower() name = name.replace('-', '') name = name.replace(' ', '') if name.startswith('crc'): name = name[len('crc'):] return name _crc_definitions_by_name = {} _crc_definitions_by_identifier = {} _crc_definitions = [] _crc_table_headings = [ 'name', 'identifier', 'poly', 'reverse', 'init', 'xor_out', 'check' ] for table_entry in _crc_definitions_table: crc_definition = dict(zip(_crc_table_headings, table_entry)) _crc_definitions.append(crc_definition) name = _simplify_name(table_entry[0]) if name in _crc_definitions_by_name: raise Exception("Duplicate entry for '%s' in CRC table" % name) _crc_definitions_by_name[name] = crc_definition _crc_definitions_by_identifier[table_entry[1]] = crc_definition def _get_definition_by_name(crc_name): definition = _crc_definitions_by_name.get(_simplify_name(crc_name), None) if not definition: definition = _crc_definitions_by_identifier.get(crc_name, None) if not definition: raise KeyError("Unkown CRC name '%s'" % crc_name) return definition class PredefinedCrc(crcmod.Crc): def __init__(self, crc_name): definition = _get_definition_by_name(crc_name) crcmod.Crc.__init__(self, poly=definition['poly'], initCrc=definition['init'], rev=definition['reverse'], xorOut=definition['xor_out']) # crcmod.predefined.Crc is an alias for crcmod.predefined.PredefinedCrc Crc = PredefinedCrc def mkPredefinedCrcFun(crc_name): definition = _get_definition_by_name(crc_name) return crcmod.mkCrcFun(poly=definition['poly'], initCrc=definition['init'], rev=definition['reverse'], xorOut=definition['xor_out']) # crcmod.predefined.mkCrcFun is an alias for crcmod.predefined.mkPredefinedCrcFun mkCrcFun = mkPredefinedCrcFun crcmod-1.7/python2/crcmod/__init__.py0000644000175000017500000000030211411635253017167 0ustar rlbrlb00000000000000try: from crcmod.crcmod import * import crcmod.predefined except ImportError: # Make this backward compatible from crcmod import * import predefined __doc__ = crcmod.__doc__ crcmod-1.7/python2/crcmod/_crcfunpy.py0000644000175000017500000000600111411635253017422 0ustar rlbrlb00000000000000#----------------------------------------------------------------------------- # Low level CRC functions for use by crcmod. This version is implemented in # Python for a couple of reasons. 1) Provide a reference implememtation. # 2) Provide a version that can be used on systems where a C compiler is not # available for building extension modules. # # Copyright (c) 2004 Raymond L. Buvel # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. #----------------------------------------------------------------------------- def _crc8(data, crc, table): crc = crc & 0xFF for x in data: crc = table[ord(x) ^ crc] return crc def _crc8r(data, crc, table): crc = crc & 0xFF for x in data: crc = table[ord(x) ^ crc] return crc def _crc16(data, crc, table): crc = crc & 0xFFFF for x in data: crc = table[ord(x) ^ ((crc>>8) & 0xFF)] ^ ((crc << 8) & 0xFF00) return crc def _crc16r(data, crc, table): crc = crc & 0xFFFF for x in data: crc = table[ord(x) ^ (crc & 0xFF)] ^ (crc >> 8) return crc def _crc24(data, crc, table): crc = crc & 0xFFFFFF for x in data: crc = table[ord(x) ^ (int(crc>>16) & 0xFF)] ^ ((crc << 8) & 0xFFFF00) return crc def _crc24r(data, crc, table): crc = crc & 0xFFFFFF for x in data: crc = table[ord(x) ^ int(crc & 0xFF)] ^ (crc >> 8) return crc def _crc32(data, crc, table): crc = crc & 0xFFFFFFFFL for x in data: crc = table[ord(x) ^ (int(crc>>24) & 0xFF)] ^ ((crc << 8) & 0xFFFFFF00L) return crc def _crc32r(data, crc, table): crc = crc & 0xFFFFFFFFL for x in data: crc = table[ord(x) ^ int(crc & 0xFFL)] ^ (crc >> 8) return crc def _crc64(data, crc, table): crc = crc & 0xFFFFFFFFFFFFFFFFL for x in data: crc = table[ord(x) ^ (int(crc>>56) & 0xFF)] ^ ((crc << 8) & 0xFFFFFFFFFFFFFF00L) return crc def _crc64r(data, crc, table): crc = crc & 0xFFFFFFFFFFFFFFFFL for x in data: crc = table[ord(x) ^ int(crc & 0xFFL)] ^ (crc >> 8) return crc crcmod-1.7/python2/crcmod/test.py0000644000175000017500000004116311411635253016421 0ustar rlbrlb00000000000000#----------------------------------------------------------------------------- # Copyright (c) 2010 Raymond L. Buvel # Copyright (c) 2010 Craig McQueen # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. #----------------------------------------------------------------------------- '''Unit tests for crcmod functionality''' import unittest import binascii from crcmod import mkCrcFun, Crc try: from crcmod.crcmod import _usingExtension from crcmod.predefined import PredefinedCrc from crcmod.predefined import mkPredefinedCrcFun from crcmod.predefined import _crc_definitions as _predefined_crc_definitions except ImportError: from crcmod import _usingExtension from predefined import PredefinedCrc from predefined import mkPredefinedCrcFun from predefined import _crc_definitions as _predefined_crc_definitions #----------------------------------------------------------------------------- # This polynomial was chosen because it is the product of two irreducible # polynomials. # g8 = (x^7+x+1)*(x+1) g8 = 0x185 #----------------------------------------------------------------------------- # The following reproduces all of the entries in the Numerical Recipes table. # This is the standard CCITT polynomial. g16 = 0x11021 #----------------------------------------------------------------------------- g24 = 0x15D6DCB #----------------------------------------------------------------------------- # This is the standard AUTODIN-II polynomial which appears to be used in a # wide variety of standards and applications. g32 = 0x104C11DB7 #----------------------------------------------------------------------------- # I was able to locate a couple of 64-bit polynomials on the web. To make it # easier to input the representation, define a function that builds a # polynomial from a list of the bits that need to be turned on. def polyFromBits(bits): p = 0L for n in bits: p = p | (1L << n) return p # The following is from the paper "An Improved 64-bit Cyclic Redundancy Check # for Protein Sequences" by David T. Jones g64a = polyFromBits([64, 63, 61, 59, 58, 56, 55, 52, 49, 48, 47, 46, 44, 41, 37, 36, 34, 32, 31, 28, 26, 23, 22, 19, 16, 13, 12, 10, 9, 6, 4, 3, 0]) # The following is from Standard ECMA-182 "Data Interchange on 12,7 mm 48-Track # Magnetic Tape Cartridges -DLT1 Format-", December 1992. g64b = polyFromBits([64, 62, 57, 55, 54, 53, 52, 47, 46, 45, 40, 39, 38, 37, 35, 33, 32, 31, 29, 27, 24, 23, 22, 21, 19, 17, 13, 12, 10, 9, 7, 4, 1, 0]) #----------------------------------------------------------------------------- # This class is used to check the CRC calculations against a direct # implementation using polynomial division. class poly: '''Class implementing polynomials over the field of integers mod 2''' def __init__(self,p): p = long(p) if p < 0: raise ValueError('invalid polynomial') self.p = p def __long__(self): return self.p def __eq__(self,other): return self.p == other.p def __ne__(self,other): return self.p != other.p # To allow sorting of polynomials, use their long integer form for # comparison def __cmp__(self,other): return cmp(self.p, other.p) def __nonzero__(self): return self.p != 0L def __neg__(self): return self # These polynomials are their own inverse under addition def __invert__(self): n = max(self.deg() + 1, 1) x = (1L << n) - 1 return poly(self.p ^ x) def __add__(self,other): return poly(self.p ^ other.p) def __sub__(self,other): return poly(self.p ^ other.p) def __mul__(self,other): a = self.p b = other.p if a == 0 or b == 0: return poly(0) x = 0L while b: if b&1: x = x ^ a a = a<<1 b = b>>1 return poly(x) def __divmod__(self,other): u = self.p m = self.deg() v = other.p n = other.deg() if v == 0: raise ZeroDivisionError('polynomial division by zero') if n == 0: return (self,poly(0)) if m < n: return (poly(0),self) k = m-n a = 1L << m v = v << k q = 0L while k > 0: if a & u: u = u ^ v q = q | 1L q = q << 1 a = a >> 1 v = v >> 1 k -= 1 if a & u: u = u ^ v q = q | 1L return (poly(q),poly(u)) def __div__(self,other): return self.__divmod__(other)[0] def __mod__(self,other): return self.__divmod__(other)[1] def __repr__(self): return 'poly(0x%XL)' % self.p def __str__(self): p = self.p if p == 0: return '0' lst = { 0:[], 1:['1'], 2:['x'], 3:['1','x'] }[p&3] p = p>>2 n = 2 while p: if p&1: lst.append('x^%d' % n) p = p>>1 n += 1 lst.reverse() return '+'.join(lst) def deg(self): '''return the degree of the polynomial''' a = self.p if a == 0: return -1 n = 0 while a >= 0x10000L: n += 16 a = a >> 16 a = int(a) while a > 1: n += 1 a = a >> 1 return n #----------------------------------------------------------------------------- # The following functions compute the CRC using direct polynomial division. # These functions are checked against the result of the table driven # algorithms. g8p = poly(g8) x8p = poly(1L<<8) def crc8p(d): d = map(ord, d) p = 0L for i in d: p = p*256L + i p = poly(p) return long(p*x8p%g8p) g16p = poly(g16) x16p = poly(1L<<16) def crc16p(d): d = map(ord, d) p = 0L for i in d: p = p*256L + i p = poly(p) return long(p*x16p%g16p) g24p = poly(g24) x24p = poly(1L<<24) def crc24p(d): d = map(ord, d) p = 0L for i in d: p = p*256L + i p = poly(p) return long(p*x24p%g24p) g32p = poly(g32) x32p = poly(1L<<32) def crc32p(d): d = map(ord, d) p = 0L for i in d: p = p*256L + i p = poly(p) return long(p*x32p%g32p) g64ap = poly(g64a) x64p = poly(1L<<64) def crc64ap(d): d = map(ord, d) p = 0L for i in d: p = p*256L + i p = poly(p) return long(p*x64p%g64ap) g64bp = poly(g64b) def crc64bp(d): d = map(ord, d) p = 0L for i in d: p = p*256L + i p = poly(p) return long(p*x64p%g64bp) class KnownAnswerTests(unittest.TestCase): test_messages = [ 'T', 'CatMouse987654321', ] known_answers = [ [ (g8,0,0), (0xFE, 0x9D) ], [ (g8,-1,1), (0x4F, 0x9B) ], [ (g8,0,1), (0xFE, 0x62) ], [ (g16,0,0), (0x1A71, 0xE556) ], [ (g16,-1,1), (0x1B26, 0xF56E) ], [ (g16,0,1), (0x14A1, 0xC28D) ], [ (g24,0,0), (0xBCC49D, 0xC4B507) ], [ (g24,-1,1), (0x59BD0E, 0x0AAA37) ], [ (g24,0,1), (0xD52B0F, 0x1523AB) ], [ (g32,0,0), (0x6B93DDDB, 0x12DCA0F4) ], [ (g32,0xFFFFFFFFL,1), (0x41FB859FL, 0xF7B400A7L) ], [ (g32,0,1), (0x6C0695EDL, 0xC1A40EE5L) ], [ (g32,0,1,0xFFFFFFFF), (0xBE047A60L, 0x084BFF58L) ], ] def test_known_answers(self): for crcfun_params, v in self.known_answers: crcfun = mkCrcFun(*crcfun_params) self.assertEqual(crcfun('',0), 0, "Wrong answer for CRC parameters %s, input ''" % (crcfun_params,)) for i, msg in enumerate(self.test_messages): self.assertEqual(crcfun(msg), v[i], "Wrong answer for CRC parameters %s, input '%s'" % (crcfun_params,msg)) self.assertEqual(crcfun(msg[4:], crcfun(msg[:4])), v[i], "Wrong answer for CRC parameters %s, input '%s'" % (crcfun_params,msg)) self.assertEqual(crcfun(msg[-1:], crcfun(msg[:-1])), v[i], "Wrong answer for CRC parameters %s, input '%s'" % (crcfun_params,msg)) class CompareReferenceCrcTest(unittest.TestCase): test_messages = [ '', 'T', '123456789', 'CatMouse987654321', ] test_poly_crcs = [ [ (g8,0,0), crc8p ], [ (g16,0,0), crc16p ], [ (g24,0,0), crc24p ], [ (g32,0,0), crc32p ], [ (g64a,0,0), crc64ap ], [ (g64b,0,0), crc64bp ], ] @staticmethod def reference_crc32(d, crc=0): """This function modifies the return value of binascii.crc32 to be an unsigned 32-bit value. I.e. in the range 0 to 2**32-1.""" # Work around the future warning on constants. if crc > 0x7FFFFFFFL: x = int(crc & 0x7FFFFFFFL) crc = x | -2147483648 x = binascii.crc32(d,crc) return long(x) & 0xFFFFFFFFL def test_compare_crc32(self): """The binascii module has a 32-bit CRC function that is used in a wide range of applications including the checksum used in the ZIP file format. This test compares the CRC-32 implementation of this crcmod module to that of binascii.crc32.""" # The following function should produce the same result as # self.reference_crc32 which is derived from binascii.crc32. crc32 = mkCrcFun(g32,0,1,0xFFFFFFFF) for msg in self.test_messages: self.assertEqual(crc32(msg), self.reference_crc32(msg)) def test_compare_poly(self): """Compare various CRCs of this crcmod module to a pure polynomial-based implementation.""" for crcfun_params, crc_poly_fun in self.test_poly_crcs: # The following function should produce the same result as # the associated polynomial CRC function. crcfun = mkCrcFun(*crcfun_params) for msg in self.test_messages: self.assertEqual(crcfun(msg), crc_poly_fun(msg)) class CrcClassTest(unittest.TestCase): """Verify the Crc class""" msg = 'CatMouse987654321' def test_simple_crc32_class(self): """Verify the CRC class when not using xorOut""" crc = Crc(g32) str_rep = \ '''poly = 0x104C11DB7 reverse = True initCrc = 0xFFFFFFFF xorOut = 0x00000000 crcValue = 0xFFFFFFFF''' self.assertEqual(str(crc), str_rep) self.assertEqual(crc.digest(), '\xff\xff\xff\xff') self.assertEqual(crc.hexdigest(), 'FFFFFFFF') crc.update(self.msg) self.assertEqual(crc.crcValue, 0xF7B400A7L) self.assertEqual(crc.digest(), '\xf7\xb4\x00\xa7') self.assertEqual(crc.hexdigest(), 'F7B400A7') # Verify the .copy() method x = crc.copy() self.assertTrue(x is not crc) str_rep = \ '''poly = 0x104C11DB7 reverse = True initCrc = 0xFFFFFFFF xorOut = 0x00000000 crcValue = 0xF7B400A7''' self.assertEqual(str(crc), str_rep) self.assertEqual(str(x), str_rep) def test_full_crc32_class(self): """Verify the CRC class when using xorOut""" crc = Crc(g32, initCrc=0, xorOut= ~0L) str_rep = \ '''poly = 0x104C11DB7 reverse = True initCrc = 0x00000000 xorOut = 0xFFFFFFFF crcValue = 0x00000000''' self.assertEqual(str(crc), str_rep) self.assertEqual(crc.digest(), '\x00\x00\x00\x00') self.assertEqual(crc.hexdigest(), '00000000') crc.update(self.msg) self.assertEqual(crc.crcValue, 0x84BFF58L) self.assertEqual(crc.digest(), '\x08\x4b\xff\x58') self.assertEqual(crc.hexdigest(), '084BFF58') # Verify the .copy() method x = crc.copy() self.assertTrue(x is not crc) str_rep = \ '''poly = 0x104C11DB7 reverse = True initCrc = 0x00000000 xorOut = 0xFFFFFFFF crcValue = 0x084BFF58''' self.assertEqual(str(crc), str_rep) self.assertEqual(str(x), str_rep) # Verify the .new() method y = crc.new() self.assertTrue(y is not crc) self.assertTrue(y is not x) str_rep = \ '''poly = 0x104C11DB7 reverse = True initCrc = 0x00000000 xorOut = 0xFFFFFFFF crcValue = 0x00000000''' self.assertEqual(str(y), str_rep) class PredefinedCrcTest(unittest.TestCase): """Verify the predefined CRCs""" test_messages_for_known_answers = [ '', # Test cases below depend on this first entry being the empty string. 'T', 'CatMouse987654321', ] known_answers = [ [ 'crc-aug-ccitt', (0x1D0F, 0xD6ED, 0x5637) ], [ 'x-25', (0x0000, 0xE4D9, 0x0A91) ], [ 'crc-32', (0x00000000, 0xBE047A60, 0x084BFF58) ], ] def test_known_answers(self): for crcfun_name, v in self.known_answers: crcfun = mkPredefinedCrcFun(crcfun_name) self.assertEqual(crcfun('',0), 0, "Wrong answer for CRC '%s', input ''" % crcfun_name) for i, msg in enumerate(self.test_messages_for_known_answers): self.assertEqual(crcfun(msg), v[i], "Wrong answer for CRC %s, input '%s'" % (crcfun_name,msg)) self.assertEqual(crcfun(msg[4:], crcfun(msg[:4])), v[i], "Wrong answer for CRC %s, input '%s'" % (crcfun_name,msg)) self.assertEqual(crcfun(msg[-1:], crcfun(msg[:-1])), v[i], "Wrong answer for CRC %s, input '%s'" % (crcfun_name,msg)) def test_class_with_known_answers(self): for crcfun_name, v in self.known_answers: for i, msg in enumerate(self.test_messages_for_known_answers): crc1 = PredefinedCrc(crcfun_name) crc1.update(msg) self.assertEqual(crc1.crcValue, v[i], "Wrong answer for crc1 %s, input '%s'" % (crcfun_name,msg)) crc2 = crc1.new() # Check that crc1 maintains its same value, after .new() call. self.assertEqual(crc1.crcValue, v[i], "Wrong state for crc1 %s, input '%s'" % (crcfun_name,msg)) # Check that the new class instance created by .new() contains the initialisation value. # This depends on the first string in self.test_messages_for_known_answers being # the empty string. self.assertEqual(crc2.crcValue, v[0], "Wrong state for crc2 %s, input '%s'" % (crcfun_name,msg)) crc2.update(msg) # Check that crc1 maintains its same value, after crc2 has called .update() self.assertEqual(crc1.crcValue, v[i], "Wrong state for crc1 %s, input '%s'" % (crcfun_name,msg)) # Check that crc2 contains the right value after calling .update() self.assertEqual(crc2.crcValue, v[i], "Wrong state for crc2 %s, input '%s'" % (crcfun_name,msg)) def test_function_predefined_table(self): for table_entry in _predefined_crc_definitions: # Check predefined function crc_func = mkPredefinedCrcFun(table_entry['name']) calc_value = crc_func("123456789") self.assertEqual(calc_value, table_entry['check'], "Wrong answer for CRC '%s'" % table_entry['name']) def test_class_predefined_table(self): for table_entry in _predefined_crc_definitions: # Check predefined class crc1 = PredefinedCrc(table_entry['name']) crc1.update("123456789") self.assertEqual(crc1.crcValue, table_entry['check'], "Wrong answer for CRC '%s'" % table_entry['name']) def runtests(): print "Using extension:", _usingExtension print unittest.main() if __name__ == '__main__': runtests() crcmod-1.7/MANIFEST.in0000644000175000017500000000030011411635253013740 0ustar rlbrlb00000000000000include README include LICENSE include MANIFEST.in include changelog include setup.py recursive-include python2 * recursive-include python3 * recursive-include test * recursive-include docs * crcmod-1.7/changelog0000644000175000017500000000161611411635253014067 0ustar rlbrlb000000000000001.7 Enhancement Release - Jun 27, 2010 * Improve the installation process. * For Python3 don't allow unicode and require an object that supports the buffer interface. * Added Sphinx documentation. * Added LICENSE file. 1.6.1 Enhancement Release - Mar 7, 2010 Enhancements made by Craig McQueen * Code cleanup * Updated database of pre-defined CRC algorithms 1.6 Enhancement Release - Jan 24, 2010 Enhancements made by Craig McQueen * Added XOR out feature to allow creation of standard CRC algorithms * Added a database of pre-defined CRC algorithms 1.5 Enhancement Release - Mar 7, 2009 * Added Python 3.x version. * Upgraded some unit tests. 1.4 Enhancement Release - Jul 28, 2007 * Add 24-bit CRCs as one of the options. 1.3 Enhancement Release - Apr 22, 2006 * Make compatible with Python 2.5 on 64-bit platforms. * Improve the install procedure. 1.2 Initial Public Release - Jul 10, 2004 crcmod-1.7/PKG-INFO0000644000175000017500000001413011411642620013301 0ustar rlbrlb00000000000000Metadata-Version: 1.0 Name: crcmod Version: 1.7 Summary: CRC Generator Home-page: http://crcmod.sourceforge.net/ Author: Ray Buvel Author-email: rlbuvel@gmail.com License: MIT Download-URL: http://sourceforge.net/projects/crcmod Description: =========================== crcmod for Calculating CRCs =========================== The software in this package is a Python module for generating objects that compute the Cyclic Redundancy Check (CRC). There is no attempt in this package to explain how the CRC works. There are a number of resources on the web that give a good explanation of the algorithms. Just do a Google search for "crc calculation" and browse till you find what you need. Another resource can be found in chapter 20 of the book "Numerical Recipes in C" by Press et. al. This package allows the use of any 8, 16, 24, 32, or 64 bit CRC. You can generate a Python function for the selected polynomial or an instance of the Crc class which provides the same interface as the ``md5`` and ``sha`` modules from the Python standard library. A ``Crc`` class instance can also generate C/C++ source code that can be used in another application. ---------- Guidelines ---------- Documentation is available from the doc strings. It is up to you to decide what polynomials to use in your application. If someone has not specified the polynomials to use, you will need to do some research to find one suitable for your application. Examples are available in the unit test script ``test.py``. You may also use the ``predefined`` module to select one of the standard polynomials. If you need to generate code for another language, I suggest you subclass the ``Crc`` class and replace the method ``generateCode``. Use ``generateCode`` as a model for the new version. ------------ Dependencies ------------ Python Version ^^^^^^^^^^^^^^ The package has separate code to support the 2.x and 3.x Python series. For the 2.x versions of Python, these versions have been tested: * 2.4 * 2.5 * 2.6 * 2.7 It may still work on earlier versions of Python 2.x, but these have not been recently tested. For the 3.x versions of Python, these versions have been tested: * 3.1 Building C extension ^^^^^^^^^^^^^^^^^^^^ To build the C extension, the appropriate compiler tools for your platform must be installed. Refer to the Python documentation for building C extensions for details. ------------ Installation ------------ The crcmod package is installed using ``distutils``. Run the following command:: python setup.py install If the extension module builds, it will be installed. Otherwise, the installation will include the pure Python version. This will run significantly slower than the extension module but will allow the package to be used. For Windows users who want to use the mingw32 compiler, run this command:: python setup.py build --compiler=mingw32 install For Python 3.x, the install process is the same but you need to use the 3.x interpreter. ------------ Unit Testing ------------ The ``crcmod`` package has a module ``crcmod.test``, which contains unit tests for both ``crcmod`` and ``crcmod.predefined``. When you first install ``crcmod``, you should run the unit tests to make sure everything is installed properly. The test script performs a number of tests including a comparison to the direct method which uses a class implementing polynomials over the integers mod 2. To run the unit tests on Python >=2.5:: python -m crcmod.test Alternatively, in the ``test`` directory run:: python test_crcmod.py --------------- Code Generation --------------- The crcmod package is capable of generating C functions that can be compiled with a C or C++ compiler. In the test directory, there is an examples.py script that demonstrates how to use the code generator. The result of this is written out to the file ``examples.c``. The generated code was checked to make sure it compiles with the GCC compiler. ------- License ------- The ``crcmod`` package is released under the MIT license. See the ``LICENSE`` file for details. ------------ Contributors ------------ Craig McQueen Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: Intended Audience :: Education Classifier: Intended Audience :: End Users/Desktop Classifier: Intended Audience :: Information Technology Classifier: Intended Audience :: Science/Research Classifier: License :: OSI Approved :: MIT License Classifier: Operating System :: OS Independent Classifier: Programming Language :: C Classifier: Programming Language :: C++ Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.4 Classifier: Programming Language :: Python :: 2.5 Classifier: Programming Language :: Python :: 2.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.1 Classifier: Topic :: Communications Classifier: Topic :: Scientific/Engineering :: Interface Engine/Protocol Translator Classifier: Topic :: Scientific/Engineering :: Mathematics Classifier: Topic :: Utilities crcmod-1.7/python3/0000755000175000017500000000000011411642620013611 5ustar rlbrlb00000000000000crcmod-1.7/python3/src/0000755000175000017500000000000011411642620014400 5ustar rlbrlb00000000000000crcmod-1.7/python3/src/_crcfunext.c0000644000175000017500000004011011411635253016704 0ustar rlbrlb00000000000000//----------------------------------------------------------------------------- // Low level CRC functions for use by crcmod. This version is the C // implementation that corresponds to the Python module _crcfunpy. This module // will be used by crcmod if it is built for the target platform. Otherwise, // the Python module is used. // // Copyright (c) 2010 Raymond L. Buvel // Copyright (c) 2010 Craig McQueen // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- #define PY_SSIZE_T_CLEAN #include // Note: the type declarations are set up to work on 32-bit and 64-bit // platforms using the GNU C compiler. They may need to be adjusted for other // platforms. // Define a few types to make it easier to port to other platforms. typedef unsigned char UINT8; typedef unsigned short UINT16; typedef unsigned int UINT32; typedef unsigned long long UINT64; // Define some macros for the data format strings. The INPUT strings are for // decoding the input parameters to the function which are (data, crc, table). #define INPUT8 "OBs#" #define INPUT16 "OHs#" #define INPUT32 "OIs#" #define INPUT64 "OKs#" // The following macro is taken from hashlib.h in the Python 3.1 code, // providing "Common code for use by all hashlib related modules". // Given a PyObject* obj, fill in the Py_buffer* viewp with the result // of PyObject_GetBuffer. Sets an exception and issues a return NULL // on any errors. #define GET_BUFFER_VIEW_OR_ERROUT(obj, viewp) do { \ if (PyUnicode_Check((obj))) { \ PyErr_SetString(PyExc_TypeError, \ "Unicode-objects must be encoded before calculating a CRC");\ return NULL; \ } \ if (!PyObject_CheckBuffer((obj))) { \ PyErr_SetString(PyExc_TypeError, \ "object supporting the buffer API required"); \ return NULL; \ } \ if (PyObject_GetBuffer((obj), (viewp), PyBUF_SIMPLE) == -1) { \ return NULL; \ } \ if ((viewp)->ndim > 1) { \ PyErr_SetString(PyExc_BufferError, \ "Buffer must be single dimension"); \ PyBuffer_Release((viewp)); \ return NULL; \ } \ } while(0); // Define some macros that extract the specified byte from an integral value in // what should be a platform independent manner. #define BYTE0(x) ((UINT8)(x)) #define BYTE1(x) ((UINT8)((x) >> 8)) #define BYTE2(x) ((UINT8)((x) >> 16)) #define BYTE3(x) ((UINT8)((x) >> 24)) #define BYTE7(x) ((UINT8)((x) >> 56)) //----------------------------------------------------------------------------- // Compute a 8-bit crc over the input data. // Inputs: // data - string containing the data // crc - unsigned integer containing the initial crc // table - string containing the 8-bit table corresponding to the generator // polynomial. // Returns: // crc - unsigned integer containing the resulting crc static PyObject* _crc8(PyObject* self, PyObject* args) { PyObject *obj; Py_buffer buf; UINT8 crc; UINT8* data; Py_ssize_t dataLen; UINT8* table; Py_ssize_t tableLen; if (!PyArg_ParseTuple(args, INPUT8, &obj, &crc, &table, &tableLen)) { return NULL; } if (tableLen != 256) { PyErr_SetString(PyExc_ValueError, "invalid CRC table"); return NULL; } GET_BUFFER_VIEW_OR_ERROUT(obj, &buf); data = buf.buf; dataLen = buf.len; while (dataLen--) { crc = table[*data ^ crc]; data++; } PyBuffer_Release(&buf); return PyLong_FromLong((long)crc); } //----------------------------------------------------------------------------- // Compute a 8-bit crc over the input data. The data stream is bit reversed // during the computation. // Inputs: // data - string containing the data // crc - unsigned integer containing the initial crc // table - string containing the 8-bit table corresponding to the generator // polynomial. // Returns: // crc - unsigned integer containing the resulting crc static PyObject* _crc8r(PyObject* self, PyObject* args) { PyObject *obj; Py_buffer buf; UINT8 crc; UINT8* data; Py_ssize_t dataLen; UINT8* table; Py_ssize_t tableLen; if (!PyArg_ParseTuple(args, INPUT8, &obj, &crc, &table, &tableLen)) { return NULL; } if (tableLen != 256) { PyErr_SetString(PyExc_ValueError, "invalid CRC table"); return NULL; } GET_BUFFER_VIEW_OR_ERROUT(obj, &buf); data = buf.buf; dataLen = buf.len; while (dataLen--) { crc = table[*data ^ crc]; data++; } PyBuffer_Release(&buf); return PyLong_FromLong((long)crc); } //----------------------------------------------------------------------------- // Compute a 16-bit crc over the input data. // Inputs: // data - string containing the data // crc - unsigned integer containing the initial crc // table - string containing the 16-bit table corresponding to the generator // polynomial. // Returns: // crc - unsigned integer containing the resulting crc static PyObject* _crc16(PyObject* self, PyObject* args) { PyObject *obj; Py_buffer buf; UINT16 crc; UINT8* data; Py_ssize_t dataLen; UINT16* table; Py_ssize_t tableLen; if (!PyArg_ParseTuple(args, INPUT16, &obj, &crc, &table, &tableLen)) { return NULL; } if (tableLen != 256*2) { PyErr_SetString(PyExc_ValueError, "invalid CRC table"); return NULL; } GET_BUFFER_VIEW_OR_ERROUT(obj, &buf); data = buf.buf; dataLen = buf.len; while (dataLen--) { crc = table[*data ^ BYTE1(crc)] ^ (crc << 8); data++; } PyBuffer_Release(&buf); return PyLong_FromLong((long)crc); } //----------------------------------------------------------------------------- // Compute a 16-bit crc over the input data. The data stream is bit reversed // during the computation. // Inputs: // data - string containing the data // crc - unsigned integer containing the initial crc // table - string containing the 16-bit table corresponding to the generator // polynomial. // Returns: // crc - unsigned integer containing the resulting crc static PyObject* _crc16r(PyObject* self, PyObject* args) { PyObject *obj; Py_buffer buf; UINT16 crc; UINT8* data; Py_ssize_t dataLen; UINT16* table; Py_ssize_t tableLen; if (!PyArg_ParseTuple(args, INPUT16, &obj, &crc, &table, &tableLen)) { return NULL; } if (tableLen != 256*2) { PyErr_SetString(PyExc_ValueError, "invalid CRC table"); return NULL; } GET_BUFFER_VIEW_OR_ERROUT(obj, &buf); data = buf.buf; dataLen = buf.len; while (dataLen--) { crc = table[*data ^ BYTE0(crc)] ^ (crc >> 8); data++; } PyBuffer_Release(&buf); return PyLong_FromLong((long)crc); } //----------------------------------------------------------------------------- // Compute a 24-bit crc over the input data. // Inputs: // data - string containing the data // crc - unsigned integer containing the initial crc // table - string containing the 24-bit table corresponding to the generator // polynomial. // Returns: // crc - unsigned integer containing the resulting crc static PyObject* _crc24(PyObject* self, PyObject* args) { PyObject *obj; Py_buffer buf; UINT32 crc; UINT8* data; Py_ssize_t dataLen; UINT32* table; Py_ssize_t tableLen; if (!PyArg_ParseTuple(args, INPUT32, &obj, &crc, &table, &tableLen)) { return NULL; } if (tableLen != 256*4) { PyErr_SetString(PyExc_ValueError, "invalid CRC table"); return NULL; } GET_BUFFER_VIEW_OR_ERROUT(obj, &buf); data = buf.buf; dataLen = buf.len; while (dataLen--) { crc = table[*data ^ BYTE2(crc)] ^ (crc << 8); data++; } PyBuffer_Release(&buf); return PyLong_FromLong((long)(crc & 0xFFFFFFU)); } //----------------------------------------------------------------------------- // Compute a 24-bit crc over the input data. The data stream is bit reversed // during the computation. // Inputs: // data - string containing the data // crc - unsigned integer containing the initial crc // table - string containing the 24-bit table corresponding to the generator // polynomial. // Returns: // crc - unsigned integer containing the resulting crc static PyObject* _crc24r(PyObject* self, PyObject* args) { PyObject *obj; Py_buffer buf; UINT32 crc; UINT8* data; Py_ssize_t dataLen; UINT32* table; Py_ssize_t tableLen; if (!PyArg_ParseTuple(args, INPUT32, &obj, &crc, &table, &tableLen)) { return NULL; } if (tableLen != 256*4) { PyErr_SetString(PyExc_ValueError, "invalid CRC table"); return NULL; } GET_BUFFER_VIEW_OR_ERROUT(obj, &buf); data = buf.buf; dataLen = buf.len; crc = crc & 0xFFFFFFU; while (dataLen--) { crc = table[*data ^ BYTE0(crc)] ^ (crc >> 8); data++; } PyBuffer_Release(&buf); return PyLong_FromLong((long)crc); } //----------------------------------------------------------------------------- // Compute a 32-bit crc over the input data. // Inputs: // data - string containing the data // crc - unsigned integer containing the initial crc // table - string containing the 32-bit table corresponding to the generator // polynomial. // Returns: // crc - unsigned integer containing the resulting crc static PyObject* _crc32(PyObject* self, PyObject* args) { PyObject *obj; Py_buffer buf; UINT32 crc; UINT8* data; Py_ssize_t dataLen; UINT32* table; Py_ssize_t tableLen; if (!PyArg_ParseTuple(args, INPUT32, &obj, &crc, &table, &tableLen)) { return NULL; } if (tableLen != 256*4) { PyErr_SetString(PyExc_ValueError, "invalid CRC table"); return NULL; } GET_BUFFER_VIEW_OR_ERROUT(obj, &buf); data = buf.buf; dataLen = buf.len; while (dataLen--) { crc = table[*data ^ BYTE3(crc)] ^ (crc << 8); data++; } PyBuffer_Release(&buf); return PyLong_FromUnsignedLong(crc); } //----------------------------------------------------------------------------- // Compute a 32-bit crc over the input data. The data stream is bit reversed // during the computation. // Inputs: // data - string containing the data // crc - unsigned integer containing the initial crc // table - string containing the 32-bit table corresponding to the generator // polynomial. // Returns: // crc - unsigned integer containing the resulting crc static PyObject* _crc32r(PyObject* self, PyObject* args) { PyObject *obj; Py_buffer buf; UINT32 crc; UINT8* data; Py_ssize_t dataLen; UINT32* table; Py_ssize_t tableLen; if (!PyArg_ParseTuple(args, INPUT32, &obj, &crc, &table, &tableLen)) { return NULL; } if (tableLen != 256*4) { PyErr_SetString(PyExc_ValueError, "invalid CRC table"); return NULL; } GET_BUFFER_VIEW_OR_ERROUT(obj, &buf); data = buf.buf; dataLen = buf.len; while (dataLen--) { crc = table[*data ^ BYTE0(crc)] ^ (crc >> 8); data++; } PyBuffer_Release(&buf); return PyLong_FromUnsignedLong(crc); } //----------------------------------------------------------------------------- // Compute a 64-bit crc over the input data. // Inputs: // data - string containing the data // crc - unsigned integer containing the initial crc // table - string containing the 64-bit table corresponding to the generator // polynomial. // Returns: // crc - unsigned integer containing the resulting crc static PyObject* _crc64(PyObject* self, PyObject* args) { PyObject *obj; Py_buffer buf; UINT64 crc; UINT8* data; Py_ssize_t dataLen; UINT64* table; Py_ssize_t tableLen; if (!PyArg_ParseTuple(args, INPUT64, &obj, &crc, &table, &tableLen)) { return NULL; } if (tableLen != 256*8) { PyErr_SetString(PyExc_ValueError, "invalid CRC table"); return NULL; } GET_BUFFER_VIEW_OR_ERROUT(obj, &buf); data = buf.buf; dataLen = buf.len; while (dataLen--) { crc = table[*data ^ BYTE7(crc)] ^ (crc << 8); data++; } PyBuffer_Release(&buf); return PyLong_FromUnsignedLongLong(crc); } //----------------------------------------------------------------------------- // Compute a 64-bit crc over the input data. The data stream is bit reversed // during the computation. // Inputs: // data - string containing the data // crc - unsigned integer containing the initial crc // table - string containing the 64-bit table corresponding to the generator // polynomial. // Returns: // crc - unsigned integer containing the resulting crc static PyObject* _crc64r(PyObject* self, PyObject* args) { PyObject *obj; Py_buffer buf; UINT64 crc; UINT8* data; Py_ssize_t dataLen; UINT64* table; Py_ssize_t tableLen; if (!PyArg_ParseTuple(args, INPUT64, &obj, &crc, &table, &tableLen)) { return NULL; } if (tableLen != 256*8) { PyErr_SetString(PyExc_ValueError, "invalid CRC table"); return NULL; } GET_BUFFER_VIEW_OR_ERROUT(obj, &buf); data = buf.buf; dataLen = buf.len; while (dataLen--) { crc = table[*data ^ BYTE0(crc)] ^ (crc >> 8); data++; } PyBuffer_Release(&buf); return PyLong_FromUnsignedLongLong(crc); } //----------------------------------------------------------------------------- static PyMethodDef methodTable[] = { {"_crc8", _crc8, METH_VARARGS}, {"_crc8r", _crc8r, METH_VARARGS}, {"_crc16", _crc16, METH_VARARGS}, {"_crc16r", _crc16r, METH_VARARGS}, {"_crc24", _crc24, METH_VARARGS}, {"_crc24r", _crc24r, METH_VARARGS}, {"_crc32", _crc32, METH_VARARGS}, {"_crc32r", _crc32r, METH_VARARGS}, {"_crc64", _crc64, METH_VARARGS}, {"_crc64r", _crc64r, METH_VARARGS}, {NULL, NULL} }; //----------------------------------------------------------------------------- static struct PyModuleDef moduleDef = { PyModuleDef_HEAD_INIT, "_crcfunext", // name of module NULL, // module documentation, may be NULL -1, // size of per-interpreter state of the module, // or -1 if the module keeps state in global variables. methodTable }; //----------------------------------------------------------------------------- PyMODINIT_FUNC PyInit__crcfunext(void) { if ((sizeof(UINT8) != 1) || (sizeof(UINT16) != 2) || (sizeof(UINT32) != 4) || (sizeof(UINT64) != 8)) { Py_FatalError("crcfunext: One of the data types is invalid"); } return PyModule_Create(&moduleDef); } crcmod-1.7/python3/crcmod/0000755000175000017500000000000011411642620015060 5ustar rlbrlb00000000000000crcmod-1.7/python3/crcmod/crcmod.py0000644000175000017500000004034211411635253016710 0ustar rlbrlb00000000000000#----------------------------------------------------------------------------- # Copyright (c) 2010 Raymond L. Buvel # Copyright (c) 2010 Craig McQueen # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. #----------------------------------------------------------------------------- '''crcmod is a Python module for gererating objects that compute the Cyclic Redundancy Check. Any 8, 16, 24, 32, or 64 bit polynomial can be used. The following are the public components of this module. Crc -- a class that creates instances providing the same interface as the algorithms in the hashlib module in the Python standard library. These instances also provide a method for generating a C/C++ function to compute the CRC. mkCrcFun -- create a Python function to compute the CRC using the specified polynomial and initial value. This provides a much simpler interface if all you need is a function for CRC calculation. ''' __all__ = '''mkCrcFun Crc '''.split() # Select the appropriate set of low-level CRC functions for this installation. # If the extension module was not built, drop back to the Python implementation # even though it is significantly slower. try: import crcmod._crcfunext as _crcfun _usingExtension = True except ImportError: import crcmod._crcfunpy as _crcfun _usingExtension = False import sys, struct #----------------------------------------------------------------------------- class Crc: '''Compute a Cyclic Redundancy Check (CRC) using the specified polynomial. Instances of this class have the same interface as the algorithms in the hashlib module in the Python standard library. See the documentation of this module for examples of how to use a Crc instance. The string representation of a Crc instance identifies the polynomial, initial value, XOR out value, and the current CRC value. The print statement can be used to output this information. If you need to generate a C/C++ function for use in another application, use the generateCode method. If you need to generate code for another language, subclass Crc and override the generateCode method. The following are the parameters supplied to the constructor. poly -- The generator polynomial to use in calculating the CRC. The value is specified as a Python integer. The bits in this integer are the coefficients of the polynomial. The only polynomials allowed are those that generate 8, 16, 24, 32, or 64 bit CRCs. initCrc -- Initial value used to start the CRC calculation. This initial value should be the initial shift register value XORed with the final XOR value. That is equivalent to the CRC result the algorithm should return for a zero-length string. Defaults to all bits set because that starting value will take leading zero bytes into account. Starting with zero will ignore all leading zero bytes. rev -- A flag that selects a bit reversed algorithm when True. Defaults to True because the bit reversed algorithms are more efficient. xorOut -- Final value to XOR with the calculated CRC value. Used by some CRC algorithms. Defaults to zero. ''' def __init__(self, poly, initCrc=~0, rev=True, xorOut=0, initialize=True): if not initialize: # Don't want to perform the initialization when using new or copy # to create a new instance. return (sizeBits, initCrc, xorOut) = _verifyParams(poly, initCrc, xorOut) self.digest_size = sizeBits//8 self.initCrc = initCrc self.xorOut = xorOut self.poly = poly self.reverse = rev (crcfun, table) = _mkCrcFun(poly, sizeBits, initCrc, rev, xorOut) self._crc = crcfun self.table = table self.crcValue = self.initCrc def __str__(self): lst = [] lst.append('poly = 0x%X' % self.poly) lst.append('reverse = %s' % self.reverse) fmt = '0x%%0%dX' % (self.digest_size*2) lst.append('initCrc = %s' % (fmt % self.initCrc)) lst.append('xorOut = %s' % (fmt % self.xorOut)) lst.append('crcValue = %s' % (fmt % self.crcValue)) return '\n'.join(lst) def new(self, arg=None): '''Create a new instance of the Crc class initialized to the same values as the original instance. The current CRC is set to the initial value. If a string is provided in the optional arg parameter, it is passed to the update method. ''' n = Crc(poly=None, initialize=False) n._crc = self._crc n.digest_size = self.digest_size n.initCrc = self.initCrc n.xorOut = self.xorOut n.table = self.table n.crcValue = self.initCrc n.reverse = self.reverse n.poly = self.poly if arg is not None: n.update(arg) return n def copy(self): '''Create a new instance of the Crc class initialized to the same values as the original instance. The current CRC is set to the current value. This allows multiple CRC calculations using a common initial string. ''' c = self.new() c.crcValue = self.crcValue return c def update(self, data): '''Update the current CRC value using the string specified as the data parameter. ''' self.crcValue = self._crc(data, self.crcValue) def digest(self): '''Return the current CRC value as a string of bytes. The length of this string is specified in the digest_size attribute. ''' n = self.digest_size crc = self.crcValue lst = [] while n > 0: lst.append(crc & 0xFF) crc = crc >> 8 n -= 1 lst.reverse() return bytes(lst) def hexdigest(self): '''Return the current CRC value as a string of hex digits. The length of this string is twice the digest_size attribute. ''' n = self.digest_size crc = self.crcValue lst = [] while n > 0: lst.append('%02X' % (crc & 0xFF)) crc = crc >> 8 n -= 1 lst.reverse() return ''.join(lst) def generateCode(self, functionName, out, dataType=None, crcType=None): '''Generate a C/C++ function. functionName -- String specifying the name of the function. out -- An open file-like object with a write method. This specifies where the generated code is written. dataType -- An optional parameter specifying the data type of the input data to the function. Defaults to UINT8. crcType -- An optional parameter specifying the data type of the CRC value. Defaults to one of UINT8, UINT16, UINT32, or UINT64 depending on the size of the CRC value. ''' if dataType is None: dataType = 'UINT8' if crcType is None: size = 8*self.digest_size if size == 24: size = 32 crcType = 'UINT%d' % size if self.digest_size == 1: # Both 8-bit CRC algorithms are the same crcAlgor = 'table[*data ^ (%s)crc]' elif self.reverse: # The bit reverse algorithms are all the same except for the data # type of the crc variable which is specified elsewhere. crcAlgor = 'table[*data ^ (%s)crc] ^ (crc >> 8)' else: # The forward CRC algorithms larger than 8 bits have an extra shift # operation to get the high byte. shift = 8*(self.digest_size - 1) crcAlgor = 'table[*data ^ (%%s)(crc >> %d)] ^ (crc << 8)' % shift fmt = '0x%%0%dX' % (2*self.digest_size) if self.digest_size <= 4: fmt = fmt + 'U,' else: # Need the long long type identifier to keep gcc from complaining. fmt = fmt + 'ULL,' # Select the number of entries per row in the output code. n = {1:8, 2:8, 3:4, 4:4, 8:2}[self.digest_size] lst = [] for i, val in enumerate(self.table): if (i % n) == 0: lst.append('\n ') lst.append(fmt % val) poly = 'polynomial: 0x%X' % self.poly if self.reverse: poly = poly + ', bit reverse algorithm' if self.xorOut: # Need to remove the comma from the format. preCondition = '\n crc = crc ^ %s;' % (fmt[:-1] % self.xorOut) postCondition = preCondition else: preCondition = '' postCondition = '' if self.digest_size == 3: # The 24-bit CRC needs to be conditioned so that only 24-bits are # used from the 32-bit variable. if self.reverse: preCondition += '\n crc = crc & 0xFFFFFFU;' else: postCondition += '\n crc = crc & 0xFFFFFFU;' parms = { 'dataType' : dataType, 'crcType' : crcType, 'name' : functionName, 'crcAlgor' : crcAlgor % dataType, 'crcTable' : ''.join(lst), 'poly' : poly, 'preCondition' : preCondition, 'postCondition' : postCondition, } out.write(_codeTemplate % parms) #----------------------------------------------------------------------------- def mkCrcFun(poly, initCrc=~0, rev=True, xorOut=0): '''Return a function that computes the CRC using the specified polynomial. poly -- integer representation of the generator polynomial initCrc -- default initial CRC value rev -- when true, indicates that the data is processed bit reversed. xorOut -- the final XOR value The returned function has the following user interface def crcfun(data, crc=initCrc): ''' # First we must verify the params (sizeBits, initCrc, xorOut) = _verifyParams(poly, initCrc, xorOut) # Make the function (and table), return the function return _mkCrcFun(poly, sizeBits, initCrc, rev, xorOut)[0] #----------------------------------------------------------------------------- # Naming convention: # All function names ending with r are bit reverse variants of the ones # without the r. #----------------------------------------------------------------------------- # Check the polynomial to make sure that it is acceptable and return the number # of bits in the CRC. def _verifyPoly(poly): msg = 'The degree of the polynomial must be 8, 16, 24, 32 or 64' for n in (8,16,24,32,64): low = 1<> 1 return y #----------------------------------------------------------------------------- # The following functions compute the CRC for a single byte. These are used # to build up the tables needed in the CRC algorithm. Assumes the high order # bit of the polynomial has been stripped off. def _bytecrc(crc, poly, n): mask = 1<<(n-1) for i in range(8): if crc & mask: crc = (crc << 1) ^ poly else: crc = crc << 1 mask = (1<> 1) ^ poly else: crc = crc >> 1 mask = (1< 0) { crc = %(crcAlgor)s; data++; len--; }%(postCondition)s return crc; } ''' crcmod-1.7/python3/crcmod/predefined.py0000644000175000017500000002260611411635253017551 0ustar rlbrlb00000000000000#----------------------------------------------------------------------------- # Copyright (c) 2010 Craig McQueen # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. #----------------------------------------------------------------------------- ''' crcmod.predefined defines some well-known CRC algorithms. To use it, e.g.: import crcmod.predefined crc32func = crcmod.predefined.mkPredefinedCrcFun("crc-32") crc32class = crcmod.predefined.PredefinedCrc("crc-32") crcmod.predefined.Crc is an alias for crcmod.predefined.PredefinedCrc But if doing 'from crc.predefined import *', only PredefinedCrc is imported. ''' # local imports import crcmod __all__ = [ 'PredefinedCrc', 'mkPredefinedCrcFun', ] REVERSE = True NON_REVERSE = False # The following table defines the parameters of well-known CRC algorithms. # The "Check" value is the CRC for the ASCII byte sequence b"123456789". It # can be used for unit tests. _crc_definitions_table = [ # Name Identifier-name, Poly Reverse Init-value XOR-out Check [ 'crc-8', 'Crc8', 0x107, NON_REVERSE, 0x00, 0x00, 0xF4, ], [ 'crc-8-darc', 'Crc8Darc', 0x139, REVERSE, 0x00, 0x00, 0x15, ], [ 'crc-8-i-code', 'Crc8ICode', 0x11D, NON_REVERSE, 0xFD, 0x00, 0x7E, ], [ 'crc-8-itu', 'Crc8Itu', 0x107, NON_REVERSE, 0x55, 0x55, 0xA1, ], [ 'crc-8-maxim', 'Crc8Maxim', 0x131, REVERSE, 0x00, 0x00, 0xA1, ], [ 'crc-8-rohc', 'Crc8Rohc', 0x107, REVERSE, 0xFF, 0x00, 0xD0, ], [ 'crc-8-wcdma', 'Crc8Wcdma', 0x19B, REVERSE, 0x00, 0x00, 0x25, ], [ 'crc-16', 'Crc16', 0x18005, REVERSE, 0x0000, 0x0000, 0xBB3D, ], [ 'crc-16-buypass', 'Crc16Buypass', 0x18005, NON_REVERSE, 0x0000, 0x0000, 0xFEE8, ], [ 'crc-16-dds-110', 'Crc16Dds110', 0x18005, NON_REVERSE, 0x800D, 0x0000, 0x9ECF, ], [ 'crc-16-dect', 'Crc16Dect', 0x10589, NON_REVERSE, 0x0001, 0x0001, 0x007E, ], [ 'crc-16-dnp', 'Crc16Dnp', 0x13D65, REVERSE, 0xFFFF, 0xFFFF, 0xEA82, ], [ 'crc-16-en-13757', 'Crc16En13757', 0x13D65, NON_REVERSE, 0xFFFF, 0xFFFF, 0xC2B7, ], [ 'crc-16-genibus', 'Crc16Genibus', 0x11021, NON_REVERSE, 0x0000, 0xFFFF, 0xD64E, ], [ 'crc-16-maxim', 'Crc16Maxim', 0x18005, REVERSE, 0xFFFF, 0xFFFF, 0x44C2, ], [ 'crc-16-mcrf4xx', 'Crc16Mcrf4xx', 0x11021, REVERSE, 0xFFFF, 0x0000, 0x6F91, ], [ 'crc-16-riello', 'Crc16Riello', 0x11021, REVERSE, 0x554D, 0x0000, 0x63D0, ], [ 'crc-16-t10-dif', 'Crc16T10Dif', 0x18BB7, NON_REVERSE, 0x0000, 0x0000, 0xD0DB, ], [ 'crc-16-teledisk', 'Crc16Teledisk', 0x1A097, NON_REVERSE, 0x0000, 0x0000, 0x0FB3, ], [ 'crc-16-usb', 'Crc16Usb', 0x18005, REVERSE, 0x0000, 0xFFFF, 0xB4C8, ], [ 'x-25', 'CrcX25', 0x11021, REVERSE, 0x0000, 0xFFFF, 0x906E, ], [ 'xmodem', 'CrcXmodem', 0x11021, NON_REVERSE, 0x0000, 0x0000, 0x31C3, ], [ 'modbus', 'CrcModbus', 0x18005, REVERSE, 0xFFFF, 0x0000, 0x4B37, ], # Note definitions of CCITT are disputable. See: # http://homepages.tesco.net/~rainstorm/crc-catalogue.htm # http://web.archive.org/web/20071229021252/http://www.joegeluso.com/software/articles/ccitt.htm [ 'kermit', 'CrcKermit', 0x11021, REVERSE, 0x0000, 0x0000, 0x2189, ], [ 'crc-ccitt-false', 'CrcCcittFalse', 0x11021, NON_REVERSE, 0xFFFF, 0x0000, 0x29B1, ], [ 'crc-aug-ccitt', 'CrcAugCcitt', 0x11021, NON_REVERSE, 0x1D0F, 0x0000, 0xE5CC, ], [ 'crc-24', 'Crc24', 0x1864CFB, NON_REVERSE, 0xB704CE, 0x000000, 0x21CF02, ], [ 'crc-24-flexray-a', 'Crc24FlexrayA', 0x15D6DCB, NON_REVERSE, 0xFEDCBA, 0x000000, 0x7979BD, ], [ 'crc-24-flexray-b', 'Crc24FlexrayB', 0x15D6DCB, NON_REVERSE, 0xABCDEF, 0x000000, 0x1F23B8, ], [ 'crc-32', 'Crc32', 0x104C11DB7, REVERSE, 0x00000000, 0xFFFFFFFF, 0xCBF43926, ], [ 'crc-32-bzip2', 'Crc32Bzip2', 0x104C11DB7, NON_REVERSE, 0x00000000, 0xFFFFFFFF, 0xFC891918, ], [ 'crc-32c', 'Crc32C', 0x11EDC6F41, REVERSE, 0x00000000, 0xFFFFFFFF, 0xE3069283, ], [ 'crc-32d', 'Crc32D', 0x1A833982B, REVERSE, 0x00000000, 0xFFFFFFFF, 0x87315576, ], [ 'crc-32-mpeg', 'Crc32Mpeg', 0x104C11DB7, NON_REVERSE, 0xFFFFFFFF, 0x00000000, 0x0376E6E7, ], [ 'posix', 'CrcPosix', 0x104C11DB7, NON_REVERSE, 0xFFFFFFFF, 0xFFFFFFFF, 0x765E7680, ], [ 'crc-32q', 'Crc32Q', 0x1814141AB, NON_REVERSE, 0x00000000, 0x00000000, 0x3010BF7F, ], [ 'jamcrc', 'CrcJamCrc', 0x104C11DB7, REVERSE, 0xFFFFFFFF, 0x00000000, 0x340BC6D9, ], [ 'xfer', 'CrcXfer', 0x1000000AF, NON_REVERSE, 0x00000000, 0x00000000, 0xBD0BE338, ], # 64-bit # Name Identifier-name, Poly Reverse Init-value XOR-out Check [ 'crc-64', 'Crc64', 0x1000000000000001B, REVERSE, 0x0000000000000000, 0x0000000000000000, 0x46A5A9388A5BEFFE, ], [ 'crc-64-we', 'Crc64We', 0x142F0E1EBA9EA3693, NON_REVERSE, 0x0000000000000000, 0xFFFFFFFFFFFFFFFF, 0x62EC59E3F1A4F00A, ], [ 'crc-64-jones', 'Crc64Jones', 0x1AD93D23594C935A9, REVERSE, 0xFFFFFFFFFFFFFFFF, 0x0000000000000000, 0xCAA717168609F281, ], ] def _simplify_name(name): """ Reduce CRC definition name to a simplified form: * lowercase * dashes removed * spaces removed * any initial "CRC" string removed """ name = name.lower() name = name.replace('-', '') name = name.replace(' ', '') if name.startswith('crc'): name = name[len('crc'):] return name _crc_definitions_by_name = {} _crc_definitions_by_identifier = {} _crc_definitions = [] _crc_table_headings = [ 'name', 'identifier', 'poly', 'reverse', 'init', 'xor_out', 'check' ] for table_entry in _crc_definitions_table: crc_definition = dict(zip(_crc_table_headings, table_entry)) _crc_definitions.append(crc_definition) name = _simplify_name(table_entry[0]) if name in _crc_definitions_by_name: raise Exception("Duplicate entry for '{0}' in CRC table".format(name)) _crc_definitions_by_name[name] = crc_definition _crc_definitions_by_identifier[table_entry[1]] = crc_definition def _get_definition_by_name(crc_name): definition = _crc_definitions_by_name.get(_simplify_name(crc_name), None) if not definition: definition = _crc_definitions_by_identifier.get(crc_name, None) if not definition: raise KeyError("Unkown CRC name '{0}'".format(crc_name)) return definition class PredefinedCrc(crcmod.Crc): def __init__(self, crc_name): definition = _get_definition_by_name(crc_name) super().__init__(poly=definition['poly'], initCrc=definition['init'], rev=definition['reverse'], xorOut=definition['xor_out']) # crcmod.predefined.Crc is an alias for crcmod.predefined.PredefinedCrc Crc = PredefinedCrc def mkPredefinedCrcFun(crc_name): definition = _get_definition_by_name(crc_name) return crcmod.mkCrcFun(poly=definition['poly'], initCrc=definition['init'], rev=definition['reverse'], xorOut=definition['xor_out']) # crcmod.predefined.mkCrcFun is an alias for crcmod.predefined.mkPredefinedCrcFun mkCrcFun = mkPredefinedCrcFun crcmod-1.7/python3/crcmod/__init__.py0000644000175000017500000000030211411635253017170 0ustar rlbrlb00000000000000try: from crcmod.crcmod import * import crcmod.predefined except ImportError: # Make this backward compatible from crcmod import * import predefined __doc__ = crcmod.__doc__ crcmod-1.7/python3/crcmod/_crcfunpy.py0000644000175000017500000000716611411635253017440 0ustar rlbrlb00000000000000#----------------------------------------------------------------------------- # Low level CRC functions for use by crcmod. This version is implemented in # Python for a couple of reasons. 1) Provide a reference implememtation. # 2) Provide a version that can be used on systems where a C compiler is not # available for building extension modules. # # Copyright (c) 2009 Raymond L. Buvel # Copyright (c) 2010 Craig McQueen # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. #----------------------------------------------------------------------------- def _get_buffer_view(in_obj): if isinstance(in_obj, str): raise TypeError('Unicode-objects must be encoded before calculating a CRC') mv = memoryview(in_obj) if mv.ndim > 1: raise BufferError('Buffer must be single dimension') return mv def _crc8(data, crc, table): mv = _get_buffer_view(data) crc = crc & 0xFF for x in mv.tobytes(): crc = table[x ^ crc] return crc def _crc8r(data, crc, table): mv = _get_buffer_view(data) crc = crc & 0xFF for x in mv.tobytes(): crc = table[x ^ crc] return crc def _crc16(data, crc, table): mv = _get_buffer_view(data) crc = crc & 0xFFFF for x in mv.tobytes(): crc = table[x ^ ((crc>>8) & 0xFF)] ^ ((crc << 8) & 0xFF00) return crc def _crc16r(data, crc, table): mv = _get_buffer_view(data) crc = crc & 0xFFFF for x in mv.tobytes(): crc = table[x ^ (crc & 0xFF)] ^ (crc >> 8) return crc def _crc24(data, crc, table): mv = _get_buffer_view(data) crc = crc & 0xFFFFFF for x in mv.tobytes(): crc = table[x ^ (crc>>16 & 0xFF)] ^ ((crc << 8) & 0xFFFF00) return crc def _crc24r(data, crc, table): mv = _get_buffer_view(data) crc = crc & 0xFFFFFF for x in mv.tobytes(): crc = table[x ^ (crc & 0xFF)] ^ (crc >> 8) return crc def _crc32(data, crc, table): mv = _get_buffer_view(data) crc = crc & 0xFFFFFFFF for x in mv.tobytes(): crc = table[x ^ ((crc>>24) & 0xFF)] ^ ((crc << 8) & 0xFFFFFF00) return crc def _crc32r(data, crc, table): mv = _get_buffer_view(data) crc = crc & 0xFFFFFFFF for x in mv.tobytes(): crc = table[x ^ (crc & 0xFF)] ^ (crc >> 8) return crc def _crc64(data, crc, table): mv = _get_buffer_view(data) crc = crc & 0xFFFFFFFFFFFFFFFF for x in mv.tobytes(): crc = table[x ^ ((crc>>56) & 0xFF)] ^ ((crc << 8) & 0xFFFFFFFFFFFFFF00) return crc def _crc64r(data, crc, table): mv = _get_buffer_view(data) crc = crc & 0xFFFFFFFFFFFFFFFF for x in mv.tobytes(): crc = table[x ^ (crc & 0xFF)] ^ (crc >> 8) return crc crcmod-1.7/python3/crcmod/test.py0000644000175000017500000004400111411635253016414 0ustar rlbrlb00000000000000#----------------------------------------------------------------------------- # Copyright (c) 2010 Raymond L. Buvel # Copyright (c) 2010 Craig McQueen # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. #----------------------------------------------------------------------------- '''Unit tests for crcmod functionality''' import unittest from array import array import binascii from .crcmod import mkCrcFun, Crc from .crcmod import _usingExtension from .predefined import PredefinedCrc from .predefined import mkPredefinedCrcFun from .predefined import _crc_definitions as _predefined_crc_definitions #----------------------------------------------------------------------------- # This polynomial was chosen because it is the product of two irreducible # polynomials. # g8 = (x^7+x+1)*(x+1) g8 = 0x185 #----------------------------------------------------------------------------- # The following reproduces all of the entries in the Numerical Recipes table. # This is the standard CCITT polynomial. g16 = 0x11021 #----------------------------------------------------------------------------- g24 = 0x15D6DCB #----------------------------------------------------------------------------- # This is the standard AUTODIN-II polynomial which appears to be used in a # wide variety of standards and applications. g32 = 0x104C11DB7 #----------------------------------------------------------------------------- # I was able to locate a couple of 64-bit polynomials on the web. To make it # easier to input the representation, define a function that builds a # polynomial from a list of the bits that need to be turned on. def polyFromBits(bits): p = 0 for n in bits: p = p | (1 << n) return p # The following is from the paper "An Improved 64-bit Cyclic Redundancy Check # for Protein Sequences" by David T. Jones g64a = polyFromBits([64, 63, 61, 59, 58, 56, 55, 52, 49, 48, 47, 46, 44, 41, 37, 36, 34, 32, 31, 28, 26, 23, 22, 19, 16, 13, 12, 10, 9, 6, 4, 3, 0]) # The following is from Standard ECMA-182 "Data Interchange on 12,7 mm 48-Track # Magnetic Tape Cartridges -DLT1 Format-", December 1992. g64b = polyFromBits([64, 62, 57, 55, 54, 53, 52, 47, 46, 45, 40, 39, 38, 37, 35, 33, 32, 31, 29, 27, 24, 23, 22, 21, 19, 17, 13, 12, 10, 9, 7, 4, 1, 0]) #----------------------------------------------------------------------------- # This class is used to check the CRC calculations against a direct # implementation using polynomial division. class poly: '''Class implementing polynomials over the field of integers mod 2''' def __init__(self,p): p = int(p) if p < 0: raise ValueError('invalid polynomial') self.p = p def __int__(self): return self.p def __eq__(self,other): return self.p == other.p def __ne__(self,other): return self.p != other.p # To allow sorting of polynomials, use their long integer form for # comparison def __cmp__(self,other): return cmp(self.p, other.p) def __bool__(self): return self.p != 0 def __neg__(self): return self # These polynomials are their own inverse under addition def __invert__(self): n = max(self.deg() + 1, 1) x = (1 << n) - 1 return poly(self.p ^ x) def __add__(self,other): return poly(self.p ^ other.p) def __sub__(self,other): return poly(self.p ^ other.p) def __mul__(self,other): a = self.p b = other.p if a == 0 or b == 0: return poly(0) x = 0 while b: if b&1: x = x ^ a a = a<<1 b = b>>1 return poly(x) def __divmod__(self,other): u = self.p m = self.deg() v = other.p n = other.deg() if v == 0: raise ZeroDivisionError('polynomial division by zero') if n == 0: return (self,poly(0)) if m < n: return (poly(0),self) k = m-n a = 1 << m v = v << k q = 0 while k > 0: if a & u: u = u ^ v q = q | 1 q = q << 1 a = a >> 1 v = v >> 1 k -= 1 if a & u: u = u ^ v q = q | 1 return (poly(q),poly(u)) def __div__(self,other): return self.__divmod__(other)[0] def __mod__(self,other): return self.__divmod__(other)[1] def __repr__(self): return 'poly(0x%XL)' % self.p def __str__(self): p = self.p if p == 0: return '0' lst = { 0:[], 1:['1'], 2:['x'], 3:['1','x'] }[p&3] p = p>>2 n = 2 while p: if p&1: lst.append('x^%d' % n) p = p>>1 n += 1 lst.reverse() return '+'.join(lst) def deg(self): '''return the degree of the polynomial''' a = self.p if a == 0: return -1 n = 0 while a >= 0x10000: n += 16 a = a >> 16 a = int(a) while a > 1: n += 1 a = a >> 1 return n #----------------------------------------------------------------------------- # The following functions compute the CRC using direct polynomial division. # These functions are checked against the result of the table driven # algorithms. g8p = poly(g8) x8p = poly(1<<8) def crc8p(d): p = 0 for i in d: p = p*256 + i p = poly(p) return int(p*x8p%g8p) g16p = poly(g16) x16p = poly(1<<16) def crc16p(d): p = 0 for i in d: p = p*256 + i p = poly(p) return int(p*x16p%g16p) g24p = poly(g24) x24p = poly(1<<24) def crc24p(d): p = 0 for i in d: p = p*256 + i p = poly(p) return int(p*x24p%g24p) g32p = poly(g32) x32p = poly(1<<32) def crc32p(d): p = 0 for i in d: p = p*256 + i p = poly(p) return int(p*x32p%g32p) g64ap = poly(g64a) x64p = poly(1<<64) def crc64ap(d): p = 0 for i in d: p = p*256 + i p = poly(p) return int(p*x64p%g64ap) g64bp = poly(g64b) def crc64bp(d): p = 0 for i in d: p = p*256 + i p = poly(p) return int(p*x64p%g64bp) class KnownAnswerTests(unittest.TestCase): test_messages = [ b'T', b'CatMouse987654321', ] known_answers = [ [ (g8,0,0), (0xFE, 0x9D) ], [ (g8,-1,1), (0x4F, 0x9B) ], [ (g8,0,1), (0xFE, 0x62) ], [ (g16,0,0), (0x1A71, 0xE556) ], [ (g16,-1,1), (0x1B26, 0xF56E) ], [ (g16,0,1), (0x14A1, 0xC28D) ], [ (g24,0,0), (0xBCC49D, 0xC4B507) ], [ (g24,-1,1), (0x59BD0E, 0x0AAA37) ], [ (g24,0,1), (0xD52B0F, 0x1523AB) ], [ (g32,0,0), (0x6B93DDDB, 0x12DCA0F4) ], [ (g32,0xFFFFFFFF,1), (0x41FB859F, 0xF7B400A7) ], [ (g32,0,1), (0x6C0695ED, 0xC1A40EE5) ], [ (g32,0,1,0xFFFFFFFF), (0xBE047A60, 0x084BFF58) ], ] def test_known_answers(self): for crcfun_params, v in self.known_answers: crcfun = mkCrcFun(*crcfun_params) self.assertEqual(crcfun(b'',0), 0, "Wrong answer for CRC parameters %s, input ''" % (crcfun_params,)) for i, msg in enumerate(self.test_messages): self.assertEqual(crcfun(msg), v[i], "Wrong answer for CRC parameters %s, input '%s'" % (crcfun_params,msg)) self.assertEqual(crcfun(msg[4:], crcfun(msg[:4])), v[i], "Wrong answer for CRC parameters %s, input '%s'" % (crcfun_params,msg)) self.assertEqual(crcfun(msg[-1:], crcfun(msg[:-1])), v[i], "Wrong answer for CRC parameters %s, input '%s'" % (crcfun_params,msg)) class CompareReferenceCrcTest(unittest.TestCase): test_messages = [ b'', b'T', b'123456789', b'CatMouse987654321', ] test_poly_crcs = [ [ (g8,0,0), crc8p ], [ (g16,0,0), crc16p ], [ (g24,0,0), crc24p ], [ (g32,0,0), crc32p ], [ (g64a,0,0), crc64ap ], [ (g64b,0,0), crc64bp ], ] @staticmethod def reference_crc32(d, crc=0): """This function modifies the return value of binascii.crc32 to be an unsigned 32-bit value. I.e. in the range 0 to 2**32-1.""" # Work around the future warning on constants. if crc > 0x7FFFFFFF: x = int(crc & 0x7FFFFFFF) crc = x | -2147483648 x = binascii.crc32(d,crc) return int(x) & 0xFFFFFFFF def test_compare_crc32(self): """The binascii module has a 32-bit CRC function that is used in a wide range of applications including the checksum used in the ZIP file format. This test compares the CRC-32 implementation of this crcmod module to that of binascii.crc32.""" # The following function should produce the same result as # self.reference_crc32 which is derived from binascii.crc32. crc32 = mkCrcFun(g32,0,1,0xFFFFFFFF) for msg in self.test_messages: self.assertEqual(crc32(msg), self.reference_crc32(msg)) def test_compare_poly(self): """Compare various CRCs of this crcmod module to a pure polynomial-based implementation.""" for crcfun_params, crc_poly_fun in self.test_poly_crcs: # The following function should produce the same result as # the associated polynomial CRC function. crcfun = mkCrcFun(*crcfun_params) for msg in self.test_messages: self.assertEqual(crcfun(msg), crc_poly_fun(msg)) class CrcClassTest(unittest.TestCase): """Verify the Crc class""" msg = b'CatMouse987654321' def test_simple_crc32_class(self): """Verify the CRC class when not using xorOut""" crc = Crc(g32) str_rep = \ '''poly = 0x104C11DB7 reverse = True initCrc = 0xFFFFFFFF xorOut = 0x00000000 crcValue = 0xFFFFFFFF''' self.assertEqual(str(crc), str_rep) self.assertEqual(crc.digest(), b'\xff\xff\xff\xff') self.assertEqual(crc.hexdigest(), 'FFFFFFFF') crc.update(self.msg) self.assertEqual(crc.crcValue, 0xF7B400A7) self.assertEqual(crc.digest(), b'\xf7\xb4\x00\xa7') self.assertEqual(crc.hexdigest(), 'F7B400A7') # Verify the .copy() method x = crc.copy() self.assertTrue(x is not crc) str_rep = \ '''poly = 0x104C11DB7 reverse = True initCrc = 0xFFFFFFFF xorOut = 0x00000000 crcValue = 0xF7B400A7''' self.assertEqual(str(crc), str_rep) self.assertEqual(str(x), str_rep) def test_full_crc32_class(self): """Verify the CRC class when using xorOut""" crc = Crc(g32, initCrc=0, xorOut= ~0) str_rep = \ '''poly = 0x104C11DB7 reverse = True initCrc = 0x00000000 xorOut = 0xFFFFFFFF crcValue = 0x00000000''' self.assertEqual(str(crc), str_rep) self.assertEqual(crc.digest(), b'\x00\x00\x00\x00') self.assertEqual(crc.hexdigest(), '00000000') crc.update(self.msg) self.assertEqual(crc.crcValue, 0x84BFF58) self.assertEqual(crc.digest(), b'\x08\x4b\xff\x58') self.assertEqual(crc.hexdigest(), '084BFF58') # Verify the .copy() method x = crc.copy() self.assertTrue(x is not crc) str_rep = \ '''poly = 0x104C11DB7 reverse = True initCrc = 0x00000000 xorOut = 0xFFFFFFFF crcValue = 0x084BFF58''' self.assertEqual(str(crc), str_rep) self.assertEqual(str(x), str_rep) # Verify the .new() method y = crc.new() self.assertTrue(y is not crc) self.assertTrue(y is not x) str_rep = \ '''poly = 0x104C11DB7 reverse = True initCrc = 0x00000000 xorOut = 0xFFFFFFFF crcValue = 0x00000000''' self.assertEqual(str(y), str_rep) class PredefinedCrcTest(unittest.TestCase): """Verify the predefined CRCs""" test_messages_for_known_answers = [ b'', # Test cases below depend on this first entry being the empty string. b'T', b'CatMouse987654321', ] known_answers = [ [ 'crc-aug-ccitt', (0x1D0F, 0xD6ED, 0x5637) ], [ 'x-25', (0x0000, 0xE4D9, 0x0A91) ], [ 'crc-32', (0x00000000, 0xBE047A60, 0x084BFF58) ], ] def test_known_answers(self): for crcfun_name, v in self.known_answers: crcfun = mkPredefinedCrcFun(crcfun_name) self.assertEqual(crcfun(b'',0), 0, "Wrong answer for CRC '%s', input ''" % crcfun_name) for i, msg in enumerate(self.test_messages_for_known_answers): self.assertEqual(crcfun(msg), v[i], "Wrong answer for CRC %s, input '%s'" % (crcfun_name,msg)) self.assertEqual(crcfun(msg[4:], crcfun(msg[:4])), v[i], "Wrong answer for CRC %s, input '%s'" % (crcfun_name,msg)) self.assertEqual(crcfun(msg[-1:], crcfun(msg[:-1])), v[i], "Wrong answer for CRC %s, input '%s'" % (crcfun_name,msg)) def test_class_with_known_answers(self): for crcfun_name, v in self.known_answers: for i, msg in enumerate(self.test_messages_for_known_answers): crc1 = PredefinedCrc(crcfun_name) crc1.update(msg) self.assertEqual(crc1.crcValue, v[i], "Wrong answer for crc1 %s, input '%s'" % (crcfun_name,msg)) crc2 = crc1.new() # Check that crc1 maintains its same value, after .new() call. self.assertEqual(crc1.crcValue, v[i], "Wrong state for crc1 %s, input '%s'" % (crcfun_name,msg)) # Check that the new class instance created by .new() contains the initialisation value. # This depends on the first string in self.test_messages_for_known_answers being # the empty string. self.assertEqual(crc2.crcValue, v[0], "Wrong state for crc2 %s, input '%s'" % (crcfun_name,msg)) crc2.update(msg) # Check that crc1 maintains its same value, after crc2 has called .update() self.assertEqual(crc1.crcValue, v[i], "Wrong state for crc1 %s, input '%s'" % (crcfun_name,msg)) # Check that crc2 contains the right value after calling .update() self.assertEqual(crc2.crcValue, v[i], "Wrong state for crc2 %s, input '%s'" % (crcfun_name,msg)) def test_function_predefined_table(self): for table_entry in _predefined_crc_definitions: # Check predefined function crc_func = mkPredefinedCrcFun(table_entry['name']) calc_value = crc_func(b"123456789") self.assertEqual(calc_value, table_entry['check'], "Wrong answer for CRC '%s'" % table_entry['name']) def test_class_predefined_table(self): for table_entry in _predefined_crc_definitions: # Check predefined class crc1 = PredefinedCrc(table_entry['name']) crc1.update(b"123456789") self.assertEqual(crc1.crcValue, table_entry['check'], "Wrong answer for CRC '%s'" % table_entry['name']) class InputTypesTest(unittest.TestCase): """Check the various input types that CRC functions can accept.""" msg = b'CatMouse987654321' check_crc_names = [ 'crc-aug-ccitt', 'x-25', 'crc-32', ] array_check_types = [ 'B', 'H', 'I', 'L', ] def test_bytearray_input(self): """Test that bytearray inputs are accepted, as an example of a type that implements the buffer protocol.""" for crc_name in self.check_crc_names: crcfun = mkPredefinedCrcFun(crc_name) for i in range(len(self.msg) + 1): test_msg = self.msg[:i] bytes_answer = crcfun(test_msg) bytearray_answer = crcfun(bytearray(test_msg)) self.assertEqual(bytes_answer, bytearray_answer) def test_array_input(self): """Test that array inputs are accepted, as an example of a type that implements the buffer protocol.""" for crc_name in self.check_crc_names: crcfun = mkPredefinedCrcFun(crc_name) for i in range(len(self.msg) + 1): test_msg = self.msg[:i] bytes_answer = crcfun(test_msg) for array_type in self.array_check_types: if i % array(array_type).itemsize == 0: test_array = array(array_type, test_msg) array_answer = crcfun(test_array) self.assertEqual(bytes_answer, array_answer) def test_unicode_input(self): """Test that Unicode input raises TypeError""" for crc_name in self.check_crc_names: crcfun = mkPredefinedCrcFun(crc_name) with self.assertRaises(TypeError): crcfun("123456789") def runtests(): print("Using extension:", _usingExtension) print() unittest.main() if __name__ == '__main__': runtests() crcmod-1.7/test/0000755000175000017500000000000011411642620013164 5ustar rlbrlb00000000000000crcmod-1.7/test/examples.py0000644000175000017500000000317011403155556015365 0ustar rlbrlb00000000000000#----------------------------------------------------------------------------- # Demonstrate the use of the code generator from crcmod import Crc g8 = 0x185 g16 = 0x11021 g24 = 0x15D6DCB g32 = 0x104C11DB7 def polyFromBits(bits): p = 0 for n in bits: p = p | (1 << n) return p # The following is from Standard ECMA-182 "Data Interchange on 12,7 mm 48-Track # Magnetic Tape Cartridges -DLT1 Format-", December 1992. g64 = polyFromBits([64, 62, 57, 55, 54, 53, 52, 47, 46, 45, 40, 39, 38, 37, 35, 33, 32, 31, 29, 27, 24, 23, 22, 21, 19, 17, 13, 12, 10, 9, 7, 4, 1, 0]) print('Generating examples.c') out = open('examples.c', 'w') out.write('''// Define the required data types typedef unsigned char UINT8; typedef unsigned short UINT16; typedef unsigned int UINT32; typedef unsigned long long UINT64; ''') Crc(g8, rev=False).generateCode('crc8',out) Crc(g8, rev=True).generateCode('crc8r',out) Crc(g16, rev=False).generateCode('crc16',out) Crc(g16, rev=True).generateCode('crc16r',out) Crc(g24, rev=False).generateCode('crc24',out) Crc(g24, rev=True).generateCode('crc24r',out) Crc(g32, rev=False).generateCode('crc32',out) Crc(g32, rev=True).generateCode('crc32r',out) Crc(g64, rev=False).generateCode('crc64',out) Crc(g64, rev=True).generateCode('crc64r',out) # Check out the XOR-out feature. Crc(g16, initCrc=0, rev=True, xorOut=~0).generateCode('crc16x',out) Crc(g24, initCrc=0, rev=True, xorOut=~0).generateCode('crc24x',out) Crc(g32, initCrc=0, rev=True, xorOut=~0).generateCode('crc32x',out) Crc(g64, initCrc=0, rev=True, xorOut=~0).generateCode('crc64x',out) out.close() print('Done') crcmod-1.7/test/test_crcmod.py0000644000175000017500000000011011406653375016051 0ustar rlbrlb00000000000000 import unittest import crcmod.test unittest.main(module=crcmod.test) crcmod-1.7/LICENSE0000644000175000017500000000234111411635253013216 0ustar rlbrlb00000000000000---------------------------------------------------------------------------- Copyright (c) 2010 Raymond L. Buvel Copyright (c) 2010 Craig McQueen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ---------------------------------------------------------------------------- crcmod-1.7/README0000644000175000017500000000750011411635253013073 0ustar rlbrlb00000000000000=========================== crcmod for Calculating CRCs =========================== The software in this package is a Python module for generating objects that compute the Cyclic Redundancy Check (CRC). There is no attempt in this package to explain how the CRC works. There are a number of resources on the web that give a good explanation of the algorithms. Just do a Google search for "crc calculation" and browse till you find what you need. Another resource can be found in chapter 20 of the book "Numerical Recipes in C" by Press et. al. This package allows the use of any 8, 16, 24, 32, or 64 bit CRC. You can generate a Python function for the selected polynomial or an instance of the Crc class which provides the same interface as the ``md5`` and ``sha`` modules from the Python standard library. A ``Crc`` class instance can also generate C/C++ source code that can be used in another application. ---------- Guidelines ---------- Documentation is available from the doc strings. It is up to you to decide what polynomials to use in your application. If someone has not specified the polynomials to use, you will need to do some research to find one suitable for your application. Examples are available in the unit test script ``test.py``. You may also use the ``predefined`` module to select one of the standard polynomials. If you need to generate code for another language, I suggest you subclass the ``Crc`` class and replace the method ``generateCode``. Use ``generateCode`` as a model for the new version. ------------ Dependencies ------------ Python Version ^^^^^^^^^^^^^^ The package has separate code to support the 2.x and 3.x Python series. For the 2.x versions of Python, these versions have been tested: * 2.4 * 2.5 * 2.6 * 2.7 It may still work on earlier versions of Python 2.x, but these have not been recently tested. For the 3.x versions of Python, these versions have been tested: * 3.1 Building C extension ^^^^^^^^^^^^^^^^^^^^ To build the C extension, the appropriate compiler tools for your platform must be installed. Refer to the Python documentation for building C extensions for details. ------------ Installation ------------ The crcmod package is installed using ``distutils``. Run the following command:: python setup.py install If the extension module builds, it will be installed. Otherwise, the installation will include the pure Python version. This will run significantly slower than the extension module but will allow the package to be used. For Windows users who want to use the mingw32 compiler, run this command:: python setup.py build --compiler=mingw32 install For Python 3.x, the install process is the same but you need to use the 3.x interpreter. ------------ Unit Testing ------------ The ``crcmod`` package has a module ``crcmod.test``, which contains unit tests for both ``crcmod`` and ``crcmod.predefined``. When you first install ``crcmod``, you should run the unit tests to make sure everything is installed properly. The test script performs a number of tests including a comparison to the direct method which uses a class implementing polynomials over the integers mod 2. To run the unit tests on Python >=2.5:: python -m crcmod.test Alternatively, in the ``test`` directory run:: python test_crcmod.py --------------- Code Generation --------------- The crcmod package is capable of generating C functions that can be compiled with a C or C++ compiler. In the test directory, there is an examples.py script that demonstrates how to use the code generator. The result of this is written out to the file ``examples.c``. The generated code was checked to make sure it compiles with the GCC compiler. ------- License ------- The ``crcmod`` package is released under the MIT license. See the ``LICENSE`` file for details. ------------ Contributors ------------ Craig McQueen crcmod-1.7/docs/0000755000175000017500000000000011411642620013135 5ustar rlbrlb00000000000000crcmod-1.7/docs/html/0000755000175000017500000000000011411642620014101 5ustar rlbrlb00000000000000crcmod-1.7/docs/html/genindex.html0000644000175000017500000001471511410125142016572 0ustar rlbrlb00000000000000 Index — crcmod v1.7 documentation crcmod-1.7/docs/html/_sources/0000755000175000017500000000000011411642620015723 5ustar rlbrlb00000000000000crcmod-1.7/docs/html/_sources/crcmod.txt0000644000175000017500000002045511407132660017744 0ustar rlbrlb00000000000000 :mod:`crcmod` -- CRC calculation ================================ .. module:: crcmod :synopsis: CRC calculation .. moduleauthor:: Raymond L Buvel .. sectionauthor:: Craig McQueen This module provides a function factory :func:`mkCrcFun` and a class :class:`Crc` for calculating CRCs of byte strings using common CRC algorithms. .. note:: This documentation normally shows Python 2.x usage. Python 3.x usage is very similar, with the main difference that input strings must be explicitly defined as :keyword:`bytes` type, or an object that supports the buffer protocol. E.g.:: >>> crc_value = crc_function(b'123456789') >>> crc_value = crc_function(bytearray((49, 50, 51, 52, 53, 54, 55, 56, 57))) :func:`mkCrcFun` -- CRC function factory ---------------------------------------- The function factory provides a simple interface for CRC calculation. .. function:: mkCrcFun(poly[, initCrc, rev, xorOut]) Function factory that returns a new function for calculating CRCs using a specified CRC algorithm. :param poly: The generator polynomial to use in calculating the CRC. The value is specified as a Python integer or long integer. The bits in this integer are the coefficients of the polynomial. The only polynomials allowed are those that generate 8, 16, 24, 32, or 64 bit CRCs. :param initCrc: Initial value used to start the CRC calculation. This initial value should be the initial shift register value, reversed if it uses a reversed algorithm, and then XORed with the final XOR value. That is equivalent to the CRC result the algorithm should return for a zero-length string. Defaults to all bits set because that starting value will take leading zero bytes into account. Starting with zero will ignore all leading zero bytes. :param rev: A flag that selects a bit reversed algorithm when :keyword:`True`. Defaults to :keyword:`True` because the bit reversed algorithms are more efficient. :param xorOut: Final value to XOR with the calculated CRC value. Used by some CRC algorithms. Defaults to zero. :return: CRC calculation function :rtype: function The function that is returned is as follows: .. function:: .crc_function(data[, crc=initCrc]) :param data: Data for which to calculate the CRC. :type data: byte string :param crc: Initial CRC value. :return: Calculated CRC value. :rtype: integer Examples ^^^^^^^^ **CRC-32** Example:: >>> import crcmod >>> crc32_func = crcmod.mkCrcFun(0x104c11db7, initCrc=0, xorOut=0xFFFFFFFF) >>> hex(crc32_func('123456789')) '0xcbf43926L' The CRC-32 uses a "reversed" algorithm, used for many common CRC algorithms. Less common is the non-reversed algorithm, as used by the 16-bit **XMODEM** CRC:: >>> xmodem_crc_func = crcmod.mkCrcFun(0x11021, rev=False, initCrc=0x0000, xorOut=0x0000) >>> hex(xmodem_crc_func('123456789')) '0x31c3' The CRC function can be called multiple times. On subsequent calls, pass the CRC value previously calculated as a second parameter:: >>> crc_value = crc32_func('1234') >>> crc_value = crc32_func('56789', crc_value) >>> hex(crc_value) '0xcbf43926L' Python 3.x example: Unicode strings are not accepted as input. Byte strings are acceptable. You may calculate a CRC for an object that implements the buffer protocol:: >>> import crcmod >>> crc32_func = crcmod.mkCrcFun(0x104c11db7, initCrc=0, xorOut=0xFFFFFFFF) >>> hex(crc32_func('123456789')) ... TypeError: Unicode-objects must be encoded before calculating a CRC >>> hex(crc32_func(b'123456789')) '0xcbf43926' >>> hex(crc32_func(bytearray((49, 50, 51, 52, 53, 54, 55, 56, 57)))) '0xcbf43926' Class :class:`Crc` ------------------ The class provides an interface similar to the Python :mod:`hashlib`, :mod:`md5` and :mod:`sha` modules. .. class:: Crc(poly[, initCrc, rev, xorOut]) Returns a new :class:`Crc` object for calculating CRCs using a specified CRC algorithm. The parameters are the same as those for the factory function :func:`mkCrcFun`. :param poly: The generator polynomial to use in calculating the CRC. The value is specified as a Python integer or long integer. The bits in this integer are the coefficients of the polynomial. The only polynomials allowed are those that generate 8, 16, 24, 32, or 64 bit CRCs. :param initCrc: Initial value used to start the CRC calculation. This initial value should be the initial shift register value, reversed if it uses a reversed algorithm, and then XORed with the final XOR value. That is equivalent to the CRC result the algorithm should return for a zero-length string. Defaults to all bits set because that starting value will take leading zero bytes into account. Starting with zero will ignore all leading zero bytes. :param rev: A flag that selects a bit reversed algorithm when :keyword:`True`. Defaults to :keyword:`True` because the bit reversed algorithms are more efficient. :param xorOut: Final value to XOR with the calculated CRC value. Used by some CRC algorithms. Defaults to zero. :class:`Crc` objects contain the following constant values: .. attribute:: digest_size The size of the resulting digest in bytes. This depends on the width of the CRC polynomial. E.g. for a 32-bit CRC, :data:`digest_size` will be ``4``. .. attribute:: crcValue The calculated CRC value, as an integer, for the data that has been input using :meth:`update`. This value is updated after each call to :meth:`update`. :class:`Crc` objects support the following methods: .. method:: new([arg]) Create a new instance of the :class:`Crc` class initialized to the same values as the original instance. The CRC value is set to the initial value. If a string is provided in the optional ``arg`` parameter, it is passed to the :meth:`update` method. .. method:: copy() Create a new instance of the :class:`Crc` class initialized to the same values as the original instance. The CRC value is copied from the current value. This allows multiple CRC calculations using a common initial string. .. method:: update(data) :param data: Data for which to calculate the CRC :type data: byte string Update the calculated CRC value for the specified input data. .. method:: digest() Return the current CRC value as a string of bytes. The length of this string is specified in the :attr:`digest_size` attribute. .. method:: hexdigest() Return the current CRC value as a string of hex digits. The length of this string is twice the :attr:`digest_size` attribute. .. method:: generateCode(functionName, out, [dataType, crcType]) Generate a C/C++ function. :param functionName: String specifying the name of the function. :param out: An open file-like object with a write method. This specifies where the generated code is written. :param dataType: An optional parameter specifying the data type of the input data to the function. Defaults to ``UINT8``. :param crcType: An optional parameter specifying the data type of the CRC value. Defaults to one of ``UINT8``, ``UINT16``, ``UINT32``, or ``UINT64`` depending on the size of the CRC value. Examples ^^^^^^^^ **CRC-32** Example:: >>> import crcmod >>> crc32 = crcmod.Crc(0x104c11db7, initCrc=0, xorOut=0xFFFFFFFF) >>> crc32.update('123456789') >>> hex(crc32.crcValue) '0xcbf43926L' >>> crc32.hexdigest() 'CBF43926' The :meth:`Crc.update` method can be called multiple times, and the CRC value is updated with each call:: >>> crc32new = crc32.new() >>> crc32new.update('1234') >>> crc32new.hexdigest() '9BE3E0A3' >>> crc32new.update('56789') >>> crc32new.hexdigest() 'CBF43926' crcmod-1.7/docs/html/_sources/index.txt0000644000175000017500000000071411406653375017612 0ustar rlbrlb00000000000000.. crcmod documentation master file, created by sphinx-quickstart on Thu Jan 21 14:04:12 2010. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. crcmod documentation ==================== This is the documentation for the :mod:`crcmod` Python library. .. toctree:: :maxdepth: 2 intro.rst crcmod.rst crcmod.predefined.rst * :ref:`genindex` * :ref:`modindex` * :ref:`search` crcmod-1.7/docs/html/_sources/crcmod.predefined.txt0000644000175000017500000002202311406653375022053 0ustar rlbrlb00000000000000 :mod:`crcmod.predefined` -- CRC calculation using predefined algorithms ======================================================================= .. module:: crcmod.predefined :synopsis: CRC calculation using predefined algorithms .. moduleauthor:: Craig McQueen .. sectionauthor:: Craig McQueen This module provides a function factory :func:`mkPredefinedCrcFun` and a class :class:`PredefinedCrc` for calculating CRCs of byte strings using common predefined CRC algorithms. The function factory and the class are very similar to those defined in :mod:`crcmod`, except that the CRC algorithm is specified by a predefined name, rather than the individual polynomial, reflection, and initial and final-XOR parameters. Predefined CRC algorithms ------------------------- The :mod:`crcmod.predefined` module offers the following predefined algorithms: ================================ ====================== ========== ==================== ==================== ==================== Name Polynomial Reversed? Init-value XOR-out Check ================================ ====================== ========== ==================== ==================== ==================== ``crc-8`` 0x107 False 0x00 0x00 0xF4 ``crc-8-darc`` 0x139 True 0x00 0x00 0x15 ``crc-8-i-code`` 0x11D False 0xFD 0x00 0x7E ``crc-8-itu`` 0x107 False 0x55 0x55 0xA1 ``crc-8-maxim`` 0x131 True 0x00 0x00 0xA1 ``crc-8-rohc`` 0x107 True 0xFF 0x00 0xD0 ``crc-8-wcdma`` 0x19B True 0x00 0x00 0x25 ``crc-16`` 0x18005 True 0x0000 0x0000 0xBB3D ``crc-16-buypass`` 0x18005 False 0x0000 0x0000 0xFEE8 ``crc-16-dds-110`` 0x18005 False 0x800D 0x0000 0x9ECF ``crc-16-dect`` 0x10589 False 0x0001 0x0001 0x007E ``crc-16-dnp`` 0x13D65 True 0xFFFF 0xFFFF 0xEA82 ``crc-16-en-13757`` 0x13D65 False 0xFFFF 0xFFFF 0xC2B7 ``crc-16-genibus`` 0x11021 False 0x0000 0xFFFF 0xD64E ``crc-16-maxim`` 0x18005 True 0xFFFF 0xFFFF 0x44C2 ``crc-16-mcrf4xx`` 0x11021 True 0xFFFF 0x0000 0x6F91 ``crc-16-riello`` 0x11021 True 0x554D 0x0000 0x63D0 ``crc-16-t10-dif`` 0x18BB7 False 0x0000 0x0000 0xD0DB ``crc-16-teledisk`` 0x1A097 False 0x0000 0x0000 0x0FB3 ``crc-16-usb`` 0x18005 True 0x0000 0xFFFF 0xB4C8 ``x-25`` 0x11021 True 0x0000 0xFFFF 0x906E ``xmodem`` 0x11021 False 0x0000 0x0000 0x31C3 ``modbus`` 0x18005 True 0xFFFF 0x0000 0x4B37 ``kermit`` [#ccitt]_ 0x11021 True 0x0000 0x0000 0x2189 ``crc-ccitt-false`` [#ccitt]_ 0x11021 False 0xFFFF 0x0000 0x29B1 ``crc-aug-ccitt`` [#ccitt]_ 0x11021 False 0x1D0F 0x0000 0xE5CC ``crc-24`` 0x1864CFB False 0xB704CE 0x000000 0x21CF02 ``crc-24-flexray-a`` 0x15D6DCB False 0xFEDCBA 0x000000 0x7979BD ``crc-24-flexray-b`` 0x15D6DCB False 0xABCDEF 0x000000 0x1F23B8 ``crc-32`` 0x104C11DB7 True 0x00000000 0xFFFFFFFF 0xCBF43926 ``crc-32-bzip2`` 0x104C11DB7 False 0x00000000 0xFFFFFFFF 0xFC891918 ``crc-32c`` 0x11EDC6F41 True 0x00000000 0xFFFFFFFF 0xE3069283 ``crc-32d`` 0x1A833982B True 0x00000000 0xFFFFFFFF 0x87315576 ``crc-32-mpeg`` 0x104C11DB7 False 0xFFFFFFFF 0x00000000 0x0376E6E7 ``posix`` 0x104C11DB7 False 0xFFFFFFFF 0xFFFFFFFF 0x765E7680 ``crc-32q`` 0x1814141AB False 0x00000000 0x00000000 0x3010BF7F ``jamcrc`` 0x104C11DB7 True 0xFFFFFFFF 0x00000000 0x340BC6D9 ``xfer`` 0x1000000AF False 0x00000000 0x00000000 0xBD0BE338 ``crc-64`` 0x1000000000000001B True 0x0000000000000000 0x0000000000000000 0x46A5A9388A5BEFFE ``crc-64-we`` 0x142F0E1EBA9EA3693 False 0x0000000000000000 0xFFFFFFFFFFFFFFFF 0x62EC59E3F1A4F00A ``crc-64-jones`` 0x1AD93D23594C935A9 True 0xFFFFFFFFFFFFFFFF 0x0000000000000000 0xCAA717168609F281 ================================ ====================== ========== ==================== ==================== ==================== .. rubric:: Notes .. [#ccitt] Definitions of CCITT are disputable. See: * http://homepages.tesco.net/~rainstorm/crc-catalogue.htm * http://web.archive.org/web/20071229021252/http://www.joegeluso.com/software/articles/ccitt.htm :func:`mkPredefinedCrcFun` -- CRC function factory -------------------------------------------------- The function factory provides a simple interface for CRC calculation. It is similar to :func:`crcmod.mkCrcFun`, except that it specifies a CRC algorithm by name rather than its parameters. .. function:: mkPredefinedCrcFun(crc_name) Function factory that returns a new function for calculating CRCs using a specified CRC algorithm. :param crc_name: The name of the predefined CRC algorithm to use. :type crc_name: string :return: CRC calculation function :rtype: function The function that is returned is the same as that returned by :func:`crcmod.mkCrcFun`: .. function:: .crc_function(data[, crc=initCrc]) :param data: Data for which to calculate the CRC. :type data: byte string :param crc: Initial CRC value. :return: Calculated CRC value. :rtype: integer .. function:: mkCrcFun(crc_name) This is an alias for :func:`crcmod.predefined.mkPredefinedCrcFun`. However, it is not defined when :mod:`crcmod.predefined` is imported using the form:: >>> from crcmod.predefined import * Examples ^^^^^^^^ **CRC-32** example:: >>> import crcmod.predefined >>> crc32_func = crcmod.predefined.mkCrcFun('crc-32') >>> hex(crc32_func('123456789')) '0xcbf43926L' **XMODEM** example:: >>> xmodem_crc_func = crcmod.predefined.mkCrcFun('xmodem') >>> hex(xmodem_crc_func('123456789')) '0x31c3' Class :class:`PredefinedCrc` ---------------------------- This class is inherited from the :class:`crcmod.Crc` class, and is the same except for the initialization. It specifies a CRC algorithm by name rather than its parameters. .. class:: PredefinedCrc(crc_name) Returns a new :class:`Crc` object for calculating CRCs using a specified CRC algorithm. The parameter is the same as that for the factory function :func:`crcmod.predefined.mkPredefinedCrcFun`. :param crc_name: The name of the predefined CRC algorithm to use. :type crc_name: string .. class:: Crc(poly[, initCrc, rev, xorOut]) This is an alias for :class:`crcmod.predefined.PredefinedCrc`. However, it is not defined when :mod:`crcmod.predefined` is imported using the form:: >>> from crcmod.predefined import * Examples ^^^^^^^^ **CRC-32** Example:: >>> import crcmod.predefined >>> crc32 = crcmod.predefined.Crc('crc-32') >>> crc32.update('123456789') >>> hex(crc32.crcValue) '0xcbf43926L' >>> crc32.hexdigest() 'CBF43926' crcmod-1.7/docs/html/_sources/intro.txt0000644000175000017500000001073511410124617017625 0ustar rlbrlb00000000000000 ============ Introduction ============ The software in this package is a Python module for generating objects that compute the Cyclic Redundancy Check (CRC). It includes a (optional) C extension for fast calculation, as well as a pure Python implementation. There is no attempt in this package to explain how the CRC works. There are a number of resources on the web that give a good explanation of the algorithms. Just do a Google search for "crc calculation" and browse till you find what you need. Another resource can be found in chapter 20 of the book "Numerical Recipes in C" by Press et. al. This package allows the use of any 8, 16, 24, 32, or 64 bit CRC. You can generate a Python function for the selected polynomial or an instance of the :class:`crcmod.Crc` class which provides the same interface as the :mod:`hashlib`, :mod:`md5` and :mod:`sha` modules from the Python standard library. A :class:`crcmod.Crc` class instance can also generate C/C++ source code that can be used in another application. ---------- Guidelines ---------- Documentation is available here as well as from the doc strings. It is up to you to decide what polynomials to use in your application. Some common CRC algorithms are predefined in :mod:`crcmod.predefined`. If someone has not specified the polynomials to use, you will need to do some research to find one suitable for your application. Examples are available in the unit test script :file:`test.py`. If you need to generate code for another language, I suggest you subclass the :class:`crcmod.Crc` class and replace the method :meth:`crcmod.Crc.generateCode`. Use :meth:`crcmod.Crc.generateCode` as a model for the new version. ------------ Dependencies ------------ Python Version ^^^^^^^^^^^^^^ The package has separate code to support the 2.x and 3.x Python series. For the 2.x versions of Python, these versions have been tested: * 2.4 * 2.5 * 2.6 * 2.7 It may still work on earlier versions of Python 2.x, but these have not been recently tested. For the 3.x versions of Python, these versions have been tested: * 3.1 Building C extension ^^^^^^^^^^^^^^^^^^^^ To build the C extension, the appropriate compiler tools for your platform must be installed. Refer to the Python documentation for building C extensions for details. ------------ Installation ------------ The :mod:`crcmod` package is installed using :mod:`distutils`. Run the following command:: python setup.py install If the extension module builds, it will be installed. Otherwise, the installation will include the pure Python version. This will run significantly slower than the extension module but will allow the package to be used. For Windows users who want to use the mingw32 compiler, run this command:: python setup.py build --compiler=mingw32 install For Python 3.x, the install process is the same but you need to use the 3.x interpreter. ------------ Unit Testing ------------ The :mod:`crcmod` package has a module :mod:`crcmod.test`, which contains unit tests for both :mod:`crcmod` and :mod:`crcmod.predefined`. When you first install :mod:`crcmod`, you should run the unit tests to make sure everything is installed properly. The test script performs a number of tests including a comparison to the direct method which uses a class implementing polynomials over the integers mod 2. To run the unit tests on Python >=2.5:: python -m crcmod.test Alternatively, in the :file:`test` directory run:: python test_crcmod.py --------------- Code Generation --------------- The :mod:`crcmod` package is capable of generating C functions that can be compiled with a C or C++ compiler. In the :file:`test` directory, there is an :file:`examples.py` script that demonstrates how to use the code generator. The result of this is written out to the file :file:`examples.c`. The generated code was checked to make sure it compiles with the GCC compiler. ------- License ------- The :mod:`crcmod` package is released under the MIT license. See the :file:`LICENSE` file for details. ---------- References ---------- .. seealso:: :func:`binascii.crc32` function from the :mod:`binascii` module CRC-32 implementation :func:`zlib.crc32` function from the :mod:`zlib` module CRC-32 implementation Module :mod:`hashlib` Secure hash and message digest algorithms. Module :mod:`md5` RSA's MD5 message digest algorithm. Module :mod:`sha` NIST's secure hash algorithm, SHA. Module :mod:`hmac` Keyed-hashing for message authentication. crcmod-1.7/docs/html/_static/0000755000175000017500000000000011411642620015527 5ustar rlbrlb00000000000000crcmod-1.7/docs/html/_static/jquery.js0000644000175000017500000015473611345457043017435 0ustar rlbrlb00000000000000/* * jQuery 1.2.6 - New Wave Javascript * * Copyright (c) 2008 John Resig (jquery.com) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * $Date: 2008-05-24 14:22:17 -0400 (Sat, 24 May 2008) $ * $Rev: 5685 $ */ (function(){var _jQuery=window.jQuery,_$=window.$;var jQuery=window.jQuery=window.$=function(selector,context){return new jQuery.fn.init(selector,context);};var quickExpr=/^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/,isSimple=/^.[^:#\[\.]*$/,undefined;jQuery.fn=jQuery.prototype={init:function(selector,context){selector=selector||document;if(selector.nodeType){this[0]=selector;this.length=1;return this;}if(typeof selector=="string"){var match=quickExpr.exec(selector);if(match&&(match[1]||!context)){if(match[1])selector=jQuery.clean([match[1]],context);else{var elem=document.getElementById(match[3]);if(elem){if(elem.id!=match[3])return jQuery().find(selector);return jQuery(elem);}selector=[];}}else return jQuery(context).find(selector);}else if(jQuery.isFunction(selector))return jQuery(document)[jQuery.fn.ready?"ready":"load"](selector);return this.setArray(jQuery.makeArray(selector));},jquery:"1.2.6",size:function(){return this.length;},length:0,get:function(num){return num==undefined?jQuery.makeArray(this):this[num];},pushStack:function(elems){var ret=jQuery(elems);ret.prevObject=this;return ret;},setArray:function(elems){this.length=0;Array.prototype.push.apply(this,elems);return this;},each:function(callback,args){return jQuery.each(this,callback,args);},index:function(elem){var ret=-1;return jQuery.inArray(elem&&elem.jquery?elem[0]:elem,this);},attr:function(name,value,type){var options=name;if(name.constructor==String)if(value===undefined)return this[0]&&jQuery[type||"attr"](this[0],name);else{options={};options[name]=value;}return this.each(function(i){for(name in options)jQuery.attr(type?this.style:this,name,jQuery.prop(this,options[name],type,i,name));});},css:function(key,value){if((key=='width'||key=='height')&&parseFloat(value)<0)value=undefined;return this.attr(key,value,"curCSS");},text:function(text){if(typeof text!="object"&&text!=null)return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(text));var ret="";jQuery.each(text||this,function(){jQuery.each(this.childNodes,function(){if(this.nodeType!=8)ret+=this.nodeType!=1?this.nodeValue:jQuery.fn.text([this]);});});return ret;},wrapAll:function(html){if(this[0])jQuery(html,this[0].ownerDocument).clone().insertBefore(this[0]).map(function(){var elem=this;while(elem.firstChild)elem=elem.firstChild;return elem;}).append(this);return this;},wrapInner:function(html){return this.each(function(){jQuery(this).contents().wrapAll(html);});},wrap:function(html){return this.each(function(){jQuery(this).wrapAll(html);});},append:function(){return this.domManip(arguments,true,false,function(elem){if(this.nodeType==1)this.appendChild(elem);});},prepend:function(){return this.domManip(arguments,true,true,function(elem){if(this.nodeType==1)this.insertBefore(elem,this.firstChild);});},before:function(){return this.domManip(arguments,false,false,function(elem){this.parentNode.insertBefore(elem,this);});},after:function(){return this.domManip(arguments,false,true,function(elem){this.parentNode.insertBefore(elem,this.nextSibling);});},end:function(){return this.prevObject||jQuery([]);},find:function(selector){var elems=jQuery.map(this,function(elem){return jQuery.find(selector,elem);});return this.pushStack(/[^+>] [^+>]/.test(selector)||selector.indexOf("..")>-1?jQuery.unique(elems):elems);},clone:function(events){var ret=this.map(function(){if(jQuery.browser.msie&&!jQuery.isXMLDoc(this)){var clone=this.cloneNode(true),container=document.createElement("div");container.appendChild(clone);return jQuery.clean([container.innerHTML])[0];}else return this.cloneNode(true);});var clone=ret.find("*").andSelf().each(function(){if(this[expando]!=undefined)this[expando]=null;});if(events===true)this.find("*").andSelf().each(function(i){if(this.nodeType==3)return;var events=jQuery.data(this,"events");for(var type in events)for(var handler in events[type])jQuery.event.add(clone[i],type,events[type][handler],events[type][handler].data);});return ret;},filter:function(selector){return this.pushStack(jQuery.isFunction(selector)&&jQuery.grep(this,function(elem,i){return selector.call(elem,i);})||jQuery.multiFilter(selector,this));},not:function(selector){if(selector.constructor==String)if(isSimple.test(selector))return this.pushStack(jQuery.multiFilter(selector,this,true));else selector=jQuery.multiFilter(selector,this);var isArrayLike=selector.length&&selector[selector.length-1]!==undefined&&!selector.nodeType;return this.filter(function(){return isArrayLike?jQuery.inArray(this,selector)<0:this!=selector;});},add:function(selector){return this.pushStack(jQuery.unique(jQuery.merge(this.get(),typeof selector=='string'?jQuery(selector):jQuery.makeArray(selector))));},is:function(selector){return!!selector&&jQuery.multiFilter(selector,this).length>0;},hasClass:function(selector){return this.is("."+selector);},val:function(value){if(value==undefined){if(this.length){var elem=this[0];if(jQuery.nodeName(elem,"select")){var index=elem.selectedIndex,values=[],options=elem.options,one=elem.type=="select-one";if(index<0)return null;for(var i=one?index:0,max=one?index+1:options.length;i=0||jQuery.inArray(this.name,value)>=0);else if(jQuery.nodeName(this,"select")){var values=jQuery.makeArray(value);jQuery("option",this).each(function(){this.selected=(jQuery.inArray(this.value,values)>=0||jQuery.inArray(this.text,values)>=0);});if(!values.length)this.selectedIndex=-1;}else this.value=value;});},html:function(value){return value==undefined?(this[0]?this[0].innerHTML:null):this.empty().append(value);},replaceWith:function(value){return this.after(value).remove();},eq:function(i){return this.slice(i,i+1);},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments));},map:function(callback){return this.pushStack(jQuery.map(this,function(elem,i){return callback.call(elem,i,elem);}));},andSelf:function(){return this.add(this.prevObject);},data:function(key,value){var parts=key.split(".");parts[1]=parts[1]?"."+parts[1]:"";if(value===undefined){var data=this.triggerHandler("getData"+parts[1]+"!",[parts[0]]);if(data===undefined&&this.length)data=jQuery.data(this[0],key);return data===undefined&&parts[1]?this.data(parts[0]):data;}else return this.trigger("setData"+parts[1]+"!",[parts[0],value]).each(function(){jQuery.data(this,key,value);});},removeData:function(key){return this.each(function(){jQuery.removeData(this,key);});},domManip:function(args,table,reverse,callback){var clone=this.length>1,elems;return this.each(function(){if(!elems){elems=jQuery.clean(args,this.ownerDocument);if(reverse)elems.reverse();}var obj=this;if(table&&jQuery.nodeName(this,"table")&&jQuery.nodeName(elems[0],"tr"))obj=this.getElementsByTagName("tbody")[0]||this.appendChild(this.ownerDocument.createElement("tbody"));var scripts=jQuery([]);jQuery.each(elems,function(){var elem=clone?jQuery(this).clone(true)[0]:this;if(jQuery.nodeName(elem,"script"))scripts=scripts.add(elem);else{if(elem.nodeType==1)scripts=scripts.add(jQuery("script",elem).remove());callback.call(obj,elem);}});scripts.each(evalScript);});}};jQuery.fn.init.prototype=jQuery.fn;function evalScript(i,elem){if(elem.src)jQuery.ajax({url:elem.src,async:false,dataType:"script"});else jQuery.globalEval(elem.text||elem.textContent||elem.innerHTML||"");if(elem.parentNode)elem.parentNode.removeChild(elem);}function now(){return+new Date;}jQuery.extend=jQuery.fn.extend=function(){var target=arguments[0]||{},i=1,length=arguments.length,deep=false,options;if(target.constructor==Boolean){deep=target;target=arguments[1]||{};i=2;}if(typeof target!="object"&&typeof target!="function")target={};if(length==i){target=this;--i;}for(;i-1;}},swap:function(elem,options,callback){var old={};for(var name in options){old[name]=elem.style[name];elem.style[name]=options[name];}callback.call(elem);for(var name in options)elem.style[name]=old[name];},css:function(elem,name,force){if(name=="width"||name=="height"){var val,props={position:"absolute",visibility:"hidden",display:"block"},which=name=="width"?["Left","Right"]:["Top","Bottom"];function getWH(){val=name=="width"?elem.offsetWidth:elem.offsetHeight;var padding=0,border=0;jQuery.each(which,function(){padding+=parseFloat(jQuery.curCSS(elem,"padding"+this,true))||0;border+=parseFloat(jQuery.curCSS(elem,"border"+this+"Width",true))||0;});val-=Math.round(padding+border);}if(jQuery(elem).is(":visible"))getWH();else jQuery.swap(elem,props,getWH);return Math.max(0,val);}return jQuery.curCSS(elem,name,force);},curCSS:function(elem,name,force){var ret,style=elem.style;function color(elem){if(!jQuery.browser.safari)return false;var ret=defaultView.getComputedStyle(elem,null);return!ret||ret.getPropertyValue("color")=="";}if(name=="opacity"&&jQuery.browser.msie){ret=jQuery.attr(style,"opacity");return ret==""?"1":ret;}if(jQuery.browser.opera&&name=="display"){var save=style.outline;style.outline="0 solid black";style.outline=save;}if(name.match(/float/i))name=styleFloat;if(!force&&style&&style[name])ret=style[name];else if(defaultView.getComputedStyle){if(name.match(/float/i))name="float";name=name.replace(/([A-Z])/g,"-$1").toLowerCase();var computedStyle=defaultView.getComputedStyle(elem,null);if(computedStyle&&!color(elem))ret=computedStyle.getPropertyValue(name);else{var swap=[],stack=[],a=elem,i=0;for(;a&&color(a);a=a.parentNode)stack.unshift(a);for(;i]*?)\/>/g,function(all,front,tag){return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?all:front+">";});var tags=jQuery.trim(elem).toLowerCase(),div=context.createElement("div");var wrap=!tags.indexOf("",""]||!tags.indexOf("",""]||tags.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"","
"]||!tags.indexOf("",""]||(!tags.indexOf("",""]||!tags.indexOf("",""]||jQuery.browser.msie&&[1,"div
","
"]||[0,"",""];div.innerHTML=wrap[1]+elem+wrap[2];while(wrap[0]--)div=div.lastChild;if(jQuery.browser.msie){var tbody=!tags.indexOf(""&&tags.indexOf("=0;--j)if(jQuery.nodeName(tbody[j],"tbody")&&!tbody[j].childNodes.length)tbody[j].parentNode.removeChild(tbody[j]);if(/^\s/.test(elem))div.insertBefore(context.createTextNode(elem.match(/^\s*/)[0]),div.firstChild);}elem=jQuery.makeArray(div.childNodes);}if(elem.length===0&&(!jQuery.nodeName(elem,"form")&&!jQuery.nodeName(elem,"select")))return;if(elem[0]==undefined||jQuery.nodeName(elem,"form")||elem.options)ret.push(elem);else ret=jQuery.merge(ret,elem);});return ret;},attr:function(elem,name,value){if(!elem||elem.nodeType==3||elem.nodeType==8)return undefined;var notxml=!jQuery.isXMLDoc(elem),set=value!==undefined,msie=jQuery.browser.msie;name=notxml&&jQuery.props[name]||name;if(elem.tagName){var special=/href|src|style/.test(name);if(name=="selected"&&jQuery.browser.safari)elem.parentNode.selectedIndex;if(name in elem&¬xml&&!special){if(set){if(name=="type"&&jQuery.nodeName(elem,"input")&&elem.parentNode)throw"type property can't be changed";elem[name]=value;}if(jQuery.nodeName(elem,"form")&&elem.getAttributeNode(name))return elem.getAttributeNode(name).nodeValue;return elem[name];}if(msie&¬xml&&name=="style")return jQuery.attr(elem.style,"cssText",value);if(set)elem.setAttribute(name,""+value);var attr=msie&¬xml&&special?elem.getAttribute(name,2):elem.getAttribute(name);return attr===null?undefined:attr;}if(msie&&name=="opacity"){if(set){elem.zoom=1;elem.filter=(elem.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(value)+''=="NaN"?"":"alpha(opacity="+value*100+")");}return elem.filter&&elem.filter.indexOf("opacity=")>=0?(parseFloat(elem.filter.match(/opacity=([^)]*)/)[1])/100)+'':"";}name=name.replace(/-([a-z])/ig,function(all,letter){return letter.toUpperCase();});if(set)elem[name]=value;return elem[name];},trim:function(text){return(text||"").replace(/^\s+|\s+$/g,"");},makeArray:function(array){var ret=[];if(array!=null){var i=array.length;if(i==null||array.split||array.setInterval||array.call)ret[0]=array;else while(i)ret[--i]=array[i];}return ret;},inArray:function(elem,array){for(var i=0,length=array.length;i*",this).remove();while(this.firstChild)this.removeChild(this.firstChild);}},function(name,fn){jQuery.fn[name]=function(){return this.each(fn,arguments);};});jQuery.each(["Height","Width"],function(i,name){var type=name.toLowerCase();jQuery.fn[type]=function(size){return this[0]==window?jQuery.browser.opera&&document.body["client"+name]||jQuery.browser.safari&&window["inner"+name]||document.compatMode=="CSS1Compat"&&document.documentElement["client"+name]||document.body["client"+name]:this[0]==document?Math.max(Math.max(document.body["scroll"+name],document.documentElement["scroll"+name]),Math.max(document.body["offset"+name],document.documentElement["offset"+name])):size==undefined?(this.length?jQuery.css(this[0],type):null):this.css(type,size.constructor==String?size:size+"px");};});function num(elem,prop){return elem[0]&&parseInt(jQuery.curCSS(elem[0],prop,true),10)||0;}var chars=jQuery.browser.safari&&parseInt(jQuery.browser.version)<417?"(?:[\\w*_-]|\\\\.)":"(?:[\\w\u0128-\uFFFF*_-]|\\\\.)",quickChild=new RegExp("^>\\s*("+chars+"+)"),quickID=new RegExp("^("+chars+"+)(#)("+chars+"+)"),quickClass=new RegExp("^([#.]?)("+chars+"*)");jQuery.extend({expr:{"":function(a,i,m){return m[2]=="*"||jQuery.nodeName(a,m[2]);},"#":function(a,i,m){return a.getAttribute("id")==m[2];},":":{lt:function(a,i,m){return im[3]-0;},nth:function(a,i,m){return m[3]-0==i;},eq:function(a,i,m){return m[3]-0==i;},first:function(a,i){return i==0;},last:function(a,i,m,r){return i==r.length-1;},even:function(a,i){return i%2==0;},odd:function(a,i){return i%2;},"first-child":function(a){return a.parentNode.getElementsByTagName("*")[0]==a;},"last-child":function(a){return jQuery.nth(a.parentNode.lastChild,1,"previousSibling")==a;},"only-child":function(a){return!jQuery.nth(a.parentNode.lastChild,2,"previousSibling");},parent:function(a){return a.firstChild;},empty:function(a){return!a.firstChild;},contains:function(a,i,m){return(a.textContent||a.innerText||jQuery(a).text()||"").indexOf(m[3])>=0;},visible:function(a){return"hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden";},hidden:function(a){return"hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden";},enabled:function(a){return!a.disabled;},disabled:function(a){return a.disabled;},checked:function(a){return a.checked;},selected:function(a){return a.selected||jQuery.attr(a,"selected");},text:function(a){return"text"==a.type;},radio:function(a){return"radio"==a.type;},checkbox:function(a){return"checkbox"==a.type;},file:function(a){return"file"==a.type;},password:function(a){return"password"==a.type;},submit:function(a){return"submit"==a.type;},image:function(a){return"image"==a.type;},reset:function(a){return"reset"==a.type;},button:function(a){return"button"==a.type||jQuery.nodeName(a,"button");},input:function(a){return/input|select|textarea|button/i.test(a.nodeName);},has:function(a,i,m){return jQuery.find(m[3],a).length;},header:function(a){return/h\d/i.test(a.nodeName);},animated:function(a){return jQuery.grep(jQuery.timers,function(fn){return a==fn.elem;}).length;}}},parse:[/^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,/^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,new RegExp("^([:.#]*)("+chars+"+)")],multiFilter:function(expr,elems,not){var old,cur=[];while(expr&&expr!=old){old=expr;var f=jQuery.filter(expr,elems,not);expr=f.t.replace(/^\s*,\s*/,"");cur=not?elems=f.r:jQuery.merge(cur,f.r);}return cur;},find:function(t,context){if(typeof t!="string")return[t];if(context&&context.nodeType!=1&&context.nodeType!=9)return[];context=context||document;var ret=[context],done=[],last,nodeName;while(t&&last!=t){var r=[];last=t;t=jQuery.trim(t);var foundToken=false,re=quickChild,m=re.exec(t);if(m){nodeName=m[1].toUpperCase();for(var i=0;ret[i];i++)for(var c=ret[i].firstChild;c;c=c.nextSibling)if(c.nodeType==1&&(nodeName=="*"||c.nodeName.toUpperCase()==nodeName))r.push(c);ret=r;t=t.replace(re,"");if(t.indexOf(" ")==0)continue;foundToken=true;}else{re=/^([>+~])\s*(\w*)/i;if((m=re.exec(t))!=null){r=[];var merge={};nodeName=m[2].toUpperCase();m=m[1];for(var j=0,rl=ret.length;j=0;if(!not&&pass||not&&!pass)tmp.push(r[i]);}return tmp;},filter:function(t,r,not){var last;while(t&&t!=last){last=t;var p=jQuery.parse,m;for(var i=0;p[i];i++){m=p[i].exec(t);if(m){t=t.substring(m[0].length);m[2]=m[2].replace(/\\/g,"");break;}}if(!m)break;if(m[1]==":"&&m[2]=="not")r=isSimple.test(m[3])?jQuery.filter(m[3],r,true).r:jQuery(r).not(m[3]);else if(m[1]==".")r=jQuery.classFilter(r,m[2],not);else if(m[1]=="["){var tmp=[],type=m[3];for(var i=0,rl=r.length;i=0)^not)tmp.push(a);}r=tmp;}else if(m[1]==":"&&m[2]=="nth-child"){var merge={},tmp=[],test=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(m[3]=="even"&&"2n"||m[3]=="odd"&&"2n+1"||!/\D/.test(m[3])&&"0n+"+m[3]||m[3]),first=(test[1]+(test[2]||1))-0,last=test[3]-0;for(var i=0,rl=r.length;i=0)add=true;if(add^not)tmp.push(node);}r=tmp;}else{var fn=jQuery.expr[m[1]];if(typeof fn=="object")fn=fn[m[2]];if(typeof fn=="string")fn=eval("false||function(a,i){return "+fn+";}");r=jQuery.grep(r,function(elem,i){return fn(elem,i,m,r);},not);}}return{r:r,t:t};},dir:function(elem,dir){var matched=[],cur=elem[dir];while(cur&&cur!=document){if(cur.nodeType==1)matched.push(cur);cur=cur[dir];}return matched;},nth:function(cur,result,dir,elem){result=result||1;var num=0;for(;cur;cur=cur[dir])if(cur.nodeType==1&&++num==result)break;return cur;},sibling:function(n,elem){var r=[];for(;n;n=n.nextSibling){if(n.nodeType==1&&n!=elem)r.push(n);}return r;}});jQuery.event={add:function(elem,types,handler,data){if(elem.nodeType==3||elem.nodeType==8)return;if(jQuery.browser.msie&&elem.setInterval)elem=window;if(!handler.guid)handler.guid=this.guid++;if(data!=undefined){var fn=handler;handler=this.proxy(fn,function(){return fn.apply(this,arguments);});handler.data=data;}var events=jQuery.data(elem,"events")||jQuery.data(elem,"events",{}),handle=jQuery.data(elem,"handle")||jQuery.data(elem,"handle",function(){if(typeof jQuery!="undefined"&&!jQuery.event.triggered)return jQuery.event.handle.apply(arguments.callee.elem,arguments);});handle.elem=elem;jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];handler.type=parts[1];var handlers=events[type];if(!handlers){handlers=events[type]={};if(!jQuery.event.special[type]||jQuery.event.special[type].setup.call(elem)===false){if(elem.addEventListener)elem.addEventListener(type,handle,false);else if(elem.attachEvent)elem.attachEvent("on"+type,handle);}}handlers[handler.guid]=handler;jQuery.event.global[type]=true;});elem=null;},guid:1,global:{},remove:function(elem,types,handler){if(elem.nodeType==3||elem.nodeType==8)return;var events=jQuery.data(elem,"events"),ret,index;if(events){if(types==undefined||(typeof types=="string"&&types.charAt(0)=="."))for(var type in events)this.remove(elem,type+(types||""));else{if(types.type){handler=types.handler;types=types.type;}jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];if(events[type]){if(handler)delete events[type][handler.guid];else for(handler in events[type])if(!parts[1]||events[type][handler].type==parts[1])delete events[type][handler];for(ret in events[type])break;if(!ret){if(!jQuery.event.special[type]||jQuery.event.special[type].teardown.call(elem)===false){if(elem.removeEventListener)elem.removeEventListener(type,jQuery.data(elem,"handle"),false);else if(elem.detachEvent)elem.detachEvent("on"+type,jQuery.data(elem,"handle"));}ret=null;delete events[type];}}});}for(ret in events)break;if(!ret){var handle=jQuery.data(elem,"handle");if(handle)handle.elem=null;jQuery.removeData(elem,"events");jQuery.removeData(elem,"handle");}}},trigger:function(type,data,elem,donative,extra){data=jQuery.makeArray(data);if(type.indexOf("!")>=0){type=type.slice(0,-1);var exclusive=true;}if(!elem){if(this.global[type])jQuery("*").add([window,document]).trigger(type,data);}else{if(elem.nodeType==3||elem.nodeType==8)return undefined;var val,ret,fn=jQuery.isFunction(elem[type]||null),event=!data[0]||!data[0].preventDefault;if(event){data.unshift({type:type,target:elem,preventDefault:function(){},stopPropagation:function(){},timeStamp:now()});data[0][expando]=true;}data[0].type=type;if(exclusive)data[0].exclusive=true;var handle=jQuery.data(elem,"handle");if(handle)val=handle.apply(elem,data);if((!fn||(jQuery.nodeName(elem,'a')&&type=="click"))&&elem["on"+type]&&elem["on"+type].apply(elem,data)===false)val=false;if(event)data.shift();if(extra&&jQuery.isFunction(extra)){ret=extra.apply(elem,val==null?data:data.concat(val));if(ret!==undefined)val=ret;}if(fn&&donative!==false&&val!==false&&!(jQuery.nodeName(elem,'a')&&type=="click")){this.triggered=true;try{elem[type]();}catch(e){}}this.triggered=false;}return val;},handle:function(event){var val,ret,namespace,all,handlers;event=arguments[0]=jQuery.event.fix(event||window.event);namespace=event.type.split(".");event.type=namespace[0];namespace=namespace[1];all=!namespace&&!event.exclusive;handlers=(jQuery.data(this,"events")||{})[event.type];for(var j in handlers){var handler=handlers[j];if(all||handler.type==namespace){event.handler=handler;event.data=handler.data;ret=handler.apply(this,arguments);if(val!==false)val=ret;if(ret===false){event.preventDefault();event.stopPropagation();}}}return val;},fix:function(event){if(event[expando]==true)return event;var originalEvent=event;event={originalEvent:originalEvent};var props="altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target timeStamp toElement type view wheelDelta which".split(" ");for(var i=props.length;i;i--)event[props[i]]=originalEvent[props[i]];event[expando]=true;event.preventDefault=function(){if(originalEvent.preventDefault)originalEvent.preventDefault();originalEvent.returnValue=false;};event.stopPropagation=function(){if(originalEvent.stopPropagation)originalEvent.stopPropagation();originalEvent.cancelBubble=true;};event.timeStamp=event.timeStamp||now();if(!event.target)event.target=event.srcElement||document;if(event.target.nodeType==3)event.target=event.target.parentNode;if(!event.relatedTarget&&event.fromElement)event.relatedTarget=event.fromElement==event.target?event.toElement:event.fromElement;if(event.pageX==null&&event.clientX!=null){var doc=document.documentElement,body=document.body;event.pageX=event.clientX+(doc&&doc.scrollLeft||body&&body.scrollLeft||0)-(doc.clientLeft||0);event.pageY=event.clientY+(doc&&doc.scrollTop||body&&body.scrollTop||0)-(doc.clientTop||0);}if(!event.which&&((event.charCode||event.charCode===0)?event.charCode:event.keyCode))event.which=event.charCode||event.keyCode;if(!event.metaKey&&event.ctrlKey)event.metaKey=event.ctrlKey;if(!event.which&&event.button)event.which=(event.button&1?1:(event.button&2?3:(event.button&4?2:0)));return event;},proxy:function(fn,proxy){proxy.guid=fn.guid=fn.guid||proxy.guid||this.guid++;return proxy;},special:{ready:{setup:function(){bindReady();return;},teardown:function(){return;}},mouseenter:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseover",jQuery.event.special.mouseenter.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseover",jQuery.event.special.mouseenter.handler);return true;},handler:function(event){if(withinElement(event,this))return true;event.type="mouseenter";return jQuery.event.handle.apply(this,arguments);}},mouseleave:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseout",jQuery.event.special.mouseleave.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseout",jQuery.event.special.mouseleave.handler);return true;},handler:function(event){if(withinElement(event,this))return true;event.type="mouseleave";return jQuery.event.handle.apply(this,arguments);}}}};jQuery.fn.extend({bind:function(type,data,fn){return type=="unload"?this.one(type,data,fn):this.each(function(){jQuery.event.add(this,type,fn||data,fn&&data);});},one:function(type,data,fn){var one=jQuery.event.proxy(fn||data,function(event){jQuery(this).unbind(event,one);return(fn||data).apply(this,arguments);});return this.each(function(){jQuery.event.add(this,type,one,fn&&data);});},unbind:function(type,fn){return this.each(function(){jQuery.event.remove(this,type,fn);});},trigger:function(type,data,fn){return this.each(function(){jQuery.event.trigger(type,data,this,true,fn);});},triggerHandler:function(type,data,fn){return this[0]&&jQuery.event.trigger(type,data,this[0],false,fn);},toggle:function(fn){var args=arguments,i=1;while(i=0){var selector=url.slice(off,url.length);url=url.slice(0,off);}callback=callback||function(){};var type="GET";if(params)if(jQuery.isFunction(params)){callback=params;params=null;}else{params=jQuery.param(params);type="POST";}var self=this;jQuery.ajax({url:url,type:type,dataType:"html",data:params,complete:function(res,status){if(status=="success"||status=="notmodified")self.html(selector?jQuery("
").append(res.responseText.replace(//g,"")).find(selector):res.responseText);self.each(callback,[res.responseText,status,res]);}});return this;},serialize:function(){return jQuery.param(this.serializeArray());},serializeArray:function(){return this.map(function(){return jQuery.nodeName(this,"form")?jQuery.makeArray(this.elements):this;}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password/i.test(this.type));}).map(function(i,elem){var val=jQuery(this).val();return val==null?null:val.constructor==Array?jQuery.map(val,function(val,i){return{name:elem.name,value:val};}):{name:elem.name,value:val};}).get();}});jQuery.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(i,o){jQuery.fn[o]=function(f){return this.bind(o,f);};});var jsc=now();jQuery.extend({get:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data=null;}return jQuery.ajax({type:"GET",url:url,data:data,success:callback,dataType:type});},getScript:function(url,callback){return jQuery.get(url,null,callback,"script");},getJSON:function(url,data,callback){return jQuery.get(url,data,callback,"json");},post:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data={};}return jQuery.ajax({type:"POST",url:url,data:data,success:callback,dataType:type});},ajaxSetup:function(settings){jQuery.extend(jQuery.ajaxSettings,settings);},ajaxSettings:{url:location.href,global:true,type:"GET",timeout:0,contentType:"application/x-www-form-urlencoded",processData:true,async:true,data:null,username:null,password:null,accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(s){s=jQuery.extend(true,s,jQuery.extend(true,{},jQuery.ajaxSettings,s));var jsonp,jsre=/=\?(&|$)/g,status,data,type=s.type.toUpperCase();if(s.data&&s.processData&&typeof s.data!="string")s.data=jQuery.param(s.data);if(s.dataType=="jsonp"){if(type=="GET"){if(!s.url.match(jsre))s.url+=(s.url.match(/\?/)?"&":"?")+(s.jsonp||"callback")+"=?";}else if(!s.data||!s.data.match(jsre))s.data=(s.data?s.data+"&":"")+(s.jsonp||"callback")+"=?";s.dataType="json";}if(s.dataType=="json"&&(s.data&&s.data.match(jsre)||s.url.match(jsre))){jsonp="jsonp"+jsc++;if(s.data)s.data=(s.data+"").replace(jsre,"="+jsonp+"$1");s.url=s.url.replace(jsre,"="+jsonp+"$1");s.dataType="script";window[jsonp]=function(tmp){data=tmp;success();complete();window[jsonp]=undefined;try{delete window[jsonp];}catch(e){}if(head)head.removeChild(script);};}if(s.dataType=="script"&&s.cache==null)s.cache=false;if(s.cache===false&&type=="GET"){var ts=now();var ret=s.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+ts+"$2");s.url=ret+((ret==s.url)?(s.url.match(/\?/)?"&":"?")+"_="+ts:"");}if(s.data&&type=="GET"){s.url+=(s.url.match(/\?/)?"&":"?")+s.data;s.data=null;}if(s.global&&!jQuery.active++)jQuery.event.trigger("ajaxStart");var remote=/^(?:\w+:)?\/\/([^\/?#]+)/;if(s.dataType=="script"&&type=="GET"&&remote.test(s.url)&&remote.exec(s.url)[1]!=location.host){var head=document.getElementsByTagName("head")[0];var script=document.createElement("script");script.src=s.url;if(s.scriptCharset)script.charset=s.scriptCharset;if(!jsonp){var done=false;script.onload=script.onreadystatechange=function(){if(!done&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){done=true;success();complete();head.removeChild(script);}};}head.appendChild(script);return undefined;}var requestDone=false;var xhr=window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();if(s.username)xhr.open(type,s.url,s.async,s.username,s.password);else xhr.open(type,s.url,s.async);try{if(s.data)xhr.setRequestHeader("Content-Type",s.contentType);if(s.ifModified)xhr.setRequestHeader("If-Modified-Since",jQuery.lastModified[s.url]||"Thu, 01 Jan 1970 00:00:00 GMT");xhr.setRequestHeader("X-Requested-With","XMLHttpRequest");xhr.setRequestHeader("Accept",s.dataType&&s.accepts[s.dataType]?s.accepts[s.dataType]+", */*":s.accepts._default);}catch(e){}if(s.beforeSend&&s.beforeSend(xhr,s)===false){s.global&&jQuery.active--;xhr.abort();return false;}if(s.global)jQuery.event.trigger("ajaxSend",[xhr,s]);var onreadystatechange=function(isTimeout){if(!requestDone&&xhr&&(xhr.readyState==4||isTimeout=="timeout")){requestDone=true;if(ival){clearInterval(ival);ival=null;}status=isTimeout=="timeout"&&"timeout"||!jQuery.httpSuccess(xhr)&&"error"||s.ifModified&&jQuery.httpNotModified(xhr,s.url)&&"notmodified"||"success";if(status=="success"){try{data=jQuery.httpData(xhr,s.dataType,s.dataFilter);}catch(e){status="parsererror";}}if(status=="success"){var modRes;try{modRes=xhr.getResponseHeader("Last-Modified");}catch(e){}if(s.ifModified&&modRes)jQuery.lastModified[s.url]=modRes;if(!jsonp)success();}else jQuery.handleError(s,xhr,status);complete();if(s.async)xhr=null;}};if(s.async){var ival=setInterval(onreadystatechange,13);if(s.timeout>0)setTimeout(function(){if(xhr){xhr.abort();if(!requestDone)onreadystatechange("timeout");}},s.timeout);}try{xhr.send(s.data);}catch(e){jQuery.handleError(s,xhr,null,e);}if(!s.async)onreadystatechange();function success(){if(s.success)s.success(data,status);if(s.global)jQuery.event.trigger("ajaxSuccess",[xhr,s]);}function complete(){if(s.complete)s.complete(xhr,status);if(s.global)jQuery.event.trigger("ajaxComplete",[xhr,s]);if(s.global&&!--jQuery.active)jQuery.event.trigger("ajaxStop");}return xhr;},handleError:function(s,xhr,status,e){if(s.error)s.error(xhr,status,e);if(s.global)jQuery.event.trigger("ajaxError",[xhr,s,e]);},active:0,httpSuccess:function(xhr){try{return!xhr.status&&location.protocol=="file:"||(xhr.status>=200&&xhr.status<300)||xhr.status==304||xhr.status==1223||jQuery.browser.safari&&xhr.status==undefined;}catch(e){}return false;},httpNotModified:function(xhr,url){try{var xhrRes=xhr.getResponseHeader("Last-Modified");return xhr.status==304||xhrRes==jQuery.lastModified[url]||jQuery.browser.safari&&xhr.status==undefined;}catch(e){}return false;},httpData:function(xhr,type,filter){var ct=xhr.getResponseHeader("content-type"),xml=type=="xml"||!type&&ct&&ct.indexOf("xml")>=0,data=xml?xhr.responseXML:xhr.responseText;if(xml&&data.documentElement.tagName=="parsererror")throw"parsererror";if(filter)data=filter(data,type);if(type=="script")jQuery.globalEval(data);if(type=="json")data=eval("("+data+")");return data;},param:function(a){var s=[];if(a.constructor==Array||a.jquery)jQuery.each(a,function(){s.push(encodeURIComponent(this.name)+"="+encodeURIComponent(this.value));});else for(var j in a)if(a[j]&&a[j].constructor==Array)jQuery.each(a[j],function(){s.push(encodeURIComponent(j)+"="+encodeURIComponent(this));});else s.push(encodeURIComponent(j)+"="+encodeURIComponent(jQuery.isFunction(a[j])?a[j]():a[j]));return s.join("&").replace(/%20/g,"+");}});jQuery.fn.extend({show:function(speed,callback){return speed?this.animate({height:"show",width:"show",opacity:"show"},speed,callback):this.filter(":hidden").each(function(){this.style.display=this.oldblock||"";if(jQuery.css(this,"display")=="none"){var elem=jQuery("<"+this.tagName+" />").appendTo("body");this.style.display=elem.css("display");if(this.style.display=="none")this.style.display="block";elem.remove();}}).end();},hide:function(speed,callback){return speed?this.animate({height:"hide",width:"hide",opacity:"hide"},speed,callback):this.filter(":visible").each(function(){this.oldblock=this.oldblock||jQuery.css(this,"display");this.style.display="none";}).end();},_toggle:jQuery.fn.toggle,toggle:function(fn,fn2){return jQuery.isFunction(fn)&&jQuery.isFunction(fn2)?this._toggle.apply(this,arguments):fn?this.animate({height:"toggle",width:"toggle",opacity:"toggle"},fn,fn2):this.each(function(){jQuery(this)[jQuery(this).is(":hidden")?"show":"hide"]();});},slideDown:function(speed,callback){return this.animate({height:"show"},speed,callback);},slideUp:function(speed,callback){return this.animate({height:"hide"},speed,callback);},slideToggle:function(speed,callback){return this.animate({height:"toggle"},speed,callback);},fadeIn:function(speed,callback){return this.animate({opacity:"show"},speed,callback);},fadeOut:function(speed,callback){return this.animate({opacity:"hide"},speed,callback);},fadeTo:function(speed,to,callback){return this.animate({opacity:to},speed,callback);},animate:function(prop,speed,easing,callback){var optall=jQuery.speed(speed,easing,callback);return this[optall.queue===false?"each":"queue"](function(){if(this.nodeType!=1)return false;var opt=jQuery.extend({},optall),p,hidden=jQuery(this).is(":hidden"),self=this;for(p in prop){if(prop[p]=="hide"&&hidden||prop[p]=="show"&&!hidden)return opt.complete.call(this);if(p=="height"||p=="width"){opt.display=jQuery.css(this,"display");opt.overflow=this.style.overflow;}}if(opt.overflow!=null)this.style.overflow="hidden";opt.curAnim=jQuery.extend({},prop);jQuery.each(prop,function(name,val){var e=new jQuery.fx(self,opt,name);if(/toggle|show|hide/.test(val))e[val=="toggle"?hidden?"show":"hide":val](prop);else{var parts=val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),start=e.cur(true)||0;if(parts){var end=parseFloat(parts[2]),unit=parts[3]||"px";if(unit!="px"){self.style[name]=(end||1)+unit;start=((end||1)/e.cur(true))*start;self.style[name]=start+unit;}if(parts[1])end=((parts[1]=="-="?-1:1)*end)+start;e.custom(start,end,unit);}else e.custom(start,val,"");}});return true;});},queue:function(type,fn){if(jQuery.isFunction(type)||(type&&type.constructor==Array)){fn=type;type="fx";}if(!type||(typeof type=="string"&&!fn))return queue(this[0],type);return this.each(function(){if(fn.constructor==Array)queue(this,type,fn);else{queue(this,type).push(fn);if(queue(this,type).length==1)fn.call(this);}});},stop:function(clearQueue,gotoEnd){var timers=jQuery.timers;if(clearQueue)this.queue([]);this.each(function(){for(var i=timers.length-1;i>=0;i--)if(timers[i].elem==this){if(gotoEnd)timers[i](true);timers.splice(i,1);}});if(!gotoEnd)this.dequeue();return this;}});var queue=function(elem,type,array){if(elem){type=type||"fx";var q=jQuery.data(elem,type+"queue");if(!q||array)q=jQuery.data(elem,type+"queue",jQuery.makeArray(array));}return q;};jQuery.fn.dequeue=function(type){type=type||"fx";return this.each(function(){var q=queue(this,type);q.shift();if(q.length)q[0].call(this);});};jQuery.extend({speed:function(speed,easing,fn){var opt=speed&&speed.constructor==Object?speed:{complete:fn||!fn&&easing||jQuery.isFunction(speed)&&speed,duration:speed,easing:fn&&easing||easing&&easing.constructor!=Function&&easing};opt.duration=(opt.duration&&opt.duration.constructor==Number?opt.duration:jQuery.fx.speeds[opt.duration])||jQuery.fx.speeds.def;opt.old=opt.complete;opt.complete=function(){if(opt.queue!==false)jQuery(this).dequeue();if(jQuery.isFunction(opt.old))opt.old.call(this);};return opt;},easing:{linear:function(p,n,firstNum,diff){return firstNum+diff*p;},swing:function(p,n,firstNum,diff){return((-Math.cos(p*Math.PI)/2)+0.5)*diff+firstNum;}},timers:[],timerId:null,fx:function(elem,options,prop){this.options=options;this.elem=elem;this.prop=prop;if(!options.orig)options.orig={};}});jQuery.fx.prototype={update:function(){if(this.options.step)this.options.step.call(this.elem,this.now,this);(jQuery.fx.step[this.prop]||jQuery.fx.step._default)(this);if(this.prop=="height"||this.prop=="width")this.elem.style.display="block";},cur:function(force){if(this.elem[this.prop]!=null&&this.elem.style[this.prop]==null)return this.elem[this.prop];var r=parseFloat(jQuery.css(this.elem,this.prop,force));return r&&r>-10000?r:parseFloat(jQuery.curCSS(this.elem,this.prop))||0;},custom:function(from,to,unit){this.startTime=now();this.start=from;this.end=to;this.unit=unit||this.unit||"px";this.now=this.start;this.pos=this.state=0;this.update();var self=this;function t(gotoEnd){return self.step(gotoEnd);}t.elem=this.elem;jQuery.timers.push(t);if(jQuery.timerId==null){jQuery.timerId=setInterval(function(){var timers=jQuery.timers;for(var i=0;ithis.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var done=true;for(var i in this.options.curAnim)if(this.options.curAnim[i]!==true)done=false;if(done){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(jQuery.css(this.elem,"display")=="none")this.elem.style.display="block";}if(this.options.hide)this.elem.style.display="none";if(this.options.hide||this.options.show)for(var p in this.options.curAnim)jQuery.attr(this.elem.style,p,this.options.orig[p]);}if(done)this.options.complete.call(this.elem);return false;}else{var n=t-this.startTime;this.state=n/this.options.duration;this.pos=jQuery.easing[this.options.easing||(jQuery.easing.swing?"swing":"linear")](this.state,n,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update();}return true;}};jQuery.extend(jQuery.fx,{speeds:{slow:600,fast:200,def:400},step:{scrollLeft:function(fx){fx.elem.scrollLeft=fx.now;},scrollTop:function(fx){fx.elem.scrollTop=fx.now;},opacity:function(fx){jQuery.attr(fx.elem.style,"opacity",fx.now);},_default:function(fx){fx.elem.style[fx.prop]=fx.now+fx.unit;}}});jQuery.fn.offset=function(){var left=0,top=0,elem=this[0],results;if(elem)with(jQuery.browser){var parent=elem.parentNode,offsetChild=elem,offsetParent=elem.offsetParent,doc=elem.ownerDocument,safari2=safari&&parseInt(version)<522&&!/adobeair/i.test(userAgent),css=jQuery.curCSS,fixed=css(elem,"position")=="fixed";if(elem.getBoundingClientRect){var box=elem.getBoundingClientRect();add(box.left+Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),box.top+Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));add(-doc.documentElement.clientLeft,-doc.documentElement.clientTop);}else{add(elem.offsetLeft,elem.offsetTop);while(offsetParent){add(offsetParent.offsetLeft,offsetParent.offsetTop);if(mozilla&&!/^t(able|d|h)$/i.test(offsetParent.tagName)||safari&&!safari2)border(offsetParent);if(!fixed&&css(offsetParent,"position")=="fixed")fixed=true;offsetChild=/^body$/i.test(offsetParent.tagName)?offsetChild:offsetParent;offsetParent=offsetParent.offsetParent;}while(parent&&parent.tagName&&!/^body|html$/i.test(parent.tagName)){if(!/^inline|table.*$/i.test(css(parent,"display")))add(-parent.scrollLeft,-parent.scrollTop);if(mozilla&&css(parent,"overflow")!="visible")border(parent);parent=parent.parentNode;}if((safari2&&(fixed||css(offsetChild,"position")=="absolute"))||(mozilla&&css(offsetChild,"position")!="absolute"))add(-doc.body.offsetLeft,-doc.body.offsetTop);if(fixed)add(Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));}results={top:top,left:left};}function border(elem){add(jQuery.curCSS(elem,"borderLeftWidth",true),jQuery.curCSS(elem,"borderTopWidth",true));}function add(l,t){left+=parseInt(l,10)||0;top+=parseInt(t,10)||0;}return results;};jQuery.fn.extend({position:function(){var left=0,top=0,results;if(this[0]){var offsetParent=this.offsetParent(),offset=this.offset(),parentOffset=/^body|html$/i.test(offsetParent[0].tagName)?{top:0,left:0}:offsetParent.offset();offset.top-=num(this,'marginTop');offset.left-=num(this,'marginLeft');parentOffset.top+=num(offsetParent,'borderTopWidth');parentOffset.left+=num(offsetParent,'borderLeftWidth');results={top:offset.top-parentOffset.top,left:offset.left-parentOffset.left};}return results;},offsetParent:function(){var offsetParent=this[0].offsetParent;while(offsetParent&&(!/^body|html$/i.test(offsetParent.tagName)&&jQuery.css(offsetParent,'position')=='static'))offsetParent=offsetParent.offsetParent;return jQuery(offsetParent);}});jQuery.each(['Left','Top'],function(i,name){var method='scroll'+name;jQuery.fn[method]=function(val){if(!this[0])return;return val!=undefined?this.each(function(){this==window||this==document?window.scrollTo(!i?val:jQuery(window).scrollLeft(),i?val:jQuery(window).scrollTop()):this[method]=val;}):this[0]==window||this[0]==document?self[i?'pageYOffset':'pageXOffset']||jQuery.boxModel&&document.documentElement[method]||document.body[method]:this[0][method];};});jQuery.each(["Height","Width"],function(i,name){var tl=i?"Left":"Top",br=i?"Right":"Bottom";jQuery.fn["inner"+name]=function(){return this[name.toLowerCase()]()+num(this,"padding"+tl)+num(this,"padding"+br);};jQuery.fn["outer"+name]=function(margin){return this["inner"+name]()+num(this,"border"+tl+"Width")+num(this,"border"+br+"Width")+(margin?num(this,"margin"+tl)+num(this,"margin"+br):0);};});})();crcmod-1.7/docs/html/_static/pygments.css0000644000175000017500000000623011410125142020102 0ustar rlbrlb00000000000000.hll { background-color: #ffffcc } .c { color: #408090; font-style: italic } /* Comment */ .err { border: 1px solid #FF0000 } /* Error */ .k { color: #007020; font-weight: bold } /* Keyword */ .o { color: #666666 } /* Operator */ .cm { color: #408090; font-style: italic } /* Comment.Multiline */ .cp { color: #007020 } /* Comment.Preproc */ .c1 { color: #408090; font-style: italic } /* Comment.Single */ .cs { color: #408090; background-color: #fff0f0 } /* Comment.Special */ .gd { color: #A00000 } /* Generic.Deleted */ .ge { font-style: italic } /* Generic.Emph */ .gr { color: #FF0000 } /* Generic.Error */ .gh { color: #000080; font-weight: bold } /* Generic.Heading */ .gi { color: #00A000 } /* Generic.Inserted */ .go { color: #303030 } /* Generic.Output */ .gp { color: #c65d09; font-weight: bold } /* Generic.Prompt */ .gs { font-weight: bold } /* Generic.Strong */ .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ .gt { color: #0040D0 } /* Generic.Traceback */ .kc { color: #007020; font-weight: bold } /* Keyword.Constant */ .kd { color: #007020; font-weight: bold } /* Keyword.Declaration */ .kn { color: #007020; font-weight: bold } /* Keyword.Namespace */ .kp { color: #007020 } /* Keyword.Pseudo */ .kr { color: #007020; font-weight: bold } /* Keyword.Reserved */ .kt { color: #902000 } /* Keyword.Type */ .m { color: #208050 } /* Literal.Number */ .s { color: #4070a0 } /* Literal.String */ .na { color: #4070a0 } /* Name.Attribute */ .nb { color: #007020 } /* Name.Builtin */ .nc { color: #0e84b5; font-weight: bold } /* Name.Class */ .no { color: #60add5 } /* Name.Constant */ .nd { color: #555555; font-weight: bold } /* Name.Decorator */ .ni { color: #d55537; font-weight: bold } /* Name.Entity */ .ne { color: #007020 } /* Name.Exception */ .nf { color: #06287e } /* Name.Function */ .nl { color: #002070; font-weight: bold } /* Name.Label */ .nn { color: #0e84b5; font-weight: bold } /* Name.Namespace */ .nt { color: #062873; font-weight: bold } /* Name.Tag */ .nv { color: #bb60d5 } /* Name.Variable */ .ow { color: #007020; font-weight: bold } /* Operator.Word */ .w { color: #bbbbbb } /* Text.Whitespace */ .mf { color: #208050 } /* Literal.Number.Float */ .mh { color: #208050 } /* Literal.Number.Hex */ .mi { color: #208050 } /* Literal.Number.Integer */ .mo { color: #208050 } /* Literal.Number.Oct */ .sb { color: #4070a0 } /* Literal.String.Backtick */ .sc { color: #4070a0 } /* Literal.String.Char */ .sd { color: #4070a0; font-style: italic } /* Literal.String.Doc */ .s2 { color: #4070a0 } /* Literal.String.Double */ .se { color: #4070a0; font-weight: bold } /* Literal.String.Escape */ .sh { color: #4070a0 } /* Literal.String.Heredoc */ .si { color: #70a0d0; font-style: italic } /* Literal.String.Interpol */ .sx { color: #c65d09 } /* Literal.String.Other */ .sr { color: #235388 } /* Literal.String.Regex */ .s1 { color: #4070a0 } /* Literal.String.Single */ .ss { color: #517918 } /* Literal.String.Symbol */ .bp { color: #007020 } /* Name.Builtin.Pseudo */ .vc { color: #bb60d5 } /* Name.Variable.Class */ .vg { color: #bb60d5 } /* Name.Variable.Global */ .vi { color: #bb60d5 } /* Name.Variable.Instance */ .il { color: #208050 } /* Literal.Number.Integer.Long */crcmod-1.7/docs/html/_static/plus.png0000644000175000017500000000030711345457043017231 0ustar rlbrlb00000000000000PNG  IHDR &q pHYs  tIME 1l9tEXtComment̖RIDATcz(BpipPc |IENDB`crcmod-1.7/docs/html/_static/default.css0000644000175000017500000000664411410125142017671 0ustar rlbrlb00000000000000/** * Sphinx stylesheet -- default theme * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ @import url("basic.css"); /* -- page layout ----------------------------------------------------------- */ body { font-family: sans-serif; font-size: 100%; background-color: #11303d; color: #000; margin: 0; padding: 0; } div.document { background-color: #1c4e63; } div.documentwrapper { float: left; width: 100%; } div.bodywrapper { margin: 0 0 0 230px; } div.body { background-color: #ffffff; color: #000000; padding: 0 20px 30px 20px; } div.footer { color: #ffffff; width: 100%; padding: 9px 0 9px 0; text-align: center; font-size: 75%; } div.footer a { color: #ffffff; text-decoration: underline; } div.related { background-color: #133f52; line-height: 30px; color: #ffffff; } div.related a { color: #ffffff; } div.sphinxsidebar { } div.sphinxsidebar h3 { font-family: 'Trebuchet MS', sans-serif; color: #ffffff; font-size: 1.4em; font-weight: normal; margin: 0; padding: 0; } div.sphinxsidebar h3 a { color: #ffffff; } div.sphinxsidebar h4 { font-family: 'Trebuchet MS', sans-serif; color: #ffffff; font-size: 1.3em; font-weight: normal; margin: 5px 0 0 0; padding: 0; } div.sphinxsidebar p { color: #ffffff; } div.sphinxsidebar p.topless { margin: 5px 10px 10px 10px; } div.sphinxsidebar ul { margin: 10px; padding: 0; color: #ffffff; } div.sphinxsidebar a { color: #98dbcc; } div.sphinxsidebar input { border: 1px solid #98dbcc; font-family: sans-serif; font-size: 1em; } /* -- body styles ----------------------------------------------------------- */ a { color: #355f7c; text-decoration: none; } a:hover { text-decoration: underline; } div.body p, div.body dd, div.body li { text-align: justify; line-height: 130%; } div.body h1, div.body h2, div.body h3, div.body h4, div.body h5, div.body h6 { font-family: 'Trebuchet MS', sans-serif; background-color: #f2f2f2; font-weight: normal; color: #20435c; border-bottom: 1px solid #ccc; margin: 20px -20px 10px -20px; padding: 3px 0 3px 10px; } div.body h1 { margin-top: 0; font-size: 200%; } div.body h2 { font-size: 160%; } div.body h3 { font-size: 140%; } div.body h4 { font-size: 120%; } div.body h5 { font-size: 110%; } div.body h6 { font-size: 100%; } a.headerlink { color: #c60f0f; font-size: 0.8em; padding: 0 4px 0 4px; text-decoration: none; } a.headerlink:hover { background-color: #c60f0f; color: white; } div.body p, div.body dd, div.body li { text-align: justify; line-height: 130%; } div.admonition p.admonition-title + p { display: inline; } div.note { background-color: #eee; border: 1px solid #ccc; } div.seealso { background-color: #ffc; border: 1px solid #ff6; } div.topic { background-color: #eee; } div.warning { background-color: #ffe4e4; border: 1px solid #f66; } p.admonition-title { display: inline; } p.admonition-title:after { content: ":"; } pre { padding: 5px; background-color: #eeffcc; color: #333333; line-height: 120%; border: 1px solid #ac9; border-left: none; border-right: none; } tt { background-color: #ecf0f3; padding: 0 1px 0 1px; font-size: 0.95em; } .warning tt { background: #efc2c2; } .note tt { background: #d6d6d6; }crcmod-1.7/docs/html/_static/basic.css0000644000175000017500000001466311345457043017345 0ustar rlbrlb00000000000000/** * Sphinx stylesheet -- basic theme * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ /* -- main layout ----------------------------------------------------------- */ div.clearer { clear: both; } /* -- relbar ---------------------------------------------------------------- */ div.related { width: 100%; font-size: 90%; } div.related h3 { display: none; } div.related ul { margin: 0; padding: 0 0 0 10px; list-style: none; } div.related li { display: inline; } div.related li.right { float: right; margin-right: 5px; } /* -- sidebar --------------------------------------------------------------- */ div.sphinxsidebarwrapper { padding: 10px 5px 0 10px; } div.sphinxsidebar { float: left; width: 230px; margin-left: -100%; font-size: 90%; } div.sphinxsidebar ul { list-style: none; } div.sphinxsidebar ul ul, div.sphinxsidebar ul.want-points { margin-left: 20px; list-style: square; } div.sphinxsidebar ul ul { margin-top: 0; margin-bottom: 0; } div.sphinxsidebar form { margin-top: 10px; } div.sphinxsidebar input { border: 1px solid #98dbcc; font-family: sans-serif; font-size: 1em; } img { border: 0; } /* -- search page ----------------------------------------------------------- */ ul.search { margin: 10px 0 0 20px; padding: 0; } ul.search li { padding: 5px 0 5px 20px; background-image: url(file.png); background-repeat: no-repeat; background-position: 0 7px; } ul.search li a { font-weight: bold; } ul.search li div.context { color: #888; margin: 2px 0 0 30px; text-align: left; } ul.keywordmatches li.goodmatch a { font-weight: bold; } /* -- index page ------------------------------------------------------------ */ table.contentstable { width: 90%; } table.contentstable p.biglink { line-height: 150%; } a.biglink { font-size: 1.3em; } span.linkdescr { font-style: italic; padding-top: 5px; font-size: 90%; } /* -- general index --------------------------------------------------------- */ table.indextable td { text-align: left; vertical-align: top; } table.indextable dl, table.indextable dd { margin-top: 0; margin-bottom: 0; } table.indextable tr.pcap { height: 10px; } table.indextable tr.cap { margin-top: 10px; background-color: #f2f2f2; } img.toggler { margin-right: 3px; margin-top: 3px; cursor: pointer; } /* -- general body styles --------------------------------------------------- */ a.headerlink { visibility: hidden; } h1:hover > a.headerlink, h2:hover > a.headerlink, h3:hover > a.headerlink, h4:hover > a.headerlink, h5:hover > a.headerlink, h6:hover > a.headerlink, dt:hover > a.headerlink { visibility: visible; } div.body p.caption { text-align: inherit; } div.body td { text-align: left; } .field-list ul { padding-left: 1em; } .first { margin-top: 0 !important; } p.rubric { margin-top: 30px; font-weight: bold; } /* -- sidebars -------------------------------------------------------------- */ div.sidebar { margin: 0 0 0.5em 1em; border: 1px solid #ddb; padding: 7px 7px 0 7px; background-color: #ffe; width: 40%; float: right; } p.sidebar-title { font-weight: bold; } /* -- topics ---------------------------------------------------------------- */ div.topic { border: 1px solid #ccc; padding: 7px 7px 0 7px; margin: 10px 0 10px 0; } p.topic-title { font-size: 1.1em; font-weight: bold; margin-top: 10px; } /* -- admonitions ----------------------------------------------------------- */ div.admonition { margin-top: 10px; margin-bottom: 10px; padding: 7px; } div.admonition dt { font-weight: bold; } div.admonition dl { margin-bottom: 0; } p.admonition-title { margin: 0px 10px 5px 0px; font-weight: bold; } div.body p.centered { text-align: center; margin-top: 25px; } /* -- tables ---------------------------------------------------------------- */ table.docutils { border: 0; border-collapse: collapse; } table.docutils td, table.docutils th { padding: 1px 8px 1px 0; border-top: 0; border-left: 0; border-right: 0; border-bottom: 1px solid #aaa; } table.field-list td, table.field-list th { border: 0 !important; } table.footnote td, table.footnote th { border: 0 !important; } th { text-align: left; padding-right: 5px; } /* -- other body styles ----------------------------------------------------- */ dl { margin-bottom: 15px; } dd p { margin-top: 0px; } dd ul, dd table { margin-bottom: 10px; } dd { margin-top: 3px; margin-bottom: 10px; margin-left: 30px; } dt:target, .highlight { background-color: #fbe54e; } dl.glossary dt { font-weight: bold; font-size: 1.1em; } .field-list ul { margin: 0; padding-left: 1em; } .field-list p { margin: 0; } .refcount { color: #060; } .optional { font-size: 1.3em; } .versionmodified { font-style: italic; } .system-message { background-color: #fda; padding: 5px; border: 3px solid red; } .footnote:target { background-color: #ffa } .line-block { display: block; margin-top: 1em; margin-bottom: 1em; } .line-block .line-block { margin-top: 0; margin-bottom: 0; margin-left: 1.5em; } /* -- code displays --------------------------------------------------------- */ pre { overflow: auto; } td.linenos pre { padding: 5px 0px; border: 0; background-color: transparent; color: #aaa; } table.highlighttable { margin-left: 0.5em; } table.highlighttable td { padding: 0 0.5em 0 0.5em; } tt.descname { background-color: transparent; font-weight: bold; font-size: 1.2em; } tt.descclassname { background-color: transparent; } tt.xref, a tt { background-color: transparent; font-weight: bold; } h1 tt, h2 tt, h3 tt, h4 tt, h5 tt, h6 tt { background-color: transparent; } /* -- math display ---------------------------------------------------------- */ img.math { vertical-align: middle; } div.body div.math p { text-align: center; } span.eqno { float: right; } /* -- printout stylesheet --------------------------------------------------- */ @media print { div.document, div.documentwrapper, div.bodywrapper { margin: 0 !important; width: 100%; } div.sphinxsidebar, div.related, div.footer, #top-link { display: none; } } crcmod-1.7/docs/html/_static/searchtools.js0000644000175000017500000003050111345457043020423 0ustar rlbrlb00000000000000/** * helper function to return a node containing the * search summary for a given text. keywords is a list * of stemmed words, hlwords is the list of normal, unstemmed * words. the first one is used to find the occurance, the * latter for highlighting it. */ jQuery.makeSearchSummary = function(text, keywords, hlwords) { var textLower = text.toLowerCase(); var start = 0; $.each(keywords, function() { var i = textLower.indexOf(this.toLowerCase()); if (i > -1) start = i; }); start = Math.max(start - 120, 0); var excerpt = ((start > 0) ? '...' : '') + $.trim(text.substr(start, 240)) + ((start + 240 - text.length) ? '...' : ''); var rv = $('
').text(excerpt); $.each(hlwords, function() { rv = rv.highlightText(this, 'highlight'); }); return rv; } /** * Porter Stemmer */ var PorterStemmer = function() { var step2list = { ational: 'ate', tional: 'tion', enci: 'ence', anci: 'ance', izer: 'ize', bli: 'ble', alli: 'al', entli: 'ent', eli: 'e', ousli: 'ous', ization: 'ize', ation: 'ate', ator: 'ate', alism: 'al', iveness: 'ive', fulness: 'ful', ousness: 'ous', aliti: 'al', iviti: 'ive', biliti: 'ble', logi: 'log' }; var step3list = { icate: 'ic', ative: '', alize: 'al', iciti: 'ic', ical: 'ic', ful: '', ness: '' }; var c = "[^aeiou]"; // consonant var v = "[aeiouy]"; // vowel var C = c + "[^aeiouy]*"; // consonant sequence var V = v + "[aeiou]*"; // vowel sequence var mgr0 = "^(" + C + ")?" + V + C; // [C]VC... is m>0 var meq1 = "^(" + C + ")?" + V + C + "(" + V + ")?$"; // [C]VC[V] is m=1 var mgr1 = "^(" + C + ")?" + V + C + V + C; // [C]VCVC... is m>1 var s_v = "^(" + C + ")?" + v; // vowel in stem this.stemWord = function (w) { var stem; var suffix; var firstch; var origword = w; if (w.length < 3) return w; var re; var re2; var re3; var re4; firstch = w.substr(0,1); if (firstch == "y") w = firstch.toUpperCase() + w.substr(1); // Step 1a re = /^(.+?)(ss|i)es$/; re2 = /^(.+?)([^s])s$/; if (re.test(w)) w = w.replace(re,"$1$2"); else if (re2.test(w)) w = w.replace(re2,"$1$2"); // Step 1b re = /^(.+?)eed$/; re2 = /^(.+?)(ed|ing)$/; if (re.test(w)) { var fp = re.exec(w); re = new RegExp(mgr0); if (re.test(fp[1])) { re = /.$/; w = w.replace(re,""); } } else if (re2.test(w)) { var fp = re2.exec(w); stem = fp[1]; re2 = new RegExp(s_v); if (re2.test(stem)) { w = stem; re2 = /(at|bl|iz)$/; re3 = new RegExp("([^aeiouylsz])\\1$"); re4 = new RegExp("^" + C + v + "[^aeiouwxy]$"); if (re2.test(w)) w = w + "e"; else if (re3.test(w)) { re = /.$/; w = w.replace(re,""); } else if (re4.test(w)) w = w + "e"; } } // Step 1c re = /^(.+?)y$/; if (re.test(w)) { var fp = re.exec(w); stem = fp[1]; re = new RegExp(s_v); if (re.test(stem)) w = stem + "i"; } // Step 2 re = /^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/; if (re.test(w)) { var fp = re.exec(w); stem = fp[1]; suffix = fp[2]; re = new RegExp(mgr0); if (re.test(stem)) w = stem + step2list[suffix]; } // Step 3 re = /^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/; if (re.test(w)) { var fp = re.exec(w); stem = fp[1]; suffix = fp[2]; re = new RegExp(mgr0); if (re.test(stem)) w = stem + step3list[suffix]; } // Step 4 re = /^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/; re2 = /^(.+?)(s|t)(ion)$/; if (re.test(w)) { var fp = re.exec(w); stem = fp[1]; re = new RegExp(mgr1); if (re.test(stem)) w = stem; } else if (re2.test(w)) { var fp = re2.exec(w); stem = fp[1] + fp[2]; re2 = new RegExp(mgr1); if (re2.test(stem)) w = stem; } // Step 5 re = /^(.+?)e$/; if (re.test(w)) { var fp = re.exec(w); stem = fp[1]; re = new RegExp(mgr1); re2 = new RegExp(meq1); re3 = new RegExp("^" + C + v + "[^aeiouwxy]$"); if (re.test(stem) || (re2.test(stem) && !(re3.test(stem)))) w = stem; } re = /ll$/; re2 = new RegExp(mgr1); if (re.test(w) && re2.test(w)) { re = /.$/; w = w.replace(re,""); } // and turn initial Y back to y if (firstch == "y") w = firstch.toLowerCase() + w.substr(1); return w; } } /** * Search Module */ var Search = { _index : null, _queued_query : null, _pulse_status : -1, init : function() { var params = $.getQueryParameters(); if (params.q) { var query = params.q[0]; $('input[name="q"]')[0].value = query; this.performSearch(query); } }, /** * Sets the index */ setIndex : function(index) { var q; this._index = index; if ((q = this._queued_query) !== null) { this._queued_query = null; Search.query(q); } }, hasIndex : function() { return this._index !== null; }, deferQuery : function(query) { this._queued_query = query; }, stopPulse : function() { this._pulse_status = 0; }, startPulse : function() { if (this._pulse_status >= 0) return; function pulse() { Search._pulse_status = (Search._pulse_status + 1) % 4; var dotString = ''; for (var i = 0; i < Search._pulse_status; i++) dotString += '.'; Search.dots.text(dotString); if (Search._pulse_status > -1) window.setTimeout(pulse, 500); }; pulse(); }, /** * perform a search for something */ performSearch : function(query) { // create the required interface elements this.out = $('#search-results'); this.title = $('

' + _('Searching') + '

').appendTo(this.out); this.dots = $('').appendTo(this.title); this.status = $('

').appendTo(this.out); this.output = $('