Supplementary object files (#426)
[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 from pathlib import Path
16
17 StringIO = io.StringIO
18 BytesIO = io.BytesIO
19
20 # Functions for acting on bytestrings and strings. In Python 2 and 3,
21 # strings and bytes are the same and chr/ord can be used to convert between
22 # numeric byte values and their string representations. In Python 3, bytes
23 # and strings are different types and bytes hold numeric values when
24 # iterated over.
25
26 def bytes2hex(b, sep=''):
27 if not sep:
28 return b.hex()
29 return sep.join(map('{:02x}'.format, b))
30
31 def bytes2str(b): return b.decode('latin-1')
32 def str2bytes(s): return s.encode('latin-1')
33 def int2byte(i): return bytes((i,))
34 def byte2int(b): return b
35
36 def iterbytes(b):
37 """Return an iterator over the elements of a bytes object.
38
39 For example, for b'abc' yields b'a', b'b' and then b'c'.
40 """
41 for i in range(len(b)):
42 yield b[i:i+1]
43
44 ifilter = filter
45
46 maxint = sys.maxsize
47
48 def path_to_posix(s):
49 return Path(s).as_posix()
50
51 else:
52 import cStringIO
53 import os
54 import posixpath
55
56 StringIO = BytesIO = cStringIO.StringIO
57
58 def bytes2hex(b, sep=''):
59 res = b.encode('hex')
60 if not sep:
61 return res
62 return sep.join(res[i:i+2] for i in range(0, len(res), 2))
63
64 def bytes2str(b): return b
65 def str2bytes(s): return s
66 int2byte = chr
67 byte2int = ord
68 def iterbytes(b):
69 return iter(b)
70
71 from itertools import ifilter
72
73 maxint = sys.maxint
74
75 def path_to_posix(s):
76 return posixpath.join(*os.path.split(s))
77
78
79 def iterkeys(d):
80 """Return an iterator over the keys of a dictionary."""
81 return getattr(d, 'keys' if PY3 else 'iterkeys')()
82
83 def itervalues(d):
84 """Return an iterator over the values of a dictionary."""
85 return getattr(d, 'values' if PY3 else 'itervalues')()
86
87 def iteritems(d):
88 """Return an iterator over the items of a dictionary."""
89 return getattr(d, 'items' if PY3 else 'iteritems')()
90
91 try:
92 from collections.abc import Mapping # python >= 3.3
93 except ImportError:
94 from collections import Mapping # python < 3.3