Patchwork [6,of,8] util: add method to peek item in lrucachedict

login
register
mail settings
Submitter Yuya Nishihara
Date Dec. 6, 2018, 12:45 p.m.
Message ID <2d23efc7274a923baffe.1544100313@mimosa>
Download mbox | patch
Permalink /patch/37028/
State Accepted
Headers show

Comments

Yuya Nishihara - Dec. 6, 2018, 12:45 p.m.
# HG changeset patch
# User Yuya Nishihara <yuya@tcha.org>
# Date 1540992545 -32400
#      Wed Oct 31 22:29:05 2018 +0900
# Node ID 2d23efc7274a923baffe9d0dc46709d651c468b4
# Parent  5f4354d1aa370a028eee8bcc6de245b1212cf35c
util: add method to peek item in lrucachedict

I want a function that doesn't unnecessarily update the internal state of
the cache dict after fork().
Pulkit Goyal - Dec. 10, 2018, 1:25 p.m.
On Thu, Dec 6, 2018 at 3:54 PM Yuya Nishihara <yuya@tcha.org> wrote:

> # HG changeset patch
> # User Yuya Nishihara <yuya@tcha.org>
> # Date 1540992545 -32400
> #      Wed Oct 31 22:29:05 2018 +0900
> # Node ID 2d23efc7274a923baffe9d0dc46709d651c468b4
> # Parent  5f4354d1aa370a028eee8bcc6de245b1212cf35c
> util: add method to peek item in lrucachedict
>
> I want a function that doesn't unnecessarily update the internal state of
> the cache dict after fork().


Queued 6,7 too. Many thanks!

Patch

diff --git a/mercurial/util.py b/mercurial/util.py
--- a/mercurial/util.py
+++ b/mercurial/util.py
@@ -1337,6 +1337,20 @@  class lrucachedict(object):
         except KeyError:
             return default
 
+    def peek(self, k, default=_notset):
+        """Get the specified item without moving it to the head
+
+        Unlike get(), this doesn't mutate the internal state. But be aware
+        that it doesn't mean peek() is thread safe.
+        """
+        try:
+            node = self._cache[k]
+            return node.value
+        except KeyError:
+            if default is _notset:
+                raise
+            return default
+
     def clear(self):
         n = self._head
         while n.key is not _notset:
diff --git a/tests/test-lrucachedict.py b/tests/test-lrucachedict.py
--- a/tests/test-lrucachedict.py
+++ b/tests/test-lrucachedict.py
@@ -79,6 +79,21 @@  class testlrucachedict(unittest.TestCase
         self.assertEqual(d.get('a'), 'va')
         self.assertEqual(list(d), ['a', 'c', 'b'])
 
+    def testpeek(self):
+        d = util.lrucachedict(4)
+        d['a'] = 'va'
+        d['b'] = 'vb'
+        d['c'] = 'vc'
+
+        with self.assertRaises(KeyError):
+            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 testcopypartial(self):
         d = util.lrucachedict(4)
         d.insert('a', 'va', cost=4)