Debian Codegraph @

python3/crcmod/crcmod.py

raw symbols SCIP
1 #-----------------------------------------------------------------------------
2 # Copyright (c) 2010 Raymond L. Buvel
3 # Copyright (c) 2010 Craig McQueen
4 #
5 # Permission is hereby granted, free of charge, to any person obtaining a copy
6 # of this software and associated documentation files (the "Software"), to deal
7 # in the Software without restriction, including without limitation the rights
8 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 # copies of the Software, and to permit persons to whom the Software is
10 # furnished to do so, subject to the following conditions:
11 #
12 # The above copyright notice and this permission notice shall be included in
13 # all copies or substantial portions of the Software.
14 #
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 # SOFTWARE.
22 #-----------------------------------------------------------------------------
23 '''crcmod is a Python module for gererating objects that compute the Cyclic
24 Redundancy Check. Any 8, 16, 24, 32, or 64 bit polynomial can be used.
25
26 The following are the public components of this module.
27
28 Crc -- a class that creates instances providing the same interface as the
29 algorithms in the hashlib module in the Python standard library. These
30 instances also provide a method for generating a C/C++ function to compute
31 the CRC.
32
33 mkCrcFun -- create a Python function to compute the CRC using the specified
34 polynomial and initial value. This provides a much simpler interface if
35 all you need is a function for CRC calculation.
36 '''
37
38 __all__ = '''mkCrcFun Crc
39 '''.split()
40
41 # Select the appropriate set of low-level CRC functions for this installation.
42 # If the extension module was not built, drop back to the Python implementation
43 # even though it is significantly slower.
44 try:
45 import crcmod._crcfunext as _crcfun
46 _usingExtension = True
47 except ImportError:
48 import crcmod._crcfunpy as _crcfun
49 _usingExtension = False
50
51 import sys, struct
52
53 #-----------------------------------------------------------------------------
54 class Crc:
55 '''Compute a Cyclic Redundancy Check (CRC) using the specified polynomial.
56
57 Instances of this class have the same interface as the algorithms in the
58 hashlib module in the Python standard library. See the documentation of
59 this module for examples of how to use a Crc instance.
60
61 The string representation of a Crc instance identifies the polynomial,
62 initial value, XOR out value, and the current CRC value. The print
63 statement can be used to output this information.
64
65 If you need to generate a C/C++ function for use in another application,
66 use the generateCode method. If you need to generate code for another
67 language, subclass Crc and override the generateCode method.
68
69 The following are the parameters supplied to the constructor.
70
71 poly -- The generator polynomial to use in calculating the CRC. The value
72 is specified as a Python integer. The bits in this integer are the
73 coefficients of the polynomial. The only polynomials allowed are those
74 that generate 8, 16, 24, 32, or 64 bit CRCs.
75
76 initCrc -- Initial value used to start the CRC calculation. This initial
77 value should be the initial shift register value XORed with the final XOR
78 value. That is equivalent to the CRC result the algorithm should return for
79 a zero-length string. Defaults to all bits set because that starting value
80 will take leading zero bytes into account. Starting with zero will ignore
81 all leading zero bytes.
82
83 rev -- A flag that selects a bit reversed algorithm when True. Defaults to
84 True because the bit reversed algorithms are more efficient.
85
86 xorOut -- Final value to XOR with the calculated CRC value. Used by some
87 CRC algorithms. Defaults to zero.
88 '''
89 def __init__(self, poly, initCrc=~0, rev=True, xorOut=0, initialize=True):
90 if not initialize:
91 # Don't want to perform the initialization when using new or copy
92 # to create a new instance.
93 return
94
95 (sizeBits, initCrc, xorOut) = _verifyParams(poly, initCrc, xorOut)
96 self.digest_size = sizeBits//8
97 self.initCrc = initCrc
98 self.xorOut = xorOut
99
100 self.poly = poly
101 self.reverse = rev
102
103 (crcfun, table) = _mkCrcFun(poly, sizeBits, initCrc, rev, xorOut)
104 self._crc = crcfun
105 self.table = table
106
107 self.crcValue = self.initCrc
108
109 def __str__(self):
110 lst = []
111 lst.append('poly = 0x%X' % self.poly)
112 lst.append('reverse = %s' % self.reverse)
113 fmt = '0x%%0%dX' % (self.digest_size*2)
114 lst.append('initCrc = %s' % (fmt % self.initCrc))
115 lst.append('xorOut = %s' % (fmt % self.xorOut))
116 lst.append('crcValue = %s' % (fmt % self.crcValue))
117 return '\n'.join(lst)
118
119 def new(self, arg=None):
120 '''Create a new instance of the Crc class initialized to the same
121 values as the original instance. The current CRC is set to the initial
122 value. If a string is provided in the optional arg parameter, it is
123 passed to the update method.
124 '''
125 n = Crc(poly=None, initialize=False)
126 n._crc = self._crc
127 n.digest_size = self.digest_size
128 n.initCrc = self.initCrc
129 n.xorOut = self.xorOut
130 n.table = self.table
131 n.crcValue = self.initCrc
132 n.reverse = self.reverse
133 n.poly = self.poly
134 if arg is not None:
135 n.update(arg)
136 return n
137
138 def copy(self):
139 '''Create a new instance of the Crc class initialized to the same
140 values as the original instance. The current CRC is set to the current
141 value. This allows multiple CRC calculations using a common initial
142 string.
143 '''
144 c = self.new()
145 c.crcValue = self.crcValue
146 return c
147
148 def update(self, data):
149 '''Update the current CRC value using the string specified as the data
150 parameter.
151 '''
152 self.crcValue = self._crc(data, self.crcValue)
153
154 def digest(self):
155 '''Return the current CRC value as a string of bytes. The length of
156 this string is specified in the digest_size attribute.
157 '''
158 n = self.digest_size
159 crc = self.crcValue
160 lst = []
161 while n > 0:
162 lst.append(crc & 0xFF)
163 crc = crc >> 8
164 n -= 1
165 lst.reverse()
166 return bytes(lst)
167
168 def hexdigest(self):
169 '''Return the current CRC value as a string of hex digits. The length
170 of this string is twice the digest_size attribute.
171 '''
172 n = self.digest_size
173 crc = self.crcValue
174 lst = []
175 while n > 0:
176 lst.append('%02X' % (crc & 0xFF))
177 crc = crc >> 8
178 n -= 1
179 lst.reverse()
180 return ''.join(lst)
181
182 def generateCode(self, functionName, out, dataType=None, crcType=None):
183 '''Generate a C/C++ function.
184
185 functionName -- String specifying the name of the function.
186
187 out -- An open file-like object with a write method. This specifies
188 where the generated code is written.
189
190 dataType -- An optional parameter specifying the data type of the input
191 data to the function. Defaults to UINT8.
192
193 crcType -- An optional parameter specifying the data type of the CRC
194 value. Defaults to one of UINT8, UINT16, UINT32, or UINT64 depending
195 on the size of the CRC value.
196 '''
197 if dataType is None:
198 dataType = 'UINT8'
199
200 if crcType is None:
201 size = 8*self.digest_size
202 if size == 24:
203 size = 32
204 crcType = 'UINT%d' % size
205
206 if self.digest_size == 1:
207 # Both 8-bit CRC algorithms are the same
208 crcAlgor = 'table[*data ^ (%s)crc]'
209 elif self.reverse:
210 # The bit reverse algorithms are all the same except for the data
211 # type of the crc variable which is specified elsewhere.
212 crcAlgor = 'table[*data ^ (%s)crc] ^ (crc >> 8)'
213 else:
214 # The forward CRC algorithms larger than 8 bits have an extra shift
215 # operation to get the high byte.
216 shift = 8*(self.digest_size - 1)
217 crcAlgor = 'table[*data ^ (%%s)(crc >> %d)] ^ (crc << 8)' % shift
218
219 fmt = '0x%%0%dX' % (2*self.digest_size)
220 if self.digest_size <= 4:
221 fmt = fmt + 'U,'
222 else:
223 # Need the long long type identifier to keep gcc from complaining.
224 fmt = fmt + 'ULL,'
225
226 # Select the number of entries per row in the output code.
227 n = {1:8, 2:8, 3:4, 4:4, 8:2}[self.digest_size]
228
229 lst = []
230 for i, val in enumerate(self.table):
231 if (i % n) == 0:
232 lst.append('\n ')
233 lst.append(fmt % val)
234
235 poly = 'polynomial: 0x%X' % self.poly
236 if self.reverse:
237 poly = poly + ', bit reverse algorithm'
238
239 if self.xorOut:
240 # Need to remove the comma from the format.
241 preCondition = '\n crc = crc ^ %s;' % (fmt[:-1] % self.xorOut)
242 postCondition = preCondition
243 else:
244 preCondition = ''
245 postCondition = ''
246
247 if self.digest_size == 3:
248 # The 24-bit CRC needs to be conditioned so that only 24-bits are
249 # used from the 32-bit variable.
250 if self.reverse:
251 preCondition += '\n crc = crc & 0xFFFFFFU;'
252 else:
253 postCondition += '\n crc = crc & 0xFFFFFFU;'
254
255
256 parms = {
257 'dataType' : dataType,
258 'crcType' : crcType,
259 'name' : functionName,
260 'crcAlgor' : crcAlgor % dataType,
261 'crcTable' : ''.join(lst),
262 'poly' : poly,
263 'preCondition' : preCondition,
264 'postCondition' : postCondition,
265 }
266 out.write(_codeTemplate % parms)
267
268 #-----------------------------------------------------------------------------
269 def mkCrcFun(poly, initCrc=~0, rev=True, xorOut=0):
270 '''Return a function that computes the CRC using the specified polynomial.
271
272 poly -- integer representation of the generator polynomial
273 initCrc -- default initial CRC value
274 rev -- when true, indicates that the data is processed bit reversed.
275 xorOut -- the final XOR value
276
277 The returned function has the following user interface
278 def crcfun(data, crc=initCrc):
279 '''
280
281 # First we must verify the params
282 (sizeBits, initCrc, xorOut) = _verifyParams(poly, initCrc, xorOut)
283 # Make the function (and table), return the function
284 return _mkCrcFun(poly, sizeBits, initCrc, rev, xorOut)[0]
285
286 #-----------------------------------------------------------------------------
287 # Naming convention:
288 # All function names ending with r are bit reverse variants of the ones
289 # without the r.
290
291 #-----------------------------------------------------------------------------
292 # Check the polynomial to make sure that it is acceptable and return the number
293 # of bits in the CRC.
294
295 def _verifyPoly(poly):
296 msg = 'The degree of the polynomial must be 8, 16, 24, 32 or 64'
297 for n in (8,16,24,32,64):
298 low = 1<<n
299 high = low*2
300 if low <= poly < high:
301 return n
302 raise ValueError(msg)
303
304 #-----------------------------------------------------------------------------
305 # Bit reverse the input value.
306
307 def _bitrev(x, n):
308 y = 0
309 for i in range(n):
310 y = (y << 1) | (x & 1)
311 x = x >> 1
312 return y
313
314 #-----------------------------------------------------------------------------
315 # The following functions compute the CRC for a single byte. These are used
316 # to build up the tables needed in the CRC algorithm. Assumes the high order
317 # bit of the polynomial has been stripped off.
318
319 def _bytecrc(crc, poly, n):
320 mask = 1<<(n-1)
321 for i in range(8):
322 if crc & mask:
323 crc = (crc << 1) ^ poly
324 else:
325 crc = crc << 1
326 mask = (1<<n) - 1
327 crc = crc & mask
328 return crc
329
330 def _bytecrc_r(crc, poly, n):
331 for i in range(8):
332 if crc & 1:
333 crc = (crc >> 1) ^ poly
334 else:
335 crc = crc >> 1
336 mask = (1<<n) - 1
337 crc = crc & mask
338 return crc
339
340 #-----------------------------------------------------------------------------
341 # The following functions compute the table needed to compute the CRC. The
342 # table is returned as a list. Note that the array module does not support
343 # 64-bit integers on a 32-bit architecture as of Python 2.3.
344 #
345 # These routines assume that the polynomial and the number of bits in the CRC
346 # have been checked for validity by the caller.
347
348 def _mkTable(poly, n):
349 mask = (1<<n) - 1
350 poly = poly & mask
351 table = [_bytecrc(i<<(n-8),poly,n) for i in range(256)]
352 return table
353
354 def _mkTable_r(poly, n):
355 mask = (1<<n) - 1
356 poly = _bitrev(poly & mask, n)
357 table = [_bytecrc_r(i,poly,n) for i in range(256)]
358 return table
359
360 #-----------------------------------------------------------------------------
361 # Map the CRC size onto the functions that handle these sizes.
362
363 _sizeMap = {
364 8 : [_crcfun._crc8, _crcfun._crc8r],
365 16 : [_crcfun._crc16, _crcfun._crc16r],
366 24 : [_crcfun._crc24, _crcfun._crc24r],
367 32 : [_crcfun._crc32, _crcfun._crc32r],
368 64 : [_crcfun._crc64, _crcfun._crc64r],
369 }
370
371 #-----------------------------------------------------------------------------
372 # Build a mapping of size to struct module type code. This table is
373 # constructed dynamically so that it has the best chance of picking the best
374 # code to use for the platform we are running on. This should properly adapt
375 # to 32 and 64 bit machines.
376
377 _sizeToTypeCode = {}
378
379 for typeCode in 'B H I L Q'.split():
380 size = {1:8, 2:16, 4:32, 8:64}.get(struct.calcsize(typeCode),None)
381 if size is not None and size not in _sizeToTypeCode:
382 _sizeToTypeCode[size] = '256%s' % typeCode
383
384 _sizeToTypeCode[24] = _sizeToTypeCode[32]
385
386 del typeCode, size
387
388 #-----------------------------------------------------------------------------
389 # The following function validates the parameters of the CRC, namely,
390 # poly, and initial/final XOR values.
391 # It returns the size of the CRC (in bits), and "sanitized" initial/final XOR values.
392
393 def _verifyParams(poly, initCrc, xorOut):
394 sizeBits = _verifyPoly(poly)
395
396 mask = (1<<sizeBits) - 1
397
398 # Adjust the initial CRC to the correct data type (unsigned value).
399 initCrc = initCrc & mask
400
401 # Similar for XOR-out value.
402 xorOut = xorOut & mask
403
404 return (sizeBits, initCrc, xorOut)
405
406 #-----------------------------------------------------------------------------
407 # The following function returns a Python function to compute the CRC.
408 #
409 # It must be passed parameters that are already verified & sanitized by
410 # _verifyParams().
411 #
412 # The returned function calls a low level function that is written in C if the
413 # extension module could be loaded. Otherwise, a Python implementation is
414 # used.
415 #
416 # In addition to this function, a list containing the CRC table is returned.
417
418 def _mkCrcFun(poly, sizeBits, initCrc, rev, xorOut):
419 if rev:
420 tableList = _mkTable_r(poly, sizeBits)
421 _fun = _sizeMap[sizeBits][1]
422 else:
423 tableList = _mkTable(poly, sizeBits)
424 _fun = _sizeMap[sizeBits][0]
425
426 _table = tableList
427 if _usingExtension:
428 _table = struct.pack(_sizeToTypeCode[sizeBits], *tableList)
429
430 if xorOut == 0:
431 def crcfun(data, crc=initCrc, table=_table, fun=_fun):
432 return fun(data, crc, table)
433 else:
434 def crcfun(data, crc=initCrc, table=_table, fun=_fun):
435 return xorOut ^ fun(data, xorOut ^ crc, table)
436
437 return crcfun, tableList
438
439 #-----------------------------------------------------------------------------
440 _codeTemplate = '''// Automatically generated CRC function
441 // %(poly)s
442 %(crcType)s
443 %(name)s(%(dataType)s *data, int len, %(crcType)s crc)
444 {
445 static const %(crcType)s table[256] = {%(crcTable)s
446 };
447 %(preCondition)s
448 while (len > 0)
449 {
450 crc = %(crcAlgor)s;
451 data++;
452 len--;
453 }%(postCondition)s
454 return crc;
455 }
456 '''
457