summaryrefslogtreecommitdiff
path: root/gitdb/utils/compat.py
blob: 93e9a7d6377425413802af9b99f349af22e33879 (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
import sys


PY3 = sys.version_info[0] >= 3

try:
    from itertools import izip
    xrange = xrange         # @UndefinedVariable
except ImportError:
    # py3
    izip = zip
    xrange = range
# end handle python version

try:
    # Python 2
    buffer = buffer         # @UndefinedVariable
    memoryview = buffer     # @ReservedAssignment

    # Assume no memory view ...
    def to_bytes(i):
        return i
except NameError:
    # Python 3 has no `buffer`; only `memoryview`
    # However, it's faster to just slice the object directly, maybe it keeps a view internally
    def buffer(obj, offset, size=None):
        if size is None:
            # return memoryview(obj)[offset:]
            return obj[offset:]
        else:
            # return memoryview(obj)[offset:offset+size]
            return obj[offset:offset + size]
    # end buffer reimplementation
    # smmap can return memory view objects, which can't be compared as buffers/bytes can ...

    def to_bytes(i):
        if isinstance(i, memoryview):
            return i.tobytes()
        return i

    memoryview = memoryview     # @ReservedAssignment

try:
    MAXSIZE = sys.maxint        # @UndefinedVariable
except AttributeError:
    MAXSIZE = sys.maxsize

try:
    from contextlib import ExitStack
except ImportError:
    from contextlib2 import ExitStack   # @UnusedImport

try:
    from struct import unpack_from      # @UnusedImport
except ImportError:
    from struct import unpack, calcsize
    __calcsize_cache = dict()

    def unpack_from(fmt, data, offset=0):
        try:
            size = __calcsize_cache[fmt]
        except KeyError:
            size = calcsize(fmt)
            __calcsize_cache[fmt] = size
        # END exception handling
        return unpack(fmt, data[offset: offset + size])
    # END own unpack_from implementation