sqlmap/lib/utils/xrange.py

80 lines
2.3 KiB
Python
Raw Normal View History

2013-01-14 19:21:40 +04:00
#!/usr/bin/env python
"""
2013-01-18 18:07:51 +04:00
Copyright (c) 2006-2013 sqlmap developers (http://sqlmap.org/)
2013-01-14 19:21:40 +04:00
See the file 'doc/COPYING' for copying permission
"""
2013-01-14 19:18:03 +04:00
class xrange(object):
"""
2013-01-14 19:24:55 +04:00
Advanced (re)implementation of xrange (supports slice/copy/etc.)
2013-01-14 19:18:03 +04:00
Reference: http://code.activestate.com/recipes/521885-a-pythonic-implementation-of-xrange/
"""
__slots__ = ['_slice']
def __init__(self, *args):
2013-01-14 19:24:28 +04:00
if args and isinstance(args[0], type(self)):
2013-01-14 19:18:03 +04:00
self._slice = slice(args[0].start, args[0].stop, args[0].step)
else:
self._slice = slice(*args)
if self._slice.stop is None:
raise TypeError("xrange stop must not be None")
@property
def start(self):
if self._slice.start is not None:
return self._slice.start
return 0
@property
def stop(self):
return self._slice.stop
@property
def step(self):
if self._slice.step is not None:
return self._slice.step
return 1
def __hash__(self):
return hash(self._slice)
def __cmp__(self, other):
return (cmp(type(self), type(other)) or
cmp(self._slice, other._slice))
def __repr__(self):
2013-01-14 19:27:50 +04:00
return '%s(%r, %r, %r)' % (type(self).__name__,
2013-01-14 19:18:03 +04:00
self.start, self.stop, self.step)
def __len__(self):
return self._len()
def _len(self):
2013-01-14 19:21:40 +04:00
return max(0, int((self.stop - self.start) / self.step))
2013-01-14 19:18:03 +04:00
def __contains__(self, value):
return (self.start <= value < self.stop) and (value - self.start) % self.step == 0
2013-01-14 19:18:03 +04:00
def __getitem__(self, index):
if isinstance(index, slice):
start, stop, step = index.indices(self._len())
return xrange(self._index(start),
self._index(stop), step*self.step)
elif isinstance(index, (int, long)):
if index < 0:
fixed_index = index + self._len()
else:
fixed_index = index
if not 0 <= fixed_index < self._len():
raise IndexError("Index %d out of %r" % (index, self))
return self._index(fixed_index)
else:
raise TypeError("xrange indices must be slices or integers")
def _index(self, i):
return self.start + self.step * i