faster-eth-abi 5.2.9__cp310-cp310-win32.whl → 5.2.11__cp310-cp310-win32.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. 29859a9e7da9d19bb98c__mypyc.cp310-win32.pyd +0 -0
  2. faster_eth_abi/_codec.cp310-win32.pyd +0 -0
  3. faster_eth_abi/_codec.py +0 -4
  4. faster_eth_abi/_decoding.cp310-win32.pyd +0 -0
  5. faster_eth_abi/_decoding.py +46 -0
  6. faster_eth_abi/_encoding.cp310-win32.pyd +0 -0
  7. faster_eth_abi/_encoding.py +12 -5
  8. faster_eth_abi/_grammar.cp310-win32.pyd +0 -0
  9. faster_eth_abi/_grammar.py +349 -0
  10. faster_eth_abi/abi.cp310-win32.pyd +0 -0
  11. faster_eth_abi/codec.py +8 -9
  12. faster_eth_abi/constants.cp310-win32.pyd +0 -0
  13. faster_eth_abi/decoding.py +11 -31
  14. faster_eth_abi/from_type_str.cp310-win32.pyd +0 -0
  15. faster_eth_abi/from_type_str.py +3 -1
  16. faster_eth_abi/grammar.py +10 -308
  17. faster_eth_abi/packed.cp310-win32.pyd +0 -0
  18. faster_eth_abi/registry.py +37 -24
  19. faster_eth_abi/tools/__init__.cp310-win32.pyd +0 -0
  20. faster_eth_abi/tools/_strategies.cp310-win32.pyd +0 -0
  21. faster_eth_abi/tools/_strategies.py +9 -5
  22. faster_eth_abi/utils/__init__.cp310-win32.pyd +0 -0
  23. faster_eth_abi/utils/numeric.cp310-win32.pyd +0 -0
  24. faster_eth_abi/utils/numeric.py +51 -20
  25. faster_eth_abi/utils/padding.cp310-win32.pyd +0 -0
  26. faster_eth_abi/utils/string.cp310-win32.pyd +0 -0
  27. faster_eth_abi/utils/validation.cp310-win32.pyd +0 -0
  28. {faster_eth_abi-5.2.9.dist-info → faster_eth_abi-5.2.11.dist-info}/METADATA +1 -1
  29. faster_eth_abi-5.2.11.dist-info/RECORD +46 -0
  30. faster_eth_abi-5.2.11.dist-info/top_level.txt +2 -0
  31. 76f9a3652d4d2667c55c__mypyc.cp310-win32.pyd +0 -0
  32. faster_eth_abi-5.2.9.dist-info/RECORD +0 -44
  33. faster_eth_abi-5.2.9.dist-info/top_level.txt +0 -2
  34. {faster_eth_abi-5.2.9.dist-info → faster_eth_abi-5.2.11.dist-info}/WHEEL +0 -0
  35. {faster_eth_abi-5.2.9.dist-info → faster_eth_abi-5.2.11.dist-info}/licenses/LICENSE +0 -0
faster_eth_abi/grammar.py CHANGED
@@ -25,6 +25,14 @@ from typing_extensions import (
25
25
  Self,
26
26
  )
27
27
 
