1 local cache_methods = {};
2 local cache_mt = { __index = cache_methods };
4 local function new(size)
5 size = assert(tonumber(size), "cache size must be a number");
6 size = math.floor(size);
7 assert(size > 0, "cache size must be greater than zero");
9 return setmetatable({ data = data, count = 0, size = size, head = nil, tail = nil }, cache_mt);
12 local function _remove(list, m)
19 if list.tail == m then
22 if list.head == m then
25 list.count = list.count - 1;
28 local function _insert(list, m)
32 m.prev, m.next = nil, list.head;
37 list.count = list.count + 1;
40 function cache_methods:set(k, v)
41 local m = self.data[k];
45 -- Bump to head of list
60 -- Check whether we need to remove oldest k/v
61 if self.count == self.size then
62 self.data[self.tail.key] = nil;
63 _remove(self, self.tail);
66 m = { key = k, value = v, prev = nil, next = nil };
71 function cache_methods:get(k)
72 local m = self.data[k];
79 function cache_methods:items()
85 local k, v = m.key, m.value;