refactor: reduce nesting

This commit is contained in:
Mike A.
2026-01-06 00:36:35 +01:00
parent 2afba5ed51
commit c9897eaaba

View File

@@ -467,36 +467,38 @@ class _AccessoryKeyGenerator(KeyGenerator[KeyPair]):
# Use bisect to find the largest index < ind in O(log n) # Use bisect to find the largest index < ind in O(log n)
pos = bisect.bisect_left(indices, ind) pos = bisect.bisect_left(indices, ind)
if pos > 0: if pos == 0: # No cached index less than ind
cached_ind = indices[pos - 1] continue
if cached_ind > best_ind:
best_ind = cached_ind cached_ind = indices[pos - 1]
best_sk = cache[cached_ind] if cached_ind > best_ind:
best_ind = cached_ind
best_sk = cache[cached_ind]
return best_ind, best_sk return best_ind, best_sk
def _update_caches(self, ind: int, sk: bytes) -> None: def _update_caches(self, ind: int, sk: bytes) -> None:
"""Update all applicable cache tiers with the computed key.""" """Update all applicable cache tiers with the computed key."""
for tier_idx, tier in enumerate(self._CACHE_TIERS): for tier_idx, tier in enumerate(self._CACHE_TIERS):
if ind % tier.interval == 0: if ind % tier.interval != 0:
cache = self._sk_caches[tier_idx] continue
indices = self._cache_indices[tier_idx]
# Add to cache if not already present cache = self._sk_caches[tier_idx]
if ind not in cache: indices = self._cache_indices[tier_idx]
cache[ind] = sk
bisect.insort(indices, ind)
# Evict if cache exceeds size limit # Add to cache if not already present
if tier.max_size is not None and len(cache) > tier.max_size: if ind in cache:
# If adding a historical key, evict smallest (oldest) continue
# If adding a future key, evict largest (newest old key) cache[ind] = sk
if indices and ind > indices[0]: bisect.insort(indices, ind)
evict_ind = indices.pop(0)
else:
evict_ind = indices.pop(-1)
del cache[evict_ind] # Evict if cache exceeds size limit
if tier.max_size is not None and len(cache) > tier.max_size:
# If adding a historical key, evict smallest index
# If adding a future key, evict largest
evict_ind = indices.pop(0 if indices and ind > indices[0] else -1)
del cache[evict_ind]
def _get_sk(self, ind: int) -> bytes: def _get_sk(self, ind: int) -> bytes:
if ind < 0: if ind < 0: