~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/lru_cache.py

  • Committer: Martin Pool
  • Date: 2009-01-13 03:06:36 UTC
  • mfrom: (3932.2.3 1.11)
  • mto: This revision was merged to the branch mainline in revision 3937.
  • Revision ID: mbp@sourcefrog.net-20090113030636-dqx4t8yaaqgdvam5
MergeĀ 1.11rc1

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006, 2008, 2009 Canonical Ltd
 
1
# Copyright (C) 2006, 2008 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
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
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
"""A simple least-recently-used (LRU) cache."""
18
18
 
19
 
from __future__ import absolute_import
20
 
 
21
 
from bzrlib import (
22
 
    symbol_versioning,
23
 
    trace,
24
 
    )
25
 
 
26
 
_null_key = object()
27
 
 
28
 
class _LRUNode(object):
29
 
    """This maintains the linked-list which is the lru internals."""
30
 
 
31
 
    __slots__ = ('prev', 'next_key', 'key', 'value')
32
 
 
33
 
    def __init__(self, key, value):
34
 
        self.prev = None
35
 
        self.next_key = _null_key
36
 
        self.key = key
37
 
        self.value = value
38
 
 
39
 
    def __repr__(self):
40
 
        if self.prev is None:
41
 
            prev_key = None
42
 
        else:
43
 
            prev_key = self.prev.key
44
 
        return '%s(%r n:%r p:%r)' % (self.__class__.__name__, self.key,
45
 
                                     self.next_key, prev_key)
 
19
from collections import deque
 
20
 
 
21
from bzrlib import symbol_versioning
46
22
 
47
23
 
48
24
class LRUCache(object):
49
25
    """A class which manages a cache of entries, removing unused ones."""
50
26
 
51
 
    def __init__(self, max_cache=100, after_cleanup_count=None):
 
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
52
35
        self._cache = {}
53
 
        # The "HEAD" of the lru linked list
54
 
        self._most_recently_used = None
55
 
        # The "TAIL" of the lru linked list
56
 
        self._least_recently_used = None
 
36
        self._cleanup = {}
 
37
        self._queue = deque() # Track when things are accessed
 
38
        self._refcount = {} # number of entries in self._queue for each key
57
39
        self._update_max_cache(max_cache, after_cleanup_count)
58
40
 
59
41
    def __contains__(self, key):
60
42
        return key in self._cache
61
43
 
62
44
    def __getitem__(self, key):
63
 
        cache = self._cache
64
 
        node = cache[key]
65
 
        # Inlined from _record_access to decrease the overhead of __getitem__
66
 
        # We also have more knowledge about structure if __getitem__ is
67
 
        # succeeding, then we know that self._most_recently_used must not be
68
 
        # None, etc.
69
 
        mru = self._most_recently_used
70
 
        if node is mru:
71
 
            # Nothing to do, this node is already at the head of the queue
72
 
            return node.value
73
 
        # Remove this node from the old location
74
 
        node_prev = node.prev
75
 
        next_key = node.next_key
76
 
        # benchmarking shows that the lookup of _null_key in globals is faster
77
 
        # than the attribute lookup for (node is self._least_recently_used)
78
 
        if next_key is _null_key:
79
 
            # 'node' is the _least_recently_used, because it doesn't have a
80
 
            # 'next' item. So move the current lru to the previous node.
81
 
            self._least_recently_used = node_prev
82
 
        else:
83
 
            node_next = cache[next_key]
84
 
            node_next.prev = node_prev
85
 
        node_prev.next_key = next_key
86
 
        # Insert this node at the front of the list
87
 
        node.next_key = mru.key
88
 
        mru.prev = node
89
 
        self._most_recently_used = node
90
 
        node.prev = None
91
 
        return node.value
 
45
        val = self._cache[key]
 
46
        self._record_access(key)
 
47
        return val
92
48
 
93
49
    def __len__(self):
94
50
        return len(self._cache)
95
51
 
96
 
    @symbol_versioning.deprecated_method(
97
 
        symbol_versioning.deprecated_in((2, 5, 0)))
98
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
99
66
        if cleanup is not None:
100
 
            raise ValueError("Per-node cleanup functions no longer supported")
101
 
        return self.__setitem__(key, value)
102
 
 
103
 
    def __setitem__(self, key, value):
104
 
        """Add a new value to the cache"""
105
 
        if key is _null_key:
106
 
            raise ValueError('cannot use _null_key as a key')
107
 
        if key in self._cache:
108
 
            node = self._cache[key]
109
 
            node.value = value
110
 
            self._record_access(node)
111
 
        else:
112
 
            node = _LRUNode(key, value)
113
 
            self._cache[key] = node
114
 
            self._record_access(node)
 
