blob: 3a08ccd0f8e70e618c12306330d059bf0796ada3 [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 Rossum805365e2007-05-07 22:24:25 +00005/* Support objects whose length is > PY_SSIZE_T_MAX.
6
7 This could be sped up for small PyLongs if they fit in an Py_ssize_t.
8 This only matters on Win64. Though we could use PY_LONG_LONG which
9 would presumably help perf.
10*/
11
Guido van Rossum12d12c51993-10-26 17:58:25 +000012typedef struct {
Guido van Rossum805365e2007-05-07 22:24:25 +000013 PyObject_HEAD
14 PyObject *start;
15 PyObject *stop;
16 PyObject *step;
Guido van Rossum12d12c51993-10-26 17:58:25 +000017} rangeobject;
18
Guido van Rossum805365e2007-05-07 22:24:25 +000019/* Helper function for validating step. Always returns a new reference or
20 NULL on error.
21*/
22static PyObject *
23validate_step(PyObject *step)
Raymond Hettingerc4c453f2002-06-05 23:12:45 +000024{
Guido van Rossum805365e2007-05-07 22:24:25 +000025 /* No step specified, use a step of 1. */
26 if (!step)
27 return PyInt_FromLong(1);
28
29 step = PyNumber_Index(step);
30 if (step) {
31 Py_ssize_t istep = PyNumber_AsSsize_t(step, NULL);
32 if (istep == -1 && PyErr_Occurred()) {
33 /* Ignore OverflowError, we know the value isn't 0. */
34 PyErr_Clear();
35 }
36 else if (istep == 0) {
37 PyErr_SetString(PyExc_ValueError,
38 "range() arg 3 must not be zero");
39 Py_CLEAR(step);
40 }
41 }
42
43 return step;
Raymond Hettingerc4c453f2002-06-05 23:12:45 +000044}
45
Guido van Rossum805365e2007-05-07 22:24:25 +000046/* XXX(nnorwitz): should we error check if the user passes any empty ranges?
47 range(-10)
48 range(0, -5)
49 range(0, 5, -1)
50*/
Raymond Hettingerc4c453f2002-06-05 23:12:45 +000051static PyObject *
52range_new(PyTypeObject *type, PyObject *args, PyObject *kw)
53{
Guido van Rossum805365e2007-05-07 22:24:25 +000054 rangeobject *obj = NULL;
55 PyObject *start = NULL, *stop = NULL, *step = NULL;
Raymond Hettingerc4c453f2002-06-05 23:12:45 +000056
Guido van Rossum805365e2007-05-07 22:24:25 +000057 if (!_PyArg_NoKeywords("range()", kw))
58 return NULL;
Georg Brandl02c42872005-08-26 06:42:30 +000059
Guido van Rossum805365e2007-05-07 22:24:25 +000060 if (PyTuple_Size(args) <= 1) {
61 if (!PyArg_UnpackTuple(args, "range", 1, 1, &stop))
62 goto Fail;
63 stop = PyNumber_Index(stop);
64 if (!stop)
65 goto Fail;
66 start = PyInt_FromLong(0);
67 step = PyInt_FromLong(1);
68 if (!start || !step)
69 goto Fail;
70 }
71 else {
72 if (!PyArg_UnpackTuple(args, "range", 2, 3,
73 &start, &stop, &step))
74 goto Fail;
Tim Petersfeec4532004-08-08 07:17:39 +000075
Guido van Rossum805365e2007-05-07 22:24:25 +000076 /* Convert borrowed refs to owned refs */
77 start = PyNumber_Index(start);
78 stop = PyNumber_Index(stop);
79 step = validate_step(step);
80 if (!start || !stop || !step)
81 goto Fail;
82 }
83
84 obj = PyObject_New(rangeobject, &PyRange_Type);
85 if (obj == NULL)
86 goto Fail;
87 obj->start = start;
88 obj->stop = stop;
89 obj->step = step;
90 return (PyObject *) obj;
91
92Fail:
93 Py_XDECREF(start);
94 Py_XDECREF(stop);
95 Py_XDECREF(step);
96 return NULL;
Raymond Hettingerc4c453f2002-06-05 23:12:45 +000097}
98
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000099PyDoc_STRVAR(range_doc,
Guido van Rossum805365e2007-05-07 22:24:25 +0000100"range([start,] stop[, step]) -> range object\n\
Raymond Hettingerc4c453f2002-06-05 23:12:45 +0000101\n\
Guido van Rossum805365e2007-05-07 22:24:25 +0000102Returns an iterator that generates the numbers in the range on demand.");
Raymond Hettingerc4c453f2002-06-05 23:12:45 +0000103
Guido van Rossum805365e2007-05-07 22:24:25 +0000104static void
105range_dealloc(rangeobject *r)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000106{
Guido van Rossum805365e2007-05-07 22:24:25 +0000107 Py_DECREF(r->start);
108 Py_DECREF(r->stop);
109 Py_DECREF(r->step);
110}
111
112/* Return number of items in range (lo, hi, step), when arguments are
113 * PyInt or PyLong objects. step > 0 required. Return a value < 0 if
114 * & only if the true value is too large to fit in a signed long.
115 * Arguments MUST return 1 with either PyInt_Check() or
116 * PyLong_Check(). Return -1 when there is an error.
117 */
118static PyObject*
119range_length_obj(rangeobject *r)
120{
121 /* -------------------------------------------------------------
122 Algorithm is equal to that of get_len_of_range(), but it operates
123 on PyObjects (which are assumed to be PyLong or PyInt objects).
124 ---------------------------------------------------------------*/
125 int cmp_result, cmp_call;
126 PyObject *lo, *hi;
127 PyObject *step = NULL;
128 PyObject *diff = NULL;
129 PyObject *one = NULL;
130 PyObject *tmp1 = NULL, *tmp2 = NULL, *result;
131 /* holds sub-expression evaluations */
132
133 PyObject *zero = PyLong_FromLong(0);
134 if (zero == NULL)
135 return NULL;
136 cmp_call = PyObject_Cmp(r->step, zero, &cmp_result);
137 Py_DECREF(zero);
138 if (cmp_call == -1)
139 return NULL;
140
141 assert(cmp_result != 0);
142 if (cmp_result > 0) {
143 lo = r->start;
144 hi = r->stop;
145 step = r->step;
146 Py_INCREF(step);
147 } else {
148 lo = r->stop;
149 hi = r->start;
150 step = PyNumber_Negative(r->step);
151 if (!step)
152 return NULL;
153 }
154
155 /* if (lo >= hi), return length of 0. */
156 if (PyObject_Compare(lo, hi) >= 0) {
157 Py_XDECREF(step);
158 return PyLong_FromLong(0);
159 }
160
161 if ((one = PyLong_FromLong(1L)) == NULL)
162 goto Fail;
163
164 if ((tmp1 = PyNumber_Subtract(hi, lo)) == NULL)
165 goto Fail;
166
167 if ((diff = PyNumber_Subtract(tmp1, one)) == NULL)
168 goto Fail;
169
170 if ((tmp2 = PyNumber_FloorDivide(diff, step)) == NULL)
171 goto Fail;
172
173 if ((result = PyNumber_Add(tmp2, one)) == NULL)
174 goto Fail;
175
176 Py_DECREF(tmp2);
177 Py_DECREF(diff);
178 Py_DECREF(step);
179 Py_DECREF(tmp1);
180 Py_DECREF(one);
181 return result;
182
183 Fail:
184 Py_XDECREF(tmp2);
185 Py_XDECREF(diff);
186 Py_XDECREF(step);
187 Py_XDECREF(tmp1);
188 Py_XDECREF(one);
189 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000190}
191
Martin v. Löwis18e16552006-02-15 17:27:45 +0000192static Py_ssize_t
Fred Drake45cfbcc2000-07-09 06:21:27 +0000193range_length(rangeobject *r)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000194{
Guido van Rossum805365e2007-05-07 22:24:25 +0000195 PyObject *len = range_length_obj(r);
196 Py_ssize_t result = -1;
197 if (len) {
198 result = PyLong_AsSsize_t(len);
199 Py_DECREF(len);
200 }
201 return result;
202}
203
204/* range(...)[x] is necessary for: seq[:] = range(...) */
205
206static PyObject *
207range_item(rangeobject *r, Py_ssize_t i)
208{
209 Py_ssize_t len = range_length(r);
210 PyObject *rem, *incr, *result;
211
212 /* XXX(nnorwitz): should negative indices be supported? */
213 /* XXX(nnorwitz): should support range[x] where x > PY_SSIZE_T_MAX? */
214 if (i < 0 || i >= len) {
215 if (!PyErr_Occurred())
216 PyErr_SetString(PyExc_IndexError,
Walter Dörwald4ad94212007-05-21 18:01:17 +0000217 "range object index out of range");
Guido van Rossum805365e2007-05-07 22:24:25 +0000218 return NULL;
219 }
220
221 /* XXX(nnorwitz): optimize for short ints. */
222 rem = PyLong_FromSsize_t(i % len);
223 if (!rem)
224 return NULL;
225 incr = PyNumber_Multiply(rem, r->step);
226 Py_DECREF(rem);
227 if (!incr)
228 return NULL;
229 result = PyNumber_Add(r->start, incr);
230 Py_DECREF(incr);
231 return result;
Guido van Rossum7d6aa511993-12-21 22:50:31 +0000232}
233
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000234static PyObject *
Fred Drake45cfbcc2000-07-09 06:21:27 +0000235range_repr(rangeobject *r)
Guido van Rossum12d12c51993-10-26 17:58:25 +0000236{
Walter Dörwald03b43d82007-05-21 10:43:34 +0000237 Py_ssize_t istep;
Tim Petersd976ab72004-08-08 06:29:10 +0000238
Guido van Rossum805365e2007-05-07 22:24:25 +0000239 /* Check for special case values for printing. We don't always
Walter Dörwald03b43d82007-05-21 10:43:34 +0000240 need the step value. We don't care about errors
Guido van Rossum805365e2007-05-07 22:24:25 +0000241 (it means overflow), so clear the errors. */
Guido van Rossum805365e2007-05-07 22:24:25 +0000242 istep = PyNumber_AsSsize_t(r->step, NULL);
243 if (istep != 1 || (istep == -1 && PyErr_Occurred())) {
244 PyErr_Clear();
Guido van Rossum805365e2007-05-07 22:24:25 +0000245 }
246
Walter Dörwald03b43d82007-05-21 10:43:34 +0000247 if (istep == 1)
Walter Dörwald850e5162007-05-20 08:19:54 +0000248 return PyUnicode_FromFormat("range(%R, %R)", r->start, r->stop);
249 else
250 return PyUnicode_FromFormat("range(%R, %R, %R)",
251 r->start, r->stop, r->step);
Thomas Woutersefafcea2001-07-09 12:30:54 +0000252}
253
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000254static PySequenceMethods range_as_sequence = {
Guido van Rossum805365e2007-05-07 22:24:25 +0000255 (lenfunc)range_length, /* sq_length */
256 0, /* sq_concat */
257 0, /* sq_repeat */
258 (ssizeargfunc)range_item, /* sq_item */
259 0, /* sq_slice */
Guido van Rossum12d12c51993-10-26 17:58:25 +0000260};
261
Jeremy Hylton938ace62002-07-17 16:30:39 +0000262static PyObject * range_iter(PyObject *seq);
Raymond Hettinger85c20a42003-11-06 14:06:48 +0000263static PyObject * range_reverse(PyObject *seq);
264
265PyDoc_STRVAR(reverse_doc,
266"Returns a reverse iterator.");
267
268static PyMethodDef range_methods[] = {
Guido van Rossum805365e2007-05-07 22:24:25 +0000269 {"__reversed__", (PyCFunction)range_reverse, METH_NOARGS,
270 reverse_doc},
271 {NULL, NULL} /* sentinel */
Raymond Hettinger85c20a42003-11-06 14:06:48 +0000272};
Raymond Hettinger48165d42002-06-05 20:08:48 +0000273
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000274PyTypeObject PyRange_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000275 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum805365e2007-05-07 22:24:25 +0000276 "range", /* Name of this type */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000277 sizeof(rangeobject), /* Basic object size */
278 0, /* Item size for varobject */
Guido van Rossum805365e2007-05-07 22:24:25 +0000279 (destructor)range_dealloc, /* tp_dealloc */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000280 0, /* tp_print */
281 0, /* tp_getattr */
282 0, /* tp_setattr */
283 0, /* tp_compare */
284 (reprfunc)range_repr, /* tp_repr */
285 0, /* tp_as_number */
286 &range_as_sequence, /* tp_as_sequence */
287 0, /* tp_as_mapping */
288 0, /* tp_hash */
289 0, /* tp_call */
290 0, /* tp_str */
291 PyObject_GenericGetAttr, /* tp_getattro */
292 0, /* tp_setattro */
293 0, /* tp_as_buffer */
294 Py_TPFLAGS_DEFAULT, /* tp_flags */
295 range_doc, /* tp_doc */
296 0, /* tp_traverse */
297 0, /* tp_clear */
298 0, /* tp_richcompare */
299 0, /* tp_weaklistoffset */
300 range_iter, /* tp_iter */
301 0, /* tp_iternext */
302 range_methods, /* tp_methods */
303 0, /* tp_members */
304 0, /* tp_getset */
305 0, /* tp_base */
306 0, /* tp_dict */
307 0, /* tp_descr_get */
308 0, /* tp_descr_set */
309 0, /* tp_dictoffset */
310 0, /* tp_init */
311 0, /* tp_alloc */
312 range_new, /* tp_new */
Guido van Rossum12d12c51993-10-26 17:58:25 +0000313};
Raymond Hettinger48165d42002-06-05 20:08:48 +0000314
Walter Dörwald4ad94212007-05-21 18:01:17 +0000315/*********************** range Iterator **************************/
Raymond Hettinger48165d42002-06-05 20:08:48 +0000316
Guido van Rossum805365e2007-05-07 22:24:25 +0000317/* There are 2 types of iterators, one for C longs, the other for
318 Python longs (ie, PyObjects). This should make iteration fast
319 in the normal case, but possible for any numeric value.
320*/
321
Raymond Hettinger48165d42002-06-05 20:08:48 +0000322typedef struct {
323 PyObject_HEAD
324 long index;
325 long start;
326 long step;
327 long len;
328} rangeiterobject;
329
Raymond Hettinger85c20a42003-11-06 14:06:48 +0000330static PyObject *
Raymond Hettinger48165d42002-06-05 20:08:48 +0000331rangeiter_next(rangeiterobject *r)
332{
Guido van Rossum805365e2007-05-07 22:24:25 +0000333 if (r->index < r->len)
334 return PyInt_FromLong(r->start + (r->index++) * r->step);
335 return NULL;
Raymond Hettinger48165d42002-06-05 20:08:48 +0000336}
337
Raymond Hettinger6b27cda2005-09-24 21:23:05 +0000338static PyObject *
Raymond Hettingeref9bf402004-03-10 10:10:42 +0000339rangeiter_len(rangeiterobject *r)
340{
Guido van Rossum805365e2007-05-07 22:24:25 +0000341 return PyInt_FromLong(r->len - r->index);
Raymond Hettingeref9bf402004-03-10 10:10:42 +0000342}
343
Guido van Rossum805365e2007-05-07 22:24:25 +0000344typedef struct {
345 PyObject_HEAD
346 PyObject *index;
347 PyObject *start;
348 PyObject *step;
349 PyObject *len;
350} longrangeiterobject;
351
352static PyObject *
353longrangeiter_len(longrangeiterobject *r, PyObject *no_args)
354{
355 return PyNumber_Subtract(r->len, r->index);
356}
Guido van Rossum317e7742007-05-08 15:18:31 +0000357
Guido van Rossum805365e2007-05-07 22:24:25 +0000358static PyObject *rangeiter_new(PyTypeObject *, PyObject *args, PyObject *kw);
359
360PyDoc_STRVAR(length_hint_doc,
361 "Private method returning an estimate of len(list(it)).");
Raymond Hettingeref9bf402004-03-10 10:10:42 +0000362
Raymond Hettinger6b27cda2005-09-24 21:23:05 +0000363static PyMethodDef rangeiter_methods[] = {
Guido van Rossum805365e2007-05-07 22:24:25 +0000364 {"__length_hint__", (PyCFunction)rangeiter_len, METH_NOARGS,
365 length_hint_doc},
366 {NULL, NULL} /* sentinel */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +0000367};
Raymond Hettingeref9bf402004-03-10 10:10:42 +0000368
Guido van Rossum805365e2007-05-07 22:24:25 +0000369PyTypeObject Pyrangeiter_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000370 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Neal Norwitz56f46f82002-06-06 14:58:21 +0000371 "rangeiterator", /* tp_name */
372 sizeof(rangeiterobject), /* tp_basicsize */
Raymond Hettinger48165d42002-06-05 20:08:48 +0000373 0, /* tp_itemsize */
374 /* methods */
375 (destructor)PyObject_Del, /* tp_dealloc */
376 0, /* tp_print */
377 0, /* tp_getattr */
378 0, /* tp_setattr */
379 0, /* tp_compare */
380 0, /* tp_repr */
381 0, /* tp_as_number */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +0000382 0, /* tp_as_sequence */
Raymond Hettinger48165d42002-06-05 20:08:48 +0000383 0, /* tp_as_mapping */
384 0, /* tp_hash */
385 0, /* tp_call */
386 0, /* tp_str */
387 PyObject_GenericGetAttr, /* tp_getattro */
388 0, /* tp_setattro */
389 0, /* tp_as_buffer */
390 Py_TPFLAGS_DEFAULT, /* tp_flags */
391 0, /* tp_doc */
392 0, /* tp_traverse */
393 0, /* tp_clear */
394 0, /* tp_richcompare */
395 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +0000396 PyObject_SelfIter, /* tp_iter */
Raymond Hettinger48165d42002-06-05 20:08:48 +0000397 (iternextfunc)rangeiter_next, /* tp_iternext */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +0000398 rangeiter_methods, /* tp_methods */
Guido van Rossum805365e2007-05-07 22:24:25 +0000399 0, /* tp_members */
400 0, /* tp_getset */
401 0, /* tp_base */
402 0, /* tp_dict */
403 0, /* tp_descr_get */
404 0, /* tp_descr_set */
405 0, /* tp_dictoffset */
406 0, /* tp_init */
407 0, /* tp_alloc */
408 rangeiter_new, /* tp_new */
409};
410
411/* Return number of items in range/xrange (lo, hi, step). step > 0
412 * required. Return a value < 0 if & only if the true value is too
413 * large to fit in a signed long.
414 */
415static long
416get_len_of_range(long lo, long hi, long step)
417{
418 /* -------------------------------------------------------------
419 If lo >= hi, the range is empty.
420 Else if n values are in the range, the last one is
421 lo + (n-1)*step, which must be <= hi-1. Rearranging,
422 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
423 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
424 the RHS is non-negative and so truncation is the same as the
425 floor. Letting M be the largest positive long, the worst case
426 for the RHS numerator is hi=M, lo=-M-1, and then
427 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
428 precision to compute the RHS exactly.
429 ---------------------------------------------------------------*/
430 long n = 0;
431 if (lo < hi) {
432 unsigned long uhi = (unsigned long)hi;
433 unsigned long ulo = (unsigned long)lo;
434 unsigned long diff = uhi - ulo - 1;
435 n = (long)(diff / (unsigned long)step + 1);
436 }
437 return n;
438}
439
440static PyObject *
441int_range_iter(long start, long stop, long step)
442{
443 rangeiterobject *it = PyObject_New(rangeiterobject, &Pyrangeiter_Type);
444 if (it == NULL)
445 return NULL;
446 it->start = start;
447 it->step = step;
448 if (step > 0)
449 it->len = get_len_of_range(start, stop, step);
450 else
451 it->len = get_len_of_range(stop, start, -step);
452 it->index = 0;
453 return (PyObject *)it;
454}
455
456static PyObject *
457rangeiter_new(PyTypeObject *type, PyObject *args, PyObject *kw)
458{
459 long start, stop, step;
460
461 if (!_PyArg_NoKeywords("rangeiter()", kw))
462 return NULL;
463
464 if (!PyArg_ParseTuple(args, "lll;rangeiter() requires 3 int arguments",
465 &start, &stop, &step))
466 return NULL;
467
468 return int_range_iter(start, stop, step);
469}
470
471static PyMethodDef longrangeiter_methods[] = {
472 {"__length_hint__", (PyCFunction)longrangeiter_len, METH_NOARGS,
473 length_hint_doc},
474 {NULL, NULL} /* sentinel */
475};
476
477static void
478longrangeiter_dealloc(longrangeiterobject *r)
479{
480 Py_XDECREF(r->index);
Guido van Rossum317e7742007-05-08 15:18:31 +0000481 Py_XDECREF(r->start);
482 Py_XDECREF(r->step);
483 Py_XDECREF(r->len);
Guido van Rossum805365e2007-05-07 22:24:25 +0000484}
485
486static PyObject *
487longrangeiter_next(longrangeiterobject *r)
488{
489 PyObject *one, *product, *new_index, *result;
490 if (PyObject_RichCompareBool(r->index, r->len, Py_LT) != 1)
491 return NULL;
492
493 one = PyLong_FromLong(1);
494 if (!one)
495 return NULL;
496
497 product = PyNumber_Multiply(r->index, r->step);
498 if (!product) {
499 Py_DECREF(one);
500 return NULL;
501 }
502
503 new_index = PyNumber_Add(r->index, one);
504 Py_DECREF(one);
505 if (!new_index) {
506 Py_DECREF(product);
507 return NULL;
508 }
509
510 result = PyNumber_Add(r->start, product);
511 Py_DECREF(product);
512 if (result) {
513 Py_DECREF(r->index);
514 r->index = new_index;
515 }
516
517 return result;
518}
519
520static PyTypeObject Pylongrangeiter_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000521 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum805365e2007-05-07 22:24:25 +0000522 "rangeiterator", /* tp_name */
523 sizeof(longrangeiterobject), /* tp_basicsize */
524 0, /* tp_itemsize */
525 /* methods */
526 (destructor)longrangeiter_dealloc, /* tp_dealloc */
527 0, /* tp_print */
528 0, /* tp_getattr */
529 0, /* tp_setattr */
530 0, /* tp_compare */
531 0, /* tp_repr */
532 0, /* tp_as_number */
533 0, /* tp_as_sequence */
534 0, /* tp_as_mapping */
535 0, /* tp_hash */
536 0, /* tp_call */
537 0, /* tp_str */
538 PyObject_GenericGetAttr, /* tp_getattro */
539 0, /* tp_setattro */
540 0, /* tp_as_buffer */
541 Py_TPFLAGS_DEFAULT, /* tp_flags */
542 0, /* tp_doc */
543 0, /* tp_traverse */
544 0, /* tp_clear */
545 0, /* tp_richcompare */
546 0, /* tp_weaklistoffset */
547 PyObject_SelfIter, /* tp_iter */
548 (iternextfunc)longrangeiter_next, /* tp_iternext */
549 longrangeiter_methods, /* tp_methods */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +0000550 0,
Raymond Hettinger48165d42002-06-05 20:08:48 +0000551};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000552
553static PyObject *
554range_iter(PyObject *seq)
555{
Guido van Rossum805365e2007-05-07 22:24:25 +0000556 rangeobject *r = (rangeobject *)seq;
557 longrangeiterobject *it;
558 PyObject *tmp, *len;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000559
Guido van Rossum805365e2007-05-07 22:24:25 +0000560 assert(PyRange_Check(seq));
561 if (_PyLong_FitsInLong(r->start) &&
562 _PyLong_FitsInLong(r->stop) &&
563 _PyLong_FitsInLong(r->step))
564 return int_range_iter(PyLong_AsLong(r->start),
565 PyLong_AsLong(r->stop),
566 PyLong_AsLong(r->step));
567
568 it = PyObject_New(longrangeiterobject, &Pylongrangeiter_Type);
569 if (it == NULL)
570 return NULL;
Guido van Rossum317e7742007-05-08 15:18:31 +0000571
572 /* Do all initialization here, so we can DECREF on failure. */
Guido van Rossum805365e2007-05-07 22:24:25 +0000573 it->start = r->start;
Guido van Rossum317e7742007-05-08 15:18:31 +0000574 it->step = r->step;
575 Py_INCREF(it->start);
576 Py_INCREF(it->step);
577
578 it->len = it->index = NULL;
579
Guido van Rossum805365e2007-05-07 22:24:25 +0000580 /* Calculate length: (r->stop - r->start) / r->step */
581 tmp = PyNumber_Subtract(r->stop, r->start);
582 if (!tmp)
583 goto create_failure;
584 len = PyNumber_FloorDivide(tmp, r->step);
585 Py_DECREF(tmp);
586 if (!len)
587 goto create_failure;
588 it->len = len;
Guido van Rossum805365e2007-05-07 22:24:25 +0000589 it->index = PyLong_FromLong(0);
590 if (!it->index)
591 goto create_failure;
592
Guido van Rossum805365e2007-05-07 22:24:25 +0000593 return (PyObject *)it;
594
595create_failure:
Guido van Rossum317e7742007-05-08 15:18:31 +0000596 Py_DECREF(it);
Guido van Rossum805365e2007-05-07 22:24:25 +0000597 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000598}
599
600static PyObject *
601range_reverse(PyObject *seq)
602{
Guido van Rossum805365e2007-05-07 22:24:25 +0000603 rangeobject *range = (rangeobject*) seq;
604 longrangeiterobject *it;
605 PyObject *one, *sum, *diff, *len = NULL, *product;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000606
Guido van Rossum805365e2007-05-07 22:24:25 +0000607 /* XXX(nnorwitz): do the calc for the new start/stop first,
608 then if they fit, call the proper iter()?
609 */
610 assert(PyRange_Check(seq));
611 if (_PyLong_FitsInLong(range->start) &&
612 _PyLong_FitsInLong(range->stop) &&
613 _PyLong_FitsInLong(range->step)) {
614 long start = PyLong_AsLong(range->start);
615 long step = PyLong_AsLong(range->step);
616 long stop = PyLong_AsLong(range->stop);
617 /* XXX(nnorwitz): need to check for overflow and simplify. */
618 long len = get_len_of_range(start, stop, step);
619 long new_start = start + (len - 1) * step;
620 long new_stop = start;
621 if (step > 0)
622 new_stop -= 1;
623 else
624 new_stop += 1;
625 return int_range_iter(new_start, new_stop, -step);
626 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000627
Guido van Rossum805365e2007-05-07 22:24:25 +0000628 it = PyObject_New(longrangeiterobject, &Pylongrangeiter_Type);
629 if (it == NULL)
630 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000631
Guido van Rossum805365e2007-05-07 22:24:25 +0000632 /* start + (len - 1) * step */
633 len = range_length_obj(range);
634 if (!len)
635 goto create_failure;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000636
Guido van Rossum805365e2007-05-07 22:24:25 +0000637 one = PyLong_FromLong(1);
638 if (!one)
639 goto create_failure;
640
641 diff = PyNumber_Subtract(len, one);
642 Py_DECREF(one);
643 if (!diff)
644 goto create_failure;
645
646 product = PyNumber_Multiply(len, range->step);
647 if (!product)
648 goto create_failure;
649
650 sum = PyNumber_Add(range->start, product);
651 Py_DECREF(product);
652 it->start = sum;
653 if (!it->start)
654 goto create_failure;
655 it->step = PyNumber_Negative(range->step);
656 if (!it->step) {
657 Py_DECREF(it->start);
658 PyObject_Del(it);
659 return NULL;
660 }
661
662 /* Steal reference to len. */
663 it->len = len;
664
665 it->index = PyLong_FromLong(0);
666 if (!it->index) {
667 Py_DECREF(it);
668 return NULL;
669 }
670
671 return (PyObject *)it;
672
673create_failure:
674 Py_XDECREF(len);
675 PyObject_Del(it);
676 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000677}