/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: Jelmer Vernooij
  • Date: 2020-02-07 02:14:30 UTC
  • mto: This revision was merged to the branch mainline in revision 7492.
  • Revision ID: jelmer@jelmer.uk-20200207021430-m49iq3x4x8xlib6x
Drop python2 support.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006, 2008, 2009 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
"""A simple least-recently-used (LRU) cache."""
 
18
 
 
19
from __future__ import absolute_import, division
 
20
 
 
21
from . import (
 
22
    trace,
 
23
    )
 
24
 
 
25
 
 
26
_null_key = object()
 
27
 
 
28
 
 
29
class _LRUNode(object):
 
30
    """This maintains the linked-list which is the lru internals."""
 
31
 
 
32
    __slots__ = ('prev', 'next_key', 'key', 'value')
 
33
 
 
34
    def __init__(self, key, value):
 
35
        self.prev = None
 
36
        self.next_key = _null_key
 
37
        self.key = key
 
38
        self.value = value
 
39
 
 
40
    def __repr__(self):
 
41
        if self.prev is None:
 
42
            prev_key = None
 
43
        else:
 
44
            prev_key = self.prev.key
 
45
        return '%s(%r n:%r p:%r)' % (self.__class__.__name__, self.key,
 
46
                                     self.next_key, prev_key)
 
47
 
 
48
 
 
49
class LRUCache(object):
 
50
    """A class which manages a cache of entries, removing unused ones."""
 
51
 
 
52
    def __init__(self, max_cache=100, after_cleanup_count=None):
 
53
        self._cache = {}
 
54
        # The "HEAD" of the lru linked list
 
55
        self._most_recently_used = None
 
56
        # The "TAIL" of the lru linked list
 
57
        self._least_recently_used = None
 
58
        self._update_max_cache(max_cache, after_cleanup_count)
 
59
 
 
60
    def __contains__(self, key):
 
61
        return key in self._cache
 
62
 
 
63
    def __getitem__(self, key):
 
64
        cache = self._cache
 
65
        node = cache[key]
 
66
        # Inlined from _record_access to decrease the overhead of __getitem__
 
67
        # We also have more knowledge about structure if __getitem__ is
 
68
        # succeeding, then we know that self._most_recently_used must not be
 
69
        # None, etc.
 
70
        mru = self._most_recently_used
 
71
        if node is mru:
 
72
            # Nothing to do, this node is already at the head of the queue
 
73
            return node.value
 
74
        # Remove this node from the old location
 
75
        node_prev = node.prev
 
76
        next_key = node.next_key
 
77
        # benchmarking shows that the lookup of _null_key in globals is faster
 
78
        # than the attribute lookup for (node is self._least_recently_used)
 
79
        if next_key is _null_key:
 
80
            # 'node' is the _least_recently_used, because it doesn't have a
 
81
            # 'next' item. So move the current lru to the previous node.
 
82
            self._least_recently_used = node_prev
 
83
        else:
 
84
            node_next = cache[next_key]
 
85
            node_next.prev = node_prev
 
86
        node_prev.next_key = next_key
 
87
        # Insert this node at the front of the list
 
88
        node.next_key = mru.key
 
89
        mru.prev = node
 
90
        self._most_recently_used = node
 
91
        node.prev = None
 
92
        return node.value
 
93
 
 
94
    def __len__(self):
 
95
        return len(self._cache)
 
96
 
 
97
    def __setitem__(self, key, value):
 
98
        """Add a new value to the cache"""
 
99
        if key is _null_key:
 
100
            raise ValueError('cannot use _null_key as a key')
 
101
        if key in self._cache:
 
102
            node = self._cache[key]
 
103
            node.value = value
 
104
            self._record_access(node)
 
105
        else:
 
106
            node = _LRUNode(key, value)
 
107
            self._cache[key] = node
 
108
            self._record_access(node)
 
109
 
 
110
        if len(self._cache) > self._max_cache:
 
111
            # Trigger the cleanup
 
112
            self.cleanup()
 
113
 
 
114
    def cache_size(self):
 
115
        """Get the number of entries we will cache."""
 
116
        return self._max_cache
 