67
            self._cleanup[key] = cleanup
 
68
        self._record_access(key)
115
69
 
116
70
        if len(self._cache) > self._max_cache:
117
71
            # Trigger the cleanup
118
72
            self.cleanup()
119
73
 
120
 
    def cache_size(self):
121
 
        """Get the number of entries we will cache."""
122
 
        return self._max_cache
123
 
 
124
74
    def get(self, key, default=None):
125
 
        node = self._cache.get(key, None)
126
 
        if node is None:
127
 
            return default
128
 
        self._record_access(node)
129
 
        return node.value
 
75
        if key in self._cache:
 
76
            return self[key]
 
77
        return default
130
78
 
131
79
    def keys(self):
132
80
        """Get the list of keys currently cached.
139
87
        """
140
88
        return self._cache.keys()
141
89
 
142
 
    def as_dict(self):
143
 
        """Get a new dict with the same key:value pairs as the cache"""
144
 
        return dict((k, n.value) for k, n in self._cache.iteritems())
145
 
 
146
 
    items = symbol_versioning.deprecated_method(
147
 
        symbol_versioning.deprecated_in((2, 5, 0)))(as_dict)
148
 
 
149
90
    def cleanup(self):
150
91
        """Clear the cache until it shrinks to the requested size.
151
92
 
155
96
        # Make sure the cache is shrunk to the correct size
156
97
        while len(self._cache) > self._after_cleanup_count:
157
98
            self._remove_lru()
158
 
 
159
 
    def _record_access(self, node):
 
99
        # No need to compact the queue at this point, because the code that
 
100
        # calls this would have already triggered it based on queue length
 
101
 
 
102
    def __setitem__(self, key, value):
 
103
        """Add a value to the cache, there will be no cleanup function."""
 
104
        self.add(key, value, cleanup=None)
 
105
 
 
106
    def _record_access(self, key):
160
107
        """Record that key was accessed."""
161
 
        # Move 'node' to the front of the queue
162
 
        if self._most_recently_used is None:
163
 
            self._most_recently_used = node
164
 
            self._least_recently_used = node
165
 
            return
166
 
        elif node is self._most_recently_used:
167
 
            # Nothing to do, this node is already at the head of the queue
168
 
            return
169
 
        # We've taken care of the tail pointer, remove the node, and insert it
170
 
        # at the front
171
 
        # REMOVE
172
 
        if node is self._least_recently_used:
173
 
            self._least_recently_used = node.prev
174
 
        if node.prev is not None:
175
 
            node.prev.next_key = node.next_key
176
 
        if node.next_key is not _null_key:
177
 
            node_next = self._cache[node.next_key]
178
 
            node_next.prev = node.prev
179
 
        # INSERT
180
 
        node.next_key = self._most_recently_used.key
181
 
        self._most_recently_used.prev = node
182
 
        self._most_recently_used = node
183
 
        node.prev = None
184
 
 
185
 
    def _remove_node(self, node):
186
 
        if node is self._least_recently_used:
187
 
            self._least_recently_used = node.prev
188
 
        self._cache.pop(node.key)
189
 
        # If we have removed all entries, remove the head pointer as well
190
 
        if self._least_recently_used is None:
191
 
            self._most_recently_used = None
192
 
        if node.prev is not None:
193
 
            node.prev.next_key = node.next_key
194
 
        if node.next_key is not _null_key:
195
 
            node_next = self._cache[node.next_key]
196
 
            node_next.prev = node.prev
197
 
        # And remove this node's pointers
198
 
        node.prev = None
199
 
        node.next_key = _null_key
 
108
        self._queue.append(key)
 
109
        # Can't use setdefault because you can't += 1 the result
 
110
        self._refcount[key] = self._refcount.get(key, 0) + 1
 
111
 
 
112
        # If our access queue is too large, clean it up too
 
113
        if len(self._queue) > self._compact_queue_length:
 
114
            self._compact_queue()
 
115
 
 
116
    def _compact_queue(self):
 
117
        """Compact the queue, leaving things in sorted last appended order."""
 
118
        new_queue = deque()
 
119
        for item in self._queue:
 
120
            if self._refcount[item] == 1:
 
121
                new_queue.append(item)
 
122
            else:
 
123
                self._refcount[item] -= 1
 
124
        self._queue = new_queue
 
125
        # All entries should be of the same size. There should be one entry in
 
126
        # queue for each entry in cache, and all refcounts should == 1
 
127
        if not (len(self._queue) == len(self._cache) ==
 
128
                len(self._refcount) == sum(self._refcount.itervalues())):
 
129
            raise AssertionError()
 
130
 
 
131
    def _remove(self, key):
 
132
        """Remove an entry, making sure to maintain the invariants."""
 
133
        cleanup = self._cleanup.pop(key, None)
 
134
        val = self._cache.pop(key)
 
135
        if cleanup is not None:
 
136
            cleanup(key, val)
 
137
        return val
200
138
 
201
139
    def _remove_lru(self):
202
140
        """Remove one entry from the lru, and handle consequences.
