Show More
@@ -0,0 +1,35 b'' | |||
|
1 | from mercurial import util | |
|
2 | ||
|
3 | def printifpresent(d, xs): | |
|
4 | for x in xs: | |
|
5 | present = x in d | |
|
6 | print "'%s' in d: %s" % (x, present) | |
|
7 | if present: | |
|
8 | print "d['%s']: %s" % (x, d[x]) | |
|
9 | ||
|
10 | def test_lrucachedict(): | |
|
11 | d = util.lrucachedict(4) | |
|
12 | d['a'] = 'va' | |
|
13 | d['b'] = 'vb' | |
|
14 | d['c'] = 'vc' | |
|
15 | d['d'] = 'vd' | |
|
16 | ||
|
17 | # all of these should be present | |
|
18 | printifpresent(d, ['a', 'b', 'c', 'd']) | |
|
19 | ||
|
20 | # 'a' should be dropped because it was least recently used | |
|
21 | d['e'] = 've' | |
|
22 | printifpresent(d, ['a', 'b', 'c', 'd', 'e']) | |
|
23 | ||
|
24 | # touch entries in some order (get or set). | |
|
25 | d['e'] | |
|
26 | d['c'] = 'vc2' | |
|
27 | d['d'] | |
|
28 | d['b'] = 'vb2' | |
|
29 | ||
|
30 | # 'e' should be dropped now | |
|
31 | d['f'] = 'vf' | |
|
32 | printifpresent(d, ['b', 'c', 'd', 'e', 'f']) | |
|
33 | ||
|
34 | if __name__ == '__main__': | |
|
35 | test_lrucachedict() |
@@ -0,0 +1,26 b'' | |||
|
1 | 'a' in d: True | |
|
2 | d['a']: va | |
|
3 | 'b' in d: True | |
|
4 | d['b']: vb | |
|
5 | 'c' in d: True | |
|
6 | d['c']: vc | |
|
7 | 'd' in d: True | |
|
8 | d['d']: vd | |
|
9 | 'a' in d: False | |
|
10 | 'b' in d: True | |
|
11 | d['b']: vb | |
|
12 | 'c' in d: True | |
|
13 | d['c']: vc | |
|
14 | 'd' in d: True | |
|
15 | d['d']: vd | |
|
16 | 'e' in d: True | |
|
17 | d['e']: ve | |
|
18 | 'b' in d: True | |
|
19 | d['b']: vb2 | |
|
20 | 'c' in d: True | |
|
21 | d['c']: vc2 | |
|
22 | 'd' in d: True | |
|
23 | d['d']: vd | |
|
24 | 'e' in d: False | |
|
25 | 'f' in d: True | |
|
26 | d['f']: vf |
@@ -211,6 +211,31 b' except AttributeError:' | |||
|
211 | 211 | del self[i] |
|
212 | 212 | break |
|
213 | 213 | |
|
214 | class lrucachedict(object): | |
|
215 | '''cache most recent gets from or sets to this dictionary''' | |
|
216 | def __init__(self, maxsize): | |
|
217 | self._cache = {} | |
|
218 | self._maxsize = maxsize | |
|
219 | self._order = deque() | |
|
220 | ||
|
221 | def __getitem__(self, key): | |
|
222 | value = self._cache[key] | |
|
223 | self._order.remove(key) | |
|
224 | self._order.append(key) | |
|
225 | return value | |
|
226 | ||
|
227 | def __setitem__(self, key, value): | |
|
228 | if key not in self._cache: | |
|
229 | if len(self._cache) >= self._maxsize: | |
|
230 | del self._cache[self._order.popleft()] | |
|
231 | else: | |
|
232 | self._order.remove(key) | |
|
233 | self._cache[key] = value | |
|
234 | self._order.append(key) | |
|
235 | ||
|
236 | def __contains__(self, key): | |
|
237 | return key in self._cache | |
|
238 | ||
|
214 | 239 | def lrucachefunc(func): |
|
215 | 240 | '''cache most recent results of function calls''' |
|
216 | 241 | cache = {} |
General Comments 0
You need to be logged in to leave comments.
Login now