~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/lru_cache.py

  • Committer: Vincent Ladeuil
  • Date: 2009-07-02 13:07:14 UTC
  • mto: (4524.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 4525.
  • Revision ID: v.ladeuil+lp@free.fr-20090702130714-hsyqfusi8vn3a11m
Use tree.has_changes() where appropriate (the test suite caught a
bug in has_changes() (not filtering out the root) in an impressive
number of tests)

* bzrlib/send.py:
(send): Use tree.has_changes() instead of tree.changes_from().

* bzrlib/reconfigure.py:
(Reconfigure._check): Use tree.has_changes() instead of
tree.changes_from().

* bzrlib/merge.py:
(Merger.ensure_revision_trees, Merger.compare_basis): Use
tree.has_changes() instead of tree.changes_from().

* bzrlib/builtins.py:
(cmd_remove_tree.run, cmd_push.run, cmd_merge.run): Use
tree.has_changes() instead of tree.changes_from().

Show diffs side-by-side

added added

removed removed

Lines of Context:
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
"""A simple least-recently-used (LRU) cache."""
18
18
 
19
 
from collections import deque
20
 
 
21
 
from bzrlib import symbol_versioning
 
19
from bzrlib import (
 
20
    symbol_versioning,
 
21
    trace,
 
22
    )
 
23
 
 
24
_null_key = object()
 
25
 
 
26
class _LRUNode(object):
 
27
    """This maintains the linked-list which is the lru internals."""
 
28
 
 
29
    __slots__ = ('prev', 'next_key', 'key', 'value', 'cleanup', 'size')
 
30
 
 
31
    def __init__(self, key, value, cleanup=None):
 
32
        self.prev = None
 
33
        self.next_key = _null_key
 
34
        self.key = key
 
35
        self.value = value
 
36
        self.cleanup = cleanup
 
37
        # TODO: We could compute this 'on-the-fly' like we used to, and remove
 
38
        #       one pointer from this object, we just need to decide if it
 
39
        #       actually costs us much of anything in normal usage
 
40
        self.size = None
 
41
 
 
42
    def __repr__(self):
 
43
        if self.prev is None:
 
44
            prev_key = None
 
45
        else:
 
46
            prev_key = self.prev.key
 
47
        return '%s(%r n:%r p:%r)' % (self.__class__.__name__, self.key,
 
48
                                     self.next_key, prev_key)
 
49
 
 
50
    def run_cleanup(self):
 
51
        if self.cleanup is not None:
 
52
            self.cleanup(self.key, self.value)
 
53
        self.cleanup = None
 
54
        # Just make sure to break any refcycles, etc
 
55
        self.value = None
22
56
 
23
57
 
24
58
class LRUCache(object):
33
67
                                   DeprecationWarning)
34
68
            after_cleanup_count = after_cleanup_size
35
69
        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
 
70
        # The "HEAD" of the lru linked list
 
71
        self._most_recently_used = None
 
72
        # The "TAIL" of the lru linked list
 
73
        self._least_recently_used = None
39
74
        self._update_max_cache(max_cache, after_cleanup_count)
40
75
 
41
76
    def __contains__(self, key):
42
77
        return key in self._cache
43
78
 
44
79
    def __getitem__(self, key):
45
 
        val = self._cache[key]
46
 
        self._record_access(key)
47
 
        return val
 
80
        cache = self._cache
 
81
        node = cache[key]
 
82
        # Inlined from _record_access to decrease the overhead of __getitem__
 
83
        # We also have more knowledge about structure if __getitem__ is
 
84
        # succeeding, then we know that self._most_recently_used must not be
 
85
        # None, etc.
 
86
        mru = self._most_recently_used
 
87
        if node is mru:
 
88
            # Nothing to do, this node is already at the head of the queue
 
89
            return node.value
 
90
        # Remove this node from the old location
 
91
        node_prev = node.prev
 
92
        next_key = node.next_key
 
93
        # benchmarking shows that the lookup of _null_key in globals is faster
 
94
        # than the attribute lookup for (node is self._least_recently_used)
 
95
        if next_key is _null_key:
 
96
            # 'node' is the _least_recently_used, because it doesn't have a
 
97
            # 'next' item. So move the current lru to the previous node.
 
98
            self._least_recently_used = node_prev
 
99
        else:
 
100
            node_next = cache[next_key]
 
101
            node_next.prev = node_prev
 
102
        node_prev.next_key = next_key
 
103
        # Insert this node at the front of the list
 
104
        node.next_key = mru.key
 
105
        mru.prev = node
 
106
        self._most_recently_used = node
 
107
        node.prev = None
 
108
        return node.value
48
109
 
49
110
    def __len__(self):
50
111
        return len(self._cache)
51
112
 
 
113
    def _walk_lru(self):
 
114
        """Walk the LRU list, only meant to be used in tests."""
 
