1
# Copyright (C) 2006, 2008 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
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
17
"""A simple least-recently-used (LRU) cache."""
19
from collections import deque
21
from bzrlib import symbol_versioning
24
class LRUCache(object):
25
"""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
37
self._queue = deque() # Track when things are accessed
38
self._refcount = {} # number of entries in self._queue for each key
39
self._update_max_cache(max_cache, after_cleanup_count)
41
def __contains__(self, key):
42
return key in self._cache
44
def __getitem__(self, key):
45
val = self._cache[key]
46
self._record_access(key)
50
return len(self._cache)
52
def add(self, key, value, cleanup=None):
53
"""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.
58
:param key: The key to store it under
59
:param value: The object to store
60
:param cleanup: None or a function taking (key, value) to indicate
61
'value' sohuld be cleaned up.
63
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)
70
if len(self._cache) > self._max_cache:
74
def get(self, key, default=None):
75
if key in self._cache:
80
"""Get the list of keys currently cached.
82
Note that values returned here may not be available by the time you
83
request them later. This is simply meant as a peak into the current
86
:return: An unordered list of keys that are currently cached.
88
return self._cache.keys()
91
"""Clear the cache until it shrinks to the requested size.
93
This does not completely wipe the cache, just makes sure it is under
94
the after_cleanup_count.
96
# Make sure the cache is shrunk to the correct size
97
while len(self._cache) > self._after_cleanup_count:
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
def __setitem__(self, key, value):
103
"""Add a value to the cache, there will be no cleanup function."""
104
self.add(key, value, cleanup=None)
106
def _record_access(self, key):
107
"""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:
139
def _remove_lru(self):
140
"""Remove one entry from the lru, and handle consequences.
142
If there are no more references to the lru, then this entry should be
143
removed from the cache.
145
key = self._queue.popleft()
146
self._refcount[key] -= 1
147
if not self._refcount[key]:
148
del self._refcount[key]
152
"""Clear out all of the cache."""
153
# Clean up in LRU order
157
def resize(self, max_cache, after_cleanup_count=None):
158
"""Change the number of entries that will be cached."""
159
self._update_max_cache(max_cache,
160
after_cleanup_count=after_cleanup_count)
162
def _update_max_cache(self, max_cache, after_cleanup_count=None):
163
self._max_cache = max_cache
164
if after_cleanup_count is None:
165
self._after_cleanup_count = self._max_cache * 8 / 10
167
self._after_cleanup_count = min(after_cleanup_count, self._max_cache)
169
self._compact_queue_length = 4*self._max_cache
170
if len(self._queue) > self._compact_queue_length:
171
self._compact_queue()
175
class LRUSizeCache(LRUCache):
176
"""An LRUCache that removes things based on the size of the values.
178
This differs in that it doesn't care how many actual items there are,
179
it just restricts the cache to be cleaned up after so much data is stored.
181
The values that are added must support len(value).
184
def __init__(self, max_size=1024*1024, after_cleanup_size=None,
186
"""Create a new LRUSizeCache.
188
:param max_size: The max number of bytes to store before we start
189
clearing out entries.
190
:param after_cleanup_size: After cleaning up, shrink everything to this
192
:param compute_size: A function to compute the size of the values. We
193
use a function here, so that you can pass 'len' if you are just
194
using simple strings, or a more complex function if you are using
195
something like a list of strings, or even a custom object.
196
The function should take the form "compute_size(value) => integer".
197
If not supplied, it defaults to 'len()'
200
self._compute_size = compute_size
201
if compute_size is None:
202
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
self._update_max_size(max_size, after_cleanup_size=after_cleanup_size)
207
LRUCache.__init__(self, max_cache=max(int(max_size/512), 1))
209
def add(self, key, value, cleanup=None):
210
"""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.
215
:param key: The key to store it under
216
:param value: The object to store
217
:param cleanup: None or a function taking (key, value) to indicate
218
'value' sohuld be cleaned up.
220
if key in self._cache:
222
value_len = self._compute_size(value)
223
if value_len >= self._after_cleanup_size:
225
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)
231
if self._value_size > self._max_size:
236
"""Clear the cache until it shrinks to the requested size.
238
This does not completely wipe the cache, just makes sure it is under
239
the after_cleanup_size.
241
# Make sure the cache is shrunk to the correct size
242
while self._value_size > self._after_cleanup_size:
245
def _remove(self, key):
246
"""Remove an entry, making sure to maintain the invariants."""
247
val = LRUCache._remove(self, key)
248
self._value_size -= self._compute_size(val)
250
def resize(self, max_size, after_cleanup_size=None):
251
"""Change the number of bytes that will be cached."""
252
self._update_max_size(max_size, after_cleanup_size=after_cleanup_size)
253
max_cache = max(int(max_size/512), 1)
254
self._update_max_cache(max_cache)
256
def _update_max_size(self, max_size, after_cleanup_size=None):
257
self._max_size = max_size
258
if after_cleanup_size is None:
259
self._after_cleanup_size = self._max_size * 8 / 10
261
self._after_cleanup_size = min(after_cleanup_size, self._max_size)