28
+ from faster_eth_abi._grammar import (
29
+ TYPE_ALIASES,
30
+ TYPE_ALIAS_RE,
31
+ ABIType,
32
+ BasicType,
33
+ TupleType,
34
+ normalize,
35
+ )
28
36
  from faster_eth_abi.exceptions import (
29
37
  ABITypeError,
30
38
  ParseError,
@@ -156,313 +164,7 @@ class NodeVisitor(parsimonious.NodeVisitor): # type: ignore [misc]
156
164
 
157
165
  visitor: Final = NodeVisitor()
158
166
 
159
-
160
- class ABIType:
161
- """
162
- Base class for results of type string parsing operations.
163
- """
164
-
165
- __slots__ = ("arrlist", "node")
166
-
167
- def __init__(
168
- self, arrlist: Optional[Sequence] = None, node: Optional[Node] = None
169
- ) -> None:
170
- self.arrlist: Final = arrlist
171
- """
172
- The list of array dimensions for a parsed type. Equal to ``None`` if
173
- type string has no array dimensions.
174
- """
175
-
176
- self.node: Final = node
177
- """
178
- The parsimonious ``Node`` instance associated with this parsed type.
179
- Used to generate error messages for invalid types.
180
- """
181
-
182
- def __repr__(self) -> str: # pragma: no cover
183
- return f"<{type(self).__qualname__} {self.to_type_str()!r}>"
184
-
185
- def __eq__(self, other: Any) -> bool:
186
- # Two ABI types are equal if their string representations are equal
187
- return type(self) is type(other) and self.to_type_str() == other.to_type_str()
188
-
189
- def to_type_str(self) -> TypeStr: # pragma: no cover
190
- """
191
- Returns the string representation of an ABI type. This will be equal to
192
- the type string from which it was created.
193
- """
194
- raise NotImplementedError("Must implement `to_type_str`")
195
-
196
- @property
197
- def item_type(self) -> Self:
198
- """
199
- If this type is an array type, equal to an appropriate
200
- :class:`~faster_eth_abi.grammar.ABIType` instance for the array's items.
201
- """
202
- raise NotImplementedError("Must implement `item_type`")
203
-
204
- def validate(self) -> None: # pragma: no cover
205
- """
206
- Validates the properties of an ABI type against the solidity ABI spec:
207
-
208
- https://solidity.readthedocs.io/en/develop/abi-spec.html
209
-
210
- Raises :class:`~faster_eth_abi.exceptions.ABITypeError` if validation fails.
211
- """
212
- raise NotImplementedError("Must implement `validate`")
213
-
214
- def invalidate(self, error_msg: str) -> NoReturn:
215
- # Invalidates an ABI type with the given error message. Expects that a
216
- # parsimonious node was provided from the original parsing operation
217
- # that yielded this type.
218
- node = self.node
219
-
220
- raise ABITypeError(
221
- f"For '{node.text}' type at column {node.start + 1} "
222
- f"in '{node.full_text}': {error_msg}"
223
- )
224
-
225
- @property
226
- def is_array(self) -> bool:
227
- """
228
- Equal to ``True`` if a type is an array type (i.e. if it has an array
229
- dimension list). Otherwise, equal to ``False``.
230
- """
231
- return self.arrlist is not None
232
-
233
- @property
234
- def is_dynamic(self) -> bool:
235
- """
236
- Equal to ``True`` if a type has a dynamically sized encoding.
237
- Otherwise, equal to ``False``.
238
- """
239
- raise NotImplementedError("Must implement `is_dynamic`")
240
-
241
- @property
242
- def _has_dynamic_arrlist(self) -> bool:
243
- return self.is_array and any(len(dim) == 0 for dim in self.arrlist)
244
-
245
-
246
- TComp = TypeVar("TComp", bound=ABIType)
247
-
248
-
249
- @final
250
- class TupleType(ABIType):
251
- """
252
- Represents the result of parsing a tuple type string e.g. "(int,bool)".
253
- """
254
-
255
- __slots__ = ("components",)
256
-
257
- def __init__(
258
- self,
259
- components: Tuple[TComp, ...],
260
- arrlist: Optional[Sequence] = None,
261
- *,
262
- node: Optional[Node] = None,
263
- ) -> None:
264
- super().__init__(arrlist, node)
265
-
266
- self.components: Final = components
267
- """
268
- A tuple of :class:`~faster_eth_abi.grammar.ABIType` instances for each of the
269
- tuple type's components.
270
- """
271
-
272
- def to_type_str(self) -> TypeStr:
273
- arrlist = self.arrlist
274
-
275
- if isinstance(arrlist, tuple):
276
- arrlist = "".join(repr(list(a)) for a in arrlist)
277
- else:
278
- arrlist = ""
279
-
280
- return f"({','.join(c.to_type_str() for c in self.components)}){arrlist}"
281
-
282
- @property
283
- def item_type(self) -> Self:
284
- if not self.is_array:
285
- raise ValueError(
286
- f"Cannot determine item type for non-array type '{self.to_type_str()}'"
287
- )
288
-
289
- return type(self)(
290
- self.components,
291
- self.arrlist[:-1] or None, # type: ignore [index]
292
- node=self.node,
293
- )
294
-
295
- def validate(self) -> None:
296
- for c in self.components:
297
- c.validate()
298
-
299
- @property
300
- def is_dynamic(self) -> bool:
301
- if self._has_dynamic_arrlist:
302
- return True
303
-
304
- return any(c.is_dynamic for c in self.components)
305
-
306
-
307
- @final
308
- class BasicType(ABIType):
309
- """
310
- Represents the result of parsing a basic type string e.g. "uint", "address",
311
- "ufixed128x19[][2]".
312
- """
313
-
314
- __slots__ = ("base", "sub")
315
-
316
- def __init__(
317
- self,
318
- base: str,
319
- sub: Any = None,
320
- arrlist: Optional[Sequence] = None,
321
- *,
322
- node: Optional[Node] = None,
323
- ) -> None:
324
- super().__init__(arrlist, node)
325
-
326
- self.base: Final = base
327
- """The base of a basic type e.g. "uint" for "uint256" etc."""
328
-
329
- self.sub: Final = sub
330
- """
331
- The sub type of a basic type e.g. ``256`` for "uint256" or ``(128, 18)``
332
- for "ufixed128x18" etc. Equal to ``None`` if type string has no sub
333
- type.
334
- """
335
-
336
- def to_type_str(self) -> TypeStr:
337
- sub, arrlist = self.sub, self.arrlist
338
-
339
- if isinstance(sub, int):
340
- substr = str(sub)
341
- elif isinstance(sub, tuple):
342
- substr = "x".join(str(s) for s in sub)
343
- else:
344
- substr = ""
345
-
346
- if isinstance(arrlist, tuple):
347
- return self.base + substr + "".join(repr(list(a)) for a in arrlist)
348
- else:
349
- return self.base + substr
350
-
351
- @property
352
- def item_type(self) -> Self:
353
- if not self.is_array:
354
- raise ValueError(
355
- f"Cannot determine item type for non-array type '{self.to_type_str()}'"
356
- )
357
-
358
- return type(self)(
359
- self.base,
360
- self.sub,
361
- self.arrlist[:-1] or None, # type: ignore [index]
362
- node=self.node,
363
- )
364
-
365
- @property
366
- def is_dynamic(self) -> bool:
367
- if self._has_dynamic_arrlist:
368
- return True
369
-
370
- if self.base == "string":
371
- return True
372
-
373
- if self.base == "bytes" and self.sub is None:
374
- return True
375
-
376
- return False
377
-
378
- def validate(self) -> None:
379
- base, sub = self.base, self.sub
380
-
381
- # Check validity of string type
382
- if base == "string":
383
- if sub is not None:
384
- self.invalidate("string type cannot have suffix")
385
-
386
- # Check validity of bytes type
387
- elif base == "bytes":
388
- if not (sub is None or isinstance(sub, int)):
389
- self.invalidate(
390
- "bytes type must have either no suffix or a numerical suffix"
391
- )
392
-
393
- if isinstance(sub, int) and sub > 32:
394
- self.invalidate("maximum 32 bytes for fixed-length bytes")
395
-
396
- # Check validity of integer type
397
- elif base in ("int", "uint"):
398
- if not isinstance(sub, int):
399
- self.invalidate("integer type must have numerical suffix")
400
-
401
- if sub < 8 or sub > 256:
402
- self.invalidate("integer size out of bounds (max 256 bits)")
403
-
404
- if sub % 8 != 0:
405
- self.invalidate("integer size must be multiple of 8")
406
-
407
- # Check validity of fixed type
408
- elif base in ("fixed", "ufixed"):
409
- if not isinstance(sub, tuple):
410
- self.invalidate(
411
- "fixed type must have suffix of form <bits>x<exponent>, "
412
- "e.g. 128x19",
413
- )
414
-
415
- bits, minus_e = sub
416
-
417
- if bits < 8 or bits > 256:
418
- self.invalidate("fixed size out of bounds (max 256 bits)")
419
-
420
- if bits % 8 != 0:
421
- self.invalidate("fixed size must be multiple of 8")
422
-
423
- if minus_e < 1 or minus_e > 80:
424
- self.invalidate(
425
- f"fixed exponent size out of bounds, {minus_e} must be in 1-80"
426
- )
427
-
428
- # Check validity of hash type
429
- elif base == "hash":
430
- if not isinstance(sub, int):
431
- self.invalidate("hash type must have numerical suffix")
432
-
433
- # Check validity of address type
434
- elif base == "address":
435
- if sub is not None:
436
- self.invalidate("address cannot have suffix")
437
-
438
-
439
- TYPE_ALIASES: Final = {
440
- "int": "int256",
441
- "uint": "uint256",
442
- "fixed": "fixed128x18",
443
- "ufixed": "ufixed128x18",
444
- "function": "bytes24",
445
- "byte": "bytes1",
446
- }
447
-
448
- TYPE_ALIAS_RE: Final = re.compile(
449
- rf"\b({'|'.join(re.escape(a) for a in TYPE_ALIASES.keys())})\b"
450
- )
451
-
452
-
453
- def normalize(type_str: TypeStr) -> TypeStr:
454
- """
455
- Normalizes a type string into its canonical version e.g. the type string
456
- 'int' becomes 'int256', etc.
457
-
458
- :param type_str: The type string to be normalized.
459
- :returns: The canonical version of the input type string.
460
- """
461
- return TYPE_ALIAS_RE.sub(__normalize, type_str)
462
-
463
-
464
- def __normalize(match: "re.Match[str]") -> str:
465
- return TYPE_ALIASES[match.group(0)]
167
+ parse: Final = visitor.parse
466
168
 
467
169
 
468
- parse: Final = visitor.parse
170
+ __all__ = ["NodeVisitor", "ABIType", "TupleType", "BasicType", "grammar", "parse", "normalize", "visitor", "TYPE_ALIASES", "TYPE_ALIAS_RE"]
Binary file
@@ -1,17 +1,24 @@
1
1
  import abc
2
- import copy
3
2
  import functools
3
+ from copy import copy
4
4
  from typing import (
5
5
  Any,
6
6
  Callable,
7
+ Dict,
8
+ Final,
9
+ Generic,
7
10
  Optional,
8
11
  Type,
12
+ TypeVar,
9
13
  Union,
10
14
  )
11
15
 
12
16
  from eth_typing import (
13
17
  TypeStr,
14
18
  )
19
+ from typing_extensions import (
20
+ Self,
21
+ )
15
22
 
16
23
  from . import (
17
24
  decoding,
@@ -30,6 +37,8 @@ from .io import (
30
37
  ContextFramesBytesIO,
31
38
  )
32
39
 
40
+ T = TypeVar("T")
41
+
33
42
  Lookup = Union[TypeStr, Callable[[TypeStr], bool]]
34
43
 
35
44
  EncoderCallable = Callable[[Any], bytes]
@@ -51,34 +60,35 @@ class Copyable(abc.ABC):
51
60
  return self.copy()
52
61
 
53
62
 
54
- class PredicateMapping(Copyable):
63
+ class PredicateMapping(Copyable, Generic[T]):
55
64
  """
56
65
  Acts as a mapping from predicate functions to values. Values are retrieved
57
66
  when their corresponding predicate matches a given input. Predicates can
58
67
  also be labeled to facilitate removal from the mapping.
59
68
  """
60
69
 
61
- def __init__(self, name):
62
- self._name = name
63
- self._values = {}
64
- self._labeled_predicates = {}
70
+ def __init__(self, name: str):
71
+ self._name: Final = name
72
+ self._values: Dict[Lookup, T] = {}
73
+ self._labeled_predicates: Dict[str, Lookup] = {}
65
74
 
66
- def add(self, predicate, value, label=None):
75
+ def add(self, predicate: Lookup, value: T, label: Optional[str] = None) -> None:
67
76
  if predicate in self._values:
68
77
  raise ValueError(f"Matcher {predicate!r} already exists in {self._name}")
69
78
 
70
79
  if label is not None:
71
- if label in self._labeled_predicates:
80
+ labeled_predicates = self._labeled_predicates
81
+ if label in labeled_predicates:
72
82
  raise ValueError(
73
83
  f"Matcher {predicate!r} with label '{label}' "
74
84
  f"already exists in {self._name}"
75
85
  )
76
86
 
77
- self._labeled_predicates[label] = predicate
87
+ labeled_predicates[label] = predicate
78
88
 
79
89
  self._values[predicate] = value
80
90
 
81
- def find(self, type_str):
91
+ def find(self, type_str: TypeStr) -> T:
82
92
  results = tuple(
83
93
  (predicate, value)
84
94
  for predicate, value in self._values.items()
@@ -103,9 +113,9 @@ class PredicateMapping(Copyable):
103
113
  "documentation for more information."
104
114
  )
105
115
 
106
- return values[0]
116
+ return values[0] # type: ignore [no-any-return]
107
117
 
108
- def remove_by_equality(self, predicate):
118
+ def remove_by_equality(self, predicate: Lookup) -> None:
109
119
  # Delete the predicate mapping to the previously stored value
110
120
  try:
111
121
  del self._values[predicate]
@@ -120,7 +130,7 @@ class PredicateMapping(Copyable):
120
130
  else:
121
131
  del self._labeled_predicates[label]
122
132
 
123
- def _label_for_predicate(self, predicate):
133
+ def _label_for_predicate(self, predicate: Lookup) -> str:
124
134
  # Both keys and values in `_labeled_predicates` are unique since the
125
135
  # `add` method enforces this
126
136
  for key, value in self._labeled_predicates.items():
@@ -131,16 +141,17 @@ class PredicateMapping(Copyable):
131
141
  f"Matcher {predicate!r} not referred to by any label in {self._name}"
132
142
  )
133
143
 
134
- def remove_by_label(self, label):
144
+ def remove_by_label(self, label: str) -> None:
145
+ labeled_predicates = self._labeled_predicates
135
146
  try:
136
- predicate = self._labeled_predicates[label]
147
+ predicate = labeled_predicates[label]
137
148
  except KeyError:
138
149
  raise KeyError(f"Label '{label}' not found in {self._name}")
139
150
 
140
- del self._labeled_predicates[label]
151
+ del labeled_predicates[label]
141
152
  del self._values[predicate]
142
153
 
143
- def remove(self, predicate_or_label):
154
+ def remove(self, predicate_or_label: Union[Lookup, str]) -> None:
144
155
  if callable(predicate_or_label):
145
156
  self.remove_by_equality(predicate_or_label)
146
157
  elif isinstance(predicate_or_label, str):
@@ -151,11 +162,11 @@ class PredicateMapping(Copyable):
151
162
  f"{type(predicate_or_label)}"
152
163
  )
