|
1 |
| -from typing import Dict, Generic, TypeVar, TYPE_CHECKING |
2 |
| -import sys |
| 1 | +from threading import Lock |
| 2 | +from typing import Dict, Generic, List, Optional, TypeVar, Union, overload |
3 | 3 |
|
4 | 4 | CacheKey = TypeVar("CacheKey")
|
5 | 5 | CacheValue = TypeVar("CacheValue")
|
| 6 | +DefaultValue = TypeVar("DefaultValue") |
6 | 7 |
|
7 |
| -if sys.version_info < (3, 9): |
8 |
| - from typing_extensions import OrderedDict |
9 |
| -else: |
10 |
| - from collections import OrderedDict |
11 | 8 |
|
12 |
| - |
13 |
| -class LRUCache(OrderedDict[CacheKey, CacheValue]): |
| 9 | +class LRUCache(Generic[CacheKey, CacheValue]): |
14 | 10 | """
|
15 | 11 | A dictionary-like container that stores a given maximum items.
|
16 | 12 |
|
17 | 13 | If an additional item is added when the LRUCache is full, the least
|
18 | 14 | recently used key is discarded to make room for the new item.
|
19 | 15 |
|
| 16 | + The implementation is similar to functools.lru_cache, which uses a linked |
| 17 | + list to keep track of the most recently used items. |
| 18 | +
|
| 19 | + Each entry is stored as [PREV, NEXT, KEY, VALUE] where PREV is a reference |
| 20 | + to the previous entry, and NEXT is a reference to the next value. |
| 21 | +
|
20 | 22 | """
|
21 | 23 |
|
22 |
| - def __init__(self, cache_size: int) -> None: |
23 |
| - self.cache_size = cache_size |
| 24 | + def __init__(self, maxsize: int) -> None: |
| 25 | + self.maxsize = maxsize |
| 26 | + self.cache: Dict[CacheKey, List[object]] = {} |
| 27 | + self.full = False |
| 28 | + self.root: List[object] = [] |
| 29 | + self._lock = Lock() |
24 | 30 | super().__init__()
|
25 | 31 |
|
26 |
| - def __setitem__(self, key: CacheKey, value: CacheValue) -> None: |
27 |
| - """Store a new views, potentially discarding an old value.""" |
28 |
| - if key not in self: |
29 |
| - if len(self) >= self.cache_size: |
30 |
| - self.popitem(last=False) |
31 |
| - super().__setitem__(key, value) |
| 32 | + def __len__(self) -> int: |
| 33 | + return len(self.cache) |
| 34 | + |
| 35 | + def set(self, key: CacheKey, value: CacheValue) -> None: |
| 36 | + """Set a value. |
| 37 | +
|
| 38 | + Args: |
| 39 | + key (CacheKey): Key. |
| 40 | + value (CacheValue): Value. |
| 41 | + """ |
| 42 | + with self._lock: |
| 43 | + link = self.cache.get(key) |
| 44 | + if link is None: |
| 45 | + root = self.root |
| 46 | + if not root: |
| 47 | + self.root[:] = [self.root, self.root, key, value] |
| 48 | + else: |
| 49 | + self.root = [root[0], root, key, value] |
| 50 | + root[0][1] = self.root # type: ignore[index] |
| 51 | + root[0] = self.root |
| 52 | + self.cache[key] = self.root |
| 53 | + |
| 54 | + if self.full or len(self.cache) > self.maxsize: |
| 55 | + self.full = True |
| 56 | + root = self.root |
| 57 | + last = root[0] |
| 58 | + last[0][1] = root # type: ignore[index] |
| 59 | + root[0] = last[0] # type: ignore[index] |
| 60 | + del self.cache[last[2]] # type: ignore[index] |
| 61 | + |
| 62 | + __setitem__ = set |
| 63 | + |
| 64 | + @overload |
| 65 | + def get(self, key: CacheKey) -> Optional[CacheValue]: |
| 66 | + ... |
| 67 | + |
| 68 | + @overload |
| 69 | + def get( |
| 70 | + self, key: CacheKey, default: DefaultValue |
| 71 | + ) -> Union[CacheValue, DefaultValue]: |
| 72 | + ... |
| 73 | + |
| 74 | + def get( |
| 75 | + self, key: CacheKey, default: Optional[DefaultValue] = None |
| 76 | + ) -> Union[CacheValue, Optional[DefaultValue]]: |
| 77 | + """Get a value from the cache, or return a default if the key is not present. |
| 78 | +
|
| 79 | + Args: |
| 80 | + key (CacheKey): Key |
| 81 | + default (Optional[DefaultValue], optional): Default to return if key is not present. Defaults to None. |
| 82 | +
|
| 83 | + Returns: |
| 84 | + Union[CacheValue, Optional[DefaultValue]]: Either the value or a default. |
| 85 | + """ |
| 86 | + link = self.cache.get(key) |
| 87 | + if link is None: |
| 88 | + return default |
| 89 | + if link is not self.root: |
| 90 | + with self._lock: |
| 91 | + link[0][1] = link[1] # type: ignore[index] |
| 92 | + link[1][0] = link[0] # type: ignore[index] |
| 93 | + root = self.root |
| 94 | + link[0] = root[0] |
| 95 | + link[1] = root |
| 96 | + root[0][1] = link # type: ignore[index] |
| 97 | + root[0] = link |
| 98 | + self.root = link |
| 99 | + return link[3] # type: ignore[return-value] |
32 | 100 |
|
33 | 101 | def __getitem__(self, key: CacheKey) -> CacheValue:
|
34 |
| - """Gets the item, but also makes it most recent.""" |
35 |
| - value: CacheValue = super().__getitem__(key) |
36 |
| - super().__delitem__(key) |
37 |
| - super().__setitem__(key, value) |
38 |
| - return value |
| 102 | + link = self.cache[key] |
| 103 | + if link is not self.root: |
| 104 | + with self._lock: |
| 105 | + link[0][1] = link[1] # type: ignore[index] |
| 106 | + link[1][0] = link[0] # type: ignore[index] |
| 107 | + root = self.root |
| 108 | + link[0] = root[0] |
| 109 | + link[1] = root |
| 110 | + root[0][1] = link # type: ignore[index] |
| 111 | + root[0] = link |
| 112 | + self.root = link |
| 113 | + return link[3] # type: ignore[return-value] |
| 114 | + |
| 115 | + def __contains__(self, key: CacheKey) -> bool: |
| 116 | + return key in self.cache |
0 commit comments