diff mercurial/smartset.py @ 32819:4710cc4dac99

smartset: extract method to slice abstractsmartset Sub classes can provide optimized implementations.
author Yuya Nishihara <yuya@tcha.org>
date Tue, 24 Mar 2015 00:14:53 +0900
parents 9ddb18ae342e
children 653d60455dbe
line wrap: on
line diff
--- a/mercurial/smartset.py	Sun May 24 11:07:14 2015 +0900
+++ b/mercurial/smartset.py	Tue Mar 24 00:14:53 2015 +0900
@@ -8,6 +8,7 @@
 from __future__ import absolute_import
 
 from . import (
+    error,
     util,
 )
 
@@ -155,6 +156,28 @@
             condition = util.cachefunc(condition)
         return filteredset(self, condition, condrepr)
 
+    def slice(self, start, stop):
+        """Return new smartset that contains selected elements from this set"""
+        if start < 0 or stop < 0:
+            raise error.ProgrammingError('negative index not allowed')
+        return self._slice(start, stop)
+
+    def _slice(self, start, stop):
+        # sub classes may override this. start and stop must not be negative,
+        # but start > stop is allowed, which should be an empty set.
+        ys = []
+        it = iter(self)
+        for x in xrange(start):
+            y = next(it, None)
+            if y is None:
+                break
+        for x in xrange(stop - start):
+            y = next(it, None)
+            if y is None:
+                break
+            ys.append(y)
+        return baseset(ys, datarepr=('slice=%d:%d %r', start, stop, self))
+
 class baseset(abstractsmartset):
     """Basic data structure that represents a revset and contains the basic
     operation that it should be able to perform.