46bbfb325ab09123fa14310f13d2af14b9bf4507
1 #-------------------------------------------------------------------------------
2 # elftools: common/py3compat.py
4 # Python 2/3 compatibility code
6 # Eli Bendersky (eliben@gmail.com)
7 # This code is in the public domain
8 #-------------------------------------------------------------------------------
10 PY3
= sys
.version_info
[0] == 3
15 from pathlib
import Path
17 StringIO
= io
.StringIO
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
26 def bytes2hex(b
, sep
=''):
29 return sep
.join(map('{:02x}'.format
, b
))
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
37 """Return an iterator over the elements of a bytes object.
39 For example, for b'abc' yields b'a', b'b' and then b'c'.
41 for i
in range(len(b
)):
49 return Path(s
).as_posix()
56 StringIO
= BytesIO
= cStringIO
.StringIO
58 def bytes2hex(b
, sep
=''):
62 return sep
.join(res
[i
:i
+2] for i
in range(0, len(res
), 2))
64 def bytes2str(b
): return b
65 def str2bytes(s
): return s
71 from itertools
import ifilter
76 return posixpath
.join(*os
.path
.split(s
))
80 """Return an iterator over the keys of a dictionary."""
81 return getattr(d
, 'keys' if PY3
else 'iterkeys')()
84 """Return an iterator over the values of a dictionary."""
85 return getattr(d
, 'values' if PY3
else 'itervalues')()
88 """Return an iterator over the items of a dictionary."""
89 return getattr(d
, 'items' if PY3
else 'iteritems')()
92 from collections
.abc
import Mapping
# python >= 3.3
94 from collections
import Mapping
# python < 3.3