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