115
        node = self._most_recently_used
 
116
        if node is not None:
 
117
            if node.prev is not None:
 
118
                raise AssertionError('the _most_recently_used entry is not'
 
119
                                     ' supposed to have a previous entry'
 
120
                                     ' %s' % (node,))
 
121
        while node is not None:
 
122
            if node.next_key is _null_key:
 
123
                if node is not self._least_recently_used:
 
124
                    raise AssertionError('only the last node should have'
 
125
                                         ' no next value: %s' % (node,))
 
126
                node_next = None
 
127
            else:
 
128
                node_next = self._cache[node.next_key]
 
129
                if node_next.prev is not node:
 
130
                    raise AssertionError('inconsistency found, node.next.prev'
 
131
                                         ' != node: %s' % (node,))
 
132
            if node.prev is None:
 
133
                if node is not self._most_recently_used:
 
134
                    raise AssertionError('only the _most_recently_used should'
 
135
                                         ' not have a previous node: %s'
 
136
                                         % (node,))
 
137
            else:
 
138
                if node.prev.next_key != node.key:
 
139
                    raise AssertionError('inconsistency found, node.prev.next'
 
140
                                         ' != node: %s' % (node,))
 
141
            yield node
 
142
            node = node_next
 
143
 
52
144
    def add(self, key, value, cleanup=None):
53
145
        """Add a new value to the cache.
54
146
 
55
 
        Also, if the entry is ever removed from the queue, call cleanup.
56
 
        Passing it the key and value being removed.
 
147
        Also, if the entry is ever removed from the cache, call
 
148
        cleanup(key, value).
57
149
 
58
150
        :param key: The key to store it under
59
151
        :param value: The object to store
60
152
        :param cleanup: None or a function taking (key, value) to indicate
61
 
                        'value' sohuld be cleaned up.
 
153
                        'value' should be cleaned up.
62
154
        """
 
155
        if key is _null_key:
 
156
            raise ValueError('cannot use _null_key as a key')
63
157
        if key in self._cache:
64
 
            self._remove(key)
65
 
        self._cache[key] = value
66
 
        if cleanup is not None:
67
 
            self._cleanup[key] = cleanup
68
 
        self._record_access(key)
 
158
            node = self._cache[key]
 
159
            node.run_cleanup()
 
160
            node.value = value
 
161
            node.cleanup = cleanup
 
162
        else:
 
163
            node = _LRUNode(key, value, cleanup=cleanup)
 
164
            self._cache[key] = node
 
165
        self._record_access(node)
69
166
 
70
167
        if len(self._cache) > self._max_cache:
71
168
            # Trigger the cleanup
72
169
            self.cleanup()
73
170
 
 
171
    def cache_size(self):
 
172
        """Get the number of entries we will cache."""
 
173
        return self._max_cache
 
174
 
74
175
    def get(self, key, default=None):
75
 
        if key in self._cache:
76
 
            return self[key]
77
 
        return default
 
176
        node = self._cache.get(key, None)
 
177
        if node is None:
 
178
            return default
 
179
        self._record_access(node)
 
180
        return node.value
78
181
 
79
182
    def keys(self):
80
183
        """Get the list of keys currently cached.
87
190
        """
88
191
        return self._cache.keys()
89
192
 
 
193
    def items(self):
 
194
        """Get the key:value pairs as a dict."""
 
195
        return dict((k, n.value) for k, n in self._cache.iteritems())
 
196
 
90
197
    def cleanup(self):
91
198
        """Clear the cache until it shrinks to the requested size.
92
199
 
96
203
        # Make sure the cache is shrunk to the correct size
97
204
        while len(self._cache) > self._after_cleanup_count:
98
205
            self._remove_lru()
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
206
 
102
207
    def __setitem__(self, key, value):
103
208
        """Add a value to the cache, there will be no cleanup function."""
104
209
        self.add(key, value, cleanup=None)
105
210
 
106
 
    def _record_access(self, key):
 
211
    def _record_access(self, node):
107
212
        """Record that key was accessed."""
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
 
213
        # Move 'node' to the front of the queue
 
214
        if self._most_recently_used is None:
 
215
            self._most_recently_used = node
 
216
            self._least_recently_used = node
 
217
            return
 
218
        elif node is self._most_recently_used:
 
219
            # Nothing to do, this node is already at the head of the queue
 
220
            return
 
221
        # We've taken care of the tail pointer, remove the node, and insert it
 
222
        # at the front
 
223
        # REMOVE
 
224
        if node is self._least_recently_used:
 
225
            self._least_recently_used = node.prev
 
226
        if node.prev is not None:
 
227
            node.prev.next_key = node.next_key
 
228
        if node.next_key is not _null_key:
 
229
            node_next = self._cache[node.next_key]
 
230
            node_next.prev = node.prev
 
231
        # INSERT
 
232
        node.next_key = self._most_recently_used.key
 
233
        self._most_recently_used.prev = node
 
234
        self._most_recently_used = node
 
235
        node.prev = None
 
236
 
 
237
    def _remove_node(self, node):
 
238
        if node is self._least_recently_used:
 
239
            self._least_recently_used = node.prev
 
240
        self._cache.pop(node.key)
 
241
        # If we have removed all entries, remove the head pointer as well
 
242
        if self._least_recently_used is None:
 
243
            self._most_recently_used = None
 
244
        node.run_cleanup()
 
245
        # Now remove this node from the linked list
 
246
        if node.prev is not None:
 
247
            node.prev.next_key = node.next_key
 
248
        if node.next_key is not _null_key:
 
249
            node_next = self._cache[node.next_key]
 
250
            node_next.prev = node.prev
 
251
        # And remove this node's pointers
 
252
        node.prev = None
 
253
        node.next_key = _null_key
138
254
 
139
255
    def _remove_lru(self):
140
256
        """Remove one entry from the lru, and handle consequences.
