0086132c76f487804670e20785c833975391d66e
[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 assert PY3, '''\
12 Python 2 is no longer supported by pyelftools; if you need to use Python 2,
13 please download an older pyelftools version (such as version 0.29).
14 '''
15
16
17 if PY3:
18 import io
19 from pathlib import Path
20
21 StringIO = io.StringIO
22 BytesIO = io.BytesIO
23
24 # Functions for acting on bytestrings and strings. In Python 2 and 3,
25 # strings and bytes are the same and chr/ord can be used to convert between
26 # numeric byte values and their string representations. In Python 3, bytes
27 # and strings are different types and bytes hold numeric values when
28 # iterated over.
29
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 maxint = sys.maxsize
37
38 def path_to_posix(s):
39 return Path(s).as_posix()
40
41 else:
42 import cStringIO
43 import os
44 import posixpath
45
46 StringIO = BytesIO = cStringIO.StringIO
47
48 def bytes2str(b): return b
49 def str2bytes(s): return s
50 int2byte = chr
51 byte2int = ord
52 def iterbytes(b):
53 return iter(b)
54
55 maxint = sys.maxint
56
57 def path_to_posix(s):
58 return posixpath.join(*os.path.split(s))