Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/scapy/dadict.py: 69%
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# SPDX-License-Identifier: GPL-2.0-only
2# This file is part of Scapy
3# See https://scapy.net/ for more information
4# Copyright (C) Philippe Biondi <phil@secdev.org>
6"""
7Direct Access dictionary.
8"""
10from scapy.error import log_runtime, Scapy_Exception
11from scapy.compat import plain_str
13# Typing
14from typing import (
15 Any,
16 Callable,
17 Dict,
18 Generic,
19 Iterator,
20 List,
21 Optional,
22 Tuple,
23 Type,
24 TypeVar,
25 Union,
26)
27from scapy.compat import Self
30###############################
31# Direct Access dictionary #
32###############################
35def fixname(x):
36 # type: (Union[bytes, str]) -> str
37 """
38 Modifies a string to make sure it can be used as an attribute name.
39 """
40 x = plain_str(x)
41 if x and str(x[0]) in "0123456789":
42 x = "n_" + x
43 return x.translate(
44 "________________________________________________"
45 "0123456789_______ABCDEFGHIJKLMNOPQRSTUVWXYZ______"
46 "abcdefghijklmnopqrstuvwxyz____________________________"
47 "______________________________________________________"
48 "___________________________________________________"
49 )
52class DADict_Exception(Scapy_Exception):
53 pass
56_K = TypeVar('_K') # Key type
57_V = TypeVar('_V') # Value type
60class DADict(Generic[_K, _V]):
61 """
62 Direct Access Dictionary
64 This acts like a dict, but it provides a direct attribute access
65 to its keys through its values. This is used to store protocols,
66 manuf...
68 For instance, scapy fields will use a DADict as an enum::
70 ETHER_TYPES[2048] -> IPv4
72 Whereas humans can access::
74 ETHER_TYPES.IPv4 -> 2048
76 :param lazy_load: optional callable returning a DADict or dict, called on
77 first access to the contents. Failed loads are retried on next access.
78 """
79 __slots__ = ["_name", "_d", "_lazy_load"]
81 def __init__(self, _name="DADict", lazy_load=None, **kargs):
82 # type: (str, Optional[Callable[[], Union[DADict[_K, _V], Dict[_K, _V]]]], **Any) -> None # noqa: E501
83 self._name = _name
84 self._d = {} # type: Dict[_K, _V]
85 self._lazy_load = lazy_load
86 self.update(kargs) # type: ignore
88 @property
89 def d(self):
90 # type: () -> Dict[_K, _V]
91 if self._lazy_load is not None:
92 log_runtime.debug("Lazy loaded DADict [%s]" % self._name)
93 loaded = self._lazy_load()
94 if isinstance(loaded, DADict):
95 self._d = loaded.d
96 self._name = loaded._name
97 else:
98 self._d = loaded
99 self._lazy_load = None
100 return self._d
102 @d.setter
103 def d(self, value):
104 # type: (Dict[_K, _V]) -> None
105 self._d = value
106 self._lazy_load = None
108 def ident(self, v):
109 # type: (_V) -> str
110 """
111 Return value that is used as key for the direct access
112 """
113 if isinstance(v, (str, bytes)):
114 return fixname(v)
115 return "unknown"
117 def update(self, *args, **kwargs):
118 # type: (*Dict[_K, _V], **Dict[_K, _V]) -> None
119 for k, v in dict(*args, **kwargs).items():
120 self[k] = v # type: ignore
122 def iterkeys(self):
123 # type: () -> Iterator[_K]
124 for x in self.d:
125 if not isinstance(x, str) or x[0] != "_":
126 yield x
128 def keys(self):
129 # type: () -> List[_K]
130 return list(self.iterkeys())
132 def __iter__(self):
133 # type: () -> Iterator[_K]
134 return self.iterkeys()
136 def itervalues(self):
137 # type: () -> Iterator[_V]
138 return self.d.values() # type: ignore
140 def values(self):
141 # type: () -> List[_V]
142 return list(self.itervalues())
144 def _show(self):
145 # type: () -> None
146 for k in self.iterkeys():
147 print("%10s = %r" % (k, self[k]))
149 def __repr__(self):
150 # type: () -> str
151 return "<%s - %s elements>" % (self._name, len(self))
153 def __getitem__(self, attr):
154 # type: (_K) -> _V
155 return self.d[attr]
157 def __setitem__(self, attr, val):
158 # type: (_K, _V) -> None
159 self.d[attr] = val
161 def __len__(self):
162 # type: () -> int
163 return len(self.d)
165 def __nonzero__(self):
166 # type: () -> bool
167 # Always has at least its name
168 return len(self) > 1
169 __bool__ = __nonzero__
171 def __getattr__(self, attr):
172 # type: (str) -> _K
173 if attr in ("d", "_d", "_lazy_load"):
174 raise AttributeError(attr)
175 try:
176 return object.__getattribute__(self, attr) # type: ignore
177 except AttributeError:
178 for k, v in self.d.items():
179 if self.ident(v) == attr:
180 return k
181 raise AttributeError
183 def __dir__(self):
184 # type: () -> List[str]
185 return [self.ident(x) for x in self.itervalues()]
187 def __reduce__(self):
188 # type: () -> Tuple[Type[Self], Tuple[str], Tuple[Dict[_K, _V]]]
189 data = self.d
190 return (self.__class__, (self._name,), (data,))
192 def __setstate__(self, state):
193 # type: (Tuple[Dict[_K, _V]]) -> Self
194 self.d.update(state[0])
195 return self