utils.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. # This file is dual licensed under the terms of the Apache License, Version
  2. # 2.0, and the BSD License. See the LICENSE file in the root of this repository
  3. # for complete details.
  4. from __future__ import absolute_import, division, print_function
  5. import abc
  6. import binascii
  7. import inspect
  8. import sys
  9. import warnings
  10. # We use a UserWarning subclass, instead of DeprecationWarning, because CPython
  11. # decided deprecation warnings should be invisble by default.
  12. class CryptographyDeprecationWarning(UserWarning):
  13. pass
  14. # Several APIs were deprecated with no specific end-of-life date because of the
  15. # ubiquity of their use. They should not be removed until we agree on when that
  16. # cycle ends.
  17. PersistentlyDeprecated2017 = CryptographyDeprecationWarning
  18. PersistentlyDeprecated2019 = CryptographyDeprecationWarning
  19. def _check_bytes(name, value):
  20. if not isinstance(value, bytes):
  21. raise TypeError("{} must be bytes".format(name))
  22. def _check_byteslike(name, value):
  23. try:
  24. memoryview(value)
  25. except TypeError:
  26. raise TypeError("{} must be bytes-like".format(name))
  27. def read_only_property(name):
  28. return property(lambda self: getattr(self, name))
  29. def register_interface(iface):
  30. def register_decorator(klass):
  31. verify_interface(iface, klass)
  32. iface.register(klass)
  33. return klass
  34. return register_decorator
  35. def register_interface_if(predicate, iface):
  36. def register_decorator(klass):
  37. if predicate:
  38. verify_interface(iface, klass)
  39. iface.register(klass)
  40. return klass
  41. return register_decorator
  42. if hasattr(int, "from_bytes"):
  43. int_from_bytes = int.from_bytes
  44. else:
  45. def int_from_bytes(data, byteorder, signed=False):
  46. assert byteorder == "big"
  47. assert not signed
  48. return int(binascii.hexlify(data), 16)
  49. if hasattr(int, "to_bytes"):
  50. def int_to_bytes(integer, length=None):
  51. return integer.to_bytes(
  52. length or (integer.bit_length() + 7) // 8 or 1, "big"
  53. )
  54. else:
  55. def int_to_bytes(integer, length=None):
  56. hex_string = "%x" % integer
  57. if length is None:
  58. n = len(hex_string)
  59. else:
  60. n = length * 2
  61. return binascii.unhexlify(hex_string.zfill(n + (n & 1)))
  62. class InterfaceNotImplemented(Exception):
  63. pass
  64. if hasattr(inspect, "signature"):
  65. signature = inspect.signature
  66. else:
  67. signature = inspect.getargspec
  68. def verify_interface(iface, klass):
  69. for method in iface.__abstractmethods__:
  70. if not hasattr(klass, method):
  71. raise InterfaceNotImplemented(
  72. "{} is missing a {!r} method".format(klass, method)
  73. )
  74. if isinstance(getattr(iface, method), abc.abstractproperty):
  75. # Can't properly verify these yet.
  76. continue
  77. sig = signature(getattr(iface, method))
  78. actual = signature(getattr(klass, method))
  79. if sig != actual:
  80. raise InterfaceNotImplemented(
  81. "{}.{}'s signature differs from the expected. Expected: "
  82. "{!r}. Received: {!r}".format(klass, method, sig, actual)
  83. )
  84. class _DeprecatedValue(object):
  85. def __init__(self, value, message, warning_class):
  86. self.value = value
  87. self.message = message
  88. self.warning_class = warning_class
  89. class _ModuleWithDeprecations(object):
  90. def __init__(self, module):
  91. self.__dict__["_module"] = module
  92. def __getattr__(self, attr):
  93. obj = getattr(self._module, attr)
  94. if isinstance(obj, _DeprecatedValue):
  95. warnings.warn(obj.message, obj.warning_class, stacklevel=2)
  96. obj = obj.value
  97. return obj
  98. def __setattr__(self, attr, value):
  99. setattr(self._module, attr, value)
  100. def __delattr__(self, attr):
  101. obj = getattr(self._module, attr)
  102. if isinstance(obj, _DeprecatedValue):
  103. warnings.warn(obj.message, obj.warning_class, stacklevel=2)
  104. delattr(self._module, attr)
  105. def __dir__(self):
  106. return ["_module"] + dir(self._module)
  107. def deprecated(value, module_name, message, warning_class):
  108. module = sys.modules[module_name]
  109. if not isinstance(module, _ModuleWithDeprecations):
  110. sys.modules[module_name] = _ModuleWithDeprecations(module)
  111. return _DeprecatedValue(value, message, warning_class)
  112. def cached_property(func):
  113. cached_name = "_cached_{}".format(func)
  114. sentinel = object()
  115. def inner(instance):
  116. cache = getattr(instance, cached_name, sentinel)
  117. if cache is not sentinel:
  118. return cache
  119. result = func(instance)
  120. setattr(instance, cached_name, result)
  121. return result
  122. return property(inner)