Simplify bytes/hex conversion functions now that we're Python 3+ only.
This commit is contained in:
parent
168326e184
commit
0c04db33d8
39
lib/util.py
39
lib/util.py
|
@ -291,44 +291,23 @@ def to_bytes(something, encoding='utf8'):
|
||||||
else:
|
else:
|
||||||
raise TypeError("Not a string or bytes like object")
|
raise TypeError("Not a string or bytes like object")
|
||||||
|
|
||||||
bfh_builder = lambda x: bytes.fromhex(x)
|
|
||||||
|
|
||||||
|
bfh = bytes.fromhex
|
||||||
def hfu(x):
|
hfu = binascii.hexlify
|
||||||
"""
|
|
||||||
py2-py3 aware wrapper for str.encode('hex')
|
|
||||||
:param x: str
|
|
||||||
:return: str
|
|
||||||
"""
|
|
||||||
assert_bytes(x)
|
|
||||||
return binascii.hexlify(x)
|
|
||||||
|
|
||||||
|
|
||||||
def bfh(x):
|
|
||||||
"""
|
|
||||||
py2-py3 aware wrapper to "bytes.fromhex()" func
|
|
||||||
:param x: str
|
|
||||||
:rtype: bytes
|
|
||||||
"""
|
|
||||||
if isinstance(x, str):
|
|
||||||
return bfh_builder(x)
|
|
||||||
# TODO: check for iterator interface
|
|
||||||
elif isinstance(x, (list, tuple, map)):
|
|
||||||
return [bfh(sub) for sub in x]
|
|
||||||
else:
|
|
||||||
raise TypeError('Unexpected type: ' + str(type(x)))
|
|
||||||
|
|
||||||
|
|
||||||
def bh2u(x):
|
def bh2u(x):
|
||||||
"""
|
"""
|
||||||
unicode with hex representation of bytes()
|
str with hex representation of a bytes-like object
|
||||||
e.g. x = bytes([1, 2, 10])
|
|
||||||
bh2u(x) -> '01020A'
|
>>> x = bytes((1, 2, 10))
|
||||||
|
>>> bh2u(x)
|
||||||
|
'01020A'
|
||||||
|
|
||||||
:param x: bytes
|
:param x: bytes
|
||||||
:rtype: str
|
:rtype: str
|
||||||
"""
|
"""
|
||||||
assert_bytes(x)
|
return hfu(x).decode('ascii')
|
||||||
return binascii.hexlify(x).decode('ascii')
|
|
||||||
|
|
||||||
|
|
||||||
def user_dir():
|
def user_dir():
|
||||||
|
|
Loading…
Reference in New Issue