153
164
 
154
- def copy(self):
165
+ def copy(self) -> Self:
155
166
  cpy = type(self)(self._name)
156
167
 
157
- cpy._values = copy.copy(self._values)
158
- cpy._labeled_predicates = copy.copy(self._labeled_predicates)
168
+ cpy._values = copy(self._values)
169
+ cpy._labeled_predicates = copy(self._labeled_predicates)
159
170
 
160
171
  return cpy
161
172
 
@@ -282,6 +293,7 @@ def _clear_encoder_cache(old_method: Callable[..., None]) -> Callable[..., None]
282
293
  @functools.wraps(old_method)
283
294
  def new_method(self: "ABIRegistry", *args: Any, **kwargs: Any) -> None:
284
295
  self.get_encoder.cache_clear()
296
+ self.get_tuple_encoder.cache_clear()
285
297
  return old_method(self, *args, **kwargs)
286
298
 
287
299
  return new_method
@@ -291,6 +303,7 @@ def _clear_decoder_cache(old_method: Callable[..., None]) -> Callable[..., None]
291
303
  @functools.wraps(old_method)
292
304
  def new_method(self: "ABIRegistry", *args: Any, **kwargs: Any) -> None:
293
305
  self.get_decoder.cache_clear()
306
+ self.get_tuple_decoder.cache_clear()
294
307
  return old_method(self, *args, **kwargs)
