1.1 --- a/lib/__builtins__/span.py Thu Dec 01 21:23:11 2016 +0100
1.2 +++ b/lib/__builtins__/span.py Thu Dec 01 23:06:26 2016 +0100
1.3 @@ -3,7 +3,7 @@
1.4 """
1.5 Span-related objects.
1.6
1.7 -Copyright (C) 2015 Paul Boddie <paul@boddie.org.uk>
1.8 +Copyright (C) 2015, 2016 Paul Boddie <paul@boddie.org.uk>
1.9
1.10 This program is free software; you can redistribute it and/or modify it under
1.11 the terms of the GNU General Public License as published by the Free Software
1.12 @@ -19,7 +19,9 @@
1.13 this program. If not, see <http://www.gnu.org/licenses/>.
1.14 """
1.15
1.16 -class xrange(object):
1.17 +from __builtins__.sequence import _max, _min
1.18 +
1.19 +class xrange:
1.20
1.21 "Implementation of xrange."
1.22
1.23 @@ -37,8 +39,32 @@
1.24 self.end = end
1.25
1.26 self.step = step
1.27 +
1.28 + # Constrain the end according to the start and step.
1.29 +
1.30 + if step > 0:
1.31 + self.end = _max(self.start, self.end)
1.32 + elif step < 0:
1.33 + self.end = _min(self.start, self.end)
1.34 + else:
1.35 + raise ValueError(self.step)
1.36 +
1.37 self.current = self.start
1.38 - self.limited = self.end is not xrange.NO_END
1.39 +
1.40 + def __str__(self):
1.41 +
1.42 + "Return a string representation."
1.43 +
1.44 + b = buffer([self.__name__, "(", self.start, ", ", self.end, ", ", self.step, ")"])
1.45 + return str(b)
1.46 +
1.47 + __repr__ = __str__
1.48 +
1.49 + def __len__(self):
1.50 +
1.51 + "Return the length of the range."
1.52 +
1.53 + return (self.end - self.start) / self.step
1.54
1.55 def __iter__(self):
1.56
1.57 @@ -50,9 +76,8 @@
1.58
1.59 "Return the next item or raise a StopIteration exception."
1.60
1.61 - if self.limited:
1.62 - if self.step < 0 and self.current <= self.end or self.step > 0 and self.current >= self.end:
1.63 - raise StopIteration()
1.64 + if self.step < 0 and self.current <= self.end or self.step > 0 and self.current >= self.end:
1.65 + raise StopIteration()
1.66
1.67 current = self.current
1.68 self.current += self.step
1.69 @@ -68,4 +93,10 @@
1.70
1.71 get_using(xrange.__init__, self)(start_or_end, end, step)
1.72
1.73 +def range(start_or_end, end=None, step=1):
1.74 +
1.75 + "Implementation of range."
1.76 +
1.77 + return list(xrange(start_or_end, end, step))
1.78 +
1.79 # vim: tabstop=4 expandtab shiftwidth=4