Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/cryptography/utils.py: 64%
75 statements
« prev ^ index » next coverage.py v7.2.2, created at 2023-03-26 06:36 +0000
« prev ^ index » next coverage.py v7.2.2, created at 2023-03-26 06:36 +0000
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.
6import enum
7import sys
8import types
9import typing
10import warnings
13# We use a UserWarning subclass, instead of DeprecationWarning, because CPython
14# decided deprecation warnings should be invisble by default.
15class CryptographyDeprecationWarning(UserWarning):
16 pass
19# Several APIs were deprecated with no specific end-of-life date because of the
20# ubiquity of their use. They should not be removed until we agree on when that
21# cycle ends.
22DeprecatedIn36 = CryptographyDeprecationWarning
23DeprecatedIn37 = CryptographyDeprecationWarning
24DeprecatedIn39 = CryptographyDeprecationWarning
25DeprecatedIn40 = CryptographyDeprecationWarning
28def _check_bytes(name: str, value: bytes) -> None:
29 if not isinstance(value, bytes):
30 raise TypeError(f"{name} must be bytes")
33def _check_byteslike(name: str, value: bytes) -> None:
34 try:
35 memoryview(value)
36 except TypeError:
37 raise TypeError(f"{name} must be bytes-like")
40def int_to_bytes(integer: int, length: typing.Optional[int] = None) -> bytes:
41 return integer.to_bytes(
42 length or (integer.bit_length() + 7) // 8 or 1, "big"
43 )
46def _extract_buffer_length(obj: typing.Any) -> typing.Tuple[int, int]:
47 from cryptography.hazmat.bindings._rust import _openssl
49 buf = _openssl.ffi.from_buffer(obj)
50 return int(_openssl.ffi.cast("uintptr_t", buf)), len(buf)
53class InterfaceNotImplemented(Exception):
54 pass
57class _DeprecatedValue:
58 def __init__(self, value: object, message: str, warning_class):
59 self.value = value
60 self.message = message
61 self.warning_class = warning_class
64class _ModuleWithDeprecations(types.ModuleType):
65 def __init__(self, module: types.ModuleType):
66 super().__init__(module.__name__)
67 self.__dict__["_module"] = module
69 def __getattr__(self, attr: str) -> object:
70 obj = getattr(self._module, attr)
71 if isinstance(obj, _DeprecatedValue):
72 warnings.warn(obj.message, obj.warning_class, stacklevel=2)
73 obj = obj.value
74 return obj
76 def __setattr__(self, attr: str, value: object) -> None:
77 setattr(self._module, attr, value)
79 def __delattr__(self, attr: str) -> None:
80 obj = getattr(self._module, attr)
81 if isinstance(obj, _DeprecatedValue):
82 warnings.warn(obj.message, obj.warning_class, stacklevel=2)
84 delattr(self._module, attr)
86 def __dir__(self) -> typing.Sequence[str]:
87 return ["_module"] + dir(self._module)
90def deprecated(
91 value: object,
92 module_name: str,
93 message: str,
94 warning_class: typing.Type[Warning],
95 name: typing.Optional[str] = None,
96) -> _DeprecatedValue:
97 module = sys.modules[module_name]
98 if not isinstance(module, _ModuleWithDeprecations):
99 sys.modules[module_name] = module = _ModuleWithDeprecations(module)
100 dv = _DeprecatedValue(value, message, warning_class)
101 # Maintain backwards compatibility with `name is None` for pyOpenSSL.
102 if name is not None:
103 setattr(module, name, dv)
104 return dv
107def cached_property(func: typing.Callable) -> property:
108 cached_name = f"_cached_{func}"
109 sentinel = object()
111 def inner(instance: object):
112 cache = getattr(instance, cached_name, sentinel)
113 if cache is not sentinel:
114 return cache
115 result = func(instance)
116 setattr(instance, cached_name, result)
117 return result
119 return property(inner)
122# Python 3.10 changed representation of enums. We use well-defined object
123# representation and string representation from Python 3.9.
124class Enum(enum.Enum):
125 def __repr__(self) -> str:
126 return f"<{self.__class__.__name__}.{self._name_}: {self._value_!r}>"
128 def __str__(self) -> str:
129 return f"{self.__class__.__name__}.{self._name_}"