117
 
 
118
    def get(self, key, default=None):
 
119
        node = self._cache.get(key, None)
 
120
        if node is None:
 
121
            return default
 
122
        self._record_access(node)
 
123
        return node.value
 
124
 
 
125
    def keys(self):
 
126
        """Get the list of keys currently cached.
 
127
 
 
128
        Note that values returned here may not be available by the time you
 
129
        request them later. This is simply meant as a peak into the current
 
130
        state.
 
131
 
 
132
        :return: An unordered list of keys that are currently cached.
 
133
        """
 
134
        # GZ 2016-06-04: Maybe just make this return the view?
 
135
        return list(self._cache.keys())
 
136
 
 
137
    def as_dict(self):
 
138
        """Get a new dict with the same key:value pairs as the cache"""
 
139
        return dict((k, n.value) for k, n in self._cache.items())
 
140
 
 
141
    def cleanup(self):
 
142
        """Clear the cache until it shrinks to the requested size.
 
143
 
 
144
        This does not completely wipe the cache, just makes sure it is under
 
145
        the after_cleanup_count.
 
146
        """
 
147
        # Make sure the cache is shrunk to the correct size
 
148
        while len(self._cache) > self._after_cleanup_count:
 
149
            self._remove_lru()
 
150
 
 
151
    def _record_access(self, node):
 
152
        """Record that key was accessed."""
 
153
        # Move 'node' to the front of the queue
 
154
        if self._most_recently_used is None:
 
155
            self._most_recently_used = node
 
156
            self._least_recently_used = node
 
157
            return
 
158
        elif node is self._most_recently_used:
 
159
            # Nothing to do, this node is already at the head of the queue
 
160
            return
 
161
        # We've taken care of the tail pointer, remove the node, and insert it
 
162
        # at the front
 
163
        # REMOVE
 
164
        if node is self._least_recently_used:
 
165
            self._least_recently_used = node.prev
 
166
        if node.prev is not None:
 
167
            node.prev.next_key = node.next_key
 
168
        if node.next_key is not _null_key:
 
169
            node_next = self._cache[node.next_key]
 
170
            node_next.prev = node.prev
 
171
        # INSERT
 
172
        node.next_key = self._most_recently_used.key
 
173
        self._most_recently_used.prev = node
 
174
        self._most_recently_used = node
 
175
        node.prev = None
 
176
 
 
177
    def _remove_node(self, node):
 
178
        if node is self._least_recently_used:
 
179
            self._least_recently_used = node.prev
 
180
        self._cache.pop(node.key)
 
181
        # If we have removed all entries, remove the head pointer as well
 
182
        if self._least_recently_used is None:
 
183
            self._most_recently_used = None
 
184
        if node.prev is not None:
 
185
            node.prev.next_key = node.next_key
 
186
        if node.next_key is not _null_key:
 
187
            node_next = self._cache[node.next_key]
 
188
            node_next.prev = node.prev
 
189
        # And remove this node's pointers
 
190
        node.prev = None
 
191
        node.next_key = _null_key
 
192
 
 
193
    def _remove_lru(self):
 
194
        """Remove one entry from the lru, and handle consequences.
 
195
 
 
196
        If there are no more references to the lru, then this entry should be
 
197
        removed from the cache.
 
198
        """
 
199
        self._remove_node(self._least_recently_used)
 
200
 
 
201
    def clear(self):
 
202
        """Clear out all of the cache."""
 
203
        # Clean up in LRU order
 
204
        while self._cache:
 
205
            self._remove_lru()
 
206
 
 
207
    def resize(self, max_cache, after_cleanup_count=None):
 
208
        """Change the number of entries that will be cached."""
 
209
        self._update_max_cache(max_cache,
 
210
                               after_cleanup_count=after_cleanup_count)
 
211
 
 
212
    def _update_max_cache(self, max_cache, after_cleanup_count=None):
 
213
        self._max_cache = max_cache
 
214
        if after_cleanup_count is None:
 
215
            self._after_cleanup_count = self._max_cache * 8 // 10
 
216
        else:
 
217
            self._after_cleanup_count = min(after_cleanup_count,
 
218
                                            self._max_cache)
 
