follow-up 387f6db3b6 - py2 fixes
This commit is contained in:
32
lib/util.py
32
lib/util.py
@@ -247,6 +247,38 @@ def android_check_data_dir():
|
||||
def get_headers_dir(config):
|
||||
return android_headers_dir() if 'ANDROID_DATA' in os.environ else config.path
|
||||
|
||||
def to_string(x, enc):
|
||||
if isinstance(x, (bytes, bytearray)):
|
||||
return x.decode(enc)
|
||||
if isinstance(x, str):
|
||||
return x
|
||||
else:
|
||||
raise TypeError("Not a string or bytes like object")
|
||||
|
||||
def to_bytes(something, encoding='utf8'):
|
||||
"""
|
||||
cast string to bytes() like object, but for python2 support it's bytearray copy
|
||||
"""
|
||||
if isinstance(something, bytes):
|
||||
return something
|
||||
if isinstance(something, str) or isinstance(something, unicode):
|
||||
return something.encode(encoding)
|
||||
elif isinstance(something, bytearray):
|
||||
return bytes(something)
|
||||
else:
|
||||
raise TypeError("Not a string or bytes like object")
|
||||
|
||||
# based on https://stackoverflow.com/questions/16022556/has-python-3-to-bytes-been-back-ported-to-python-2-7
|
||||
def int_to_bytes(n, length, endianess='big'):
|
||||
hex_n = '%x' % n
|
||||
hex_n2 = '0'*(len(hex_n) % 2) + hex_n
|
||||
left_padded_hex_n = hex_n2.zfill(length*2)
|
||||
if len(left_padded_hex_n) > length*2:
|
||||
raise OverflowError()
|
||||
assert len(left_padded_hex_n) == length*2
|
||||
bytes_n = left_padded_hex_n.decode('hex')
|
||||
return bytes_n if endianess == 'big' else bytes_n[::-1]
|
||||
|
||||
def user_dir():
|
||||
if 'ANDROID_DATA' in os.environ:
|
||||
return android_check_data_dir()
|
||||
|
||||
Reference in New Issue
Block a user