summaryrefslogtreecommitdiff
path: root/external/construct/lib/py3compat.py
blob: 4a52c29305f91c9eee7eef71bc4eb44c21a1b1d2 (plain) (blame)
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
#-------------------------------------------------------------------------------
# py3compat.py
#
# Some Python2&3 compatibility code
#-------------------------------------------------------------------------------
import sys
PY3 = sys.version_info[0] == 3


if PY3:
    import io
    StringIO = io.StringIO
    BytesIO = io.BytesIO

    def bchr(i):
        """ When iterating over b'...' in Python 2 you get single b'_' chars
            and in Python 3 you get integers. Call bchr to always turn this
            to single b'_' chars.
        """
        return bytes((i,))

    def u(s):
        return s

    def int2byte(i):
        return bytes((i,))

    def byte2int(b):
        return b

    def str2bytes(s):
        return s.encode("latin-1")

    def str2unicode(s):
        return s

    def bytes2str(b):
        return b.decode('latin-1')

    def decodebytes(b, encoding):
        return bytes(b, encoding)

    advance_iterator = next
        
else:
    import cStringIO
    StringIO = BytesIO = cStringIO.StringIO

    int2byte = chr
    byte2int = ord
    bchr = lambda i: i

    def u(s):
        return unicode(s, "unicode_escape")

    def str2bytes(s):
        return s

    def str2unicode(s):
        return unicode(s, "unicode_escape")

    def bytes2str(b):
        return b

    def decodebytes(b, encoding):
        return b.decode(encoding)

    def advance_iterator(it):
        return it.next()