219
        self.cleanup()
 
220
 
 
221
 
 
222
class LRUSizeCache(LRUCache):
 
223
    """An LRUCache that removes things based on the size of the values.
 
224
 
 
225
    This differs in that it doesn't care how many actual items there are,
 
226
    it just restricts the cache to be cleaned up after so much data is stored.
 
227
 
 
228
    The size of items added will be computed using compute_size(value), which
 
229
    defaults to len() if not supplied.
 
230
    """
 
231
 
 
232
    def __init__(self, max_size=1024 * 1024, after_cleanup_size=None,
 
233
                 compute_size=None):
 
234
        """Create a new LRUSizeCache.
 
235
 
 
236
        :param max_size: The max number of bytes to store before we start
 
237
            clearing out entries.
 
238
        :param after_cleanup_size: After cleaning up, shrink everything to this
 
239
            size.
 
240
        :param compute_size: A function to compute the size of the values. We
 
241
            use a function here, so that you can pass 'len' if you are just
 
242
            using simple strings, or a more complex function if you are using
 
243
            something like a list of strings, or even a custom object.
 
244
            The function should take the form "compute_size(value) => integer".
 
245
            If not supplied, it defaults to 'len()'
 
246
        """
 
247
        self._value_size = 0
 
248
        self._compute_size = compute_size
 
249
        if compute_size is None:
 
250
            self._compute_size = len
 
251
        self._update_max_size(max_size, after_cleanup_size=after_cleanup_size)
 
252
        LRUCache.__init__(self, max_cache=max(int(max_size // 512), 1))
 
253
 
 
254
    def __setitem__(self, key, value):
 
255
        """Add a new value to the cache"""
 
256
        if key is _null_key:
 
257
            raise ValueError('cannot use _null_key as a key')
 
258
        node = self._cache.get(key, None)
 
259
        value_len = self._compute_size(value)
 
260
        if value_len >= self._after_cleanup_size:
 
261
            # The new value is 'too big to fit', as it would fill up/overflow
 
262
            # the cache all by itself
 
263
            trace.mutter('Adding the key %r to an LRUSizeCache failed.'
 
264
                         ' value %d is too big to fit in a the cache'
 
265
                         ' with size %d %d', key, value_len,
 
266
                         self._after_cleanup_size, self._max_size)
 
267
            if node is not None:
 
268
                # We won't be replacing the old node, so just remove it
 
269
                self._remove_node(node)
 
270
            return
 
271
        if node is None:
 
272
            node = _LRUNode(key, value)
 
273
            self._cache[key] = node
 
274
        else:
 
275
            self._value_size -= self._compute_size(node.value)
 
276
        self._value_size += value_len
 
277
        self._record_access(node)
 
278
 
 
279
        if self._value_size > self._max_size:
 
280
            # Time to cleanup
 
281
            self.cleanup()
 
282
 
 
283
    def cleanup(self):
 
284
        """Clear the cache until it shrinks to the requested size.
 
285
 
 
286
        This does not completely wipe the cache, just makes sure it is under
 
287
        the after_cleanup_size.
 
288
        """
 
289
        # Make sure the cache is shrunk to the correct size
 
290
        while self._value_size > self._after_cleanup_size:
 
291
            self._remove_lru()
 
292
 
 
293
    def _remove_node(self, node):
 
294
        self._value_size -= self._compute_size(node.value)
 
295
        LRUCache._remove_node(self, node)
 
296
 
 
297
    def resize(self, max_size, after_cleanup_size=None):
 
298
        """Change the number of bytes that will be cached."""
 
299
        self._update_max_size(max_size, after_cleanup_size=after_cleanup_size)
 
300
        max_cache = max(int(max_size // 512), 1)
 
301
        self._update_max_cache(max_cache)
 
302
 
 
303
    def _update_max_size(self, max_size, after_cleanup_size=None):
 
304
        self._max_size = max_size
 
305
        if after_cleanup_size is None:
 
306
            self._after_cleanup_size = self._max_size * 8 // 10
 
307
        else:
 
308
            self._after_cleanup_size = min(after_cleanup_size, self._max_size)