Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/dns/enum.py: 37%
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# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
3# Copyright (C) 2003-2017 Nominum, Inc.
4#
5# Permission to use, copy, modify, and distribute this software and its
6# documentation for any purpose with or without fee is hereby granted,
7# provided that the above copyright notice and this permission notice
8# appear in all copies.
9#
10# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
11# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
13# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
16# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18import enum
19from typing import Any, Self
21import dns._text_util
24class IntEnum(enum.IntEnum):
25 @classmethod
26 def _missing_(cls, value):
27 cls._check_value(value)
28 val = int.__new__(cls, value) # pyright: ignore
29 val._name_ = cls._extra_to_text(value, None) or f"{cls._prefix()}{value}"
30 val._value_ = value # pyright: ignore
31 return val
33 @classmethod
34 def _check_value(cls, value):
35 max = cls._maximum()
36 if not isinstance(value, int):
37 raise TypeError
38 if value < 0 or value > max:
39 name = cls._short_name()
40 raise ValueError(f"{name} must be an int between >= 0 and <= {max}")
42 @classmethod
43 def from_text(cls: type[Self], text: str) -> Self:
44 text = text.upper()
45 try:
46 return cls[text]
47 except KeyError:
48 pass
49 value = cls._extra_from_text(text)
50 if value:
51 return value
52 prefix = cls._prefix()
53 if text.startswith(prefix) and dns._text_util.is_ascii_digits(
54 text[len(prefix) :]
55 ):
56 value = int(text[len(prefix) :])
57 cls._check_value(value)
58 return cls(value)
59 raise cls._unknown_exception_class()
61 @classmethod
62 def to_text(cls: type[Self], value: int) -> str:
63 cls._check_value(value)
64 try:
65 text = cls(value).name
66 except ValueError:
67 text = None
68 text = cls._extra_to_text(value, text)
69 if text is None:
70 text = f"{cls._prefix()}{value}"
71 return text
73 @classmethod
74 def make(cls: type[Self], value: int | str) -> Self:
75 """Convert text or a value into an enumerated type, if possible.
77 :param value: The value to convert.
78 :type value: int or str
79 :raises ValueError: If the value is out of range.
80 :returns: An enumeration from the calling class corresponding to the
81 value, if one is defined, or an ``int`` otherwise.
82 """
84 if isinstance(value, str):
85 return cls.from_text(value)
86 cls._check_value(value)
87 return cls(value)
89 @classmethod
90 def _maximum(cls):
91 raise NotImplementedError # pragma: no cover
93 @classmethod
94 def _short_name(cls):
95 return cls.__name__.lower()
97 @classmethod
98 def _prefix(cls) -> str:
99 return ""
101 @classmethod
102 def _extra_from_text(cls, text: str) -> Any | None: # pylint: disable=W0613
103 return None
105 @classmethod
106 def _extra_to_text(cls, value, current_text): # pylint: disable=W0613
107 return current_text
109 @classmethod
110 def _unknown_exception_class(cls) -> type[Exception]:
111 return ValueError