blob: 0e9eb20154b7a0cf8d961263c6e02888d54a7632 [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"
Benjamin Peterson878ce382011-11-05 15:17:52 -04004#include "structmember.h"
Thomas Woutersefafcea2001-07-09 12:30:54 +00005
Guido van Rossum805365e2007-05-07 22:24:25 +00006/* Support objects whose length is > PY_SSIZE_T_MAX.
7
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03008 This could be sped up for small PyLongs if they fit in a Py_ssize_t.
Guido van Rossum805365e2007-05-07 22:24:25 +00009 This only matters on Win64. Though we could use PY_LONG_LONG which
10 would presumably help perf.
11*/
12
Guido van Rossum12d12c51993-10-26 17:58:25 +000013typedef struct {
Guido van Rossum805365e2007-05-07 22:24:25 +000014 PyObject_HEAD
15 PyObject *start;
16 PyObject *stop;
17 PyObject *step;
Nick Coghlan37ee8502010-12-03 14:26:13 +000018 PyObject *length;
Guido van Rossum12d12c51993-10-26 17:58:25 +000019} rangeobject;
20
Guido van Rossum805365e2007-05-07 22:24:25 +000021/* Helper function for validating step. Always returns a new reference or
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000022 NULL on error.
Guido van Rossum805365e2007-05-07 22:24:25 +000023*/
24static PyObject *
Benjamin Petersona1864f32010-11-20 23:05:39 +000025validate_step(PyObject *step)
26{
Guido van Rossum805365e2007-05-07 22:24:25 +000027 /* No step specified, use a step of 1. */
28 if (!step)
Christian Heimes217cfd12007-12-02 14:31:20 +000029 return PyLong_FromLong(1);
Guido van Rossum805365e2007-05-07 22:24:25 +000030
31 step = PyNumber_Index(step);
32 if (step) {
33 Py_ssize_t istep = PyNumber_AsSsize_t(step, NULL);
34 if (istep == -1 && PyErr_Occurred()) {
35 /* Ignore OverflowError, we know the value isn't 0. */
36 PyErr_Clear();
37 }
38 else if (istep == 0) {
39 PyErr_SetString(PyExc_ValueError,
40 "range() arg 3 must not be zero");
41 Py_CLEAR(step);
42 }
43 }
44
45 return step;
Raymond Hettingerc4c453f2002-06-05 23:12:45 +000046}
47
Nick Coghlan37ee8502010-12-03 14:26:13 +000048static PyObject *
49compute_range_length(PyObject *start, PyObject *stop, PyObject *step);
50
51static rangeobject *
52make_range_object(PyTypeObject *type, PyObject *start,
53 PyObject *stop, PyObject *step)
54{
55 rangeobject *obj = NULL;
56 PyObject *length;
57 length = compute_range_length(start, stop, step);
58 if (length == NULL) {
59 return NULL;
60 }
61 obj = PyObject_New(rangeobject, type);
62 if (obj == NULL) {
63 Py_DECREF(length);
64 return NULL;
65 }
66 obj->start = start;
67 obj->stop = stop;
68 obj->step = step;
69 obj->length = length;
70 return obj;
71}
72
Guido van Rossum805365e2007-05-07 22:24:25 +000073/* XXX(nnorwitz): should we error check if the user passes any empty ranges?
74 range(-10)
75 range(0, -5)
76 range(0, 5, -1)
77*/
Raymond Hettingerc4c453f2002-06-05 23:12:45 +000078static PyObject *
Benjamin Petersona1864f32010-11-20 23:05:39 +000079range_new(PyTypeObject *type, PyObject *args, PyObject *kw)
80{
Nick Coghlan37ee8502010-12-03 14:26:13 +000081 rangeobject *obj;
Guido van Rossum805365e2007-05-07 22:24:25 +000082 PyObject *start = NULL, *stop = NULL, *step = NULL;
Raymond Hettingerc4c453f2002-06-05 23:12:45 +000083
Guido van Rossum805365e2007-05-07 22:24:25 +000084 if (!_PyArg_NoKeywords("range()", kw))
85 return NULL;
Georg Brandl02c42872005-08-26 06:42:30 +000086
Guido van Rossum805365e2007-05-07 22:24:25 +000087 if (PyTuple_Size(args) <= 1) {
88 if (!PyArg_UnpackTuple(args, "range", 1, 1, &stop))
Raymond Hettinger94f55832009-06-12 18:40:16 +000089 return NULL;
Guido van Rossum805365e2007-05-07 22:24:25 +000090 stop = PyNumber_Index(stop);
91 if (!stop)
Raymond Hettinger94f55832009-06-12 18:40:16 +000092 return NULL;
Christian Heimes217cfd12007-12-02 14:31:20 +000093 start = PyLong_FromLong(0);
Raymond Hettinger94f55832009-06-12 18:40:16 +000094 if (!start) {
95 Py_DECREF(stop);
96 return NULL;
97 }
Christian Heimes217cfd12007-12-02 14:31:20 +000098 step = PyLong_FromLong(1);
Raymond Hettinger94f55832009-06-12 18:40:16 +000099 if (!step) {
100 Py_DECREF(stop);
101 Py_DECREF(start);
102 return NULL;
103 }
Guido van Rossum805365e2007-05-07 22:24:25 +0000104 }
105 else {
106 if (!PyArg_UnpackTuple(args, "range", 2, 3,
107 &start, &stop, &step))
Raymond Hettinger94f55832009-06-12 18:40:16 +0000108 return NULL;
Tim Petersfeec4532004-08-08 07:17:39 +0000109
Guido van Rossum805365e2007-05-07 22:24:25 +0000110 /* Convert borrowed refs to owned refs */
111 start = PyNumber_Index(start);
Raymond Hettinger94f55832009-06-12 18:40:16 +0000112 if (!start)
113 return NULL;
Guido van Rossum805365e2007-05-07 22:24:25 +0000114 stop = PyNumber_Index(stop);
Raymond Hettinger94f55832009-06-12 18:40:16 +0000115 if (!stop) {
116 Py_DECREF(start);
117 return NULL;
118 }
119 step = validate_step(step); /* Caution, this can clear exceptions */
120 if (!step) {
121 Py_DECREF(start);
122 Py_DECREF(stop);
123 return NULL;
124 }
Guido van Rossum805365e2007-05-07 22:24:25 +0000125 }
126
Nick Coghlan37ee8502010-12-03 14:26:13 +0000127 obj = make_range_object(type, start, stop, step);
128 if (obj != NULL)
129 return (PyObject *) obj;
Guido van Rossum805365e2007-05-07 22:24:25 +0000130
Nick Coghlan37ee8502010-12-03 14:26:13 +0000131 /* Failed to create object, release attributes */
Guido van Rossum805365e2007-05-07 22:24:25 +0000132 Py_XDECREF(start);
133 Py_XDECREF(stop);
134 Py_XDECREF(step);
135 return NULL;
Raymond Hettingerc4c453f2002-06-05 23:12:45 +0000136}
137
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000138PyDoc_STRVAR(range_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -0700139"range(stop) -> range object\n\
140range(start, stop[, step]) -> range object\n\
Raymond Hettingerc4c453f2002-06-05 23:12:45 +0000141\n\
Benjamin Petersonac22c6b2015-04-22 09:16:07 -0400142Return an object that produces a sequence of integers from start (inclusive)\n\
143to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1.\n\
144start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3.\n\
145These are exactly the valid indices for a list of 4 elements.\n\
146When step is given, it specifies the increment (or decrement).");
Raymond Hettingerc4c453f2002-06-05 23:12:45 +0000147
Guido van Rossum805365e2007-05-07 22:24:25 +0000148static void
Benjamin Petersona1864f32010-11-20 23:05:39 +0000149range_dealloc(rangeobject *r)
150{
Guido van Rossum805365e2007-05-07 22:24:25 +0000151 Py_DECREF(r->start);
152 Py_DECREF(r->stop);
153 Py_DECREF(r->step);
Nick Coghlan37ee8502010-12-03 14:26:13 +0000154 Py_DECREF(r->length);
Amaury Forgeot d'Arcb7f17e42007-11-15 20:52:21 +0000155 PyObject_Del(r);
Guido van Rossum805365e2007-05-07 22:24:25 +0000156}
157
Mark Dickinson732166d2009-06-28 22:08:40 +0000158/* Return number of items in range (lo, hi, step) as a PyLong object,
159 * when arguments are PyLong objects. Arguments MUST return 1 with
160 * PyLong_Check(). Return NULL when there is an error.
Guido van Rossum805365e2007-05-07 22:24:25 +0000161 */
162static PyObject*
Nick Coghlan37ee8502010-12-03 14:26:13 +0000163compute_range_length(PyObject *start, PyObject *stop, PyObject *step)
Benjamin Petersona1864f32010-11-20 23:05:39 +0000164{
Guido van Rossum805365e2007-05-07 22:24:25 +0000165 /* -------------------------------------------------------------
166 Algorithm is equal to that of get_len_of_range(), but it operates
Benjamin Petersona47af9c2009-06-24 21:14:38 +0000167 on PyObjects (which are assumed to be PyLong objects).
Guido van Rossum805365e2007-05-07 22:24:25 +0000168 ---------------------------------------------------------------*/
Mark Dickinson211c6252009-02-01 10:28:51 +0000169 int cmp_result;
Guido van Rossum805365e2007-05-07 22:24:25 +0000170 PyObject *lo, *hi;
Guido van Rossum805365e2007-05-07 22:24:25 +0000171 PyObject *diff = NULL;
172 PyObject *one = NULL;
173 PyObject *tmp1 = NULL, *tmp2 = NULL, *result;
174 /* holds sub-expression evaluations */
175
176 PyObject *zero = PyLong_FromLong(0);
177 if (zero == NULL)
178 return NULL;
Nick Coghlan37ee8502010-12-03 14:26:13 +0000179 cmp_result = PyObject_RichCompareBool(step, zero, Py_GT);
Guido van Rossum805365e2007-05-07 22:24:25 +0000180 Py_DECREF(zero);
Mark Dickinson211c6252009-02-01 10:28:51 +0000181 if (cmp_result == -1)
Guido van Rossum805365e2007-05-07 22:24:25 +0000182 return NULL;
183
Mark Dickinson211c6252009-02-01 10:28:51 +0000184 if (cmp_result == 1) {
Nick Coghlan37ee8502010-12-03 14:26:13 +0000185 lo = start;
186 hi = stop;
Guido van Rossum805365e2007-05-07 22:24:25 +0000187 Py_INCREF(step);
188 } else {
Nick Coghlan37ee8502010-12-03 14:26:13 +0000189 lo = stop;
190 hi = start;
191 step = PyNumber_Negative(step);
Guido van Rossum805365e2007-05-07 22:24:25 +0000192 if (!step)
193 return NULL;
194 }
195
196 /* if (lo >= hi), return length of 0. */
Serhiy Storchakafa494fd2015-05-30 17:45:22 +0300197 cmp_result = PyObject_RichCompareBool(lo, hi, Py_GE);
198 if (cmp_result != 0) {
Guido van Rossum805365e2007-05-07 22:24:25 +0000199 Py_XDECREF(step);
Serhiy Storchakafa494fd2015-05-30 17:45:22 +0300200 if (cmp_result < 0)
201 return NULL;
Guido van Rossum805365e2007-05-07 22:24:25 +0000202 return PyLong_FromLong(0);
203 }
204
205 if ((one = PyLong_FromLong(1L)) == NULL)
206 goto Fail;
207
208 if ((tmp1 = PyNumber_Subtract(hi, lo)) == NULL)
209 goto Fail;
210
211 if ((diff = PyNumber_Subtract(tmp1, one)) == NULL)
212 goto Fail;
213
214 if ((tmp2 = PyNumber_FloorDivide(diff, step)) == NULL)
215 goto Fail;
216
217 if ((result = PyNumber_Add(tmp2, one)) == NULL)
218 goto Fail;
219
220 Py_DECREF(tmp2);
221 Py_DECREF(diff);
222 Py_DECREF(step);
223 Py_DECREF(tmp1);
224 Py_DECREF(one);
225 return result;
226
227 Fail:
228 Py_XDECREF(tmp2);
229 Py_XDECREF(diff);
230 Py_XDECREF(step);
231 Py_XDECREF(tmp1);
232 Py_XDECREF(one);
233 return NULL;
Guido van Rossum12d12c51993-10-26 17:58:25 +0000234}
235
Martin v. Löwis18e16552006-02-15 17:27:45 +0000236static Py_ssize_t
Benjamin Petersona1864f32010-11-20 23:05:39 +0000237range_length(rangeobject *r)
238{
Nick Coghlan37ee8502010-12-03 14:26:13 +0000239 return PyLong_AsSsize_t(r->length);
Guido van Rossum805365e2007-05-07 22:24:25 +0000240}
241
Guido van Rossum805365e2007-05-07 22:24:25 +0000242static PyObject *
Nick Coghlane993b102011-01-12 03:15:52 +0000243compute_item(rangeobject *r, PyObject *i)
Benjamin Petersona1864f32010-11-20 23:05:39 +0000244{
Nick Coghlane993b102011-01-12 03:15:52 +0000245 PyObject *incr, *result;
246 /* PyLong equivalent to:
247 * return r->start + (i * r->step)
248 */
249 incr = PyNumber_Multiply(i, r->step);
Guido van Rossum805365e2007-05-07 22:24:25 +0000250 if (!incr)
251 return NULL;
252 result = PyNumber_Add(r->start, incr);
253 Py_DECREF(incr);
254 return result;
Guido van Rossum7d6aa511993-12-21 22:50:31 +0000255}
256
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000257static PyObject *
Nick Coghlane993b102011-01-12 03:15:52 +0000258compute_range_item(rangeobject *r, PyObject *arg)
Benjamin Petersona1864f32010-11-20 23:05:39 +0000259{
Nick Coghlane993b102011-01-12 03:15:52 +0000260 int cmp_result;
261 PyObject *i, *result;
Tim Petersd976ab72004-08-08 06:29:10 +0000262
Nick Coghlane993b102011-01-12 03:15:52 +0000263 PyObject *zero = PyLong_FromLong(0);
264 if (zero == NULL)
265 return NULL;
Nick Coghlan37ee8502010-12-03 14:26:13 +0000266
Nick Coghlane993b102011-01-12 03:15:52 +0000267 /* PyLong equivalent to:
268 * if (arg < 0) {
269 * i = r->length + arg
270 * } else {
271 * i = arg
272 * }
273 */
274 cmp_result = PyObject_RichCompareBool(arg, zero, Py_LT);
275 if (cmp_result == -1) {
276 Py_DECREF(zero);
Nick Coghlan37ee8502010-12-03 14:26:13 +0000277 return NULL;
Guido van Rossum805365e2007-05-07 22:24:25 +0000278 }
Nick Coghlane993b102011-01-12 03:15:52 +0000279 if (cmp_result == 1) {
280 i = PyNumber_Add(r->length, arg);
281 if (!i) {
282 Py_DECREF(zero);
283 return NULL;
284 }
285 } else {
286 i = arg;
287 Py_INCREF(i);
288 }
289
290 /* PyLong equivalent to:
291 * if (i < 0 || i >= r->length) {
292 * <report index out of bounds>
293 * }
294 */
295 cmp_result = PyObject_RichCompareBool(i, zero, Py_LT);
296 Py_DECREF(zero);
297 if (cmp_result == 0) {
298 cmp_result = PyObject_RichCompareBool(i, r->length, Py_GE);
299 }
300 if (cmp_result == -1) {
301 Py_DECREF(i);
302 return NULL;
303 }
304 if (cmp_result == 1) {
305 Py_DECREF(i);
306 PyErr_SetString(PyExc_IndexError,
307 "range object index out of range");
308 return NULL;
309 }
310
311 result = compute_item(r, i);
312 Py_DECREF(i);
313 return result;
314}
315
316static PyObject *
317range_item(rangeobject *r, Py_ssize_t i)
318{
Antoine Pitroua103b962012-05-16 14:37:54 +0200319 PyObject *res, *arg = PyLong_FromSsize_t(i);
Nick Coghlane993b102011-01-12 03:15:52 +0000320 if (!arg) {
321 return NULL;
322 }
Benjamin Peterson547d4852011-01-13 04:22:54 +0000323 res = compute_range_item(r, arg);
324 Py_DECREF(arg);
325 return res;
Nick Coghlane993b102011-01-12 03:15:52 +0000326}
327
Nick Coghlane993b102011-01-12 03:15:52 +0000328static PyObject *
329compute_slice(rangeobject *r, PyObject *_slice)
330{
331 PySliceObject *slice = (PySliceObject *) _slice;
332 rangeobject *result;
333 PyObject *start = NULL, *stop = NULL, *step = NULL;
334 PyObject *substart = NULL, *substop = NULL, *substep = NULL;
Mark Dickinsonffdb2c22012-11-17 19:18:10 +0000335 int error;
Nick Coghlane993b102011-01-12 03:15:52 +0000336
Mark Dickinsonffdb2c22012-11-17 19:18:10 +0000337 error = _PySlice_GetLongIndices(slice, r->length, &start, &stop, &step);
338 if (error == -1)
339 return NULL;
Nick Coghlane993b102011-01-12 03:15:52 +0000340
341 substep = PyNumber_Multiply(r->step, step);
342 if (substep == NULL) goto fail;
343 Py_CLEAR(step);
344
345 substart = compute_item(r, start);
346 if (substart == NULL) goto fail;
347 Py_CLEAR(start);
348
Mark Dickinsonffdb2c22012-11-17 19:18:10 +0000349 substop = compute_item(r, stop);
350 if (substop == NULL) goto fail;
Nick Coghlane993b102011-01-12 03:15:52 +0000351 Py_CLEAR(stop);
352
353 result = make_range_object(Py_TYPE(r), substart, substop, substep);
354 if (result != NULL) {
355 return (PyObject *) result;
356 }
357fail:
358 Py_XDECREF(start);
359 Py_XDECREF(stop);
360 Py_XDECREF(step);
361 Py_XDECREF(substart);
362 Py_XDECREF(substop);
363 Py_XDECREF(substep);
364 return NULL;
Alexandre Vassalotti75056072008-06-10 04:03:04 +0000365}
366
Daniel Stutzbach9f0cbf12010-09-13 21:16:29 +0000367/* Assumes (PyLong_CheckExact(ob) || PyBool_Check(ob)) */
368static int
Benjamin Petersona1864f32010-11-20 23:05:39 +0000369range_contains_long(rangeobject *r, PyObject *ob)
370{
Daniel Stutzbach9f0cbf12010-09-13 21:16:29 +0000371 int cmp1, cmp2, cmp3;
372 PyObject *tmp1 = NULL;
373 PyObject *tmp2 = NULL;
374 PyObject *zero = NULL;
375 int result = -1;
376
377 zero = PyLong_FromLong(0);
378 if (zero == NULL) /* MemoryError in int(0) */
379 goto end;
380
381 /* Check if the value can possibly be in the range. */
382
383 cmp1 = PyObject_RichCompareBool(r->step, zero, Py_GT);
384 if (cmp1 == -1)
385 goto end;
386 if (cmp1 == 1) { /* positive steps: start <= ob < stop */
387 cmp2 = PyObject_RichCompareBool(r->start, ob, Py_LE);
388 cmp3 = PyObject_RichCompareBool(ob, r->stop, Py_LT);
389 }
390 else { /* negative steps: stop < ob <= start */
391 cmp2 = PyObject_RichCompareBool(ob, r->start, Py_LE);
392 cmp3 = PyObject_RichCompareBool(r->stop, ob, Py_LT);
393 }
394
395 if (cmp2 == -1 || cmp3 == -1) /* TypeError */
396 goto end;
397 if (cmp2 == 0 || cmp3 == 0) { /* ob outside of range */
398 result = 0;
399 goto end;
400 }
401
402 /* Check that the stride does not invalidate ob's membership. */
403 tmp1 = PyNumber_Subtract(ob, r->start);
404 if (tmp1 == NULL)
405 goto end;
406 tmp2 = PyNumber_Remainder(tmp1, r->step);
407 if (tmp2 == NULL)
408 goto end;
409 /* result = (int(ob) - start % step) == 0 */
410 result = PyObject_RichCompareBool(tmp2, zero, Py_EQ);
411 end:
412 Py_XDECREF(tmp1);
413 Py_XDECREF(tmp2);
414 Py_XDECREF(zero);
415 return result;
416}
417
Mark Dickinson3e124ae2009-09-22 21:47:24 +0000418static int
Benjamin Petersona1864f32010-11-20 23:05:39 +0000419range_contains(rangeobject *r, PyObject *ob)
420{
Daniel Stutzbach9f0cbf12010-09-13 21:16:29 +0000421 if (PyLong_CheckExact(ob) || PyBool_Check(ob))
422 return range_contains_long(r, ob);
Mark Dickinson3e124ae2009-09-22 21:47:24 +0000423
Mark Dickinson3e124ae2009-09-22 21:47:24 +0000424 return (int)_PySequence_IterSearch((PyObject*)r, ob,
425 PY_ITERSEARCH_CONTAINS);
426}
427
Mark Dickinson36645682011-10-23 19:53:01 +0100428/* Compare two range objects. Return 1 for equal, 0 for not equal
429 and -1 on error. The algorithm is roughly the C equivalent of
430
431 if r0 is r1:
432 return True
433 if len(r0) != len(r1):
434 return False
435 if not len(r0):
436 return True
437 if r0.start != r1.start:
438 return False
439 if len(r0) == 1:
440 return True
441 return r0.step == r1.step
442*/
443static int
444range_equals(rangeobject *r0, rangeobject *r1)
445{
446 int cmp_result;
447 PyObject *one;
448
449 if (r0 == r1)
450 return 1;
451 cmp_result = PyObject_RichCompareBool(r0->length, r1->length, Py_EQ);
452 /* Return False or error to the caller. */
453 if (cmp_result != 1)
454 return cmp_result;
455 cmp_result = PyObject_Not(r0->length);
456 /* Return True or error to the caller. */
457 if (cmp_result != 0)
458 return cmp_result;
459 cmp_result = PyObject_RichCompareBool(r0->start, r1->start, Py_EQ);
460 /* Return False or error to the caller. */
461 if (cmp_result != 1)
462 return cmp_result;
463 one = PyLong_FromLong(1);
464 if (!one)
465 return -1;
466 cmp_result = PyObject_RichCompareBool(r0->length, one, Py_EQ);
467 Py_DECREF(one);
468 /* Return True or error to the caller. */
469 if (cmp_result != 0)
470 return cmp_result;
471 return PyObject_RichCompareBool(r0->step, r1->step, Py_EQ);
472}
473
474static PyObject *
475range_richcompare(PyObject *self, PyObject *other, int op)
476{
477 int result;
478
479 if (!PyRange_Check(other))
480 Py_RETURN_NOTIMPLEMENTED;
481 switch (op) {
482 case Py_NE:
483 case Py_EQ:
484 result = range_equals((rangeobject*)self, (rangeobject*)other);
485 if (result == -1)
486 return NULL;
487 if (op == Py_NE)
488 result = !result;
489 if (result)
490 Py_RETURN_TRUE;
491 else
492 Py_RETURN_FALSE;
493 case Py_LE:
494 case Py_GE:
495 case Py_LT:
496 case Py_GT:
497 Py_RETURN_NOTIMPLEMENTED;
498 default:
499 PyErr_BadArgument();
500 return NULL;
501 }
502}
503
504/* Hash function for range objects. Rough C equivalent of
505
506 if not len(r):
507 return hash((len(r), None, None))
508 if len(r) == 1:
509 return hash((len(r), r.start, None))
510 return hash((len(r), r.start, r.step))
511*/
512static Py_hash_t
513range_hash(rangeobject *r)
514{
515 PyObject *t;
516 Py_hash_t result = -1;
517 int cmp_result;
518
519 t = PyTuple_New(3);
520 if (!t)
521 return -1;
522 Py_INCREF(r->length);
523 PyTuple_SET_ITEM(t, 0, r->length);
524 cmp_result = PyObject_Not(r->length);
525 if (cmp_result == -1)
526 goto end;
527 if (cmp_result == 1) {
528 Py_INCREF(Py_None);
529 Py_INCREF(Py_None);
530 PyTuple_SET_ITEM(t, 1, Py_None);
531 PyTuple_SET_ITEM(t, 2, Py_None);
532 }
533 else {
534 PyObject *one;
535 Py_INCREF(r->start);
536 PyTuple_SET_ITEM(t, 1, r->start);
537 one = PyLong_FromLong(1);
538 if (!one)
539 goto end;
540 cmp_result = PyObject_RichCompareBool(r->length, one, Py_EQ);
541 Py_DECREF(one);
542 if (cmp_result == -1)
543 goto end;
544 if (cmp_result == 1) {
545 Py_INCREF(Py_None);
546 PyTuple_SET_ITEM(t, 2, Py_None);
547 }
548 else {
549 Py_INCREF(r->step);
550 PyTuple_SET_ITEM(t, 2, r->step);
551 }
552 }
553 result = PyObject_Hash(t);
554 end:
555 Py_DECREF(t);
556 return result;
557}
558
Daniel Stutzbach9f0cbf12010-09-13 21:16:29 +0000559static PyObject *
Benjamin Petersona1864f32010-11-20 23:05:39 +0000560range_count(rangeobject *r, PyObject *ob)
561{
Daniel Stutzbach9f0cbf12010-09-13 21:16:29 +0000562 if (PyLong_CheckExact(ob) || PyBool_Check(ob)) {
Georg Brandl7e5343b2010-11-20 22:40:10 +0000563 int result = range_contains_long(r, ob);
564 if (result == -1)
565 return NULL;
566 else if (result)
Benjamin Peterson0b458d52010-11-20 22:35:41 +0000567 return PyLong_FromLong(1);
Daniel Stutzbach9f0cbf12010-09-13 21:16:29 +0000568 else
Benjamin Peterson0b458d52010-11-20 22:35:41 +0000569 return PyLong_FromLong(0);
Daniel Stutzbach9f0cbf12010-09-13 21:16:29 +0000570 } else {
571 Py_ssize_t count;
572 count = _PySequence_IterSearch((PyObject*)r, ob, PY_ITERSEARCH_COUNT);
573 if (count == -1)
574 return NULL;
575 return PyLong_FromSsize_t(count);
576 }
577}
578
579static PyObject *
Benjamin Petersona1864f32010-11-20 23:05:39 +0000580range_index(rangeobject *r, PyObject *ob)
581{
Daniel Stutzbach9f0cbf12010-09-13 21:16:29 +0000582 int contains;
Daniel Stutzbach9f0cbf12010-09-13 21:16:29 +0000583
584 if (!PyLong_CheckExact(ob) && !PyBool_Check(ob)) {
585 Py_ssize_t index;
586 index = _PySequence_IterSearch((PyObject*)r, ob, PY_ITERSEARCH_INDEX);
587 if (index == -1)
588 return NULL;
589 return PyLong_FromSsize_t(index);
590 }
591
592 contains = range_contains_long(r, ob);
593 if (contains == -1)
594 return NULL;
595
Benjamin Peterson155614b2010-11-20 22:44:32 +0000596 if (contains) {
597 PyObject *idx, *tmp = PyNumber_Subtract(ob, r->start);
598 if (tmp == NULL)
599 return NULL;
600 /* idx = (ob - r.start) // r.step */
601 idx = PyNumber_FloorDivide(tmp, r->step);
602 Py_DECREF(tmp);
603 return idx;
604 }
Daniel Stutzbach9f0cbf12010-09-13 21:16:29 +0000605
606 /* object is not in the range */
Benjamin Peterson155614b2010-11-20 22:44:32 +0000607 PyErr_Format(PyExc_ValueError, "%R is not in range", ob);
Daniel Stutzbach9f0cbf12010-09-13 21:16:29 +0000608 return NULL;
609}
610
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000611static PySequenceMethods range_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 (lenfunc)range_length, /* sq_length */
Nick Coghlan37ee8502010-12-03 14:26:13 +0000613 0, /* sq_concat */
614 0, /* sq_repeat */
615 (ssizeargfunc)range_item, /* sq_item */
616 0, /* sq_slice */
617 0, /* sq_ass_item */
618 0, /* sq_ass_slice */
Mark Dickinson3e124ae2009-09-22 21:47:24 +0000619 (objobjproc)range_contains, /* sq_contains */
Guido van Rossum12d12c51993-10-26 17:58:25 +0000620};
621
Nick Coghlan37ee8502010-12-03 14:26:13 +0000622static PyObject *
623range_repr(rangeobject *r)
624{
625 Py_ssize_t istep;
626
627 /* Check for special case values for printing. We don't always
628 need the step value. We don't care about errors
629 (it means overflow), so clear the errors. */
630 istep = PyNumber_AsSsize_t(r->step, NULL);
631 if (istep != 1 || (istep == -1 && PyErr_Occurred())) {
632 PyErr_Clear();
633 }
634
635 if (istep == 1)
636 return PyUnicode_FromFormat("range(%R, %R)", r->start, r->stop);
637 else
638 return PyUnicode_FromFormat("range(%R, %R, %R)",
639 r->start, r->stop, r->step);
640}
641
642/* Pickling support */
643static PyObject *
644range_reduce(rangeobject *r, PyObject *args)
645{
646 return Py_BuildValue("(O(OOO))", Py_TYPE(r),
647 r->start, r->stop, r->step);
648}
649
650static PyObject *
651range_subscript(rangeobject* self, PyObject* item)
652{
653 if (PyIndex_Check(item)) {
Nick Coghlane993b102011-01-12 03:15:52 +0000654 PyObject *i, *result;
655 i = PyNumber_Index(item);
656 if (!i)
Nick Coghlan37ee8502010-12-03 14:26:13 +0000657 return NULL;
Nick Coghlane993b102011-01-12 03:15:52 +0000658 result = compute_range_item(self, i);
659 Py_DECREF(i);
660 return result;
Nick Coghlan37ee8502010-12-03 14:26:13 +0000661 }
662 if (PySlice_Check(item)) {
Nick Coghlane993b102011-01-12 03:15:52 +0000663 return compute_slice(self, item);
Nick Coghlan37ee8502010-12-03 14:26:13 +0000664 }
665 PyErr_Format(PyExc_TypeError,
666 "range indices must be integers or slices, not %.200s",
667 item->ob_type->tp_name);
668 return NULL;
669}
670
671
672static PyMappingMethods range_as_mapping = {
673 (lenfunc)range_length, /* mp_length */
674 (binaryfunc)range_subscript, /* mp_subscript */
675 (objobjargproc)0, /* mp_ass_subscript */
676};
677
Jeremy Hylton938ace62002-07-17 16:30:39 +0000678static PyObject * range_iter(PyObject *seq);
Raymond Hettinger85c20a42003-11-06 14:06:48 +0000679static PyObject * range_reverse(PyObject *seq);
680
681PyDoc_STRVAR(reverse_doc,
Ezio Melotti5792ce12013-10-06 00:36:45 +0300682"Return a reverse iterator.");
Raymond Hettinger85c20a42003-11-06 14:06:48 +0000683
Daniel Stutzbach9f0cbf12010-09-13 21:16:29 +0000684PyDoc_STRVAR(count_doc,
685"rangeobject.count(value) -> integer -- return number of occurrences of value");
686
687PyDoc_STRVAR(index_doc,
688"rangeobject.index(value, [start, [stop]]) -> integer -- return index of value.\n"
Ezio Melotti5792ce12013-10-06 00:36:45 +0300689"Raise ValueError if the value is not present.");
Daniel Stutzbach9f0cbf12010-09-13 21:16:29 +0000690
Raymond Hettinger85c20a42003-11-06 14:06:48 +0000691static PyMethodDef range_methods[] = {
Daniel Stutzbach9f0cbf12010-09-13 21:16:29 +0000692 {"__reversed__", (PyCFunction)range_reverse, METH_NOARGS, reverse_doc},
693 {"__reduce__", (PyCFunction)range_reduce, METH_VARARGS},
694 {"count", (PyCFunction)range_count, METH_O, count_doc},
695 {"index", (PyCFunction)range_index, METH_O, index_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 {NULL, NULL} /* sentinel */
Raymond Hettinger85c20a42003-11-06 14:06:48 +0000697};
Raymond Hettinger48165d42002-06-05 20:08:48 +0000698
Benjamin Peterson878ce382011-11-05 15:17:52 -0400699static PyMemberDef range_members[] = {
700 {"start", T_OBJECT_EX, offsetof(rangeobject, start), READONLY},
701 {"stop", T_OBJECT_EX, offsetof(rangeobject, stop), READONLY},
702 {"step", T_OBJECT_EX, offsetof(rangeobject, step), READONLY},
703 {0}
704};
705
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000706PyTypeObject PyRange_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 PyVarObject_HEAD_INIT(&PyType_Type, 0)
708 "range", /* Name of this type */
709 sizeof(rangeobject), /* Basic object size */
710 0, /* Item size for varobject */
711 (destructor)range_dealloc, /* tp_dealloc */
712 0, /* tp_print */
713 0, /* tp_getattr */
714 0, /* tp_setattr */
715 0, /* tp_reserved */
716 (reprfunc)range_repr, /* tp_repr */
717 0, /* tp_as_number */
718 &range_as_sequence, /* tp_as_sequence */
Nick Coghlan37ee8502010-12-03 14:26:13 +0000719 &range_as_mapping, /* tp_as_mapping */
Mark Dickinson36645682011-10-23 19:53:01 +0100720 (hashfunc)range_hash, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 0, /* tp_call */
722 0, /* tp_str */
723 PyObject_GenericGetAttr, /* tp_getattro */
724 0, /* tp_setattro */
725 0, /* tp_as_buffer */
726 Py_TPFLAGS_DEFAULT, /* tp_flags */
727 range_doc, /* tp_doc */
728 0, /* tp_traverse */
729 0, /* tp_clear */
Mark Dickinson36645682011-10-23 19:53:01 +0100730 range_richcompare, /* tp_richcompare */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 0, /* tp_weaklistoffset */
732 range_iter, /* tp_iter */
733 0, /* tp_iternext */
734 range_methods, /* tp_methods */
Benjamin Peterson878ce382011-11-05 15:17:52 -0400735 range_members, /* tp_members */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 0, /* tp_getset */
737 0, /* tp_base */
738 0, /* tp_dict */
739 0, /* tp_descr_get */
740 0, /* tp_descr_set */
741 0, /* tp_dictoffset */
742 0, /* tp_init */
743 0, /* tp_alloc */
744 range_new, /* tp_new */
Guido van Rossum12d12c51993-10-26 17:58:25 +0000745};
Raymond Hettinger48165d42002-06-05 20:08:48 +0000746
Walter Dörwald4ad94212007-05-21 18:01:17 +0000747/*********************** range Iterator **************************/
Raymond Hettinger48165d42002-06-05 20:08:48 +0000748
Guido van Rossum805365e2007-05-07 22:24:25 +0000749/* There are 2 types of iterators, one for C longs, the other for
Serhiy Storchaka95949422013-08-27 19:40:23 +0300750 Python ints (ie, PyObjects). This should make iteration fast
Guido van Rossum805365e2007-05-07 22:24:25 +0000751 in the normal case, but possible for any numeric value.
752*/
753
Raymond Hettinger48165d42002-06-05 20:08:48 +0000754typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 PyObject_HEAD
756 long index;
757 long start;
758 long step;
759 long len;
Raymond Hettinger48165d42002-06-05 20:08:48 +0000760} rangeiterobject;
761
Raymond Hettinger85c20a42003-11-06 14:06:48 +0000762static PyObject *
Benjamin Petersona1864f32010-11-20 23:05:39 +0000763rangeiter_next(rangeiterobject *r)
764{
Guido van Rossum805365e2007-05-07 22:24:25 +0000765 if (r->index < r->len)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 /* cast to unsigned to avoid possible signed overflow
Mark Dickinsonb43dbc22009-11-15 12:56:08 +0000767 in intermediate calculations. */
768 return PyLong_FromLong((long)(r->start +
769 (unsigned long)(r->index++) * r->step));
Guido van Rossum805365e2007-05-07 22:24:25 +0000770 return NULL;
Raymond Hettinger48165d42002-06-05 20:08:48 +0000771}
772
Raymond Hettinger6b27cda2005-09-24 21:23:05 +0000773static PyObject *
Benjamin Petersona1864f32010-11-20 23:05:39 +0000774rangeiter_len(rangeiterobject *r)
775{
Christian Heimes217cfd12007-12-02 14:31:20 +0000776 return PyLong_FromLong(r->len - r->index);
Raymond Hettingeref9bf402004-03-10 10:10:42 +0000777}
778
Guido van Rossum805365e2007-05-07 22:24:25 +0000779PyDoc_STRVAR(length_hint_doc,
780 "Private method returning an estimate of len(list(it)).");
Raymond Hettingeref9bf402004-03-10 10:10:42 +0000781
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000782static PyObject *
783rangeiter_reduce(rangeiterobject *r)
784{
785 PyObject *start=NULL, *stop=NULL, *step=NULL;
786 PyObject *range;
Chris Jerdonek042fa652012-10-07 14:56:27 -0700787
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000788 /* create a range object for pickling */
789 start = PyLong_FromLong(r->start);
790 if (start == NULL)
791 goto err;
792 stop = PyLong_FromLong(r->start + r->len * r->step);
793 if (stop == NULL)
794 goto err;
795 step = PyLong_FromLong(r->step);
796 if (step == NULL)
797 goto err;
798 range = (PyObject*)make_range_object(&PyRange_Type,
799 start, stop, step);
800 if (range == NULL)
801 goto err;
802 /* return the result */
Antoine Pitroua7013882012-04-05 00:04:20 +0200803 return Py_BuildValue("N(N)i", _PyObject_GetBuiltin("iter"), range, r->index);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000804err:
805 Py_XDECREF(start);
806 Py_XDECREF(stop);
807 Py_XDECREF(step);
808 return NULL;
809}
810
811static PyObject *
812rangeiter_setstate(rangeiterobject *r, PyObject *state)
813{
814 long index = PyLong_AsLong(state);
815 if (index == -1 && PyErr_Occurred())
816 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +0000817 /* silently clip the index value */
818 if (index < 0)
819 index = 0;
820 else if (index > r->len)
821 index = r->len; /* exhausted iterator */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000822 r->index = index;
823 Py_RETURN_NONE;
824}
825
826PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
827PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
828
Raymond Hettinger6b27cda2005-09-24 21:23:05 +0000829static PyMethodDef rangeiter_methods[] = {
Guido van Rossum805365e2007-05-07 22:24:25 +0000830 {"__length_hint__", (PyCFunction)rangeiter_len, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000832 {"__reduce__", (PyCFunction)rangeiter_reduce, METH_NOARGS,
833 reduce_doc},
834 {"__setstate__", (PyCFunction)rangeiter_setstate, METH_O,
835 setstate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 {NULL, NULL} /* sentinel */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +0000837};
Raymond Hettingeref9bf402004-03-10 10:10:42 +0000838
Nick Coghlan37ee8502010-12-03 14:26:13 +0000839static PyObject *rangeiter_new(PyTypeObject *, PyObject *args, PyObject *kw);
840
Christian Heimesa22e8bd2007-11-29 22:35:39 +0000841PyTypeObject PyRangeIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 PyVarObject_HEAD_INIT(&PyType_Type, 0)
843 "range_iterator", /* tp_name */
844 sizeof(rangeiterobject), /* tp_basicsize */
845 0, /* tp_itemsize */
846 /* methods */
847 (destructor)PyObject_Del, /* tp_dealloc */
848 0, /* tp_print */
849 0, /* tp_getattr */
850 0, /* tp_setattr */
851 0, /* tp_reserved */
852 0, /* tp_repr */
853 0, /* tp_as_number */
854 0, /* tp_as_sequence */
855 0, /* tp_as_mapping */
856 0, /* tp_hash */
857 0, /* tp_call */
858 0, /* tp_str */
859 PyObject_GenericGetAttr, /* tp_getattro */
860 0, /* tp_setattro */
861 0, /* tp_as_buffer */
862 Py_TPFLAGS_DEFAULT, /* tp_flags */
863 0, /* tp_doc */
864 0, /* tp_traverse */
865 0, /* tp_clear */
866 0, /* tp_richcompare */
867 0, /* tp_weaklistoffset */
868 PyObject_SelfIter, /* tp_iter */
869 (iternextfunc)rangeiter_next, /* tp_iternext */
870 rangeiter_methods, /* tp_methods */
871 0, /* tp_members */
872 0, /* tp_getset */
873 0, /* tp_base */
874 0, /* tp_dict */
875 0, /* tp_descr_get */
876 0, /* tp_descr_set */
877 0, /* tp_dictoffset */
878 0, /* tp_init */
879 0, /* tp_alloc */
880 rangeiter_new, /* tp_new */
Guido van Rossum805365e2007-05-07 22:24:25 +0000881};
882
Mark Dickinsond550c9a2009-11-15 09:57:26 +0000883/* Return number of items in range (lo, hi, step). step != 0
884 * required. The result always fits in an unsigned long.
Guido van Rossum805365e2007-05-07 22:24:25 +0000885 */
Mark Dickinsond550c9a2009-11-15 09:57:26 +0000886static unsigned long
Benjamin Petersona1864f32010-11-20 23:05:39 +0000887get_len_of_range(long lo, long hi, long step)
888{
Guido van Rossum805365e2007-05-07 22:24:25 +0000889 /* -------------------------------------------------------------
Mark Dickinsond550c9a2009-11-15 09:57:26 +0000890 If step > 0 and lo >= hi, or step < 0 and lo <= hi, the range is empty.
891 Else for step > 0, if n values are in the range, the last one is
Guido van Rossum805365e2007-05-07 22:24:25 +0000892 lo + (n-1)*step, which must be <= hi-1. Rearranging,
893 n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
894 the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
895 the RHS is non-negative and so truncation is the same as the
896 floor. Letting M be the largest positive long, the worst case
897 for the RHS numerator is hi=M, lo=-M-1, and then
898 hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
Mark Dickinsond550c9a2009-11-15 09:57:26 +0000899 precision to compute the RHS exactly. The analysis for step < 0
900 is similar.
Guido van Rossum805365e2007-05-07 22:24:25 +0000901 ---------------------------------------------------------------*/
Mark Dickinsond550c9a2009-11-15 09:57:26 +0000902 assert(step != 0);
903 if (step > 0 && lo < hi)
904 return 1UL + (hi - 1UL - lo) / step;
905 else if (step < 0 && lo > hi)
906 return 1UL + (lo - 1UL - hi) / (0UL - step);
907 else
908 return 0UL;
Guido van Rossum805365e2007-05-07 22:24:25 +0000909}
910
Mark Dickinsond550c9a2009-11-15 09:57:26 +0000911/* Initialize a rangeiter object. If the length of the rangeiter object
912 is not representable as a C long, OverflowError is raised. */
913
Guido van Rossum805365e2007-05-07 22:24:25 +0000914static PyObject *
Nick Coghlan37ee8502010-12-03 14:26:13 +0000915fast_range_iter(long start, long stop, long step)
Benjamin Petersona1864f32010-11-20 23:05:39 +0000916{
Christian Heimesa22e8bd2007-11-29 22:35:39 +0000917 rangeiterobject *it = PyObject_New(rangeiterobject, &PyRangeIter_Type);
Mark Dickinsond550c9a2009-11-15 09:57:26 +0000918 unsigned long ulen;
Guido van Rossum805365e2007-05-07 22:24:25 +0000919 if (it == NULL)
920 return NULL;
921 it->start = start;
922 it->step = step;
Mark Dickinsond550c9a2009-11-15 09:57:26 +0000923 ulen = get_len_of_range(start, stop, step);
924 if (ulen > (unsigned long)LONG_MAX) {
Benjamin Peterson36fbb732009-11-16 00:34:25 +0000925 Py_DECREF(it);
Mark Dickinsond550c9a2009-11-15 09:57:26 +0000926 PyErr_SetString(PyExc_OverflowError,
927 "range too large to represent as a range_iterator");
928 return NULL;
929 }
930 it->len = (long)ulen;
Guido van Rossum805365e2007-05-07 22:24:25 +0000931 it->index = 0;
932 return (PyObject *)it;
933}
934
935static PyObject *
Benjamin Petersona1864f32010-11-20 23:05:39 +0000936rangeiter_new(PyTypeObject *type, PyObject *args, PyObject *kw)
937{
Guido van Rossum805365e2007-05-07 22:24:25 +0000938 long start, stop, step;
939
940 if (!_PyArg_NoKeywords("rangeiter()", kw))
941 return NULL;
942
943 if (!PyArg_ParseTuple(args, "lll;rangeiter() requires 3 int arguments",
944 &start, &stop, &step))
945 return NULL;
946
Nick Coghlan37ee8502010-12-03 14:26:13 +0000947 return fast_range_iter(start, stop, step);
948}
949
950typedef struct {
951 PyObject_HEAD
952 PyObject *index;
953 PyObject *start;
954 PyObject *step;
955 PyObject *len;
956} longrangeiterobject;
957
958static PyObject *
959longrangeiter_len(longrangeiterobject *r, PyObject *no_args)
960{
961 return PyNumber_Subtract(r->len, r->index);
Guido van Rossum805365e2007-05-07 22:24:25 +0000962}
963
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000964static PyObject *
965longrangeiter_reduce(longrangeiterobject *r)
966{
967 PyObject *product, *stop=NULL;
968 PyObject *range;
969
970 /* create a range object for pickling. Must calculate the "stop" value */
971 product = PyNumber_Multiply(r->len, r->step);
972 if (product == NULL)
973 return NULL;
974 stop = PyNumber_Add(r->start, product);
975 Py_DECREF(product);
976 if (stop == NULL)
977 return NULL;
978 Py_INCREF(r->start);
979 Py_INCREF(r->step);
980 range = (PyObject*)make_range_object(&PyRange_Type,
981 r->start, stop, r->step);
982 if (range == NULL) {
983 Py_DECREF(r->start);
984 Py_DECREF(stop);
985 Py_DECREF(r->step);
986 return NULL;
987 }
988
989 /* return the result */
Antoine Pitroua7013882012-04-05 00:04:20 +0200990 return Py_BuildValue("N(N)O", _PyObject_GetBuiltin("iter"), range, r->index);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +0000991}
992
993static PyObject *
994longrangeiter_setstate(longrangeiterobject *r, PyObject *state)
995{
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +0000996 int cmp;
Serhiy Storchaka009b8112015-03-18 21:53:15 +0200997
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +0000998 /* clip the value */
999 PyObject *zero = PyLong_FromLong(0);
1000 if (zero == NULL)
1001 return NULL;
1002 cmp = PyObject_RichCompareBool(state, zero, Py_LT);
1003 if (cmp > 0) {
Serhiy Storchaka48842712016-04-06 09:45:48 +03001004 Py_XSETREF(r->index, zero);
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +00001005 Py_RETURN_NONE;
1006 }
1007 Py_DECREF(zero);
1008 if (cmp < 0)
1009 return NULL;
1010
1011 cmp = PyObject_RichCompareBool(r->len, state, Py_LT);
1012 if (cmp < 0)
1013 return NULL;
1014 if (cmp > 0)
1015 state = r->len;
Serhiy Storchaka009b8112015-03-18 21:53:15 +02001016
Serhiy Storchaka4a1e70f2015-12-27 12:36:18 +02001017 Py_INCREF(state);
Serhiy Storchaka48842712016-04-06 09:45:48 +03001018 Py_XSETREF(r->index, state);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001019 Py_RETURN_NONE;
1020}
1021
Guido van Rossum805365e2007-05-07 22:24:25 +00001022static PyMethodDef longrangeiter_methods[] = {
1023 {"__length_hint__", (PyCFunction)longrangeiter_len, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00001025 {"__reduce__", (PyCFunction)longrangeiter_reduce, METH_NOARGS,
1026 reduce_doc},
1027 {"__setstate__", (PyCFunction)longrangeiter_setstate, METH_O,
1028 setstate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 {NULL, NULL} /* sentinel */
Guido van Rossum805365e2007-05-07 22:24:25 +00001030};
1031
1032static void
Benjamin Petersona1864f32010-11-20 23:05:39 +00001033longrangeiter_dealloc(longrangeiterobject *r)
1034{
Guido van Rossum805365e2007-05-07 22:24:25 +00001035 Py_XDECREF(r->index);
Guido van Rossum317e7742007-05-08 15:18:31 +00001036 Py_XDECREF(r->start);
1037 Py_XDECREF(r->step);
1038 Py_XDECREF(r->len);
Amaury Forgeot d'Arcb7f17e42007-11-15 20:52:21 +00001039 PyObject_Del(r);
Guido van Rossum805365e2007-05-07 22:24:25 +00001040}
1041
1042static PyObject *
Benjamin Petersona1864f32010-11-20 23:05:39 +00001043longrangeiter_next(longrangeiterobject *r)
1044{
Guido van Rossum805365e2007-05-07 22:24:25 +00001045 PyObject *one, *product, *new_index, *result;
1046 if (PyObject_RichCompareBool(r->index, r->len, Py_LT) != 1)
1047 return NULL;
1048
1049 one = PyLong_FromLong(1);
1050 if (!one)
1051 return NULL;
1052
Guido van Rossum805365e2007-05-07 22:24:25 +00001053 new_index = PyNumber_Add(r->index, one);
1054 Py_DECREF(one);
Benjamin Peterson36fbb732009-11-16 00:34:25 +00001055 if (!new_index)
1056 return NULL;
1057
1058 product = PyNumber_Multiply(r->index, r->step);
1059 if (!product) {
1060 Py_DECREF(new_index);
Guido van Rossum805365e2007-05-07 22:24:25 +00001061 return NULL;
1062 }
1063
1064 result = PyNumber_Add(r->start, product);
1065 Py_DECREF(product);
1066 if (result) {
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001067 Py_SETREF(r->index, new_index);
Guido van Rossum805365e2007-05-07 22:24:25 +00001068 }
Benjamin Peterson36fbb732009-11-16 00:34:25 +00001069 else {
1070 Py_DECREF(new_index);
1071 }
Guido van Rossum805365e2007-05-07 22:24:25 +00001072
1073 return result;
1074}
1075
Christian Heimesa22e8bd2007-11-29 22:35:39 +00001076PyTypeObject PyLongRangeIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1078 "longrange_iterator", /* tp_name */
1079 sizeof(longrangeiterobject), /* tp_basicsize */
1080 0, /* tp_itemsize */
1081 /* methods */
1082 (destructor)longrangeiter_dealloc, /* tp_dealloc */
1083 0, /* tp_print */
1084 0, /* tp_getattr */
1085 0, /* tp_setattr */
1086 0, /* tp_reserved */
1087 0, /* tp_repr */
1088 0, /* tp_as_number */
1089 0, /* tp_as_sequence */
1090 0, /* tp_as_mapping */
1091 0, /* tp_hash */
1092 0, /* tp_call */
1093 0, /* tp_str */
1094 PyObject_GenericGetAttr, /* tp_getattro */
1095 0, /* tp_setattro */
1096 0, /* tp_as_buffer */
1097 Py_TPFLAGS_DEFAULT, /* tp_flags */
1098 0, /* tp_doc */
1099 0, /* tp_traverse */
1100 0, /* tp_clear */
1101 0, /* tp_richcompare */
1102 0, /* tp_weaklistoffset */
1103 PyObject_SelfIter, /* tp_iter */
1104 (iternextfunc)longrangeiter_next, /* tp_iternext */
1105 longrangeiter_methods, /* tp_methods */
1106 0,
Raymond Hettinger48165d42002-06-05 20:08:48 +00001107};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001108
1109static PyObject *
Benjamin Petersona1864f32010-11-20 23:05:39 +00001110range_iter(PyObject *seq)
1111{
Guido van Rossum805365e2007-05-07 22:24:25 +00001112 rangeobject *r = (rangeobject *)seq;
1113 longrangeiterobject *it;
Martin v. Löwis84451042007-12-20 22:57:23 +00001114 long lstart, lstop, lstep;
Mark Dickinsond550c9a2009-11-15 09:57:26 +00001115 PyObject *int_it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001116
Guido van Rossum805365e2007-05-07 22:24:25 +00001117 assert(PyRange_Check(seq));
Martin v. Löwis84451042007-12-20 22:57:23 +00001118
Mark Dickinsond550c9a2009-11-15 09:57:26 +00001119 /* If all three fields and the length convert to long, use the int
1120 * version */
Martin v. Löwis84451042007-12-20 22:57:23 +00001121 lstart = PyLong_AsLong(r->start);
Mark Dickinsond550c9a2009-11-15 09:57:26 +00001122 if (lstart == -1 && PyErr_Occurred()) {
1123 PyErr_Clear();
1124 goto long_range;
Martin v. Löwis84451042007-12-20 22:57:23 +00001125 }
Mark Dickinsond550c9a2009-11-15 09:57:26 +00001126 lstop = PyLong_AsLong(r->stop);
1127 if (lstop == -1 && PyErr_Occurred()) {
1128 PyErr_Clear();
1129 goto long_range;
1130 }
1131 lstep = PyLong_AsLong(r->step);
1132 if (lstep == -1 && PyErr_Occurred()) {
1133 PyErr_Clear();
1134 goto long_range;
1135 }
Nick Coghlan37ee8502010-12-03 14:26:13 +00001136 int_it = fast_range_iter(lstart, lstop, lstep);
Mark Dickinsond550c9a2009-11-15 09:57:26 +00001137 if (int_it == NULL && PyErr_ExceptionMatches(PyExc_OverflowError)) {
1138 PyErr_Clear();
1139 goto long_range;
1140 }
1141 return (PyObject *)int_it;
1142
1143 long_range:
Christian Heimesa22e8bd2007-11-29 22:35:39 +00001144 it = PyObject_New(longrangeiterobject, &PyLongRangeIter_Type);
Guido van Rossum805365e2007-05-07 22:24:25 +00001145 if (it == NULL)
1146 return NULL;
Guido van Rossum317e7742007-05-08 15:18:31 +00001147
1148 /* Do all initialization here, so we can DECREF on failure. */
Guido van Rossum805365e2007-05-07 22:24:25 +00001149 it->start = r->start;
Guido van Rossum317e7742007-05-08 15:18:31 +00001150 it->step = r->step;
Nick Coghlan37ee8502010-12-03 14:26:13 +00001151 it->len = r->length;
Guido van Rossum317e7742007-05-08 15:18:31 +00001152 Py_INCREF(it->start);
1153 Py_INCREF(it->step);
Nick Coghlan37ee8502010-12-03 14:26:13 +00001154 Py_INCREF(it->len);
Guido van Rossum317e7742007-05-08 15:18:31 +00001155
Guido van Rossum805365e2007-05-07 22:24:25 +00001156 it->index = PyLong_FromLong(0);
1157 if (!it->index)
1158 goto create_failure;
1159
Guido van Rossum805365e2007-05-07 22:24:25 +00001160 return (PyObject *)it;
1161
1162create_failure:
Guido van Rossum317e7742007-05-08 15:18:31 +00001163 Py_DECREF(it);
Guido van Rossum805365e2007-05-07 22:24:25 +00001164 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001165}
1166
1167static PyObject *
Benjamin Petersona1864f32010-11-20 23:05:39 +00001168range_reverse(PyObject *seq)
1169{
Guido van Rossum805365e2007-05-07 22:24:25 +00001170 rangeobject *range = (rangeobject*) seq;
1171 longrangeiterobject *it;
Nick Coghlan37ee8502010-12-03 14:26:13 +00001172 PyObject *one, *sum, *diff, *product;
Mark Dickinsond550c9a2009-11-15 09:57:26 +00001173 long lstart, lstop, lstep, new_start, new_stop;
1174 unsigned long ulen;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001175
Guido van Rossum805365e2007-05-07 22:24:25 +00001176 assert(PyRange_Check(seq));
Martin v. Löwis84451042007-12-20 22:57:23 +00001177
Mark Dickinsond550c9a2009-11-15 09:57:26 +00001178 /* reversed(range(start, stop, step)) can be expressed as
1179 range(start+(n-1)*step, start-step, -step), where n is the number of
1180 integers in the range.
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001181
Mark Dickinsond550c9a2009-11-15 09:57:26 +00001182 If each of start, stop, step, -step, start-step, and the length
1183 of the iterator is representable as a C long, use the int
1184 version. This excludes some cases where the reversed range is
1185 representable as a range_iterator, but it's good enough for
1186 common cases and it makes the checks simple. */
1187
1188 lstart = PyLong_AsLong(range->start);
1189 if (lstart == -1 && PyErr_Occurred()) {
1190 PyErr_Clear();
1191 goto long_range;
1192 }
1193 lstop = PyLong_AsLong(range->stop);
1194 if (lstop == -1 && PyErr_Occurred()) {
1195 PyErr_Clear();
1196 goto long_range;
1197 }
1198 lstep = PyLong_AsLong(range->step);
1199 if (lstep == -1 && PyErr_Occurred()) {
1200 PyErr_Clear();
1201 goto long_range;
1202 }
1203 /* check for possible overflow of -lstep */
1204 if (lstep == LONG_MIN)
1205 goto long_range;
1206
1207 /* check for overflow of lstart - lstep:
1208
1209 for lstep > 0, need only check whether lstart - lstep < LONG_MIN.
1210 for lstep < 0, need only check whether lstart - lstep > LONG_MAX
1211
1212 Rearrange these inequalities as:
1213
1214 lstart - LONG_MIN < lstep (lstep > 0)
1215 LONG_MAX - lstart < -lstep (lstep < 0)
1216
1217 and compute both sides as unsigned longs, to avoid the
1218 possibility of undefined behaviour due to signed overflow. */
1219
1220 if (lstep > 0) {
1221 if ((unsigned long)lstart - LONG_MIN < (unsigned long)lstep)
1222 goto long_range;
1223 }
1224 else {
1225 if (LONG_MAX - (unsigned long)lstart < 0UL - lstep)
1226 goto long_range;
1227 }
1228
Mark Dickinsond550c9a2009-11-15 09:57:26 +00001229 ulen = get_len_of_range(lstart, lstop, lstep);
1230 if (ulen > (unsigned long)LONG_MAX)
1231 goto long_range;
1232
1233 new_stop = lstart - lstep;
1234 new_start = (long)(new_stop + ulen * lstep);
Nick Coghlan37ee8502010-12-03 14:26:13 +00001235 return fast_range_iter(new_start, new_stop, -lstep);
Mark Dickinsond550c9a2009-11-15 09:57:26 +00001236
1237long_range:
Christian Heimesa22e8bd2007-11-29 22:35:39 +00001238 it = PyObject_New(longrangeiterobject, &PyLongRangeIter_Type);
Guido van Rossum805365e2007-05-07 22:24:25 +00001239 if (it == NULL)
1240 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001241
Guido van Rossum805365e2007-05-07 22:24:25 +00001242 /* start + (len - 1) * step */
Nick Coghlan37ee8502010-12-03 14:26:13 +00001243 it->len = range->length;
1244 Py_INCREF(it->len);
Benjamin Peterson36fbb732009-11-16 00:34:25 +00001245
Guido van Rossum805365e2007-05-07 22:24:25 +00001246 one = PyLong_FromLong(1);
1247 if (!one)
1248 goto create_failure;
1249
Nick Coghlan37ee8502010-12-03 14:26:13 +00001250 diff = PyNumber_Subtract(it->len, one);
Guido van Rossum805365e2007-05-07 22:24:25 +00001251 Py_DECREF(one);
1252 if (!diff)
1253 goto create_failure;
1254
Mark Dickinsond550c9a2009-11-15 09:57:26 +00001255 product = PyNumber_Multiply(diff, range->step);
1256 Py_DECREF(diff);
Guido van Rossum805365e2007-05-07 22:24:25 +00001257 if (!product)
1258 goto create_failure;
1259
1260 sum = PyNumber_Add(range->start, product);
1261 Py_DECREF(product);
1262 it->start = sum;
1263 if (!it->start)
1264 goto create_failure;
Mark Dickinsond550c9a2009-11-15 09:57:26 +00001265
Guido van Rossum805365e2007-05-07 22:24:25 +00001266 it->step = PyNumber_Negative(range->step);
Benjamin Peterson36fbb732009-11-16 00:34:25 +00001267 if (!it->step)
Mark Dickinsond550c9a2009-11-15 09:57:26 +00001268 goto create_failure;
Guido van Rossum805365e2007-05-07 22:24:25 +00001269
1270 it->index = PyLong_FromLong(0);
Benjamin Peterson36fbb732009-11-16 00:34:25 +00001271 if (!it->index)
1272 goto create_failure;
Guido van Rossum805365e2007-05-07 22:24:25 +00001273
1274 return (PyObject *)it;
1275
1276create_failure:
Benjamin Peterson36fbb732009-11-16 00:34:25 +00001277 Py_DECREF(it);
Guido van Rossum805365e2007-05-07 22:24:25 +00001278 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001279}