diff options
Diffstat (limited to 'jwt/compat.py')
-rw-r--r-- | jwt/compat.py | 28 |
1 files changed, 23 insertions, 5 deletions
diff --git a/jwt/compat.py b/jwt/compat.py index dafd0c7..b928c7d 100644 --- a/jwt/compat.py +++ b/jwt/compat.py @@ -3,8 +3,9 @@ The `compat` module provides support for backwards compatibility with older versions of python, and compatibility wrappers around optional packages. """ # flake8: noqa -import sys import hmac +import struct +import sys PY3 = sys.version_info[0] == 3 @@ -20,10 +21,6 @@ else: string_types = (text_type, binary_type) -def is_string_type(val): - return any([isinstance(val, typ) for typ in string_types]) - - def timedelta_total_seconds(delta): try: delta.total_seconds @@ -56,3 +53,24 @@ except AttributeError: result |= ord(x) ^ ord(y) return result == 0 + +# Use int.to_bytes if it exists (Python 3) +if getattr(int, 'to_bytes', None): + def bytes_from_int(val): + remaining = val + byte_length = 0 + + while remaining != 0: + remaining = remaining >> 8 + byte_length += 1 + + return val.to_bytes(byte_length, 'big', signed=False) +else: + def bytes_from_int(val): + buf = [] + while val: + val, remainder = divmod(val, 256) + buf.append(remainder) + + buf.reverse() + return struct.pack('%sB' % len(buf), *buf) |