util.cache: Call on-eviction callback when shrinking
authorKim Alvefur <zash@zash.se>
Sat, 18 Nov 2017 21:35:40 +0100
changeset 8401 3eff1b60269a
parent 8400 99d85731e3ee
child 8402 07443fe9df5b
util.cache: Call on-eviction callback when shrinking
util/cache.lua
--- a/util/cache.lua	Sat Nov 18 21:35:31 2017 +0100
+++ b/util/cache.lua	Sat Nov 18 21:35:40 2017 +0100
@@ -120,9 +120,14 @@
 	new_size = assert(tonumber(new_size), "cache size must be a number");
 	new_size = math.floor(new_size);
 	assert(new_size > 0, "cache size must be greater than zero");
+	local on_evict = self._on_evict;
 	while self._count > new_size do
 		local tail = self._tail;
-		local evicted_key = tail.key;
+		local evicted_key, evicted_value = tail.key, tail.value;
+		if on_evict ~= nil and (on_evict == false or on_evict(evicted_key, evicted_value) == false) then
+			-- Cache is full, and we're not allowed to evict
+			return false;
+		end
 		_remove(self, tail);
 		self._data[evicted_key] = nil;
 	end