Comparison

util/cache.lua @ 13175:bbdaa770b955

util.cache: Pass cache itself to eviction callback Simplifies access to the cache without moving code around a lot given the currently common pattern of local some_cache = cache.new(size, function(k,v) end)
author Kim Alvefur <zash@zash.se>
date Fri, 30 Jun 2023 22:01:55 +0200
parent 13174:8ec7b7d6556f
comparison
equal deleted inserted replaced
13174:8ec7b7d6556f 13175:bbdaa770b955
53 -- Check whether we need to remove oldest k/v 53 -- Check whether we need to remove oldest k/v
54 if self._count == self.size then 54 if self._count == self.size then
55 local tail = self._tail; 55 local tail = self._tail;
56 local 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 57
58 local do_evict = on_evict and on_evict(evicted_key, evicted_value); 58 local do_evict = on_evict and on_evict(evicted_key, evicted_value, self);
59 59
60 if do_evict == false then 60 if do_evict == false then
61 -- Cache is full, and we're not allowed to evict 61 -- Cache is full, and we're not allowed to evict
62 return false; 62 return false;
63 elseif self._count == self.size then 63 elseif self._count == self.size then
127 assert(new_size > 0, "cache size must be greater than zero"); 127 assert(new_size > 0, "cache size must be greater than zero");
128 local on_evict = self._on_evict; 128 local on_evict = self._on_evict;
129 while self._count > new_size do 129 while self._count > new_size do
130 local tail = self._tail; 130 local tail = self._tail;
131 local evicted_key, evicted_value = tail.key, tail.value; 131 local evicted_key, evicted_value = tail.key, tail.value;
132 if on_evict ~= nil and (on_evict == false or on_evict(evicted_key, evicted_value) == false) then 132 if on_evict ~= nil and (on_evict == false or on_evict(evicted_key, evicted_value, self) == false) then
133 -- Cache is full, and we're not allowed to evict 133 -- Cache is full, and we're not allowed to evict
134 return false; 134 return false;
135 end 135 end
136 _remove(self, tail); 136 _remove(self, tail);
137 self._data[evicted_key] = nil; 137 self._data[evicted_key] = nil;