util: implement pop() on lrucachedict
authorYuya Nishihara <yuya@tcha.org>
Sun, 04 Nov 2018 16:57:05 +0900
changeset 53646 7cda0cacbbf653c58a60b77828526122836b5ad7
parent 53645 0c638ff69f5c10bddf1b795c08dc5a6dd4f3ad66
child 53647 8695fbe17f7cbe5187b72b48f01984ce8cada594
push id1079
push usergszorc@mozilla.com
push dateMon, 10 Dec 2018 19:44:59 +0000
util: implement pop() on lrucachedict This moves __delitem__() to pop() as the requirement is pretty much the same, and reimplement __delitem__() by using pop().
mercurial/util.py
tests/test-lrucachedict.py
--- a/mercurial/util.py
+++ b/mercurial/util.py
@@ -1315,25 +1315,36 @@ class lrucachedict(object):
 
         if self.maxcost:
             self._enforcecostlimit()
 
     def __setitem__(self, k, v):
         self.insert(k, v)
 
     def __delitem__(self, k):
-        node = self._cache.pop(k)
+        self.pop(k)
+
+    def pop(self, k, default=_notset):
+        try:
+            node = self._cache.pop(k)
+        except KeyError:
+            if default is _notset:
+                raise
+            return default
+        value = node.value
         self.totalcost -= node.cost
         node.markempty()
 
         # Temporarily mark as newest item before re-adjusting head to make
         # this node the oldest item.
         self._movetohead(node)
         self._head = node.next
 
+        return value
+
     # Additional dict methods.
 
     def get(self, k, default=None):
         try:
             return self.__getitem__(k)
         except KeyError:
             return default
 
--- a/tests/test-lrucachedict.py
+++ b/tests/test-lrucachedict.py
@@ -89,16 +89,31 @@ class testlrucachedict(unittest.TestCase
             d.peek('missing')
         self.assertEqual(list(d), ['c', 'b', 'a'])
         self.assertIsNone(d.peek('missing', None))
         self.assertEqual(list(d), ['c', 'b', 'a'])
 
         self.assertEqual(d.peek('a'), 'va')
         self.assertEqual(list(d), ['c', 'b', 'a'])
 
+    def testpop(self):
+        d = util.lrucachedict(4)
+        d['a'] = 'va'
+        d['b'] = 'vb'
+        d['c'] = 'vc'
+
+        with self.assertRaises(KeyError):
+            d.pop('missing')
+        self.assertEqual(list(d), ['c', 'b', 'a'])
+        self.assertIsNone(d.pop('missing', None))
+        self.assertEqual(list(d), ['c', 'b', 'a'])
+
+        self.assertEqual(d.pop('b'), 'vb')
+        self.assertEqual(list(d), ['c', 'a'])
+
     def testcopypartial(self):
         d = util.lrucachedict(4)
         d.insert('a', 'va', cost=4)
         d.insert('b', 'vb', cost=2)
 
         dc = d.copy()
 
         self.assertEqual(len(dc), 2)