295
308
 
296
309
  return new_method
@@ -343,8 +356,8 @@ class BaseRegistry:
343
356
 
344
357
  class ABIRegistry(Copyable, BaseRegistry):
345
358
  def __init__(self):
346
- self._encoders = PredicateMapping("encoder registry")
347
- self._decoders = PredicateMapping("decoder registry")
359
+ self._encoders: PredicateMapping[Encoder] = PredicateMapping("encoder registry")
360
+ self._decoders: PredicateMapping[Decoder] = PredicateMapping("decoder registry")
348
361
  self.get_encoder = functools.lru_cache(maxsize=None)(self._get_encoder_uncached)
349
362
  self.get_decoder = functools.lru_cache(maxsize=None)(self._get_decoder_uncached)
350
363
  self.get_tuple_encoder = functools.lru_cache(maxsize=None)(
@@ -518,8 +531,8 @@ class ABIRegistry(Copyable, BaseRegistry):
518
531
  """
519
532
  cpy = type(self)()
520
533
 
521
- cpy._encoders = copy.copy(self._encoders)
522
- cpy._decoders = copy.copy(self._decoders)
534
+ cpy._encoders = copy(self._encoders)
535
+ cpy._decoders = copy(self._decoders)
523
536
 
524
537
  return cpy
525
538
 
@@ -2,7 +2,9 @@ from typing import (
2
2
  Callable,
3
3
  Final,
4
4
  Optional,
5
+ Tuple,
5
6
  Union,
7
+ cast,
6
8
  )
7
9
 
8
10
  from cchecksum import (
@@ -15,11 +17,13 @@ from hypothesis import (
15
17
  strategies as st,
16
18
  )
17
19
 
18
- from faster_eth_abi.grammar import (
20
+ from faster_eth_abi._grammar import (
19
21
  ABIType,
20
22
  BasicType,
21
23
  TupleType,
22
24
  normalize,
25
+ )
26
+ from faster_eth_abi.grammar import (
23
27
  parse,
24
28
  )
25
29
  from faster_eth_abi.registry import (
@@ -81,7 +85,7 @@ class StrategyRegistry(BaseRegistry):
81
85
  def get_uint_strategy(
82
86
  abi_type: BasicType, registry: StrategyRegistry
83
87
  ) -> st.SearchStrategy:
84
- bits = abi_type.sub
88
+ bits = cast(int, abi_type.sub)
85
89
 
86
90
  return st.integers(
87
91
  min_value=0,
@@ -92,7 +96,7 @@ def get_uint_strategy(
92
96
  def get_int_strategy(
93
97
  abi_type: BasicType, registry: StrategyRegistry
94
98
  ) -> st.SearchStrategy:
95
- bits = abi_type.sub
99
+ bits = cast(int, abi_type.sub)
96
100
 
97
101
  return st.integers(
98
102
  min_value=-(2 ** (bits - 1)),
@@ -107,7 +111,7 @@ bool_strategy: Final = st.booleans()
107
111
  def get_ufixed_strategy(
108
112
  abi_type: BasicType, registry: StrategyRegistry
109
113
  ) -> st.SearchStrategy:
110
- bits, places = abi_type.sub
114
+ bits, places = cast(Tuple[int, int], abi_type.sub)
111
115
 
112
116
  return st.decimals(
113
117
  min_value=0,
@@ -119,7 +123,7 @@ def get_ufixed_strategy(
119
123
  def get_fixed_strategy(
120
124
  abi_type: BasicType, registry: StrategyRegistry
121
125
  ) -> st.SearchStrategy:
122
- bits, places = abi_type.sub
126
+ bits, places = cast(Tuple[int, int], abi_type.sub)
123
127
 
124
128
  return st.decimals(
125
129
  min_value=-(2 ** (bits - 1)),
@@ -1,6 +1,7 @@
1
1
  import decimal
2
2
  from typing import (
3
3
  Callable,
4
+ Dict,
4
5
  Final,
5
6
  Tuple,
6
7
  )
@@ -8,6 +9,7 @@ from typing import (
8
9
  ABI_DECIMAL_PREC: Final = 999
9
10
 
10
11
  abi_decimal_context: Final = decimal.Context(prec=ABI_DECIMAL_PREC)
12
+ decimal_localcontext: Final = decimal.localcontext
11
13
 
12
14
  ZERO: Final = decimal.Decimal(0)
13
15
  TEN: Final = decimal.Decimal(10)
@@ -16,47 +18,76 @@ Decimal: Final = decimal.Decimal
16
18
 
17
19
 
18
20
  def ceil32(x: int) -> int:
19
- return x if x % 32 == 0 else x + 32 - (x % 32)
21
+ remainder = x % 32
22
+ return x if remainder == 0 else x + 32 - remainder
23
+
24
+
25
+ _unsigned_integer_bounds_cache: Final[Dict[int, Tuple[int, int]]] = {}
20
26
 
21
27
 
22
28
  def compute_unsigned_integer_bounds(num_bits: int) -> Tuple[int, int]:
23
- return (
24
- 0,
25
- 2**num_bits - 1,
26
- )
29
+ bounds = _unsigned_integer_bounds_cache.get(num_bits)
30
+ if bounds is None:
31
+ bounds = 0, 2**num_bits - 1
32
+ _unsigned_integer_bounds_cache[num_bits] = bounds
33
+ return bounds
34
+
35
+
36
+ _signed_integer_bounds_cache: Final[Dict[int, Tuple[int, int]]] = {}
27
37
 
28
38
 
29
39
  def compute_signed_integer_bounds(num_bits: int) -> Tuple[int, int]:
30
- return (
31
- -1 * 2 ** (num_bits - 1),
32
- 2 ** (num_bits - 1) - 1,
33
- )
40
+ bounds = _signed_integer_bounds_cache.get(num_bits)
41
+ if bounds is None:
42
+ overflow_at = 2 ** (num_bits - 1)
43
+ min_value = -overflow_at
44
+ max_value = overflow_at - 1
45
+ bounds = min_value, max_value
46
+ _signed_integer_bounds_cache[num_bits] = bounds
47
+ return bounds
48
+
49
+
50
+ _unsigned_fixed_bounds_cache: Final[Dict[Tuple[int, int], decimal.Decimal]] = {}
34
51
 
35
52
 
36
53
  def compute_unsigned_fixed_bounds(
37
54
  num_bits: int,
38
55
  frac_places: int,
39
56
  ) -> Tuple[decimal.Decimal, decimal.Decimal]:
40
- int_upper = compute_unsigned_integer_bounds(num_bits)[1]
57
+ upper = _unsigned_fixed_bounds_cache.get((num_bits, frac_places))
58
+ if upper is None:
59
+ int_upper = 2**num_bits - 1
60
+
61
+ with decimal_localcontext(abi_decimal_context):
62
+ upper = Decimal(int_upper) * TEN**-frac_places
41
63
 
42
- with decimal.localcontext(abi_decimal_context):
43
- upper = Decimal(int_upper) * TEN**-frac_places
64
+ _unsigned_fixed_bounds_cache[(num_bits, frac_places)] = upper
44
65
 
45
66
  return ZERO, upper
46
67
 
47
68
 
69
+ _signed_fixed_bounds_cache: Final[
70
+ Dict[Tuple[int, int], Tuple[decimal.Decimal, decimal.Decimal]]
71
+ ] = {}
72
+
73
+
48
74
  def compute_signed_fixed_bounds(
49
75
  num_bits: int,
50
76
  frac_places: int,
51
77
  ) -> Tuple[decimal.Decimal, decimal.Decimal]:
52
- int_lower, int_upper = compute_signed_integer_bounds(num_bits)
78
+ bounds = _signed_fixed_bounds_cache.get((num_bits, frac_places))
79
+ if bounds is None:
80
+ int_lower, int_upper = compute_signed_integer_bounds(num_bits)
81
+
82
+ with decimal_localcontext(abi_decimal_context):
83
+ exp = TEN**-frac_places
84
+ lower = Decimal(int_lower) * exp
85
+ upper = Decimal(int_upper) * exp
53
86
 
54
- with decimal.localcontext(abi_decimal_context):
55
- exp = TEN**-frac_places
56
- lower = Decimal(int_lower) * exp
57
- upper = Decimal(int_upper) * exp
87
+ bounds = lower, upper
88
+ _signed_fixed_bounds_cache[(num_bits, frac_places)] = bounds
58
89
 
59
- return lower, upper
90
+ return bounds
60
91
 
61
92
 
62
93
  def scale_places(places: int) -> Callable[[decimal.Decimal], decimal.Decimal]:
@@ -70,11 +101,11 @@ def scale_places(places: int) -> Callable[[decimal.Decimal], decimal.Decimal]:
70
101
  f"of type {type(places)}.",
71
102
  )
72
103
 
73
- with decimal.localcontext(abi_decimal_context):
104
+ with decimal_localcontext(abi_decimal_context):
74
105
  scaling_factor = TEN**-places
75
106
 
76
107
  def f(x: decimal.Decimal) -> decimal.Decimal:
77
- with decimal.localcontext(abi_decimal_context):
108
+ with decimal_localcontext(abi_decimal_context):
78
109
  return x * scaling_factor
79
110
 
80
111
  places_repr = f"Eneg{places}" if places > 0 else f"Epos{-places}"