From c53b010dd5f4da69b1e42f94d2896afffb1e287a Mon Sep 17 00:00:00 2001 From: Codex Date: Wed, 29 Jul 2026 00:27:38 -0400 Subject: [PATCH] perf: short-circuit empty hex strings --- hexbytes/_utils.py | 3 +++ tests/core/test_hexbytes.py | 5 +++++ 2 files changed, 8 insertions(+) diff --git a/hexbytes/_utils.py b/hexbytes/_utils.py index bc99e14..48bc998 100644 --- a/hexbytes/_utils.py +++ b/hexbytes/_utils.py @@ -35,6 +35,9 @@ def hexstr_to_bytes(hexstr: str) -> bytes: else: non_prefixed_hex = hexstr + if not non_prefixed_hex: + return b"" + # if the hex string is odd-length, then left-pad it to an even length if len(hexstr) % 2: padded_hex = "0" + non_prefixed_hex diff --git a/tests/core/test_hexbytes.py b/tests/core/test_hexbytes.py index 36cf1f6..eb435bf 100644 --- a/tests/core/test_hexbytes.py +++ b/tests/core/test_hexbytes.py @@ -91,6 +91,11 @@ def test_hex_inputs(hex_input): assert_equal(wrapped, expected) +@pytest.mark.parametrize("hex_input", ("", "0x", "0X")) +def test_empty_hex_inputs(hex_input): + assert_equal(HexBytes(hex_input), b"") + + def test_pretty_output(): hb = HexBytes(b"\x0f\x1a") assert repr(hb) == "HexBytes('0x0f1a')"