You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

utils.py 4.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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. PersistentlyDeprecated2018 = CryptographyDeprecationWarning
  19. DeprecatedIn25 = CryptographyDeprecationWarning
  20. DeprecatedIn27 = CryptographyDeprecationWarning
  21. def _check_bytes(name, value):
  22. if not isinstance(value, bytes):
  23. raise TypeError("{} must be bytes".format(name))
  24. def _check_byteslike(name, value):
  25. try:
  26. memoryview(value)
  27. except TypeError:
  28. raise TypeError("{} must be bytes-like".format(name))
  29. def read_only_property(name):
  30. return property(lambda self: getattr(self, name))
  31. def register_interface(iface):
  32. def register_decorator(klass):
  33. verify_interface(iface, klass)
  34. iface.register(klass)
  35. return klass
  36. return register_decorator
  37. def register_interface_if(predicate, iface):
  38. def register_decorator(klass):
  39. if predicate:
  40. verify_interface(iface, klass)
  41. iface.register(klass)
  42. return klass
  43. return register_decorator
  44. if hasattr(int, "from_bytes"):
  45. int_from_bytes = int.from_bytes
  46. else:
  47. def int_from_bytes(data, byteorder, signed=False):
  48. assert byteorder == 'big'
  49. assert not signed
  50. return int(binascii.hexlify(data), 16)
  51. if hasattr(int, "to_bytes"):
  52. def int_to_bytes(integer, length=None):
  53. return integer.to_bytes(
  54. length or (integer.bit_length() + 7) // 8 or 1, 'big'
  55. )
  56. else:
  57. def int_to_bytes(integer, length=None):
  58. hex_string = '%x' % integer
  59. if length is None:
  60. n = len(hex_string)
  61. else:
  62. n = length * 2
  63. return binascii.unhexlify(hex_string.zfill(n + (n & 1)))
  64. class InterfaceNotImplemented(Exception):
  65. pass
  66. if hasattr(inspect, "signature"):
  67. signature = inspect.signature
  68. else:
  69. signature = inspect.getargspec
  70. def verify_interface(iface, klass):
  71. for method in iface.__abstractmethods__:
  72. if not hasattr(klass, method):
  73. raise InterfaceNotImplemented(
  74. "{} is missing a {!r} method".format(klass, method)
  75. )
  76. if isinstance(getattr(iface, method), abc.abstractproperty):
  77. # Can't properly verify these yet.
  78. continue
  79. sig = signature(getattr(iface, method))
  80. actual = signature(getattr(klass, method))
  81. if sig != actual:
  82. raise InterfaceNotImplemented(
  83. "{}.{}'s signature differs from the expected. Expected: "
  84. "{!r}. Received: {!r}".format(
  85. klass, method, sig, actual
  86. )
  87. )
  88. # No longer needed as of 2.2, but retained because we have external consumers
  89. # who use it.
  90. def bit_length(x):
  91. return x.bit_length()
  92. class _DeprecatedValue(object):
  93. def __init__(self, value, message, warning_class):
  94. self.value = value
  95. self.message = message
  96. self.warning_class = warning_class
  97. class _ModuleWithDeprecations(object):
  98. def __init__(self, module):
  99. self.__dict__["_module"] = module
  100. def __getattr__(self, attr):
  101. obj = getattr(self._module, attr)
  102. if isinstance(obj, _DeprecatedValue):
  103. warnings.warn(obj.message, obj.warning_class, stacklevel=2)
  104. obj = obj.value
  105. return obj
  106. def __setattr__(self, attr, value):
  107. setattr(self._module, attr, value)
  108. def __delattr__(self, attr):
  109. obj = getattr(self._module, attr)
  110. if isinstance(obj, _DeprecatedValue):
  111. warnings.warn(obj.message, obj.warning_class, stacklevel=2)
  112. delattr(self._module, attr)
  113. def __dir__(self):
  114. return ["_module"] + dir(self._module)
  115. def deprecated(value, module_name, message, warning_class):
  116. module = sys.modules[module_name]
  117. if not isinstance(module, _ModuleWithDeprecations):
  118. sys.modules[module_name] = _ModuleWithDeprecations(module)
  119. return _DeprecatedValue(value, message, warning_class)
  120. def cached_property(func):
  121. cached_name = "_cached_{}".format(func)
  122. sentinel = object()
  123. def inner(instance):
  124. cache = getattr(instance, cached_name, sentinel)
  125. if cache is not sentinel:
  126. return cache
  127. result = func(instance)
  128. setattr(instance, cached_name, result)
  129. return result
  130. return property(inner)