# HG changeset patch # User Matthew Wild # Date 1458241660 0 # Node ID 42e7545d5ae333e3e74d1e442ff5cdd01af05780 # Parent 867f107409d9d3e3f2c175c7d420a91451e553e0 util.cache: Add head() and tail() methods (and tests) diff -r 867f107409d9 -r 42e7545d5ae3 tests/test_util_cache.lua --- a/tests/test_util_cache.lua Thu Mar 17 18:08:16 2016 +0100 +++ b/tests/test_util_cache.lua Thu Mar 17 19:07:40 2016 +0000 @@ -1,21 +1,44 @@ - function new(new) local c = new(5); + local function expect_kv(key, value, actual_key, actual_value) + assert_equal(key, actual_key, "key incorrect"); + assert_equal(value, actual_value, "value incorrect"); + end + + expect_kv(nil, nil, c:head()); + expect_kv(nil, nil, c:tail()); + assert_equal(c:count(), 0); c:set("one", 1) assert_equal(c:count(), 1); + expect_kv("one", 1, c:head()); + expect_kv("one", 1, c:tail()); + c:set("two", 2) + expect_kv("two", 2, c:head()); + expect_kv("one", 1, c:tail()); + c:set("three", 3) + expect_kv("three", 3, c:head()); + expect_kv("one", 1, c:tail()); + c:set("four", 4) c:set("five", 5); assert_equal(c:count(), 5); + expect_kv("five", 5, c:head()); + expect_kv("one", 1, c:tail()); c:set("foo", nil); assert_equal(c:count(), 5); + expect_kv("five", 5, c:head()); + expect_kv("one", 1, c:tail()); assert_equal(c:get("one"), 1); + expect_kv("five", 5, c:head()); + expect_kv("one", 1, c:tail()); + assert_equal(c:get("two"), 2); assert_equal(c:get("three"), 3); assert_equal(c:get("four"), 4); @@ -26,6 +49,8 @@ c:set("six", 6); assert_equal(c:count(), 5); + expect_kv("six", 6, c:head()); + expect_kv("two", 2, c:tail()); assert_equal(c:get("one"), nil); assert_equal(c:get("two"), 2); diff -r 867f107409d9 -r 42e7545d5ae3 util/cache.lua --- a/util/cache.lua Thu Mar 17 18:08:16 2016 +0100 +++ b/util/cache.lua Thu Mar 17 19:07:40 2016 +0000 @@ -92,6 +92,18 @@ return self._count; end +function cache_methods:head() + local head = self._head; + if not head then return nil, nil; end + return head.key, head.value; +end + +function cache_methods:tail() + local tail = self._tail; + if not tail then return nil, nil; end + return tail.key, tail.value; +end + local function new(size, on_evict) size = assert(tonumber(size), "cache size must be a number"); size = math.floor(size);