Mercurial > public > mercurial-scm > hg
diff mercurial/util.py @ 18603:2251b3184e6e
util: add an LRU cache dict
In certain cases we would like to have a cache of the last N results of a
given computation, where N is small. This will be used in an upcoming patch to
increase the size of the manifest cache from 1 to 3.
author | Siddharth Agarwal <sid0@fb.com> |
---|---|
date | Sat, 09 Feb 2013 15:41:46 +0000 |
parents | ae60735e37d2 |
children | b2586e2cc67a |
line wrap: on
line diff
--- a/mercurial/util.py Sat Feb 09 15:08:21 2013 +0000 +++ b/mercurial/util.py Sat Feb 09 15:41:46 2013 +0000 @@ -211,6 +211,31 @@ del self[i] break +class lrucachedict(object): + '''cache most recent gets from or sets to this dictionary''' + def __init__(self, maxsize): + self._cache = {} + self._maxsize = maxsize + self._order = deque() + + def __getitem__(self, key): + value = self._cache[key] + self._order.remove(key) + self._order.append(key) + return value + + def __setitem__(self, key, value): + if key not in self._cache: + if len(self._cache) >= self._maxsize: + del self._cache[self._order.popleft()] + else: + self._order.remove(key) + self._cache[key] = value + self._order.append(key) + + def __contains__(self, key): + return key in self._cache + def lrucachefunc(func): '''cache most recent results of function calls''' cache = {}