1
# Copyright (C) 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
"""A simple first-in-first-out (FIFO) cache."""
19
from collections import deque
22
class FIFOCache(dict):
23
"""A class which manages a cache of entries, removing old ones."""
25
def __init__(self, max_cache=100, after_cleanup_count=None):
27
self._max_cache = max_cache
28
if after_cleanup_count is None:
29
self._after_cleanup_count = self._max_cache * 8 / 10
31
self._after_cleanup_count = min(after_cleanup_count,
33
self._cleanup = {} # map to cleanup functions when items are removed
34
self._queue = deque() # Track when things are accessed
36
def __setitem__(self, key, value):
37
"""Add a value to the cache, there will be no cleanup function."""
38
self.add(key, value, cleanup=None)
40
def __delitem__(self, key):
41
# Remove the key from an arbitrary location in the queue
42
remove = getattr(self._queue, 'remove', None)
43
# Python2.5's has deque.remove, but Python2.4 does not
44
if remove is not None:
47
# TODO: It would probably be faster to pop()/popleft() until we get to the
48
# key, and then insert those back into the queue. We know
49
# the key should only be present in one position, and we
50
# wouldn't need to rebuild the whole queue.
51
self._queue = deque([k for k in self._queue if k != key])
54
def add(self, key, value, cleanup=None):
55
"""Add a new value to the cache.
57
Also, if the entry is ever removed from the queue, call cleanup.
58
Passing it the key and value being removed.
60
:param key: The key to store it under
61
:param value: The object to store
62
:param cleanup: None or a function taking (key, value) to indicate
63
'value' should be cleaned up
66
# Remove the earlier reference to this key, adding it again bumps
67
# it to the end of the queue
69
self._queue.append(key)
70
dict.__setitem__(self, key, value)
71
if cleanup is not None:
72
self._cleanup[key] = cleanup
73
if len(self) > self._max_cache:
77
"""Get the number of entries we will cache."""
78
return self._max_cache
81
"""Clear the cache until it shrinks to the requested size.
83
This does not completely wipe the cache, just makes sure it is under
84
the after_cleanup_count.
86
# Make sure the cache is shrunk to the correct size
87
while len(self) > self._after_cleanup_count:
89
if len(self._queue) != len(self):
90
raise AssertionError('The length of the queue should always equal'
91
' the length of the dict. %s != %s'
92
% (len(self._queue), len(self)))
95
"""Clear out all of the cache."""
96
# Clean up in FIFO order
100
def _remove(self, key):
101
"""Remove an entry, making sure to call any cleanup function."""
102
cleanup = self._cleanup.pop(key, None)
103
# We override self.pop() because it doesn't play well with cleanup
105
val = dict.pop(self, key)
106
if cleanup is not None:
110
def _remove_oldest(self):
111
"""Remove the oldest entry."""
112
key = self._queue.popleft()
115
def resize(self, max_cache, after_cleanup_count=None):
116
"""Increase/decrease the number of cached entries.
118
:param max_cache: The maximum number of entries to cache.
119
:param after_cleanup_count: After cleanup, we should have at most this
120
many entries. This defaults to 80% of max_cache.
122
self._max_cache = max_cache
123
if after_cleanup_count is None:
124
self._after_cleanup_count = max_cache * 8 / 10
126
self._after_cleanup_count = min(max_cache, after_cleanup_count)
127
if len(self) > self._max_cache:
130
# raise NotImplementedError on dict functions that would mutate the cache
131
# which have not been properly implemented yet.
133
raise NotImplementedError(self.copy)
135
def pop(self, key, default=None):
136
# If there is a cleanup() function, than it is unclear what pop()
137
# should do. Specifically, we would have to call the cleanup on the
138
# value before we return it, which should cause whatever resources were
139
# allocated to be removed, which makes the return value fairly useless.
140
# So instead, we just don't implement it.
141
raise NotImplementedError(self.pop)
145
raise NotImplementedError(self.popitem)
147
def setdefault(self, key, defaultval=None):
148
"""similar to dict.setdefault"""
151
self[key] = defaultval
154
def update(self, *args, **kwargs):
155
"""Similar to dict.update()"""
158
if isinstance(arg, dict):
159
for key, val in arg.iteritems():
162
for key, val in args[0]:
165
raise TypeError('update expected at most 1 argument, got %d'
168
for key, val in kwargs.iteritems():
172
class FIFOSizeCache(FIFOCache):
173
"""An FIFOCache that removes things based on the size of the values.
175
This differs in that it doesn't care how many actual items there are,
176
it restricts the cache to be cleaned based on the size of the data.
179
def __init__(self, max_size=1024*1024, after_cleanup_size=None,
181
"""Create a new FIFOSizeCache.
183
:param max_size: The max number of bytes to store before we start
184
clearing out entries.
185
:param after_cleanup_size: After cleaning up, shrink everything to this
186
size (defaults to 80% of max_size).
187
:param compute_size: A function to compute the size of a value. If
188
not supplied we default to 'len'.
190
# Arbitrary, we won't really be using the value anyway.
191
FIFOCache.__init__(self, max_cache=max_size)
192
self._max_size = max_size
193
if after_cleanup_size is None:
194
self._after_cleanup_size = self._max_size * 8 / 10
196
self._after_cleanup_size = min(after_cleanup_size, self._max_size)
199
self._compute_size = compute_size
200
if compute_size is None:
201
self._compute_size = len
203
def add(self, key, value, cleanup=None):
204
"""Add a new value to the cache.
206
Also, if the entry is ever removed from the queue, call cleanup.
207
Passing it the key and value being removed.
209
:param key: The key to store it under
210
:param value: The object to store, this value by itself is >=
211
after_cleanup_size, then we will not store it at all.
212
:param cleanup: None or a function taking (key, value) to indicate
213
'value' sohuld be cleaned up.
215
# Even if the new value won't be stored, we need to remove the old
218
# Remove the earlier reference to this key, adding it again bumps
219
# it to the end of the queue
221
value_len = self._compute_size(value)
222
if value_len >= self._after_cleanup_size:
224
self._queue.append(key)
225
dict.__setitem__(self, key, value)
226
if cleanup is not None:
227
self._cleanup[key] = cleanup
228
self._value_size += value_len
229
if self._value_size > self._max_size:
233
def cache_size(self):
234
"""Get the number of bytes we will cache."""
235
return self._max_size
238
"""Clear the cache until it shrinks to the requested size.
240
This does not completely wipe the cache, just makes sure it is under
241
the after_cleanup_size.
243
# Make sure the cache is shrunk to the correct size
244
while self._value_size > self._after_cleanup_size:
245
self._remove_oldest()
247
def _remove(self, key):
248
"""Remove an entry, making sure to maintain the invariants."""
249
val = FIFOCache._remove(self, key)
250
self._value_size -= self._compute_size(val)
253
def resize(self, max_size, after_cleanup_size=None):
254
"""Increase/decrease the amount of cached data.
256
:param max_size: The maximum number of bytes to cache.
257
:param after_cleanup_size: After cleanup, we should have at most this
258
many bytes cached. This defaults to 80% of max_size.
260
FIFOCache.resize(self, max_size)
261
self._max_size = max_size
262
if after_cleanup_size is None:
263
self._after_cleanup_size = max_size * 8 / 10
265
self._after_cleanup_size = min(max_size, after_cleanup_size)
266
if self._value_size > self._max_size: