~bzr-pqm/bzr/bzr.dev

2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
1
# Copyright (C) 2006 Canonical Ltd
2
#
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.
7
#
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.
12
#
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
16
17
"""A simple least-recently-used (LRU) cache."""
18
19
from collections import deque
20
import gc
21
22
23
class LRUCache(object):
24
    """A class which manages a cache of entries, removing unused ones."""
25
26
    def __init__(self, max_cache=100, after_cleanup_size=None):
27
        self._max_cache = max_cache
28
        if after_cleanup_size is None:
29
            self._after_cleanup_size = self._max_cache
30
        else:
31
            self._after_cleanup_size = min(after_cleanup_size, self._max_cache)
32
33
        self._compact_queue_length = 4*self._max_cache
34
35
        self._cache = {}
36
        self._cleanup = {}
37
        self._queue = deque() # Track when things are accessed
38
        self._refcount = {} # number of entries in self._queue for each key
39
40
    def __contains__(self, key):
41
        return key in self._cache
42
43
    def __getitem__(self, key):
44
        val = self._cache[key]
45
        self._record_access(key)
46
        return val
47
48
    def __len__(self):
49
        return len(self._cache)
50
51
    def add(self, key, value, cleanup=None):
52
        """Add a new value to the cache.
53
54
        Also, if the entry is ever removed from the queue, call cleanup.
55
        Passing it the key and value being removed.
56
57
        :param key: The key to store it under
58
        :param value: The object to store
59
        :param cleanup: None or a function taking (key, value) to indicate
60
                        'value' sohuld be cleaned up.
61
        """
62
        if key in self._cache:
63
            self._remove(key)
64
        self._cache[key] = value
65
        self._cleanup[key] = cleanup
66
        self._record_access(key)
67
68
        if len(self._cache) > self._max_cache:
69
            # Trigger the cleanup
70
            self.cleanup()
71
2998.2.1 by John Arbash Meinel
Implement LRUCache.get() which acts like dict.get()
72
    def get(self, key, default=None):
73
        if key in self._cache:
74
            return self[key]
75
        return default
76
3763.8.10 by John Arbash Meinel
Add a .keys() member to LRUCache and LRUSizeCache.
77
    def keys(self):
78
        """Get the list of keys currently cached.
79
80
        Note that values returned here may not be available by the time you
81
        request them later. This is simply meant as a peak into the current
82
        state.
83
84
        :return: An unordered list of keys that are currently cached.
85
        """
86
        return self._cache.keys()
87
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
88
    def cleanup(self):
89
        """Clear the cache until it shrinks to the requested size.
90
91
        This does not completely wipe the cache, just makes sure it is under
92
        the after_cleanup_size.
93
        """
94
        # Make sure the cache is shrunk to the correct size
95
        while len(self._cache) > self._after_cleanup_size:
96
            self._remove_lru()
97
98
    def __setitem__(self, key, value):
99
        """Add a value to the cache, there will be no cleanup function."""
100
        self.add(key, value, cleanup=None)
101
102
    def _record_access(self, key):
103
        """Record that key was accessed."""
104
        self._queue.append(key)
105
        # Can't use setdefault because you can't += 1 the result
106
        self._refcount[key] = self._refcount.get(key, 0) + 1
107
108
        # If our access queue is too large, clean it up too
109
        if len(self._queue) > self._compact_queue_length:
110
            self._compact_queue()
111
112
    def _compact_queue(self):
113
        """Compact the queue, leaving things in sorted last appended order."""
114
        new_queue = deque()
115
        for item in self._queue:
116
            if self._refcount[item] == 1:
117
                new_queue.append(item)
118
            else:
119
                self._refcount[item] -= 1
120
        self._queue = new_queue
121
        # All entries should be of the same size. There should be one entry in
122
        # queue for each entry in cache, and all refcounts should == 1
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
123
        if not (len(self._queue) == len(self._cache) ==
124
                len(self._refcount) == sum(self._refcount.itervalues())):
