lru_cache.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. # Copyright (C) 2006, 2008 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. """A simple least-recently-used (LRU) cache."""
  17. from collections import deque
  18. class LRUCache(object):
  19. """A class which manages a cache of entries, removing unused ones."""
  20. def __init__(self, max_cache=100, after_cleanup_count=None):
  21. self._cache = {}
  22. self._cleanup = {}
  23. self._queue = deque() # Track when things are accessed
  24. self._refcount = {} # number of entries in self._queue for each key
  25. self._update_max_cache(max_cache, after_cleanup_count)
  26. def __contains__(self, key):
  27. return key in self._cache
  28. def __getitem__(self, key):
  29. val = self._cache[key]
  30. self._record_access(key)
  31. return val
  32. def __len__(self):
  33. return len(self._cache)
  34. def add(self, key, value, cleanup=None):
  35. """Add a new value to the cache.
  36. Also, if the entry is ever removed from the queue, call cleanup.
  37. Passing it the key and value being removed.
  38. :param key: The key to store it under
  39. :param value: The object to store
  40. :param cleanup: None or a function taking (key, value) to indicate
  41. 'value' sohuld be cleaned up.
  42. """
  43. if key in self._cache:
  44. self._remove(key)
  45. self._cache[key] = value
  46. if cleanup is not None:
  47. self._cleanup[key] = cleanup
  48. self._record_access(key)
  49. if len(self._cache) > self._max_cache:
  50. # Trigger the cleanup
  51. self.cleanup()
  52. def get(self, key, default=None):
  53. if key in self._cache:
  54. return self[key]
  55. return default
  56. def keys(self):
  57. """Get the list of keys currently cached.
  58. Note that values returned here may not be available by the time you
  59. request them later. This is simply meant as a peak into the current
  60. state.
  61. :return: An unordered list of keys that are currently cached.
  62. """
  63. return self._cache.keys()
  64. def cleanup(self):
  65. """Clear the cache until it shrinks to the requested size.
  66. This does not completely wipe the cache, just makes sure it is under
  67. the after_cleanup_count.
  68. """
  69. # Make sure the cache is shrunk to the correct size
  70. while len(self._cache) > self._after_cleanup_count:
  71. self._remove_lru()
  72. # No need to compact the queue at this point, because the code that
  73. # calls this would have already triggered it based on queue length
  74. def __setitem__(self, key, value):
  75. """Add a value to the cache, there will be no cleanup function."""
  76. self.add(key, value, cleanup=None)
  77. def _record_access(self, key):
  78. """Record that key was accessed."""
  79. self._queue.append(key)
  80. # Can't use setdefault because you can't += 1 the result
  81. self._refcount[key] = self._refcount.get(key, 0) + 1
  82. # If our access queue is too large, clean it up too
  83. if len(self._queue) > self._compact_queue_length:
  84. self._compact_queue()
  85. def _compact_queue(self):
  86. """Compact the queue, leaving things in sorted last appended order."""
  87. new_queue = deque()
  88. for item in self._queue:
  89. if self._refcount[item] == 1:
  90. new_queue.append(item)
  91. else:
  92. self._refcount[item] -= 1
  93. self._queue = new_queue
  94. # All entries should be of the same size. There should be one entry in
  95. # queue for each entry in cache, and all refcounts should == 1
  96. if not (len(self._queue) == len(self._cache) ==
  97. len(self._refcount) == sum(self._refcount.itervalues())):
  98. raise AssertionError()
  99. def _remove(self, key):
  100. """Remove an entry, making sure to maintain the invariants."""
  101. cleanup = self._cleanup.pop(key, None)
  102. val = self._cache.pop(key)
  103. if cleanup is not None:
  104. cleanup(key, val)
  105. return val
  106. def _remove_lru(self):
  107. """Remove one entry from the lru, and handle consequences.
  108. If there are no more references to the lru, then this entry should be
  109. removed from the cache.
  110. """
  111. key = self._queue.popleft()
  112. self._refcount[key] -= 1
  113. if not self._refcount[key]:
  114. del self._refcount[key]
  115. self._remove(key)
  116. def clear(self):
  117. """Clear out all of the cache."""
  118. # Clean up in LRU order
  119. while self._cache:
  120. self._remove_lru()
  121. def resize(self, max_cache, after_cleanup_count=None):
  122. """Change the number of entries that will be cached."""
  123. self._update_max_cache(max_cache,
  124. after_cleanup_count=after_cleanup_count)
  125. def _update_max_cache(self, max_cache, after_cleanup_count=None):
  126. self._max_cache = max_cache
  127. if after_cleanup_count is None:
  128. self._after_cleanup_count = self._max_cache * 8 / 10
  129. else:
  130. self._after_cleanup_count = min(after_cleanup_count, self._max_cache)
  131. self._compact_queue_length = 4*self._max_cache
  132. if len(self._queue) > self._compact_queue_length:
  133. self._compact_queue()
  134. self.cleanup()
  135. class LRUSizeCache(LRUCache):
  136. """An LRUCache that removes things based on the size of the values.
  137. This differs in that it doesn't care how many actual items there are,
  138. it just restricts the cache to be cleaned up after so much data is stored.
  139. The values that are added must support len(value).
  140. """
  141. def __init__(self, max_size=1024*1024, after_cleanup_size=None,
  142. compute_size=None):
  143. """Create a new LRUSizeCache.
  144. :param max_size: The max number of bytes to store before we start
  145. clearing out entries.
  146. :param after_cleanup_size: After cleaning up, shrink everything to this
  147. size.
  148. :param compute_size: A function to compute the size of the values. We
  149. use a function here, so that you can pass 'len' if you are just
  150. using simple strings, or a more complex function if you are using
  151. something like a list of strings, or even a custom object.
  152. The function should take the form "compute_size(value) => integer".
  153. If not supplied, it defaults to 'len()'
  154. """
  155. self._value_size = 0
  156. self._compute_size = compute_size
  157. if compute_size is None:
  158. self._compute_size = len
  159. # This approximates that texts are > 0.5k in size. It only really
  160. # effects when we clean up the queue, so we don't want it to be too
  161. # large.
  162. self._update_max_size(max_size, after_cleanup_size=after_cleanup_size)
  163. LRUCache.__init__(self, max_cache=max(int(max_size/512), 1))
  164. def add(self, key, value, cleanup=None):
  165. """Add a new value to the cache.
  166. Also, if the entry is ever removed from the queue, call cleanup.
  167. Passing it the key and value being removed.
  168. :param key: The key to store it under
  169. :param value: The object to store
  170. :param cleanup: None or a function taking (key, value) to indicate
  171. 'value' sohuld be cleaned up.
  172. """
  173. if key in self._cache:
  174. self._remove(key)
  175. value_len = self._compute_size(value)
  176. if value_len >= self._after_cleanup_size:
  177. return
  178. self._value_size += value_len
  179. self._cache[key] = value
  180. if cleanup is not None:
  181. self._cleanup[key] = cleanup
  182. self._record_access(key)
  183. if self._value_size > self._max_size:
  184. # Time to cleanup
  185. self.cleanup()
  186. def cleanup(self):
  187. """Clear the cache until it shrinks to the requested size.
  188. This does not completely wipe the cache, just makes sure it is under
  189. the after_cleanup_size.
  190. """
  191. # Make sure the cache is shrunk to the correct size
  192. while self._value_size > self._after_cleanup_size:
  193. self._remove_lru()
  194. def _remove(self, key):
  195. """Remove an entry, making sure to maintain the invariants."""
  196. val = LRUCache._remove(self, key)
  197. self._value_size -= self._compute_size(val)
  198. def resize(self, max_size, after_cleanup_size=None):
  199. """Change the number of bytes that will be cached."""
  200. self._update_max_size(max_size, after_cleanup_size=after_cleanup_size)
  201. max_cache = max(int(max_size/512), 1)
  202. self._update_max_cache(max_cache)
  203. def _update_max_size(self, max_size, after_cleanup_size=None):
  204. self._max_size = max_size
  205. if after_cleanup_size is None:
  206. self._after_cleanup_size = self._max_size * 8 / 10
  207. else:
  208. self._after_cleanup_size = min(after_cleanup_size, self._max_size)