34 lines
1.0 KiB
Python
34 lines
1.0 KiB
Python
# ruff: noqa: INP001
|
|
"""LRU cache implementation."""
|
|
|
|
from collections import OrderedDict
|
|
|
|
|
|
class LRUCache:
|
|
"""Simple LRU cache with size limit."""
|
|
|
|
def __init__(self, max_size: int = 100) -> None:
|
|
"""Initialize cache with maximum size."""
|
|
self.cache: OrderedDict[str, bytes] = OrderedDict()
|
|
self.max_size = max_size
|
|
|
|
def get(self, key: str) -> bytes | None:
|
|
"""Get item from cache, returning None if not found."""
|
|
if key not in self.cache:
|
|
return None
|
|
# Move to end to mark as recently used
|
|
self.cache.move_to_end(key)
|
|
return self.cache[key]
|
|
|
|
def put(self, key: str, value: bytes) -> None:
|
|
"""Put item in cache, evicting oldest if at capacity."""
|
|
if key in self.cache:
|
|
self.cache.move_to_end(key)
|
|
self.cache[key] = value
|
|
if len(self.cache) > self.max_size:
|
|
self.cache.popitem(last=False)
|
|
|
|
def __contains__(self, key: str) -> bool:
|
|
"""Check if key exists in cache."""
|
|
return key in self.cache
|