1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
# Copyright (C) 2013 Helmut Grohne <helmut@subdivi.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
cimport libc.errno
import errno
import os
cdef extern from "fuzzy.h":
struct fuzzy_state
cdef enum:
FUZZY_FLAG_ELIMSEQ
FUZZY_FLAG_NOTRUNC
FUZZY_MAX_RESULT
cdef extern fuzzy_state *fuzzy_new() nogil
cdef extern int fuzzy_update(fuzzy_state *, unsigned char *, size_t) nogil
cdef extern int fuzzy_digest(fuzzy_state *, char *,
unsigned int flags) nogil
cdef extern void fuzzy_free(fuzzy_state *) nogil
class FuzzyError(Exception):
def __init__(self, errno):
self.errno = errno
def __str__(self):
return "FuzzyError: %s" % os.strerror(self.errno)
def __repr__(self):
try:
return "FuzzyError(errno.%s)" % errno.errorcode[self.errno]
except KeyError:
return "FuzzyError(%d)" % self.errno
cdef class FuzzyHash:
cdef fuzzy_state *state
def __cinit__(self):
self.state = fuzzy_new()
if self.state == NULL:
raise FuzzyError(libc.errno.errno)
def update(self, bytes buff):
if self.state == NULL:
raise FuzzyError(libc.errno.EINVAL)
if fuzzy_update(self.state, buff, len(buff)) != 0:
fuzzy_free(self.state)
self.state = NULL
raise FuzzyError(libc.errno.errno)
def digest(self, elimseq=False, notrunc=False):
if self.state == NULL:
raise FuzzyError(libc.errno.EINVAL)
cdef char result[FUZZY_MAX_RESULT]
flags = (FUZZY_FLAG_ELIMSEQ if elimseq else 0) | \
(FUZZY_FLAG_NOTRUNC if notrunc else 0)
if fuzzy_digest(self.state, result, flags) != 0:
raise FuzzyError(libc.errno.errno)
return str(result)
def __dealloc__(self):
if self.state != NULL:
fuzzy_free(self.state)
|