blob: 5203f409ac59073d796455d1f43a4ced5be49278 [file] [log] [blame]
Guido van Rossum12d12c51993-10-26 17:58:25 +00001/* Range object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
Thomas Woutersefafcea2001-07-09 12:30:54 +00004
Guido van Rossum12d12c51993-10-26 17:58:25 +00005typedef struct {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00006 PyObject_HEAD
7 long start;
8 long step;
9 long len;
Guido van Rossum12d12c51993-10-26 17:58:25 +000010} rangeobject;
11
Mark Dickinson009ae862009-11-15 12:31:13 +000012/* Return number of items in range (lo, hi, step). step != 0
13 * required. The result always fits in an unsigned long.
Raymond Hettingerc4c453f2002-06-05 23:12:45 +000014 */
Mark Dickinson009ae862009-11-15 12:31:13 +000015static unsigned long
Raymond Hettingerc4c453f2002-06-05 23:12:45 +000016get_len_of_range(long lo, long hi, long step)
17{
Mark Dickinson009ae862009-11-15 12:31:13 +000018 /* -------------------------------------------------------------
19 If step > 0 and lo >= hi, or step < 0 and lo <= hi, the range is empty.
20 Else for step > 0, if n values are in the range, the last one is
21 lo + (n-1)*step, which must be <= hi-1. Rearranging,
22 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
23 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
24 the RHS is non-negative and so truncation is the same as the
25 floor. Letting M be the largest positive long, the worst case
26 for the RHS numerator is hi=M, lo=-M-1, and then
27 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
28 precision to compute the RHS exactly. The analysis for step < 0
29 is similar.
30 ---------------------------------------------------------------*/
31 assert(step != 0);
32 if (step > 0 && lo < hi)
Antoine Pitrouc83ea132010-05-09 14:46:46 +000033 return 1UL + (hi - 1UL - lo) / step;
Mark Dickinson009ae862009-11-15 12:31:13 +000034 else if (step < 0 && lo > hi)
Antoine Pitrouc83ea132010-05-09 14:46:46 +000035 return 1UL + (lo - 1UL - hi) / (0UL - step);
Mark Dickinson009ae862009-11-15 12:31:13 +000036 else
Antoine Pitrouc83ea132010-05-09 14:46:46 +000037 return 0UL;
Raymond Hettingerc4c453f2002-06-05 23:12:45 +000038}
39
Mark Dickinson218a8ab2012-09-28 20:36:36 +010040/* Return a stop value suitable for reconstructing the xrange from
41 * a (start, stop, step) triple. Used in range_repr and range_reduce.
42 * Computes start + len * step, clipped to the range [LONG_MIN, LONG_MAX].
43 */
44static long
45get_stop_for_range(rangeobject *r)
46{
47 long last;
48
49 if (r->len == 0)
50 return r->start;
51
52 /* The tricky bit is avoiding overflow. We first compute the last entry in
53 the xrange, start + (len - 1) * step, which is guaranteed to lie within
54 the range of a long, and then add step to it. See the range_reverse
55 comments for an explanation of the casts below.
56 */
57 last = (long)(r->start + (unsigned long)(r->len - 1) * r->step);
58 if (r->step > 0)
59 return last > LONG_MAX - r->step ? LONG_MAX : last + r->step;
60 else
61 return last < LONG_MIN - r->step ? LONG_MIN : last + r->step;
62}
63
Raymond Hettingerc4c453f2002-06-05 23:12:45 +000064static PyObject *
65range_new(PyTypeObject *type, PyObject *args, PyObject *kw)
66{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000067 rangeobject *obj;
68 long ilow = 0, ihigh = 0, istep = 1;
69 unsigned long n;
Raymond Hettingerc4c453f2002-06-05 23:12:45 +000070
Antoine Pitrouc83ea132010-05-09 14:46:46 +000071 if (!_PyArg_NoKeywords("xrange()", kw))
72 return NULL;
Georg Brandl02c42872005-08-26 06:42:30 +000073
Antoine Pitrouc83ea132010-05-09 14:46:46 +000074 if (PyTuple_Size(args) <= 1) {
75 if (!PyArg_ParseTuple(args,
76 "l;xrange() requires 1-3 int arguments",
77 &ihigh))
78 return NULL;
79 }
80 else {
81 if (!PyArg_ParseTuple(args,
82 "ll|l;xrange() requires 1-3 int arguments",
83 &ilow, &ihigh, &istep))
84 return NULL;
85 }
86 if (istep == 0) {
87 PyErr_SetString(PyExc_ValueError, "xrange() arg 3 must not be zero");
88 return NULL;
89 }
90 n = get_len_of_range(ilow, ihigh, istep);
91 if (n > (unsigned long)LONG_MAX || (long)n > PY_SSIZE_T_MAX) {
92 PyErr_SetString(PyExc_OverflowError,
93 "xrange() result has too many items");
94 return NULL;
95 }
Tim Petersfeec4532004-08-08 07:17:39 +000096
Antoine Pitrouc83ea132010-05-09 14:46:46 +000097 obj = PyObject_New(rangeobject, &PyRange_Type);
98 if (obj == NULL)
99 return NULL;
100 obj->start = ilow;
101 obj->len = (long)n;
102 obj->step = istep;
103 return (PyObject *) obj;
Raymond Hettingerc4c453f2002-06-05 23:12:45 +0000104}
105
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000106PyDoc_STRVAR(range_doc,
Chris Jerdonekad4b0002012-10-07 20:37:54 -0700107"xrange(stop) -> xrange object\n\
108xrange(start, stop[, step]) -> xrange object\n\
Raymond Hettingerc4c453f2002-06-05 23:12:45 +0000109\n\
110Like range(), but instead of returning a list, returns an object that\n\
Raymond Hettingerd2bef822002-12-11 07:14:03 +0000111generates the numbers in the range on demand. For looping, this is \n\
112slightly faster than range() and more memory efficient.");
Raymond Hettingerc4c453f2002-06-05 23:12:45 +0000113
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000114static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000115range_item(rangeobject *r, Py_ssize_t i)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000116{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000117 if (i < 0 || i >= r->len) {
118 PyErr_SetString(PyExc_IndexError,
119 "xrange object index out of range");
120 return NULL;
121 }
122 /* do calculation entirely using unsigned longs, to avoid
123 undefined behaviour due to signed overflow. */
124 return PyInt_FromLong((long)(r->start + (unsigned long)i * r->step));
Guido van Rossum12d12c51993-10-26 17:58:25 +0000125}
126
Martin v. Löwis18e16552006-02-15 17:27:45 +0000127static Py_ssize_t
Fred Drake45cfbcc2000-07-09 06:21:27 +0000128range_length(rangeobject *r)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000129{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000130 return (Py_ssize_t)(r->len);
Guido van Rossum7d6aa511993-12-21 22:50:31 +0000131}
132
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000133static PyObject *
Fred Drake45cfbcc2000-07-09 06:21:27 +0000134range_repr(rangeobject *r)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000135{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000136 PyObject *rtn;
Tim Petersd976ab72004-08-08 06:29:10 +0000137
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000138 if (r->start == 0 && r->step == 1)
139 rtn = PyString_FromFormat("xrange(%ld)",
Mark Dickinson218a8ab2012-09-28 20:36:36 +0100140 get_stop_for_range(r));
Tim Peters72d421b2000-08-04 03:05:40 +0000141
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000142 else if (r->step == 1)
143 rtn = PyString_FromFormat("xrange(%ld, %ld)",
144 r->start,
Mark Dickinson218a8ab2012-09-28 20:36:36 +0100145 get_stop_for_range(r));
Tim Peters72d421b2000-08-04 03:05:40 +0000146
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000147 else
148 rtn = PyString_FromFormat("xrange(%ld, %ld, %ld)",
149 r->start,
Mark Dickinson218a8ab2012-09-28 20:36:36 +0100150 get_stop_for_range(r),
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000151 r->step);
152 return rtn;
Thomas Woutersefafcea2001-07-09 12:30:54 +0000153}
154
Alexandre Vassalotti1f2f61a2008-06-10 03:34:53 +0000155/* Pickling support */
156static PyObject *
Alexandre Vassalotti602d8db2008-06-10 04:01:23 +0000157range_reduce(rangeobject *r, PyObject *args)
Alexandre Vassalotti1f2f61a2008-06-10 03:34:53 +0000158{
Mark Dickinson218a8ab2012-09-28 20:36:36 +0100159 return Py_BuildValue("(O(lll))", Py_TYPE(r),
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000160 r->start,
Mark Dickinson218a8ab2012-09-28 20:36:36 +0100161 get_stop_for_range(r),
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000162 r->step);
Alexandre Vassalotti1f2f61a2008-06-10 03:34:53 +0000163}
164
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000165static PySequenceMethods range_as_sequence = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000166 (lenfunc)range_length, /* sq_length */
167 0, /* sq_concat */
168 0, /* sq_repeat */
169 (ssizeargfunc)range_item, /* sq_item */
170 0, /* sq_slice */
Guido van Rossum12d12c51993-10-26 17:58:25 +0000171};
172
Jeremy Hylton938ace62002-07-17 16:30:39 +0000173static PyObject * range_iter(PyObject *seq);
Raymond Hettinger85c20a42003-11-06 14:06:48 +0000174static PyObject * range_reverse(PyObject *seq);
175
176PyDoc_STRVAR(reverse_doc,
177"Returns a reverse iterator.");
178
179static PyMethodDef range_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000180 {"__reversed__", (PyCFunction)range_reverse, METH_NOARGS, reverse_doc},
181 {"__reduce__", (PyCFunction)range_reduce, METH_VARARGS},
182 {NULL, NULL} /* sentinel */
Raymond Hettinger85c20a42003-11-06 14:06:48 +0000183};
Raymond Hettinger48165d42002-06-05 20:08:48 +0000184
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000185PyTypeObject PyRange_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000186 PyObject_HEAD_INIT(&PyType_Type)
187 0, /* Number of items for varobject */
188 "xrange", /* Name of this type */
189 sizeof(rangeobject), /* Basic object size */
190 0, /* Item size for varobject */
191 (destructor)PyObject_Del, /* tp_dealloc */
192 0, /* tp_print */
193 0, /* tp_getattr */
194 0, /* tp_setattr */
195 0, /* tp_compare */
196 (reprfunc)range_repr, /* tp_repr */
197 0, /* tp_as_number */
198 &range_as_sequence, /* tp_as_sequence */
199 0, /* tp_as_mapping */
200 0, /* tp_hash */
201 0, /* tp_call */
202 0, /* tp_str */
203 PyObject_GenericGetAttr, /* tp_getattro */
204 0, /* tp_setattro */
205 0, /* tp_as_buffer */
206 Py_TPFLAGS_DEFAULT, /* tp_flags */
207 range_doc, /* tp_doc */
208 0, /* tp_traverse */
209 0, /* tp_clear */
210 0, /* tp_richcompare */
211 0, /* tp_weaklistoffset */
212 range_iter, /* tp_iter */
213 0, /* tp_iternext */
214 range_methods, /* tp_methods */
215 0, /* tp_members */
216 0, /* tp_getset */
217 0, /* tp_base */
218 0, /* tp_dict */
219 0, /* tp_descr_get */
220 0, /* tp_descr_set */
221 0, /* tp_dictoffset */
222 0, /* tp_init */
223 0, /* tp_alloc */
224 range_new, /* tp_new */
Guido van Rossum12d12c51993-10-26 17:58:25 +0000225};
Raymond Hettinger48165d42002-06-05 20:08:48 +0000226
227/*********************** Xrange Iterator **************************/
228
229typedef struct {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000230 PyObject_HEAD
231 long index;
232 long start;
233 long step;
234 long len;
Raymond Hettinger48165d42002-06-05 20:08:48 +0000235} rangeiterobject;
236
Raymond Hettinger85c20a42003-11-06 14:06:48 +0000237static PyObject *
Raymond Hettinger48165d42002-06-05 20:08:48 +0000238rangeiter_next(rangeiterobject *r)
239{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000240 if (r->index < r->len)
241 return PyInt_FromLong(r->start + (r->index++) * r->step);
242 return NULL;
Raymond Hettinger48165d42002-06-05 20:08:48 +0000243}
244
Raymond Hettinger6b27cda2005-09-24 21:23:05 +0000245static PyObject *
Raymond Hettingeref9bf402004-03-10 10:10:42 +0000246rangeiter_len(rangeiterobject *r)
247{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000248 return PyInt_FromLong(r->len - r->index);
Raymond Hettingeref9bf402004-03-10 10:10:42 +0000249}
250
Armin Rigof5b3e362006-02-11 21:32:43 +0000251PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettingeref9bf402004-03-10 10:10:42 +0000252
Raymond Hettinger6b27cda2005-09-24 21:23:05 +0000253static PyMethodDef rangeiter_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000254 {"__length_hint__", (PyCFunction)rangeiter_len, METH_NOARGS, length_hint_doc},
255 {NULL, NULL} /* sentinel */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +0000256};
Raymond Hettingeref9bf402004-03-10 10:10:42 +0000257
Neal Norwitz56f46f82002-06-06 14:58:21 +0000258static PyTypeObject Pyrangeiter_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000259 PyObject_HEAD_INIT(&PyType_Type)
260 0, /* ob_size */
261 "rangeiterator", /* tp_name */
262 sizeof(rangeiterobject), /* tp_basicsize */
263 0, /* tp_itemsize */
264 /* methods */
265 (destructor)PyObject_Del, /* tp_dealloc */
266 0, /* tp_print */
267 0, /* tp_getattr */
268 0, /* tp_setattr */
269 0, /* tp_compare */
270 0, /* tp_repr */
271 0, /* tp_as_number */
272 0, /* tp_as_sequence */
273 0, /* tp_as_mapping */
274 0, /* tp_hash */
275 0, /* tp_call */
276 0, /* tp_str */
277 PyObject_GenericGetAttr, /* tp_getattro */
278 0, /* tp_setattro */
279 0, /* tp_as_buffer */
280 Py_TPFLAGS_DEFAULT, /* tp_flags */
281 0, /* tp_doc */
282 0, /* tp_traverse */
283 0, /* tp_clear */
284 0, /* tp_richcompare */
285 0, /* tp_weaklistoffset */
286 PyObject_SelfIter, /* tp_iter */
287 (iternextfunc)rangeiter_next, /* tp_iternext */
288 rangeiter_methods, /* tp_methods */
289 0,
Raymond Hettinger48165d42002-06-05 20:08:48 +0000290};
Martin v. Löwis72d20672006-04-11 09:04:12 +0000291
292static PyObject *
293range_iter(PyObject *seq)
294{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000295 rangeiterobject *it;
Martin v. Löwis72d20672006-04-11 09:04:12 +0000296
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000297 if (!PyRange_Check(seq)) {
298 PyErr_BadInternalCall();
299 return NULL;
300 }
301 it = PyObject_New(rangeiterobject, &Pyrangeiter_Type);
302 if (it == NULL)
303 return NULL;
304 it->index = 0;
305 it->start = ((rangeobject *)seq)->start;
306 it->step = ((rangeobject *)seq)->step;
307 it->len = ((rangeobject *)seq)->len;
308 return (PyObject *)it;
Martin v. Löwis72d20672006-04-11 09:04:12 +0000309}
310
311static PyObject *
312range_reverse(PyObject *seq)
313{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000314 rangeiterobject *it;
315 long start, step, len;
Martin v. Löwis72d20672006-04-11 09:04:12 +0000316
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000317 if (!PyRange_Check(seq)) {
318 PyErr_BadInternalCall();
319 return NULL;
320 }
321 it = PyObject_New(rangeiterobject, &Pyrangeiter_Type);
322 if (it == NULL)
323 return NULL;
Martin v. Löwis72d20672006-04-11 09:04:12 +0000324
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000325 start = ((rangeobject *)seq)->start;
326 step = ((rangeobject *)seq)->step;
327 len = ((rangeobject *)seq)->len;
Martin v. Löwis72d20672006-04-11 09:04:12 +0000328
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000329 it->index = 0;
330 it->len = len;
331 /* the casts below guard against signed overflow by turning it
332 into unsigned overflow instead. The correctness of this
333 code still depends on conversion from unsigned long to long
334 wrapping modulo ULONG_MAX+1, which isn't guaranteed (see
335 C99 6.3.1.3p3) but seems to hold in practice for all
336 platforms we're likely to meet.
Mark Dickinson009ae862009-11-15 12:31:13 +0000337
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000338 If step == LONG_MIN then we still end up with LONG_MIN
339 after negation; but this works out, since we've still got
340 the correct value modulo ULONG_MAX+1, and the range_item
341 calculation is also done modulo ULONG_MAX+1.
342 */
343 it->start = (long)(start + (unsigned long)(len-1) * step);
344 it->step = (long)(0UL-step);
Martin v. Löwis72d20672006-04-11 09:04:12 +0000345
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000346 return (PyObject *)it;
Martin v. Löwis72d20672006-04-11 09:04:12 +0000347}