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
self._queue.remove(key)
45
def add(self, key, value, cleanup=None):
46
"""Add a new value to the cache.
48
Also, if the entry is ever removed from the queue, call cleanup.
49
Passing it the key and value being removed.
51
:param key: The key to store it under
52
:param value: The object to store
53
:param cleanup: None or a function taking (key, value) to indicate
54
'value' should be cleaned up
57
# Remove the earlier reference to this key, adding it again bumps
58
# it to the end of the queue
60
self._queue.append(key)
61
dict.__setitem__(self, key, value)
62
if cleanup is not None:
63
self._cleanup[key] = cleanup
64
if len(self) > self._max_cache:
68
"""Get the number of entries we will cache."""
69
return self._max_cache
72
"""Clear the cache until it shrinks to the requested size.
74
This does not completely wipe the cache, just makes sure it is under
75
the after_cleanup_count.
77
# Make sure the cache is shrunk to the correct size
78
while len(self) > self._after_cleanup_count:
80
if len(self._queue) != len(self):
81
raise AssertionError('The length of the queue should always equal'
82
' the length of the dict. %s != %s'
83
% (len(self._queue), len(self)))
86
"""Clear out all of the cache."""
87
# Clean up in FIFO order
91
def _remove(self, key):
92
"""Remove an entry, making sure to call any cleanup function."""
93
cleanup = self._cleanup.pop(key, None)
94
# We override self.pop() because it doesn't play well with cleanup
96
val = dict.pop(self, key)
97
if cleanup is not None:
101
def _remove_oldest(self):
102
"""Remove the oldest entry."""
103
key = self._queue.popleft()
106
def resize(self, max_cache, after_cleanup_count=None):
107
"""Increase/decrease the number of cached entries.
109
:param max_cache: The maximum number of entries to cache.
110
:param after_cleanup_count: After cleanup, we should have at most this
111
many entries. This defaults to 80% of max_cache.
113
self._max_cache = max_cache
114
if after_cleanup_count is None:
115
self._after_cleanup_count = max_cache * 8 // 10
117
self._after_cleanup_count = min(max_cache, after_cleanup_count)
118
if len(self) > self._max_cache:
121
# raise NotImplementedError on dict functions that would mutate the cache
122
# which have not been properly implemented yet.
124
raise NotImplementedError(self.copy)
126
def pop(self, key, default=None):
127
# If there is a cleanup() function, than it is unclear what pop()
128
# should do. Specifically, we would have to call the cleanup on the
129
# value before we return it, which should cause whatever resources were
130
# allocated to be removed, which makes the return value fairly useless.
131
# So instead, we just don't implement it.
132
raise NotImplementedError(self.pop)
136
raise NotImplementedError(self.popitem)
138
def setdefault(self, key, defaultval=None):
139
"""similar to dict.setdefault"""
142
self[key] = defaultval
145
def update(self, *args, **kwargs):
146
"""Similar to dict.update()"""
149
if isinstance(arg, dict):
151
self.add(key, arg[key])
153
for key, val in args[0]:
156
raise TypeError('update expected at most 1 argument, got %d'
160
self.add(key, kwargs[key])
163
class FIFOSizeCache(FIFOCache):
164
"""An FIFOCache that removes things based on the size of the values.
166
This differs in that it doesn't care how many actual items there are,
167
it restricts the cache to be cleaned based on the size of the data.
170
def __init__(self, max_size=1024 * 1024, after_cleanup_size=None,
172
"""Create a new FIFOSizeCache.
174
:param max_size: The max number of bytes to store before we start
175
clearing out entries.
176
:param after_cleanup_size: After cleaning up, shrink everything to this
177
size (defaults to 80% of max_size).
178
:param compute_size: A function to compute the size of a value. If
179
not supplied we default to 'len'.
181
# Arbitrary, we won't really be using the value anyway.
182
FIFOCache.__init__(self, max_cache=max_size)
183
self._max_size = max_size
184
if after_cleanup_size is None:
185
self._after_cleanup_size = self._max_size * 8 // 10
187
self._after_cleanup_size = min(after_cleanup_size, self._max_size)
190
self._compute_size = compute_size
191
if compute_size is None:
192
self._compute_size = len
194
def add(self, key, value, cleanup=None):
195
"""Add a new value to the cache.
197
Also, if the entry is ever removed from the queue, call cleanup.
198
Passing it the key and value being removed.
200
:param key: The key to store it under
201
:param value: The object to store, this value by itself is >=
202
after_cleanup_size, then we will not store it at all.
203
:param cleanup: None or a function taking (key, value) to indicate
204
'value' sohuld be cleaned up.
206
# Even if the new value won't be stored, we need to remove the old
209
# Remove the earlier reference to this key, adding it again bumps
210
# it to the end of the queue
212
value_len = self._compute_size(value)
213
if value_len >= self._after_cleanup_size:
215
self._queue.append(key)
216
dict.__setitem__(self, key, value)
217
if cleanup is not None:
218
self._cleanup[key] = cleanup
219
self._value_size += value_len
220
if self._value_size > self._max_size:
224
def cache_size(self):
225
"""Get the number of bytes we will cache."""
226
return self._max_size
229
"""Clear the cache until it shrinks to the requested size.
231
This does not completely wipe the cache, just makes sure it is under
232
the after_cleanup_size.
234
# Make sure the cache is shrunk to the correct size
235
while self._value_size > self._after_cleanup_size:
236
self._remove_oldest()
238
def _remove(self, key):
239
"""Remove an entry, making sure to maintain the invariants."""
240
val = FIFOCache._remove(self, key)
241
self._value_size -= self._compute_size(val)
244
def resize(self, max_size, after_cleanup_size=None):
245
"""Increase/decrease the amount of cached data.
247
:param max_size: The maximum number of bytes to cache.
248
:param after_cleanup_size: After cleanup, we should have at most this
249
many bytes cached. This defaults to 80% of max_size.
251
FIFOCache.resize(self, max_size)
252
self._max_size = max_size
253
if after_cleanup_size is None:
254
self._after_cleanup_size = max_size * 8 // 10
256
self._after_cleanup_size = min(max_size, after_cleanup_size)
257
if self._value_size > self._max_size: