Skip to content

Commit 819ca2e

Browse files
bluetoothbotclaudebdraco
authored
perf(gap): route parse_advertisement_data_tuple misses through bytes cache (Bluetooth-Devices#261)
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> Co-authored-by: J. Nick Koston <nick@koston.org> Co-authored-by: J. Nick Koston <nick@home-assistant.io>
1 parent 9a93fb8 commit 819ca2e

2 files changed

Lines changed: 25 additions & 3 deletions

File tree

src/bluetooth_data_tools/gap.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -190,9 +190,13 @@ def _uncached_parse_advertisement_data(data: bytes) -> BLEGAPAdvertisement:
190190
def _uncached_parse_advertisement_tuple(
191191
data: tuple[bytes, ...],
192192
) -> BLEGAPAdvertisementTupleType:
193-
return _uncached_parse_advertisement_bytes(
194-
b"".join(data) if len(data) > 1 else data[0]
195-
)
193+
# Route tuple-cache misses through the bytes-keyed cache so identical
194+
# content arriving via a fresh tuple identity still skips the full parse.
195+
# The outer lru_cache around parse_advertisement_data_tuple owns the
196+
# hit-path (C-level hash on the tuple, no join).
197+
if len(data) == 1:
198+
return parse_advertisement_data_bytes(data[0])
199+
return parse_advertisement_data_bytes(b"".join(data))
196200

197201

198202
def _uncached_parse_advertisement_bytes(

tests/test_gap.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1158,3 +1158,21 @@ def test_parse_advertisement_data_single_element_tuple_unwraps_to_bytes_cache():
11581158
from_tuple = parse_advertisement_data((payload,))
11591159
from_list = parse_advertisement_data([payload])
11601160
assert from_tuple.local_name == from_list.local_name == "RZSS"
1161+
1162+
1163+
def test_parse_advertisement_data_tuple_miss_falls_through_bytes_cache():
1164+
"""A tuple-cache miss must consult the bytes-keyed cache before paying for
1165+
a full parse, so identical content arriving via a fresh tuple identity
1166+
still benefits from a previous bytes-form call.
1167+
"""
1168+
payload = b"\x02\x01\x06\x05\tRZSS"
1169+
1170+
# Prime the bytes cache only.
1171+
parse_advertisement_data_tuple.cache_clear()
1172+
expected = parse_advertisement_data_bytes(payload)
1173+
1174+
# Tuple cache is empty, so this call must miss the tuple cache and resolve
1175+
# via the bytes cache.
1176+
assert parse_advertisement_data_tuple((payload,)) == expected
1177+
# Multi-chunk path: same content, fresh tuple identity, still bytes-cached.
1178+
assert parse_advertisement_data_tuple((b"", payload)) == expected

0 commit comments

Comments
 (0)