changeset 20536:532b114a6e02

revset: added generatorset class with cached __contains__ method
author Lucas Moscovicz <lmoscovicz@fb.com>
date Wed, 05 Feb 2014 15:23:11 -0800
parents 4849f574aa24
children c1febc167d87
files mercurial/revset.py
diffstat 1 files changed, 31 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/mercurial/revset.py	Wed Feb 19 12:56:41 2014 -0800
+++ b/mercurial/revset.py	Wed Feb 05 15:23:11 2014 -0800
@@ -2176,6 +2176,37 @@
     def set(self):
         return set([r for r in self])
 
+class generatorset(object):
+    """Wrapper structure for generators that provides lazy membership."""
+    def __init__(self, gen):
+        self._gen = gen
+        self._iter = iter(gen)
+        self._cache = {}
+
+    def __contains__(self, x):
+        if x in self._cache:
+            return self._cache[x]
+
+        while True:
+            try:
+                l = self._iter.next()
+                self._cache[l] = True
+                if l == x:
+                    return True
+            except (StopIteration):
+                break
+
+        self._cache[x] = False
+        return False
+
+    def __iter__(self):
+        for item in self._gen:
+            self._cache[item] = True
+            yield item
+
+    def set(self):
+        return self
+
 class spanset(object):
     """Duck type for baseset class which represents a range of revisions and
     can work lazily and without having all the range in memory