/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/lru_cache.py

  • Committer: Gustav Hartvigsson
  • Date: 2021-01-09 21:36:27 UTC
  • Revision ID: gustav.hartvigsson@gmail.com-20210109213627-h1xwcutzy9m7a99b
Added 'Case Preserving Working Tree Use Cases' from Canonical Wiki

* Addod a page from the Canonical Bazaar wiki
  with information on the scmeatics of case
  perserving filesystems an a case insensitive
  filesystem works.
  
  * Needs re-work, but this will do as it is the
    same inforamoton as what was on the linked
    page in the currint documentation.

Show diffs side-by-side

added added

removed removed

Lines of Context:
16
16
 
17
17
"""A simple least-recently-used (LRU) cache."""
18
18
 
19
 
from bzrlib import (
20
 
    symbol_versioning,
 
19
from . import (
21
20
    trace,
22
21
    )
23
22
 
 
23
 
24
24
_null_key = object()
25
25
 
 
26
 
26
27
class _LRUNode(object):
27
28
    """This maintains the linked-list which is the lru internals."""
28
29
 
29
 
    __slots__ = ('prev', 'next_key', 'key', 'value', 'cleanup', 'size')
 
30
    __slots__ = ('prev', 'next_key', 'key', 'value')
30
31
 
31
 
    def __init__(self, key, value, cleanup=None):
 
32
    def __init__(self, key, value):
32
33
        self.prev = None
33
34
        self.next_key = _null_key
34
35
        self.key = key
35
36
        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
37
 
42
38
    def __repr__(self):
43
39
        if self.prev is None:
47
43
        return '%s(%r n:%r p:%r)' % (self.__class__.__name__, self.key,
48
44
                                     self.next_key, prev_key)
49
45
 
50
 
    def run_cleanup(self):
51
 
        try:
52
 
            if self.cleanup is not None:
53
 
                self.cleanup(self.key, self.value)
54
 
        finally:
55
 
            # cleanup might raise an exception, but we want to make sure
56
 
            # to break refcycles, etc
57
 
            self.cleanup = None
58
 
            self.value = None
59
 
 
60
46
 
61
47
class LRUCache(object):
62
48
    """A class which manages a cache of entries, removing unused ones."""
63
49
 
64
 
    def __init__(self, max_cache=100, after_cleanup_count=None,
65
 
                 after_cleanup_size=symbol_versioning.DEPRECATED_PARAMETER):
66
 
        if symbol_versioning.deprecated_passed(after_cleanup_size):
67
 
            symbol_versioning.warn('LRUCache.__init__(after_cleanup_size) was'
68
 
                                   ' deprecated in 1.11. Use'
69
 
                                   ' after_cleanup_count instead.',
70
 
                                   DeprecationWarning)
71
 
            after_cleanup_count = after_cleanup_size
 
50
    def __init__(self, max_cache=100, after_cleanup_count=None):
72
51
        self._cache = {}
73
52
        # The "HEAD" of the lru linked list
74
53
        self._most_recently_used = None
113
92
    def __len__(self):
114
93
        return len(self._cache)
115
94
 
116
 
    def _walk_lru(self):
117
 
        """Walk the LRU list, only meant to be used in tests."""
118
 
        node = self._most_recently_used
119
 
        if node is not None:
120
 
            if node.prev is not None:
121
 
                raise AssertionError('the _most_recently_used entry is not'
122
 
                                     ' supposed to have a previous entry'
123
 
                                     ' %s' % (node,))
124
 
        while node is not None:
125
 
            if node.next_key is _null_key:
126
 
                if node is not self._least_recently_used:
127
 
                    raise AssertionError('only the last node should have'
128
 
                                         ' no next value: %s' % (node,))
129
 
                node_next = None
130
 
            else:
131
 
                node_next = self._cache[node.next_key]
132
 
                if node_next.prev is not node:
133
 
                    raise AssertionError('inconsistency found, node.next.prev'
134
 
                                         ' != node: %s' % (node,))
135
 
            if node.prev is None:
136
 
                if node is not self._most_recently_used:
137
 
                    raise AssertionError('only the _most_recently_used should'
138
 
                                         ' not have a previous node: %s'
139
 
                                         % (node,))
140
 
            else:
141
 
                if node.prev.next_key != node.key:
142
 
                    raise AssertionError('inconsistency found, node.prev.next'
143
 
                                         ' != node: %s' % (node,))
144
 
            yield node
145
 
            node = node_next
146
 
 
147
 
    def add(self, key, value, cleanup=None):
148
 
        """Add a new value to the cache.
149
 
 
150
 
        Also, if the entry is ever removed from the cache, call
151
 
        cleanup(key, value).
152
 
 
153
 
        :param key: The key to store it under
154
 
        :param value: The object to store
155
 
        :param cleanup: None or a function taking (key, value) to indicate
156
 
                        'value' should be cleaned up.
157
 
        """
 
95
    def __setitem__(self, key, value):
 
96
        """Add a new value to the cache"""
158
97
        if key is _null_key:
159
98
            raise ValueError('cannot use _null_key as a key')
160
99
        if key in self._cache:
161
100
            node = self._cache[key]
162
 
            try:
163
 
                node.run_cleanup()
164
 
            finally:
165
 
                # Maintain the LRU properties, even if cleanup raises an
166
 
                # exception
167
 
                node.value = value
168
 
                node.cleanup = cleanup
169
 
                self._record_access(node)
 
101
            node.value = value
 
102
            self._record_access(node)
170
103
        else:
171
 
            node = _LRUNode(key, value, cleanup=cleanup)
 
104
            node = _LRUNode(key, value)
172
105
            self._cache[key] = node
173
106
            self._record_access(node)
174
107
 
196
129
 
197
130
        :return: An unordered list of keys that are currently cached.
198
131
        """
199
 
        return self._cache.keys()
 
132
        # GZ 2016-06-04: Maybe just make this return the view?
 
133
        return list(self._cache.keys())
200
134
 
201
 
    def items(self):
202
 
        """Get the key:value pairs as a dict."""
203
 
        return dict((k, n.value) for k, n in self._cache.iteritems())
 
135
    def as_dict(self):
 
136
        """Get a new dict with the same key:value pairs as the cache"""
 
137
        return dict((k, n.value) for k, n in self._cache.items())
204
138
 
205
139
    def cleanup(self):
206
140
        """Clear the cache until it shrinks to the requested size.
212
146
        while len(self._cache) > self._after_cleanup_count:
213
147
            self._remove_lru()
214
148
 
215
 
    def __setitem__(self, key, value):
216
 
        """Add a value to the cache, there will be no cleanup function."""
217
 
        self.add(key, value, cleanup=None)
218
 
 
219
149
    def _record_access(self, node):
220
150
        """Record that key was accessed."""
221
151
        # Move 'node' to the front of the queue
249
179
        # If we have removed all entries, remove the head pointer as well
250
180
        if self._least_recently_used is None:
251
181
            self._most_recently_used = None
252
 
        try:
253
 
            node.run_cleanup()
254
 
        finally:
255
 
            # cleanup might raise an exception, but we want to make sure to
256
 
            # maintain the linked list
257
 
            if node.prev is not None:
258
 
                node.prev.next_key = node.next_key
259
 
            if node.next_key is not _null_key:
260
 
                node_next = self._cache[node.next_key]
261
 
                node_next.prev = node.prev
262
 
            # And remove this node's pointers
263
 
            node.prev = None
264
 
            node.next_key = _null_key
 
182
        if node.prev is not None:
 
183
            node.prev.next_key = node.next_key
 
184
        if node.next_key is not _null_key:
 
185
            node_next = self._cache[node.next_key]
 
186
            node_next.prev = node.prev
 
187
        # And remove this node's pointers
 
188
        node.prev = None
 
189
        node.next_key = _null_key
265
190
 
266
191
    def _remove_lru(self):
267
192
        """Remove one entry from the lru, and handle consequences.
285
210
    def _update_max_cache(self, max_cache, after_cleanup_count=None):
286
211
        self._max_cache = max_cache
287
212
        if after_cleanup_count is None:
288
 
            self._after_cleanup_count = self._max_cache * 8 / 10
 
213
            self._after_cleanup_count = self._max_cache * 8 // 10
289
214
        else:
290
215
            self._after_cleanup_count = min(after_cleanup_count,
291
216
                                            self._max_cache)
302
227
    defaults to len() if not supplied.
303
228
    """
304
229
 
305
 
    def __init__(self, max_size=1024*1024, after_cleanup_size=None,
 
230
    def __init__(self, max_size=1024 * 1024, after_cleanup_size=None,
306
231
                 compute_size=None):
307
232
        """Create a new LRUSizeCache.
308
233
 
322
247
        if compute_size is None:
323
248
            self._compute_size = len
324
249
        self._update_max_size(max_size, after_cleanup_size=after_cleanup_size)
325
 
        LRUCache.__init__(self, max_cache=max(int(max_size/512), 1))
326
 
 
327
 
    def add(self, key, value, cleanup=None):
328
 
        """Add a new value to the cache.
329
 
 
330
 
        Also, if the entry is ever removed from the cache, call
331
 
        cleanup(key, value).
332
 
 
333
 
        :param key: The key to store it under
334
 
        :param value: The object to store
335
 
        :param cleanup: None or a function taking (key, value) to indicate
336
 
                        'value' should be cleaned up.
337
 
        """
 
250
        LRUCache.__init__(self, max_cache=max(int(max_size // 512), 1))
 
251
 
 
252
    def __setitem__(self, key, value):
 
253
        """Add a new value to the cache"""
338
254
        if key is _null_key:
339
255
            raise ValueError('cannot use _null_key as a key')
340
256
        node = self._cache.get(key, None)
349
265
            if node is not None:
350
266
                # We won't be replacing the old node, so just remove it
351
267
                self._remove_node(node)
352
 
            if cleanup is not None:
353
 
                cleanup(key, value)
354
268
            return
355
269
        if node is None:
356
 
            node = _LRUNode(key, value, cleanup=cleanup)
 
270
            node = _LRUNode(key, value)
357
271
            self._cache[key] = node
358
272
        else:
359
 
            self._value_size -= node.size
360
 
        node.size = value_len
 
273
            self._value_size -= self._compute_size(node.value)
361
274
        self._value_size += value_len
362
275
        self._record_access(node)
363
276
 
376
289
            self._remove_lru()
377
290
 
378
291
    def _remove_node(self, node):
379
 
        self._value_size -= node.size
 
292
        self._value_size -= self._compute_size(node.value)
380
293
        LRUCache._remove_node(self, node)
381
294
 
382
295
    def resize(self, max_size, after_cleanup_size=None):
383
296
        """Change the number of bytes that will be cached."""
384
297
        self._update_max_size(max_size, after_cleanup_size=after_cleanup_size)
385
 
        max_cache = max(int(max_size/512), 1)
 
298
        max_cache = max(int(max_size // 512), 1)
386
299
        self._update_max_cache(max_cache)
387
300
 
388
301
    def _update_max_size(self, max_size, after_cleanup_size=None):
389
302
        self._max_size = max_size
390
303
        if after_cleanup_size is None:
391
 
            self._after_cleanup_size = self._max_size * 8 / 10
 
304
            self._after_cleanup_size = self._max_size * 8 // 10
392
305
        else:
393
306
            self._after_cleanup_size = min(after_cleanup_size, self._max_size)