Initial import.
[mLib-python] / crc32.pyx
1 # -*-pyrex-*-
2 #
3 # $Id$
4 #
5 # Cyclic redundancy checker
6 #
7 # (c) 2005 Straylight/Edgeware
8 #
9
10 #----- Licensing notice -----------------------------------------------------
11 #
12 # This file is part of the Python interface to mLib.
13 #
14 # mLib/Python is free software; you can redistribute it and/or modify
15 # it under the terms of the GNU General Public License as published by
16 # the Free Software Foundation; either version 2 of the License, or
17 # (at your option) any later version.
18 #
19 # mLib/Python is distributed in the hope that it will be useful,
20 # but WITHOUT ANY WARRANTY; without even the implied warranty of
21 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 # GNU General Public License for more details.
23 #
24 # You should have received a copy of the GNU General Public License
25 # along with mLib/Python; if not, write to the Free Software Foundation,
26 # Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
27
28 cdef extern from 'mLib/crc32.h':
29 ctypedef int uint32
30 uint32 c_crc32 "crc32" (uint32 a, void *p, int sz)
31
32 cdef extern from 'limits.h':
33 enum:
34 LONG_MAX
35
36 cdef extern from 'Python.h':
37 int PyObject_AsReadBuffer(obj, void **buf, int *len) except -1
38 PyInt_FromLong(long i)
39 PyLong_FromUnsignedLong(unsigned long i)
40
41 cdef _u32(uint32 x):
42 if x < LONG_MAX:
43 return PyInt_FromLong(x)
44 else:
45 return PyLong_FromUnsignedLong(x)
46
47 cdef class CRC32:
48 cdef uint32 _a
49 def __new__(me, *hunoz, **hukairz):
50 me._a = 0
51 def __init__(me):
52 pass
53 def chunk(me, data):
54 cdef void *p
55 cdef int n
56 PyObject_AsReadBuffer(data, &p, &n)
57 me._a = c_crc32(me._a, p, n)
58 return me
59 def done(me):
60 return _u32(me._a)
61
62 def crc32(data):
63 cdef void *p
64 cdef int n
65 cdef uint32 c
66 PyObject_AsReadBuffer(data, &p, &n)
67 c = c_crc32(0, p, n)
68 return _u32(c)
69
70 #----- That's all, folks ----------------------------------------------------