204
142
        If there are no more references to the lru, then this entry should be
205
143
        removed from the cache.
206
144
        """
207
 
        self._remove_node(self._least_recently_used)
 
145
        key = self._queue.popleft()
 
146
        self._refcount[key] -= 1
 
147
        if not self._refcount[key]:
 
148
            del self._refcount[key]
 
149
            self._remove(key)
208
150
 
209
151
    def clear(self):
210
152
        """Clear out all of the cache."""
222
164
        if after_cleanup_count is None:
223
165
            self._after_cleanup_count = self._max_cache * 8 / 10
224
166
        else:
225
 
            self._after_cleanup_count = min(after_cleanup_count,
226
 
                                            self._max_cache)
 
167
            self._after_cleanup_count = min(after_cleanup_count, self._max_cache)
 
168
 
 
169
        self._compact_queue_length = 4*self._max_cache
 
170
        if len(self._queue) > self._compact_queue_length:
 
171
            self._compact_queue()
227
172
        self.cleanup()
228
173
 
229
174
 
233
178
    This differs in that it doesn't care how many actual items there are,
234
179
    it just restricts the cache to be cleaned up after so much data is stored.
235
180
 
236
 
    The size of items added will be computed using compute_size(value), which
237
 
    defaults to len() if not supplied.
 
181
    The values that are added must support len(value).
238
182
    """
239
183
 
240
184
    def __init__(self, max_size=1024*1024, after_cleanup_size=None,
256
200
        self._compute_size = compute_size
257
201
        if compute_size is None:
258
202
            self._compute_size = len
 
203
        # This approximates that texts are > 0.5k in size. It only really
 
204
        # effects when we clean up the queue, so we don't want it to be too
 
205
        # large.
259
206
        self._update_max_size(max_size, after_cleanup_size=after_cleanup_size)
260
207
        LRUCache.__init__(self, max_cache=max(int(max_size/512), 1))
261
208
 
262
 
    def __setitem__(self, key, value):
263
 
        """Add a new value to the cache"""
264
 
        if key is _null_key:
265
 
            raise ValueError('cannot use _null_key as a key')
266
 
        node = self._cache.get(key, None)
 
209
    def add(self, key, value, cleanup=None):
 
210
        """Add a new value to the cache.
 
211
 
 
212
        Also, if the entry is ever removed from the queue, call cleanup.
 
213
        Passing it the key and value being removed.
 
214
 
 
215
        :param key: The key to store it under
 
216
        :param value: The object to store
 
217
        :param cleanup: None or a function taking (key, value) to indicate
 
218
                        'value' sohuld be cleaned up.
 
219
        """
 
220
        if key in self._cache:
 
221
            self._remove(key)
267
222
        value_len = self._compute_size(value)
268
223
        if value_len >= self._after_cleanup_size:
269
 
            # The new value is 'too big to fit', as it would fill up/overflow
270
 
            # the cache all by itself
271
 
            trace.mutter('Adding the key %r to an LRUSizeCache failed.'
272
 
                         ' value %d is too big to fit in a the cache'
273
 
                         ' with size %d %d', key, value_len,
274
 
                         self._after_cleanup_size, self._max_size)
275
 
            if node is not None:
276
 
                # We won't be replacing the old node, so just remove it
277
 
                self._remove_node(node)
278
224
            return
279
 
        if node is None:
280
 
            node = _LRUNode(key, value)
281
 
            self._cache[key] = node
282
 
        else:
283
 
            self._value_size -= self._compute_size(node.value)
284
225
        self._value_size += value_len
285
 
        self._record_access(node)
 
226
        self._cache[key] = value
 
227
        if cleanup is not None:
 
228
            self._cleanup[key] = cleanup
 
229
        self._record_access(key)
286
230
 
287
231
        if self._value_size > self._max_size:
288
232
            # Time to cleanup
298
242
        while self._value_size > self._after_cleanup_size:
299
243
            self._remove_lru()
300
244
 
301
 
    def _remove_node(self, node):
302
 
        self._value_size -= self._compute_size(node.value)
303
 
        LRUCache._remove_node(self, node)
 
245
    def _remove(self, key):
 
246
        """Remove an entry, making sure to maintain the invariants."""
 
247
        val = LRUCache._remove(self, key)
 
248
        self._value_size -= self._compute_size(val)
304
249
 
305
250
    def resize(self, max_size, after_cleanup_size=None):
306
251
        """Change the number of bytes that will be cached."""