summaryrefslogtreecommitdiff
path: root/pyfuzzy.pyx
blob: 2a187864a7ba7d6e0371d1e9ee0913ef4249ad68 (plain)
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
# 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_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 *) 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):
        if self.state == NULL:
            raise FuzzyError(libc.errno.EINVAL)
        cdef char result[FUZZY_MAX_RESULT]
        if fuzzy_digest(self.state, result) != 0:
            raise FuzzyError(libc.errno.errno)
        return str(result)

    def __dealloc__(self):
        if self.state != NULL:
            fuzzy_free(self.state)