13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
17
"""A simple least-recently-used (LRU) cache."""
19
from collections import deque
26
class _LRUNode(object):
27
"""This maintains the linked-list which is the lru internals."""
29
__slots__ = ('prev', 'next_key', 'key', 'value', 'cleanup', 'size')
31
def __init__(self, key, value, cleanup=None):
33
self.next_key = _null_key
36
self.cleanup = cleanup
37
# TODO: We could compute this 'on-the-fly' like we used to, and remove
38
# one pointer from this object, we just need to decide if it
39
# actually costs us much of anything in normal usage
46
prev_key = self.prev.key
47
return '%s(%r n:%r p:%r)' % (self.__class__.__name__, self.key,
48
self.next_key, prev_key)
50
def run_cleanup(self):
51
if self.cleanup is not None:
52
self.cleanup(self.key, self.value)
54
# Just make sure to break any refcycles, etc
23
58
class LRUCache(object):
24
59
"""A class which manages a cache of entries, removing unused ones."""
26
def __init__(self, max_cache=100, after_cleanup_size=None):
27
self._max_cache = max_cache
28
if after_cleanup_size is None:
29
self._after_cleanup_size = self._max_cache
31
self._after_cleanup_size = min(after_cleanup_size, self._max_cache)
33
self._compact_queue_length = 4*self._max_cache
61
def __init__(self, max_cache=100, after_cleanup_count=None,
62
after_cleanup_size=symbol_versioning.DEPRECATED_PARAMETER):
63
if symbol_versioning.deprecated_passed(after_cleanup_size):
64
symbol_versioning.warn('LRUCache.__init__(after_cleanup_size) was'
65
' deprecated in 1.11. Use'
66
' after_cleanup_count instead.',
68
after_cleanup_count = after_cleanup_size
37
self._queue = deque() # Track when things are accessed
38
self._refcount = {} # number of entries in self._queue for each key
70
# The "HEAD" of the lru linked list
71
self._most_recently_used = None
72
# The "TAIL" of the lru linked list
73
self._least_recently_used = None
74
self._update_max_cache(max_cache, after_cleanup_count)
40
76
def __contains__(self, key):
41
77
return key in self._cache
43
79
def __getitem__(self, key):
44
val = self._cache[key]
45
self._record_access(key)
82
# Inlined from _record_access to decrease the overhead of __getitem__
83
# We also have more knowledge about structure if __getitem__ is
84
# succeeding, then we know that self._most_recently_used must not be
86
mru = self._most_recently_used
88
# Nothing to do, this node is already at the head of the queue
90
# Remove this node from the old location
92
next_key = node.next_key
93
# benchmarking shows that the lookup of _null_key in globals is faster
94
# than the attribute lookup for (node is self._least_recently_used)
95
if next_key is _null_key:
96
# 'node' is the _least_recently_used, because it doesn't have a
97
# 'next' item. So move the current lru to the previous node.
98
self._least_recently_used = node_prev
100
node_next = cache[next_key]
101
node_next.prev = node_prev
102
node_prev.next_key = next_key
103
# Insert this node at the front of the list
104
node.next_key = mru.key
106
self._most_recently_used = node
48
110
def __len__(self):
49
111
return len(self._cache)
114
"""Walk the LRU list, only meant to be used in tests."""
115
node = self._most_recently_used
117
if node.prev is not None:
118
raise AssertionError('the _most_recently_used entry is not'
119
' supposed to have a previous entry'
121
while node is not None:
122
if node.next_key is _null_key:
123
if node is not self._least_recently_used:
124
raise AssertionError('only the last node should have'
125
' no next value: %s' % (node,))
128
node_next = self._cache[node.next_key]
129
if node_next.prev is not node:
130
raise AssertionError('inconsistency found, node.next.prev'
131
' != node: %s' % (node,))
132
if node.prev is None:
133
if node is not self._most_recently_used:
134
raise AssertionError('only the _most_recently_used should'
135
' not have a previous node: %s'
138
if node.prev.next_key != node.key:
139
raise AssertionError('inconsistency found, node.prev.next'
140
' != node: %s' % (node,))
51
144
def add(self, key, value, cleanup=None):
52
145
"""Add a new value to the cache.
54
Also, if the entry is ever removed from the queue, call cleanup.
55
Passing it the key and value being removed.
147
Also, if the entry is ever removed from the cache, call
57
150
:param key: The key to store it under
58
151
:param value: The object to store
59
152
:param cleanup: None or a function taking (key, value) to indicate
60
'value' sohuld be cleaned up.
153
'value' should be cleaned up.
156
raise ValueError('cannot use _null_key as a key')
62
157
if key in self._cache:
64
self._cache[key] = value
65
self._cleanup[key] = cleanup
66
self._record_access(key)
158
node = self._cache[key]
161
node.cleanup = cleanup
163
node = _LRUNode(key, value, cleanup=cleanup)
164
self._cache[key] = node
165
self._record_access(node)
68
167
if len(self._cache) > self._max_cache:
69
168
# Trigger the cleanup
171
def cache_size(self):
172
"""Get the number of entries we will cache."""
173
return self._max_cache
72
175
def get(self, key, default=None):
73
if key in self._cache:
176
node = self._cache.get(key, None)
179
self._record_access(node)
183
"""Get the list of keys currently cached.
185
Note that values returned here may not be available by the time you
186
request them later. This is simply meant as a peak into the current
189
:return: An unordered list of keys that are currently cached.
191
return self._cache.keys()
194
"""Get the key:value pairs as a dict."""
195
return dict((k, n.value) for k, n in self._cache.iteritems())
77
197
def cleanup(self):
78
198
"""Clear the cache until it shrinks to the requested size.
80
200
This does not completely wipe the cache, just makes sure it is under
81
the after_cleanup_size.
201
the after_cleanup_count.
83
203
# Make sure the cache is shrunk to the correct size
84
while len(self._cache) > self._after_cleanup_size:
204
while len(self._cache) > self._after_cleanup_count:
85
205
self._remove_lru()
87
207
def __setitem__(self, key, value):
88
208
"""Add a value to the cache, there will be no cleanup function."""
89
209
self.add(key, value, cleanup=None)
91
def _record_access(self, key):
211
def _record_access(self, node):
92
212
"""Record that key was accessed."""
93
self._queue.append(key)
94
# Can't use setdefault because you can't += 1 the result
95
self._refcount[key] = self._refcount.get(key, 0) + 1
97
# If our access queue is too large, clean it up too
98
if len(self._queue) > self._compact_queue_length:
101
def _compact_queue(self):
102
"""Compact the queue, leaving things in sorted last appended order."""
104
for item in self._queue:
105
if self._refcount[item] == 1:
106
new_queue.append(item)
108
self._refcount[item] -= 1
109
self._queue = new_queue
110
# All entries should be of the same size. There should be one entry in
111
# queue for each entry in cache, and all refcounts should == 1
112
if not (len(self._queue) == len(self._cache) ==
113
len(self._refcount) == sum(self._refcount.itervalues())):
114
raise AssertionError()
116
def _remove(self, key):
117
"""Remove an entry, making sure to maintain the invariants."""
118
cleanup = self._cleanup.pop(key)
119
val = self._cache.pop(key)
120
if cleanup is not None:
213
# Move 'node' to the front of the queue
214
if self._most_recently_used is None:
215
self._most_recently_used = node
216
self._least_recently_used = node
218
elif node is self._most_recently_used:
219
# Nothing to do, this node is already at the head of the queue
221
# We've taken care of the tail pointer, remove the node, and insert it
224
if node is self._least_recently_used:
225
self._least_recently_used = node.prev
226
if node.prev is not None:
227
node.prev.next_key = node.next_key
228
if node.next_key is not _null_key:
229
node_next = self._cache[node.next_key]
230
node_next.prev = node.prev
232
node.next_key = self._most_recently_used.key
233
self._most_recently_used.prev = node
234
self._most_recently_used = node
237
def _remove_node(self, node):
238
if node is self._least_recently_used:
239
self._least_recently_used = node.prev
240
self._cache.pop(node.key)
241
# If we have removed all entries, remove the head pointer as well
242
if self._least_recently_used is None:
243
self._most_recently_used = None
245
# Now remove this node from the linked list
246
if node.prev is not None:
247
node.prev.next_key = node.next_key
248
if node.next_key is not _null_key:
249
node_next = self._cache[node.next_key]
250
node_next.prev = node.prev
251
# And remove this node's pointers
253
node.next_key = _null_key
124
255
def _remove_lru(self):
125
256
"""Remove one entry from the lru, and handle consequences.
164
306
The function should take the form "compute_size(value) => integer".
165
307
If not supplied, it defaults to 'len()'
167
# This approximates that texts are > 0.5k in size. It only really
168
# effects when we clean up the queue, so we don't want it to be too
170
LRUCache.__init__(self, max_cache=int(max_size/512))
171
self._max_size = max_size
172
if after_cleanup_size is None:
173
self._after_cleanup_size = self._max_size
175
self._after_cleanup_size = min(after_cleanup_size, self._max_size)
177
309
self._value_size = 0
178
310
self._compute_size = compute_size
179
311
if compute_size is None:
180
312
self._compute_size = len
313
self._update_max_size(max_size, after_cleanup_size=after_cleanup_size)
314
LRUCache.__init__(self, max_cache=max(int(max_size/512), 1))
182
316
def add(self, key, value, cleanup=None):
183
317
"""Add a new value to the cache.
185
Also, if the entry is ever removed from the queue, call cleanup.
186
Passing it the key and value being removed.
319
Also, if the entry is ever removed from the cache, call
188
322
:param key: The key to store it under
189
323
:param value: The object to store
190
324
:param cleanup: None or a function taking (key, value) to indicate
191
'value' sohuld be cleaned up.
325
'value' should be cleaned up.
193
if key in self._cache:
328
raise ValueError('cannot use _null_key as a key')
329
node = self._cache.get(key, None)
195
330
value_len = self._compute_size(value)
196
331
if value_len >= self._after_cleanup_size:
332
# The new value is 'too big to fit', as it would fill up/overflow
333
# the cache all by itself
334
trace.mutter('Adding the key %r to an LRUSizeCache failed.'
335
' value %d is too big to fit in a the cache'
336
' with size %d %d', key, value_len,
337
self._after_cleanup_size, self._max_size)
339
# We won't be replacing the old node, so just remove it
340
self._remove_node(node)
341
if cleanup is not None:
345
node = _LRUNode(key, value, cleanup=cleanup)
346
self._cache[key] = node
348
self._value_size -= node.size
349
node.size = value_len
198
350
self._value_size += value_len
199
self._cache[key] = value
200
self._cleanup[key] = cleanup
201
self._record_access(key)
351
self._record_access(node)
203
353
if self._value_size > self._max_size:
204
354
# Time to cleanup