139
140
for key, val in kwargs.iteritems():
140
141
self.add(key, val)
144
class FIFOSizeCache(FIFOCache):
145
"""An FIFOCache that removes things based on the size of the values.
147
This differs in that it doesn't care how many actual items there are,
148
it restricts the cache to be cleaned based on the size of the data.
151
def __init__(self, max_size=1024*1024, after_cleanup_size=None,
153
"""Create a new FIFOSizeCache.
155
:param max_size: The max number of bytes to store before we start
156
clearing out entries.
157
:param after_cleanup_size: After cleaning up, shrink everything to this
158
size (defaults to 80% of max_size).
159
:param compute_size: A function to compute the size of a value. If
160
not supplied we default to 'len'.
162
# Arbitrary, we won't really be using the value anyway.
163
FIFOCache.__init__(self, max_cache=max_size)
164
self._max_size = max_size
165
if after_cleanup_size is None:
166
self._after_cleanup_size = self._max_size * 8 / 10
168
self._after_cleanup_size = min(after_cleanup_size, self._max_size)
171
self._compute_size = compute_size
172
if compute_size is None:
173
self._compute_size = len
175
def add(self, key, value, cleanup=None):
176
"""Add a new value to the cache.
178
Also, if the entry is ever removed from the queue, call cleanup.
179
Passing it the key and value being removed.
181
:param key: The key to store it under
182
:param value: The object to store, this value by itself is >=
183
after_cleanup_size, then we will not store it at all.
184
:param cleanup: None or a function taking (key, value) to indicate
185
'value' sohuld be cleaned up.
187
# Even if the new value won't be stored, we need to remove the old
190
# Remove the earlier reference to this key, adding it again bumps
191
# it to the end of the queue
193
value_len = self._compute_size(value)
194
if value_len >= self._after_cleanup_size:
196
self._queue.append(key)
197
dict.__setitem__(self, key, value)
198
if cleanup is not None:
199
self._cleanup[key] = cleanup
200
self._value_size += value_len
201
if self._value_size > self._max_size:
206
"""Clear the cache until it shrinks to the requested size.
208
This does not completely wipe the cache, just makes sure it is under
209
the after_cleanup_size.
211
# Make sure the cache is shrunk to the correct size
212
while self._value_size > self._after_cleanup_size:
213
self._remove_oldest()
215
def _remove(self, key):
216
"""Remove an entry, making sure to maintain the invariants."""
217
val = FIFOCache._remove(self, key)
218
self._value_size -= self._compute_size(val)