Skip to content

Commit 4065a2f

Browse files
perf: skip HexBytes allocation for int indexing (#257)
## Summary Switch HexBytes32 int indexing to use bytes.__getitem__ while keeping slice behavior on FasterHexBytes. ## Rationale Avoids allocating FasterHexBytes on int indexing in a hot path without changing results. ## Details - Int keys now go through bytes.__getitem__; slices still return FasterHexBytes. - Added assertions for positive/negative int indexing parity with bytes. - mypyc: evmspec/_new.cpython-313-x86_64-linux-gnu.so loaded during tests. ## Testing - ./.venv/bin/python -m pytest
1 parent 29b107e commit 4065a2f

File tree

2 files changed

+6
-1
lines changed

2 files changed

+6
-1
lines changed

evmspec/data/_main.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -410,7 +410,9 @@ def __getitem__(self, key: SupportsIndex) -> int: ...
410410
def __getitem__(self, key: slice) -> faster_hexbytes.HexBytes: ...
411411

412412
def __getitem__(self, key: SupportsIndex | slice) -> int | faster_hexbytes.HexBytes:
413-
return FasterHexBytes(self)[key]
413+
if isinstance(key, slice):
414+
return FasterHexBytes(self)[key]
415+
return bytes.__getitem__(self, key)
414416

415417
# TODO: keep the instance small and just task on the length for operations as needed
416418
# def __len__(self) -> Literal[32]:

tests/data/test_main.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,10 @@ def test_hexbytes32_repr_hex_strip_hash() -> None:
8484

8585
def test_hexbytes32_getitem() -> None:
8686
hb = HexBytes32(HEX32)
87+
raw = bytes(hb)
8788
assert isinstance(hb[0], int)
89+
assert hb[0] == raw[0]
90+
assert hb[-1] == raw[-1]
8891
sliced = hb[:2]
8992
assert isinstance(sliced, FasterHexBytes)
9093

0 commit comments

Comments
 (0)