Comparison

util/cache.lua @ 7290:70ab13e81cf5

util.cache: Change behaviour of on_evict (and tests). Now accepts false instead of a function (never evict), or on_evict can return false to prevent eviction.
author Matthew Wild <mwild1@gmail.com>
date Thu, 17 Mar 2016 19:08:42 +0000
parent 7289:42e7545d5ae3
child 7354:8ca7f1c2c660
comparison
equal deleted inserted replaced
7289:42e7545d5ae3 7290:70ab13e81cf5
49 -- New key 49 -- New key
50 if v == nil then 50 if v == nil then
51 return true; 51 return true;
52 end 52 end
53 -- Check whether we need to remove oldest k/v 53 -- Check whether we need to remove oldest k/v
54 local on_evict, evicted_key, evicted_value;
55 if self._count == self.size then 54 if self._count == self.size then
56 local tail = self._tail; 55 local tail = self._tail;
57 on_evict, evicted_key, evicted_value = self._on_evict, tail.key, tail.value; 56 local on_evict, evicted_key, evicted_value = self._on_evict, tail.key, tail.value;
57 if on_evict ~= nil and (on_evict == false or on_evict(evicted_key, evicted_value) == false) then
58 -- Cache is full, and we're not allowed to evict
59 return false;
60 end
58 _remove(self, tail); 61 _remove(self, tail);
59 self._data[evicted_key] = nil; 62 self._data[evicted_key] = nil;
60 end 63 end
61 64
62 m = { key = k, value = v, prev = nil, next = nil }; 65 m = { key = k, value = v, prev = nil, next = nil };
63 self._data[k] = m; 66 self._data[k] = m;
64 _insert(self, m); 67 _insert(self, m);
65 if on_evict and evicted_key then
66 on_evict(evicted_key, evicted_value, self);
67 end
68 return true; 68 return true;
69 end 69 end
70 70
71 function cache_methods:get(k) 71 function cache_methods:get(k)
72 local m = self._data[k]; 72 local m = self._data[k];