2296771956f4becb84d14476186066929b733927
[pyelftools.git] / elftools / common / py3compat.py
1 #-------------------------------------------------------------------------------
2 # elftools: common/py3compat.py
3 #
4 # Python 2/3 compatibility code
5 #
6 # Eli Bendersky (eliben@gmail.com)
7 # This code is in the public domain
8 #-------------------------------------------------------------------------------
9 import sys
10 PY3 = sys.version_info[0] == 3
11
12
13 if PY3:
14 import io
15 StringIO = io.StringIO
16 BytesIO = io.BytesIO
17
18 # Functions for acting on bytestrings and strings. In Python 2 and 3,
19 # strings and bytes are the same and chr/ord can be used to convert between
20 # numeric byte values and their string pepresentations. In Python 3, bytes
21 # and strings are different types and bytes hold numeric values when
22 # iterated over.
23
24 def bytes2str(b): return b.decode('latin-1')
25 def str2bytes(s): return s.encode('latin-1')
26 def int2byte(i): return bytes((i,))
27 def byte2int(b): return b
28
29 def iterbytes(b):
30 """Return an iterator over the elements of a bytes object.
31
32 For example, for b'abc' yields b'a', b'b' and then b'c'.
33 """
34 for i in range(len(b)):
35 yield b[i:i+1]
36
37 ifilter = filter
38
39 maxint = sys.maxsize
40 else:
41 import cStringIO
42 StringIO = BytesIO = cStringIO.StringIO
43
44 def bytes2str(b): return b
45 def str2bytes(s): return s
46 int2byte = chr
47 byte2int = ord
48 def iterbytes(b):
49 return iter(b)
50
51 from itertools import ifilter
52
53 maxint = sys.maxint
54
55
56 def iterkeys(d):
57 """Return an iterator over the keys of a dictionary."""
58 return getattr(d, 'keys' if PY3 else 'iterkeys')()
59
60 def itervalues(d):
61 """Return an iterator over the values of a dictionary."""
62 return getattr(d, 'values' if PY3 else 'itervalues')()
63
64 def iteritems(d):
65 """Return an iterator over the items of a dictionary."""
66 return getattr(d, 'items' if PY3 else 'iteritems')()
67
68 try:
69 from collections.abc import Mapping # python >= 3.3
70 except ImportError:
71 from collections import Mapping # python < 3.3