Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions hexbytes/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,14 @@ def __getitem__(self, key: slice) -> "HexBytes": # noqa: F811
def __getitem__( # noqa: F811
self, key: "SupportsIndex | slice"
) -> "int | bytes | HexBytes":
result = super().__getitem__(key)
if hasattr(result, "hex"):
return type(self)(result)
else:
result = bytes.__getitem__(self, key)
if isinstance(result, int):
return result
cls = type(self)
if cls is HexBytes:
return bytes.__new__(HexBytes, result)
else:
return cls(result)

def __repr__(self) -> str:
return f"HexBytes({'0x' + self.hex()!r})"
Expand Down
15 changes: 15 additions & 0 deletions tests/core/test_hexbytes.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,13 +116,28 @@ def test_hexbytes_index(primitive, index):
assert hexbytes[index] == primitive[index]


def test_hexbytes_index_type():
assert isinstance(HexBytes(b"abc")[0], int)


@given(st.binary(), st.integers(), st.integers())
def test_slice(primitive, start, stop):
hexbytes = HexBytes(primitive)
expected = HexBytes(primitive[start:stop])
assert hexbytes[start:stop] == expected


def test_slice_type():
assert type(HexBytes(b"abc")[:2]) is HexBytes


def test_slice_preserves_subclass():
class CustomHexBytes(HexBytes):
pass

assert type(CustomHexBytes(b"abc")[:2]) is CustomHexBytes


@given(st.binary(), st.integers(), st.integers(), st.integers())
def test_slice_stepped(primitive, start, stop, step):
hexbytes = HexBytes(primitive)
Expand Down