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
self._cleanup[key] = cleanup
67
self._record_access(key)
69
if len(self._cache) > self._max_cache:
73
def get(self, key, default=None):
74
if key in self._cache:
79
"""Get the list of keys currently cached.
81
Note that values returned here may not be available by the time you
82
request them later. This is simply meant as a peak into the current
85
:return: An unordered list of keys that are currently cached.
87
return self._cache.keys()
90
"""Clear the cache until it shrinks to the requested size.
92
This does not completely wipe the cache, just makes sure it is under
93
the after_cleanup_count.
95
# Make sure the cache is shrunk to the correct size
96
while len(self._cache) > self._after_cleanup_count:
98
# No need to compact the queue at this point, because the code that
99
# calls this would have already triggered it based on queue length
101
def __setitem__(self, key, value):
102
"""Add a value to the cache, there will be no cleanup function."""
103
self.add(key, value, cleanup=None)
105
def _record_access(self, key):
106
"""Record that key was accessed."""
107
self._queue.append(key)
108
# Can't use setdefault because you can't += 1 the result
109
self._refcount[key] = self._refcount.get(key, 0) + 1
111
# If our access queue is too large, clean it up too
112
if len(self._queue) > self._compact_queue_length:
113
self._compact_queue()
115
def _compact_queue(self):
116
"""Compact the queue, leaving things in sorted last appended order."""
118
for item in self._queue:
119
if self._refcount[item] == 1:
120
new_queue.append(item)
122
self._refcount[item] -= 1
123
self._queue = new_queue
124
# All entries should be of the same size. There should be one entry in
125
# queue for each entry in cache, and all refcounts should == 1
126
if not (len(self._queue) == len(self._cache) ==
127
len(self._refcount) == sum(self._refcount.itervalues())):
128
raise AssertionError()
130
def _remove(self, key):
131
"""Remove an entry, making sure to maintain the invariants."""
132
cleanup = self._cleanup.pop(key)
133
val = self._cache.pop(key)
134
if cleanup is not None:
138
def _remove_lru(self):
139
"""Remove one entry from the lru, and handle consequences.
141
If there are no more references to the lru, then this entry should be
142
removed from the cache.
144
key = self._queue.popleft()
145
self._refcount[key] -= 1
146
if not self._refcount[key]:
147
del self._refcount[key]
151
"""Clear out all of the cache."""
152
# Clean up in LRU order
156
def resize(self, max_cache, after_cleanup_count=None):
157
"""Change the number of entries that will be cached."""
158
self._update_max_cache(max_cache,
159
after_cleanup_count=after_cleanup_count)
161
def _update_max_cache(self, max_cache, after_cleanup_count=None):
162
self._max_cache = max_cache
163
if after_cleanup_count is None:
164
self._after_cleanup_count = self._max_cache * 8 / 10
166
self._after_cleanup_count = min(after_cleanup_count, self._max_cache)
168
self._compact_queue_length = 4*self._max_cache
169
if len(self._queue) > self._compact_queue_length:
170
self._compact_queue()
174
class LRUSizeCache(LRUCache):
175
"""An LRUCache that removes things based on the size of the values.
177
This differs in that it doesn't care how many actual items there are,
178
it just restricts the cache to be cleaned up after so much data is stored.
180
The values that are added must support len(value).
183
def __init__(self, max_size=1024*1024, after_cleanup_size=None,
185
"""Create a new LRUSizeCache.
187
:param max_size: The max number of bytes to store before we start
188
clearing out entries.
189
:param after_cleanup_size: After cleaning up, shrink everything to this
191
:param compute_size: A function to compute the size of the values. We
192
use a function here, so that you can pass 'len' if you are just
193
using simple strings, or a more complex function if you are using
194
something like a list of strings, or even a custom object.
195
The function should take the form "compute_size(value) => integer".
196
If not supplied, it defaults to 'len()'
199
self._compute_size = compute_size
200
if compute_size is None:
201
self._compute_size = len
202
# This approximates that texts are > 0.5k in size. It only really
203
# effects when we clean up the queue, so we don't want it to be too
205
self._update_max_size(max_size, after_cleanup_size=after_cleanup_size)
206
LRUCache.__init__(self, max_cache=max(int(max_size/512), 1))
208
def add(self, key, value, cleanup=None):
209
"""Add a new value to the cache.
211
Also, if the entry is ever removed from the queue, call cleanup.
212
Passing it the key and value being removed.
214
:param key: The key to store it under
215
:param value: The object to store
216
:param cleanup: None or a function taking (key, value) to indicate
217
'value' sohuld be cleaned up.
219
if key in self._cache:
221
value_len = self._compute_size(value)
222
if value_len >= self._after_cleanup_size:
224
self._value_size += value_len
225
self._cache[key] = value
226
self._cleanup[key] = cleanup
227
self._record_access(key)
229
if self._value_size > self._max_size:
234
"""Clear the cache until it shrinks to the requested size.
236
This does not completely wipe the cache, just makes sure it is under
237
the after_cleanup_size.
239
# Make sure the cache is shrunk to the correct size
240
while self._value_size > self._after_cleanup_size:
243
def _remove(self, key):
244
"""Remove an entry, making sure to maintain the invariants."""
245
val = LRUCache._remove(self, key)
246
self._value_size -= self._compute_size(val)
248
def resize(self, max_size, after_cleanup_size=None):
249
"""Change the number of bytes that will be cached."""
250
self._update_max_size(max_size, after_cleanup_size=after_cleanup_size)
251
max_cache = max(int(max_size/512), 1)
252
self._update_max_cache(max_cache)
254
def _update_max_size(self, max_size, after_cleanup_size=None):
255
self._max_size = max_size
256
if after_cleanup_size is None:
257
self._after_cleanup_size = self._max_size * 8 / 10
259
self._after_cleanup_size = min(after_cleanup_size, self._max_size)