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
21
from bzrlib import symbol_versioning
25
class _LRUNode(object):
26
"""This maintains the linked-list which is the lru internals."""
28
__slots__ = ('prev', 'next_key', 'key', 'value', 'cleanup', 'size')
30
def __init__(self, key, value, cleanup=None):
32
self.next_key = _null_key
35
self.cleanup = cleanup
36
# TODO: We could compute this 'on-the-fly' like we used to, and remove
37
# one pointer from this object, we just need to decide if it
38
# actually costs us much of anything in normal usage
45
prev_key = self.prev.key
46
return '%s(%r n:%r p:%r)' % (self.__class__.__name__, self.key,
47
self.next_key, prev_key)
49
def run_cleanup(self):
51
if self.cleanup is not None:
52
self.cleanup(self.key, self.value)
54
# cleanup might raise an exception, but we want to make sure
55
# to break refcycles, etc
24
60
class LRUCache(object):
25
61
"""A class which manages a cache of entries, removing unused ones."""
27
def __init__(self, max_cache=100, after_cleanup_count=None,
28
after_cleanup_size=symbol_versioning.DEPRECATED_PARAMETER):
29
if symbol_versioning.deprecated_passed(after_cleanup_size):
30
symbol_versioning.warn('LRUCache.__init__(after_cleanup_size) was'
31
' deprecated in 1.11. Use'
32
' after_cleanup_count instead.',
34
after_cleanup_count = after_cleanup_size
63
def __init__(self, max_cache=100, after_cleanup_count=None):
37
self._queue = deque() # Track when things are accessed
38
self._refcount = {} # number of entries in self._queue for each key
65
# The "HEAD" of the lru linked list
66
self._most_recently_used = None
67
# The "TAIL" of the lru linked list
68
self._least_recently_used = None
39
69
self._update_max_cache(max_cache, after_cleanup_count)
41
71
def __contains__(self, key):
42
72
return key in self._cache
44
74
def __getitem__(self, key):
45
val = self._cache[key]
46
self._record_access(key)
77
# Inlined from _record_access to decrease the overhead of __getitem__
78
# We also have more knowledge about structure if __getitem__ is
79
# succeeding, then we know that self._most_recently_used must not be
81
mru = self._most_recently_used
83
# Nothing to do, this node is already at the head of the queue
85
# Remove this node from the old location
87
next_key = node.next_key
88
# benchmarking shows that the lookup of _null_key in globals is faster
89
# than the attribute lookup for (node is self._least_recently_used)
90
if next_key is _null_key:
91
# 'node' is the _least_recently_used, because it doesn't have a
92
# 'next' item. So move the current lru to the previous node.
93
self._least_recently_used = node_prev
95
node_next = cache[next_key]
96
node_next.prev = node_prev
97
node_prev.next_key = next_key
98
# Insert this node at the front of the list
99
node.next_key = mru.key
101
self._most_recently_used = node
49
105
def __len__(self):
50
106
return len(self._cache)
109
"""Walk the LRU list, only meant to be used in tests."""
110
node = self._most_recently_used
112
if node.prev is not None:
113
raise AssertionError('the _most_recently_used entry is not'
114
' supposed to have a previous entry'
116
while node is not None:
117
if node.next_key is _null_key:
118
if node is not self._least_recently_used:
119
raise AssertionError('only the last node should have'
120
' no next value: %s' % (node,))
123
node_next = self._cache[node.next_key]
124
if node_next.prev is not node:
125
raise AssertionError('inconsistency found, node.next.prev'
126
' != node: %s' % (node,))
127
if node.prev is None:
128
if node is not self._most_recently_used:
129
raise AssertionError('only the _most_recently_used should'
130
' not have a previous node: %s'
133
if node.prev.next_key != node.key:
134
raise AssertionError('inconsistency found, node.prev.next'
135
' != node: %s' % (node,))
52
139
def add(self, key, value, cleanup=None):
53
140
"""Add a new value to the cache.
55
Also, if the entry is ever removed from the queue, call cleanup.
56
Passing it the key and value being removed.
142
Also, if the entry is ever removed from the cache, call
58
145
:param key: The key to store it under
59
146
:param value: The object to store
60
147
:param cleanup: None or a function taking (key, value) to indicate
61
'value' sohuld be cleaned up.
148
'value' should be cleaned up.
151
raise ValueError('cannot use _null_key as a key')
63
152
if key in self._cache:
65
self._cache[key] = value
66
if cleanup is not None:
67
self._cleanup[key] = cleanup
68
self._record_access(key)
153
node = self._cache[key]
157
# Maintain the LRU properties, even if cleanup raises an
160
node.cleanup = cleanup
161
self._record_access(node)
163
node = _LRUNode(key, value, cleanup=cleanup)
164
self._cache[key] = node
165
self._record_access(node)
70
167
if len(self._cache) > self._max_cache:
71
168
# Trigger the cleanup
171
def cache_size(self):
172
"""Get the number of entries we will cache."""
173
return self._max_cache
74
175
def get(self, key, default=None):
75
if key in self._cache:
176
node = self._cache.get(key, None)
179
self._record_access(node)
80
183
"""Get the list of keys currently cached.
96
203
# Make sure the cache is shrunk to the correct size
97
204
while len(self._cache) > self._after_cleanup_count:
98
205
self._remove_lru()
99
# No need to compact the queue at this point, because the code that
100
# calls this would have already triggered it based on queue length
102
207
def __setitem__(self, key, value):
103
208
"""Add a value to the cache, there will be no cleanup function."""
104
209
self.add(key, value, cleanup=None)
106
def _record_access(self, key):
211
def _record_access(self, node):
107
212
"""Record that key was accessed."""
108
self._queue.append(key)
109
# Can't use setdefault because you can't += 1 the result
110
self._refcount[key] = self._refcount.get(key, 0) + 1
112
# If our access queue is too large, clean it up too
113
if len(self._queue) > self._compact_queue_length:
114
self._compact_queue()
116
def _compact_queue(self):
117
"""Compact the queue, leaving things in sorted last appended order."""
119
for item in self._queue:
120
if self._refcount[item] == 1:
121
new_queue.append(item)
123
self._refcount[item] -= 1
124
self._queue = new_queue
125
# All entries should be of the same size. There should be one entry in
126
# queue for each entry in cache, and all refcounts should == 1
127
if not (len(self._queue) == len(self._cache) ==
128
len(self._refcount) == sum(self._refcount.itervalues())):
129
raise AssertionError()
131
def _remove(self, key):
132
"""Remove an entry, making sure to maintain the invariants."""
133
cleanup = self._cleanup.pop(key, None)
134
val = self._cache.pop(key)
135
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
247
# cleanup might raise an exception, but we want to make sure to
248
# maintain the linked list
249
if node.prev is not None:
250
node.prev.next_key = node.next_key
251
if node.next_key is not _null_key:
252
node_next = self._cache[node.next_key]
253
node_next.prev = node.prev
254
# And remove this node's pointers
256
node.next_key = _null_key
139
258
def _remove_lru(self):
140
259
"""Remove one entry from the lru, and handle consequences.
200
313
self._compute_size = compute_size
201
314
if compute_size is None:
202
315
self._compute_size = len
203
# This approximates that texts are > 0.5k in size. It only really
204
# effects when we clean up the queue, so we don't want it to be too
206
316
self._update_max_size(max_size, after_cleanup_size=after_cleanup_size)
207
317
LRUCache.__init__(self, max_cache=max(int(max_size/512), 1))
209
319
def add(self, key, value, cleanup=None):
210
320
"""Add a new value to the cache.
212
Also, if the entry is ever removed from the queue, call cleanup.
213
Passing it the key and value being removed.
322
Also, if the entry is ever removed from the cache, call
215
325
:param key: The key to store it under
216
326
:param value: The object to store
217
327
:param cleanup: None or a function taking (key, value) to indicate
218
'value' sohuld be cleaned up.
328
'value' should be cleaned up.
220
if key in self._cache:
331
raise ValueError('cannot use _null_key as a key')
332
node = self._cache.get(key, None)
222
333
value_len = self._compute_size(value)
223
334
if value_len >= self._after_cleanup_size:
335
# The new value is 'too big to fit', as it would fill up/overflow
336
# the cache all by itself
337
trace.mutter('Adding the key %r to an LRUSizeCache failed.'
338
' value %d is too big to fit in a the cache'
339
' with size %d %d', key, value_len,
340
self._after_cleanup_size, self._max_size)
342
# We won't be replacing the old node, so just remove it
343
self._remove_node(node)
344
if cleanup is not None:
348
node = _LRUNode(key, value, cleanup=cleanup)
349
self._cache[key] = node
351
self._value_size -= node.size
352
node.size = value_len
225
353
self._value_size += value_len
226
self._cache[key] = value
227
if cleanup is not None:
228
self._cleanup[key] = cleanup
229
self._record_access(key)
354
self._record_access(node)
231
356
if self._value_size > self._max_size:
232
357
# Time to cleanup