125
            raise AssertionError()
2993.1.1 by Robert Collins
* New module ``lru_cache`` providing a cache for use by tasks that need
126
127
    def _remove(self, key):
128
        """Remove an entry, making sure to maintain the invariants."""
129
        cleanup = self._cleanup.pop(key)
130
        val = self._cache.pop(key)
131
        if cleanup is not None:
132
            cleanup(key, val)
133
        return val
134
135
    def _remove_lru(self):
136
        """Remove one entry from the lru, and handle consequences.
137
138
        If there are no more references to the lru, then this entry should be
139
        removed from the cache.
140
        """
141
        key = self._queue.popleft()
142
        self._refcount[key] -= 1
143
        if not self._refcount[key]:
144
            del self._refcount[key]
145
            self._remove(key)
146
147
    def clear(self):
148
        """Clear out all of the cache."""
149
        # Clean up in LRU order
150
        while self._cache:
151
            self._remove_lru()
152
153
154
class LRUSizeCache(LRUCache):
155
    """An LRUCache that removes things based on the size of the values.
156
157
    This differs in that it doesn't care how many actual items there are,
158
    it just restricts the cache to be cleaned up after so much data is stored.
159
160
    The values that are added must support len(value).
161
    """
162
163
    def __init__(self, max_size=1024*1024, after_cleanup_size=None,
164
                 compute_size=None):
165
        """Create a new LRUSizeCache.
166
167
        :param max_size: The max number of bytes to store before we start
168
            clearing out entries.
169
        :param after_cleanup_size: After cleaning up, shrink everything to this
170
            size.
171
        :param compute_size: A function to compute the size of the values. We
172
            use a function here, so that you can pass 'len' if you are just
173
            using simple strings, or a more complex function if you are using
174
            something like a list of strings, or even a custom object.
175
            The function should take the form "compute_size(value) => integer".
176
            If not supplied, it defaults to 'len()'
177
        """
178
        # This approximates that texts are > 0.5k in size. It only really
179
        # effects when we clean up the queue, so we don't want it to be too
180
        # large.
181
        LRUCache.__init__(self, max_cache=int(max_size/512))
182
        self._max_size = max_size
183
        if after_cleanup_size is None:
184
            self._after_cleanup_size = self._max_size
185
        else:
186
            self._after_cleanup_size = min(after_cleanup_size, self._max_size)
187
188
        self._value_size = 0
189
        self._compute_size = compute_size
190
        if compute_size is None:
191
            self._compute_size = len
192
193
    def add(self, key, value, cleanup=None):
194
        """Add a new value to the cache.
195
196
        Also, if the entry is ever removed from the queue, call cleanup.
197
        Passing it the key and value being removed.
198
199
        :param key: The key to store it under
200
        :param value: The object to store
201
        :param cleanup: None or a function taking (key, value) to indicate
202
                        'value' sohuld be cleaned up.
203
        """
204
        if key in self._cache:
205
            self._remove(key)
206
        value_len = self._compute_size(value)
207
        if value_len >= self._after_cleanup_size:
208
            return
209
        self._value_size += value_len
210
        self._cache[key] = value
211
        self._cleanup[key] = cleanup
212
        self._record_access(key)
213
214
        if self._value_size > self._max_size:
215
            # Time to cleanup
216
            self.cleanup()
217
218
    def cleanup(self):
219
        """Clear the cache until it shrinks to the requested size.
220
221
        This does not completely wipe the cache, just makes sure it is under
222
        the after_cleanup_size.
223
        """
224
        # Make sure the cache is shrunk to the correct size
225
        while self._value_size > self._after_cleanup_size:
226
            self._remove_lru()
227
228
    def _remove(self, key):
229
        """Remove an entry, making sure to maintain the invariants."""
230
        val = LRUCache._remove(self, key)
231
        self._value_size -= self._compute_size(val)