/brz/remove-bazaar

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