Add support for .note.gnu.property notes section (#386)
[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 bytes2hex(b, sep=''):
25 if not sep:
26 return b.hex()
27 return sep.join(map('{:02x}'.format, b))
28
29 def bytes2str(b): return b.decode('latin-1')
30 def str2bytes(s): return s.encode('latin-1')
31 def int2byte(i): return bytes((i,))
32 def byte2int(b): return b
33
34 def iterbytes(b):
35 """Return an iterator over the elements of a bytes object.
36
37 For example, for b'abc' yields b'a', b'b' and then b'c'.
38 """
39 for i in range(len(b)):
40 yield b[i:i+1]
41
42 ifilter = filter
43
44 maxint = sys.maxsize
45 else:
46 import cStringIO
47 StringIO = BytesIO = cStringIO.StringIO
48
49 def bytes2hex(b, sep=''):
50 res = b.encode('hex')
51 if not sep:
52 return res
53 return sep.join(res[i:i+2] for i in range(0, len(res), 2))
54
55 def bytes2str(b): return b
56 def str2bytes(s): return s
57 int2byte = chr
58 byte2int = ord
59 def iterbytes(b):
60 return iter(b)
61
62 from itertools import ifilter
63
64 maxint = sys.maxint
65
66
67 def iterkeys(d):
68 """Return an iterator over the keys of a dictionary."""
69 return getattr(d, 'keys' if PY3 else 'iterkeys')()
70
71 def itervalues(d):
72 """Return an iterator over the values of a dictionary."""
73 return getattr(d, 'values' if PY3 else 'itervalues')()
74
75 def iteritems(d):
76 """Return an iterator over the items of a dictionary."""
77 return getattr(d, 'items' if PY3 else 'iteritems')()
78
79 try:
80 from collections.abc import Mapping # python >= 3.3
81 except ImportError:
82 from collections import Mapping # python < 3.3