Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/cryptography/utils.py: 63%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
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.
5from __future__ import annotations
7import enum
8import sys
9import types
10import typing
11import warnings
12from collections.abc import Callable, Sequence
15# We use a UserWarning subclass, instead of DeprecationWarning, because CPython
16# decided deprecation warnings should be invisible by default.
17class CryptographyDeprecationWarning(UserWarning):
18 pass
21# Several APIs were deprecated with no specific end-of-life date because of the
22# ubiquity of their use. They should not be removed until we agree on when that
23# cycle ends.
24DeprecatedIn36 = CryptographyDeprecationWarning
25DeprecatedIn40 = CryptographyDeprecationWarning
26DeprecatedIn41 = CryptographyDeprecationWarning
27DeprecatedIn42 = CryptographyDeprecationWarning
28DeprecatedIn43 = CryptographyDeprecationWarning
29DeprecatedIn47 = CryptographyDeprecationWarning
32# If you're wondering why we don't use `Buffer`, it's because `Buffer` would
33# be more accurately named: Bufferable. It means something which has an
34# `__buffer__`. Which means you can't actually treat the result as a buffer
35# (and do things like take a `len()`).
36Buffer = typing.Union[bytes, bytearray, memoryview]
39def _check_bytes(name: str, value: bytes) -> None:
40 if not isinstance(value, bytes):
41 raise TypeError(f"{name} must be bytes")
44def _check_byteslike(name: str, value: Buffer) -> None:
45 try:
46 memoryview(value)
47 except TypeError:
48 raise TypeError(f"{name} must be bytes-like")
51def int_to_bytes(integer: int, length: int | None = None) -> bytes:
52 if length == 0:
53 raise ValueError("length argument can't be 0")
54 return integer.to_bytes(
55 length or (integer.bit_length() + 7) // 8 or 1, "big"
56 )
59class InterfaceNotImplemented(Exception):
60 pass
63class _DeprecatedValue:
64 def __init__(self, value: object, message: str, warning_class):
65 self.value = value
66 self.message = message
67 self.warning_class = warning_class
70class _ModuleWithDeprecations(types.ModuleType):
71 def __init__(self, module: types.ModuleType):
72 super().__init__(module.__name__)
73 self.__dict__["_module"] = module
75 def __getattr__(self, name: str) -> typing.Any:
76 obj = getattr(self._module, name)
77 if isinstance(obj, _DeprecatedValue):
78 warnings.warn(obj.message, obj.warning_class, stacklevel=2)
79 obj = obj.value
80 return obj
82 def __setattr__(self, attr: str, value: object) -> None:
83 setattr(self._module, attr, value)
85 def __delattr__(self, attr: str) -> None:
86 obj = getattr(self._module, attr)
87 if isinstance(obj, _DeprecatedValue):
88 warnings.warn(obj.message, obj.warning_class, stacklevel=2)
90 delattr(self._module, attr)
92 def __dir__(self) -> Sequence[str]:
93 return ["_module", *dir(self._module)]
96def deprecated(
97 value: object,
98 module_name: str,
99 message: str,
100 warning_class: type[Warning],
101 name: str | None = None,
102) -> _DeprecatedValue:
103 module = sys.modules[module_name]
104 if not isinstance(module, _ModuleWithDeprecations):
105 sys.modules[module_name] = module = _ModuleWithDeprecations(module)
106 dv = _DeprecatedValue(value, message, warning_class)
107 # Maintain backwards compatibility with `name is None` for pyOpenSSL.
108 if name is not None:
109 setattr(module, name, dv)
110 return dv
113def cached_property(func: Callable) -> property:
114 cached_name = f"_cached_{func}"
115 sentinel = object()
117 def inner(instance: object):
118 cache = getattr(instance, cached_name, sentinel)
119 if cache is not sentinel:
120 return cache
121 result = func(instance)
122 setattr(instance, cached_name, result)
123 return result
125 return property(inner)
128# Python 3.10 changed representation of enums. We use well-defined object
129# representation and string representation from Python 3.9.
130class Enum(enum.Enum):
131 def __repr__(self) -> str:
132 return f"<{self.__class__.__name__}.{self._name_}: {self._value_!r}>"
134 def __str__(self) -> str:
135 return f"{self.__class__.__name__}.{self._name_}"