142
258
        If there are no more references to the lru, then this entry should be
143
259
        removed from the cache.
144
260
        """
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)
 
261
        self._remove_node(self._least_recently_used)
150
262
 
151
263
    def clear(self):
152
264
        """Clear out all of the cache."""
164
276
        if after_cleanup_count is None:
165
277
            self._after_cleanup_count = self._max_cache * 8 / 10
166
278
        else:
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()
 
279
            self._after_cleanup_count = min(after_cleanup_count,
 
280
                                            self._max_cache)
172
281
        self.cleanup()
173
282
 
174
283
 
178
287
    This differs in that it doesn't care how many actual items there are,
179
288
    it just restricts the cache to be cleaned up after so much data is stored.
180
289
 
181
 
    The values that are added must support len(value).
 
290
    The size of items added will be computed using compute_size(value), which
 
291
    defaults to len() if not supplied.
182
292
    """
183
293
 
184
294
    def __init__(self, max_size=1024*1024, after_cleanup_size=None,
200
310
        self._compute_size = compute_size
201
311
        if compute_size is None:
202
312
            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.
206
313
        self._update_max_size(max_size, after_cleanup_size=after_cleanup_size)
207
314
        LRUCache.__init__(self, max_cache=max(int(max_size/512), 1))
208
315
 
209
316
    def add(self, key, value, cleanup=None):
210
317
        """Add a new value to the cache.
211
318
 
212
 
        Also, if the entry is ever removed from the queue, call cleanup.
213
 
        Passing it the key and value being removed.
 
319
        Also, if the entry is ever removed from the cache, call
 
320
        cleanup(key, value).
214
321
 
215
322
        :param key: The key to store it under
216
323
        :param value: The object to store
217
324
        :param cleanup: None or a function taking (key, value) to indicate
218
 
                        'value' sohuld be cleaned up.
 
325
                        'value' should be cleaned up.
219
326
        """
220
 
        if key in self._cache:
221
 
            self._remove(key)
 
327
        if key is _null_key:
 
328
            raise ValueError('cannot use _null_key as a key')
 
329
        node = self._cache.get(key, None)
222
330
        value_len = self._compute_size(value)
223
331
        if value_len >= self._after_cleanup_size:
 
332
            # The new value is 'too big to fit', as it would fill up/overflow
 
333
            # the cache all by itself
 
334
            trace.mutter('Adding the key %r to an LRUSizeCache failed.'
 
335
                         ' value %d is too big to fit in a the cache'
 
336
                         ' with size %d %d', key, value_len,
 
337
                         self._after_cleanup_size, self._max_size)
 
338
            if node is not None:
 
339
                # We won't be replacing the old node, so just remove it
 
340
                self._remove_node(node)
 
341
            if cleanup is not None:
 
342
                cleanup(key, value)
224
343
            return
 
344
        if node is None:
 
345
            node = _LRUNode(key, value, cleanup=cleanup)
 
346
            self._cache[key] = node
 
347
        else:
 
348
            self._value_size -= node.size
 
349
        node.size = value_len
225
350
        self._value_size += value_len
226
 
        self._cache[key] = value
227
 
        if cleanup is not None:
228
 
            self._cleanup[key] = cleanup
229
 
        self._record_access(key)
 
351
        self._record_access(node)
230
352
 
231
353
        if self._value_size > self._max_size:
232
354
            # Time to cleanup
242
364
        while self._value_size > self._after_cleanup_size:
243
365
            self._remove_lru()
244
366
 
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)
 
367
    def _remove_node(self, node):
 
368
        self._value_size -= node.size
 
369
        LRUCache._remove_node(self, node)
249
370
 
250
371
    def resize(self, max_size, after_cleanup_size=None):
251
372
        """Change the number of bytes that will be cached."""