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 __future__ import absolute_import
21
from collections import deque
24
class FIFOCache(dict):
25
"""A class which manages a cache of entries, removing old ones."""
27
def __init__(self, max_cache=100, after_cleanup_count=None):
29
self._max_cache = max_cache
30
if after_cleanup_count is None:
31
self._after_cleanup_count = self._max_cache * 8 / 10
33
self._after_cleanup_count = min(after_cleanup_count,
35
self._cleanup = {} # map to cleanup functions when items are removed
36
self._queue = deque() # Track when things are accessed
38
def __setitem__(self, key, value):
39
"""Add a value to the cache, there will be no cleanup function."""
40
self.add(key, value, cleanup=None)
42
def __delitem__(self, key):
43
# Remove the key from an arbitrary location in the queue
44
remove = getattr(self._queue, 'remove', None)
45
# Python2.5's has deque.remove, but Python2.4 does not
46
if remove is not None:
49
# TODO: It would probably be faster to pop()/popleft() until we get to the
50
# key, and then insert those back into the queue. We know
51
# the key should only be present in one position, and we
52
# wouldn't need to rebuild the whole queue.
53
self._queue = deque([k for k in self._queue if k != key])
56
def add(self, key, value, cleanup=None):
57
"""Add a new value to the cache.
59
Also, if the entry is ever removed from the queue, call cleanup.
60
Passing it the key and value being removed.
62
:param key: The key to store it under
63
:param value: The object to store
64
:param cleanup: None or a function taking (key, value) to indicate
65
'value' should be cleaned up
68
# Remove the earlier reference to this key, adding it again bumps
69
# it to the end of the queue
71
self._queue.append(key)
72
dict.__setitem__(self, key, value)
73
if cleanup is not None:
74
self._cleanup[key] = cleanup
75
if len(self) > self._max_cache:
79
"""Get the number of entries we will cache."""
80
return self._max_cache
83
"""Clear the cache until it shrinks to the requested size.
85
This does not completely wipe the cache, just makes sure it is under
86
the after_cleanup_count.
88
# Make sure the cache is shrunk to the correct size
89
while len(self) > self._after_cleanup_count:
91
if len(self._queue) != len(self):
92
raise AssertionError('The length of the queue should always equal'
93
' the length of the dict. %s != %s'
94
% (len(self._queue), len(self)))
97
"""Clear out all of the cache."""
98
# Clean up in FIFO order
100
self._remove_oldest()
102
def _remove(self, key):
103
"""Remove an entry, making sure to call any cleanup function."""
104
cleanup = self._cleanup.pop(key, None)
105
# We override self.pop() because it doesn't play well with cleanup
107
val = dict.pop(self, key)
108
if cleanup is not None:
112
def _remove_oldest(self):
113
"""Remove the oldest entry."""
114
key = self._queue.popleft()
117
def resize(self, max_cache, after_cleanup_count=None):
118
"""Increase/decrease the number of cached entries.
120
:param max_cache: The maximum number of entries to cache.
121
:param after_cleanup_count: After cleanup, we should have at most this
122
many entries. This defaults to 80% of max_cache.
124
self._max_cache = max_cache
125
if after_cleanup_count is None:
126
self._after_cleanup_count = max_cache * 8 / 10
128
self._after_cleanup_count = min(max_cache, after_cleanup_count)
129
if len(self) > self._max_cache:
132
# raise NotImplementedError on dict functions that would mutate the cache
133
# which have not been properly implemented yet.
135
raise NotImplementedError(self.copy)
137
def pop(self, key, default=None):
138
# If there is a cleanup() function, than it is unclear what pop()
139
# should do. Specifically, we would have to call the cleanup on the
140
# value before we return it, which should cause whatever resources were
141
# allocated to be removed, which makes the return value fairly useless.
142
# So instead, we just don't implement it.
143
raise NotImplementedError(self.pop)
147
raise NotImplementedError(self.popitem)
149
def setdefault(self, key, defaultval=None):
150
"""similar to dict.setdefault"""
153
self[key] = defaultval
156
def update(self, *args, **kwargs):
157
"""Similar to dict.update()"""
160
if isinstance(arg, dict):
161
for key, val in arg.iteritems():
164
for key, val in args[0]:
167
raise TypeError('update expected at most 1 argument, got %d'
170
for key, val in kwargs.iteritems():
174
class FIFOSizeCache(FIFOCache):
175
"""An FIFOCache 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 restricts the cache to be cleaned based on the size of the data.
181
def __init__(self, max_size=1024*1024, after_cleanup_size=None,
183
"""Create a new FIFOSizeCache.
185
:param max_size: The max number of bytes to store before we start
186
clearing out entries.
187
:param after_cleanup_size: After cleaning up, shrink everything to this
188
size (defaults to 80% of max_size).
189
:param compute_size: A function to compute the size of a value. If
190
not supplied we default to 'len'.
192
# Arbitrary, we won't really be using the value anyway.
193
FIFOCache.__init__(self, max_cache=max_size)
194
self._max_size = max_size
195
if after_cleanup_size is None:
196
self._after_cleanup_size = self._max_size * 8 / 10
198
self._after_cleanup_size = min(after_cleanup_size, self._max_size)
201
self._compute_size = compute_size
202
if compute_size is None:
203
self._compute_size = len
205
def add(self, key, value, cleanup=None):
206
"""Add a new value to the cache.
208
Also, if the entry is ever removed from the queue, call cleanup.
209
Passing it the key and value being removed.
211
:param key: The key to store it under
212
:param value: The object to store, this value by itself is >=
213
after_cleanup_size, then we will not store it at all.
214
:param cleanup: None or a function taking (key, value) to indicate
215
'value' sohuld be cleaned up.
217
# Even if the new value won't be stored, we need to remove the old
220
# Remove the earlier reference to this key, adding it again bumps
221
# it to the end of the queue
223
value_len = self._compute_size(value)
224
if value_len >= self._after_cleanup_size:
226
self._queue.append(key)
227
dict.__setitem__(self, key, value)
228
if cleanup is not None:
229
self._cleanup[key] = cleanup
230
self._value_size += value_len
231
if self._value_size > self._max_size:
235
def cache_size(self):
236
"""Get the number of bytes we will cache."""
237
return self._max_size
240
"""Clear the cache until it shrinks to the requested size.
242
This does not completely wipe the cache, just makes sure it is under
243
the after_cleanup_size.
245
# Make sure the cache is shrunk to the correct size
246
while self._value_size > self._after_cleanup_size:
247
self._remove_oldest()
249
def _remove(self, key):
250
"""Remove an entry, making sure to maintain the invariants."""
251
val = FIFOCache._remove(self, key)
252
self._value_size -= self._compute_size(val)
255
def resize(self, max_size, after_cleanup_size=None):
256
"""Increase/decrease the amount of cached data.
258
:param max_size: The maximum number of bytes to cache.
259
:param after_cleanup_size: After cleanup, we should have at most this
260
many bytes cached. This defaults to 80% of max_size.
262
FIFOCache.resize(self, max_size)
263
self._max_size = max_size
264
if after_cleanup_size is None:
265
self._after_cleanup_size = max_size * 8 / 10
267
self._after_cleanup_size = min(max_size, after_cleanup_size)
268
if self._value_size > self._max_size: