compat.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. """
  2. The `compat` module provides support for backwards compatibility with older
  3. versions of python, and compatibility wrappers around optional packages.
  4. """
  5. # flake8: noqa
  6. import hmac
  7. import struct
  8. import sys
  9. PY3 = sys.version_info[0] == 3
  10. if PY3:
  11. text_type = str
  12. binary_type = bytes
  13. else:
  14. text_type = unicode
  15. binary_type = str
  16. string_types = (text_type, binary_type)
  17. try:
  18. constant_time_compare = hmac.compare_digest
  19. except AttributeError:
  20. # Fallback for Python < 2.7
  21. def constant_time_compare(val1, val2):
  22. """
  23. Returns True if the two strings are equal, False otherwise.
  24. The time taken is independent of the number of characters that match.
  25. """
  26. if len(val1) != len(val2):
  27. return False
  28. result = 0
  29. for x, y in zip(val1, val2):
  30. result |= ord(x) ^ ord(y)
  31. return result == 0
  32. # Use int.to_bytes if it exists (Python 3)
  33. if getattr(int, 'to_bytes', None):
  34. def bytes_from_int(val):
  35. remaining = val
  36. byte_length = 0
  37. while remaining != 0:
  38. remaining = remaining >> 8
  39. byte_length += 1
  40. return val.to_bytes(byte_length, 'big', signed=False)
  41. else:
  42. def bytes_from_int(val):
  43. buf = []
  44. while val:
  45. val, remainder = divmod(val, 256)
  46. buf.append(remainder)
  47. buf.reverse()
  48. return struct.pack('%sB' % len(buf), *buf)