2 local function _remove(list, m)
9 if list._tail == m then
12 if list._head == m then
15 list._count = list._count - 1;
18 local function _insert(list, m)
22 m.prev, m.next = nil, list._head;
24 if not list._tail then
27 list._count = list._count + 1;
30 local cache_methods = {};
31 local cache_mt = { __index = cache_methods };
33 function cache_methods:set(k, v)
34 local m = self._data[k];
38 -- Bump to head of list
53 -- Check whether we need to remove oldest k/v
54 if self._count == self.size then
55 local tail = self._tail;
56 local on_evict = self._on_evict;
58 on_evict(tail.key, tail.value);
61 self._data[tail.key] = nil;
64 m = { key = k, value = v, prev = nil, next = nil };
70 function cache_methods:get(k)
71 local m = self._data[k];
78 function cache_methods:items()
84 local k, v = m.key, m.value;
90 function cache_methods:count()
94 local function new(size, on_evict)
95 size = assert(tonumber(size), "cache size must be a number");
96 size = math.floor(size);
97 assert(size > 0, "cache size must be greater than zero");
99 return setmetatable({ _data = data, _count = 0, size = size, _head = nil, _tail = nil, _on_evict = on_evict }, cache_mt);