This commit was manufactured by cvs2svn to create tag 'r234c1'.
[python/dscho.git] / Objects / listobject.c
blob727c9e6d692112cd5fbb1c8d988a8c2b5a27281c
1 /* List object implementation */
3 #include "Python.h"
5 #ifdef STDC_HEADERS
6 #include <stddef.h>
7 #else
8 #include <sys/types.h> /* For size_t */
9 #endif
11 static int
12 roundupsize(int n)
14 unsigned int nbits = 0;
15 unsigned int n2 = (unsigned int)n >> 5;
17 /* Round up:
18 * If n < 256, to a multiple of 8.
19 * If n < 2048, to a multiple of 64.
20 * If n < 16384, to a multiple of 512.
21 * If n < 131072, to a multiple of 4096.
22 * If n < 1048576, to a multiple of 32768.
23 * If n < 8388608, to a multiple of 262144.
24 * If n < 67108864, to a multiple of 2097152.
25 * If n < 536870912, to a multiple of 16777216.
26 * ...
27 * If n < 2**(5+3*i), to a multiple of 2**(3*i).
29 * This over-allocates proportional to the list size, making room
30 * for additional growth. The over-allocation is mild, but is
31 * enough to give linear-time amortized behavior over a long
32 * sequence of appends() in the presence of a poorly-performing
33 * system realloc() (which is a reality, e.g., across all flavors
34 * of Windows, with Win9x behavior being particularly bad -- and
35 * we've still got address space fragmentation problems on Win9x
36 * even with this scheme, although it requires much longer lists to
37 * provoke them than it used to).
39 do {
40 n2 >>= 3;
41 nbits += 3;
42 } while (n2);
43 return ((n >> nbits) + 1) << nbits;
46 #define NRESIZE(var, type, nitems) \
47 do { \
48 size_t _new_size = roundupsize(nitems); \
49 if (_new_size <= ((~(size_t)0) / sizeof(type))) \
50 PyMem_RESIZE(var, type, _new_size); \
51 else \
52 var = NULL; \
53 } while (0)
55 PyObject *
56 PyList_New(int size)
58 PyListObject *op;
59 size_t nbytes;
60 if (size < 0) {
61 PyErr_BadInternalCall();
62 return NULL;
64 nbytes = size * sizeof(PyObject *);
65 /* Check for overflow */
66 if (nbytes / sizeof(PyObject *) != (size_t)size) {
67 return PyErr_NoMemory();
69 op = PyObject_GC_New(PyListObject, &PyList_Type);
70 if (op == NULL) {
71 return NULL;
73 if (size <= 0) {
74 op->ob_item = NULL;
76 else {
77 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
78 if (op->ob_item == NULL) {
79 return PyErr_NoMemory();
81 memset(op->ob_item, 0, sizeof(*op->ob_item) * size);
83 op->ob_size = size;
84 _PyObject_GC_TRACK(op);
85 return (PyObject *) op;
88 int
89 PyList_Size(PyObject *op)
91 if (!PyList_Check(op)) {
92 PyErr_BadInternalCall();
93 return -1;
95 else
96 return ((PyListObject *)op) -> ob_size;
99 static PyObject *indexerr;
101 PyObject *
102 PyList_GetItem(PyObject *op, int i)
104 if (!PyList_Check(op)) {
105 PyErr_BadInternalCall();
106 return NULL;
108 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
109 if (indexerr == NULL)
110 indexerr = PyString_FromString(
111 "list index out of range");
112 PyErr_SetObject(PyExc_IndexError, indexerr);
113 return NULL;
115 return ((PyListObject *)op) -> ob_item[i];
119 PyList_SetItem(register PyObject *op, register int i,
120 register PyObject *newitem)
122 register PyObject *olditem;
123 register PyObject **p;
124 if (!PyList_Check(op)) {
125 Py_XDECREF(newitem);
126 PyErr_BadInternalCall();
127 return -1;
129 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
130 Py_XDECREF(newitem);
131 PyErr_SetString(PyExc_IndexError,
132 "list assignment index out of range");
133 return -1;
135 p = ((PyListObject *)op) -> ob_item + i;
136 olditem = *p;
137 *p = newitem;
138 Py_XDECREF(olditem);
139 return 0;
142 static int
143 ins1(PyListObject *self, int where, PyObject *v)
145 int i;
146 PyObject **items;
147 if (v == NULL) {
148 PyErr_BadInternalCall();
149 return -1;
151 if (self->ob_size == INT_MAX) {
152 PyErr_SetString(PyExc_OverflowError,
153 "cannot add more objects to list");
154 return -1;
156 items = self->ob_item;
157 NRESIZE(items, PyObject *, self->ob_size+1);
158 if (items == NULL) {
159 PyErr_NoMemory();
160 return -1;
162 if (where < 0) {
163 where += self->ob_size;
164 if (where < 0)
165 where = 0;
167 if (where > self->ob_size)
168 where = self->ob_size;
169 for (i = self->ob_size; --i >= where; )
170 items[i+1] = items[i];
171 Py_INCREF(v);
172 items[where] = v;
173 self->ob_item = items;
174 self->ob_size++;
175 return 0;
179 PyList_Insert(PyObject *op, int where, PyObject *newitem)
181 if (!PyList_Check(op)) {
182 PyErr_BadInternalCall();
183 return -1;
185 return ins1((PyListObject *)op, where, newitem);
189 PyList_Append(PyObject *op, PyObject *newitem)
191 if (!PyList_Check(op)) {
192 PyErr_BadInternalCall();
193 return -1;
195 return ins1((PyListObject *)op,
196 (int) ((PyListObject *)op)->ob_size, newitem);
199 /* Methods */
201 static void
202 list_dealloc(PyListObject *op)
204 int i;
205 PyObject_GC_UnTrack(op);
206 Py_TRASHCAN_SAFE_BEGIN(op)
207 if (op->ob_item != NULL) {
208 /* Do it backwards, for Christian Tismer.
209 There's a simple test case where somehow this reduces
210 thrashing when a *very* large list is created and
211 immediately deleted. */
212 i = op->ob_size;
213 while (--i >= 0) {
214 Py_XDECREF(op->ob_item[i]);
216 PyMem_FREE(op->ob_item);
218 op->ob_type->tp_free((PyObject *)op);
219 Py_TRASHCAN_SAFE_END(op)
222 static int
223 list_print(PyListObject *op, FILE *fp, int flags)
225 int i;
227 i = Py_ReprEnter((PyObject*)op);
228 if (i != 0) {
229 if (i < 0)
230 return i;
231 fprintf(fp, "[...]");
232 return 0;
234 fprintf(fp, "[");
235 for (i = 0; i < op->ob_size; i++) {
236 if (i > 0)
237 fprintf(fp, ", ");
238 if (PyObject_Print(op->ob_item[i], fp, 0) != 0) {
239 Py_ReprLeave((PyObject *)op);
240 return -1;
243 fprintf(fp, "]");
244 Py_ReprLeave((PyObject *)op);
245 return 0;
248 static PyObject *
249 list_repr(PyListObject *v)
251 int i;
252 PyObject *s, *temp;
253 PyObject *pieces = NULL, *result = NULL;
255 i = Py_ReprEnter((PyObject*)v);
256 if (i != 0) {
257 return i > 0 ? PyString_FromString("[...]") : NULL;
260 if (v->ob_size == 0) {
261 result = PyString_FromString("[]");
262 goto Done;
265 pieces = PyList_New(0);
266 if (pieces == NULL)
267 goto Done;
269 /* Do repr() on each element. Note that this may mutate the list,
270 so must refetch the list size on each iteration. */
271 for (i = 0; i < v->ob_size; ++i) {
272 int status;
273 s = PyObject_Repr(v->ob_item[i]);
274 if (s == NULL)
275 goto Done;
276 status = PyList_Append(pieces, s);
277 Py_DECREF(s); /* append created a new ref */
278 if (status < 0)
279 goto Done;
282 /* Add "[]" decorations to the first and last items. */
283 assert(PyList_GET_SIZE(pieces) > 0);
284 s = PyString_FromString("[");
285 if (s == NULL)
286 goto Done;
287 temp = PyList_GET_ITEM(pieces, 0);
288 PyString_ConcatAndDel(&s, temp);
289 PyList_SET_ITEM(pieces, 0, s);
290 if (s == NULL)
291 goto Done;
293 s = PyString_FromString("]");
294 if (s == NULL)
295 goto Done;
296 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
297 PyString_ConcatAndDel(&temp, s);
298 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
299 if (temp == NULL)
300 goto Done;
302 /* Paste them all together with ", " between. */
303 s = PyString_FromString(", ");
304 if (s == NULL)
305 goto Done;
306 result = _PyString_Join(s, pieces);
307 Py_DECREF(s);
309 Done:
310 Py_XDECREF(pieces);
311 Py_ReprLeave((PyObject *)v);
312 return result;
315 static int
316 list_length(PyListObject *a)
318 return a->ob_size;
323 static int
324 list_contains(PyListObject *a, PyObject *el)
326 int i, cmp;
328 for (i = 0, cmp = 0 ; cmp == 0 && i < a->ob_size; ++i)
329 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
330 Py_EQ);
331 return cmp;
335 static PyObject *
336 list_item(PyListObject *a, int i)
338 if (i < 0 || i >= a->ob_size) {
339 if (indexerr == NULL)
340 indexerr = PyString_FromString(
341 "list index out of range");
342 PyErr_SetObject(PyExc_IndexError, indexerr);
343 return NULL;
345 Py_INCREF(a->ob_item[i]);
346 return a->ob_item[i];
349 static PyObject *
350 list_slice(PyListObject *a, int ilow, int ihigh)
352 PyListObject *np;
353 int i;
354 if (ilow < 0)
355 ilow = 0;
356 else if (ilow > a->ob_size)
357 ilow = a->ob_size;
358 if (ihigh < ilow)
359 ihigh = ilow;
360 else if (ihigh > a->ob_size)
361 ihigh = a->ob_size;
362 np = (PyListObject *) PyList_New(ihigh - ilow);
363 if (np == NULL)
364 return NULL;
365 for (i = ilow; i < ihigh; i++) {
366 PyObject *v = a->ob_item[i];
367 Py_INCREF(v);
368 np->ob_item[i - ilow] = v;
370 return (PyObject *)np;
373 PyObject *
374 PyList_GetSlice(PyObject *a, int ilow, int ihigh)
376 if (!PyList_Check(a)) {
377 PyErr_BadInternalCall();
378 return NULL;
380 return list_slice((PyListObject *)a, ilow, ihigh);
383 static PyObject *
384 list_concat(PyListObject *a, PyObject *bb)
386 int size;
387 int i;
388 PyListObject *np;
389 if (!PyList_Check(bb)) {
390 PyErr_Format(PyExc_TypeError,
391 "can only concatenate list (not \"%.200s\") to list",
392 bb->ob_type->tp_name);
393 return NULL;
395 #define b ((PyListObject *)bb)
396 size = a->ob_size + b->ob_size;
397 if (size < 0)
398 return PyErr_NoMemory();
399 np = (PyListObject *) PyList_New(size);
400 if (np == NULL) {
401 return NULL;
403 for (i = 0; i < a->ob_size; i++) {
404 PyObject *v = a->ob_item[i];
405 Py_INCREF(v);
406 np->ob_item[i] = v;
408 for (i = 0; i < b->ob_size; i++) {
409 PyObject *v = b->ob_item[i];
410 Py_INCREF(v);
411 np->ob_item[i + a->ob_size] = v;
413 return (PyObject *)np;
414 #undef b
417 static PyObject *
418 list_repeat(PyListObject *a, int n)
420 int i, j;
421 int size;
422 PyListObject *np;
423 PyObject **p;
424 PyObject *elem;
425 if (n < 0)
426 n = 0;
427 size = a->ob_size * n;
428 if (size == 0)
429 return PyList_New(0);
430 if (n && size/n != a->ob_size)
431 return PyErr_NoMemory();
432 np = (PyListObject *) PyList_New(size);
433 if (np == NULL)
434 return NULL;
436 if (a->ob_size == 1) {
437 elem = a->ob_item[0];
438 for (i = 0; i < n; i++) {
439 np->ob_item[i] = elem;
440 Py_INCREF(elem);
442 return (PyObject *) np;
444 p = np->ob_item;
445 for (i = 0; i < n; i++) {
446 for (j = 0; j < a->ob_size; j++) {
447 *p = a->ob_item[j];
448 Py_INCREF(*p);
449 p++;
452 return (PyObject *) np;
455 static int
456 list_ass_slice(PyListObject *a, int ilow, int ihigh, PyObject *v)
458 /* Because [X]DECREF can recursively invoke list operations on
459 this list, we must postpone all [X]DECREF activity until
460 after the list is back in its canonical shape. Therefore
461 we must allocate an additional array, 'recycle', into which
462 we temporarily copy the items that are deleted from the
463 list. :-( */
464 PyObject **recycle, **p;
465 PyObject **item;
466 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
467 int n; /* Size of replacement list */
468 int d; /* Change in size */
469 int k; /* Loop index */
470 #define b ((PyListObject *)v)
471 if (v == NULL)
472 n = 0;
473 else {
474 char msg[256];
475 if (a == b) {
476 /* Special case "a[i:j] = a" -- copy b first */
477 int ret;
478 v = list_slice(b, 0, b->ob_size);
479 if (v == NULL)
480 return -1;
481 ret = list_ass_slice(a, ilow, ihigh, v);
482 Py_DECREF(v);
483 return ret;
486 PyOS_snprintf(msg, sizeof(msg),
487 "must assign sequence"
488 " (not \"%.200s\") to slice",
489 v->ob_type->tp_name);
490 v_as_SF = PySequence_Fast(v, msg);
491 if(v_as_SF == NULL)
492 return -1;
493 n = PySequence_Fast_GET_SIZE(v_as_SF);
495 if (ilow < 0)
496 ilow = 0;
497 else if (ilow > a->ob_size)
498 ilow = a->ob_size;
499 if (ihigh < ilow)
500 ihigh = ilow;
501 else if (ihigh > a->ob_size)
502 ihigh = a->ob_size;
503 item = a->ob_item;
504 d = n - (ihigh-ilow);
505 if (ihigh > ilow) {
506 p = recycle = PyMem_NEW(PyObject *, (ihigh-ilow));
507 if (recycle == NULL) {
508 PyErr_NoMemory();
509 return -1;
512 else
513 p = recycle = NULL;
514 if (d <= 0) { /* Delete -d items; recycle ihigh-ilow items */
515 for (k = ilow; k < ihigh; k++)
516 *p++ = item[k];
517 if (d < 0) {
518 for (/*k = ihigh*/; k < a->ob_size; k++)
519 item[k+d] = item[k];
520 a->ob_size += d;
521 NRESIZE(item, PyObject *, a->ob_size); /* Can't fail */
522 a->ob_item = item;
525 else { /* Insert d items; recycle ihigh-ilow items */
526 NRESIZE(item, PyObject *, a->ob_size + d);
527 if (item == NULL) {
528 if (recycle != NULL)
529 PyMem_DEL(recycle);
530 PyErr_NoMemory();
531 return -1;
533 for (k = a->ob_size; --k >= ihigh; )
534 item[k+d] = item[k];
535 for (/*k = ihigh-1*/; k >= ilow; --k)
536 *p++ = item[k];
537 a->ob_item = item;
538 a->ob_size += d;
540 for (k = 0; k < n; k++, ilow++) {
541 PyObject *w = PySequence_Fast_GET_ITEM(v_as_SF, k);
542 Py_XINCREF(w);
543 item[ilow] = w;
545 if (recycle) {
546 while (--p >= recycle)
547 Py_XDECREF(*p);
548 PyMem_DEL(recycle);
550 if (a->ob_size == 0 && a->ob_item != NULL) {
551 PyMem_FREE(a->ob_item);
552 a->ob_item = NULL;
554 Py_XDECREF(v_as_SF);
555 return 0;
556 #undef b
560 PyList_SetSlice(PyObject *a, int ilow, int ihigh, PyObject *v)
562 if (!PyList_Check(a)) {
563 PyErr_BadInternalCall();
564 return -1;
566 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
569 static PyObject *
570 list_inplace_repeat(PyListObject *self, int n)
572 PyObject **items;
573 int size, i, j;
576 size = PyList_GET_SIZE(self);
577 if (size == 0) {
578 Py_INCREF(self);
579 return (PyObject *)self;
582 items = self->ob_item;
584 if (n < 1) {
585 self->ob_item = NULL;
586 self->ob_size = 0;
587 for (i = 0; i < size; i++)
588 Py_XDECREF(items[i]);
589 PyMem_DEL(items);
590 Py_INCREF(self);
591 return (PyObject *)self;
594 NRESIZE(items, PyObject*, size*n);
595 if (items == NULL) {
596 PyErr_NoMemory();
597 goto finally;
599 self->ob_item = items;
600 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
601 for (j = 0; j < size; j++) {
602 PyObject *o = PyList_GET_ITEM(self, j);
603 Py_INCREF(o);
604 PyList_SET_ITEM(self, self->ob_size++, o);
607 Py_INCREF(self);
608 return (PyObject *)self;
609 finally:
610 return NULL;
613 static int
614 list_ass_item(PyListObject *a, int i, PyObject *v)
616 PyObject *old_value;
617 if (i < 0 || i >= a->ob_size) {
618 PyErr_SetString(PyExc_IndexError,
619 "list assignment index out of range");
620 return -1;
622 if (v == NULL)
623 return list_ass_slice(a, i, i+1, v);
624 Py_INCREF(v);
625 old_value = a->ob_item[i];
626 a->ob_item[i] = v;
627 Py_DECREF(old_value);
628 return 0;
631 static PyObject *
632 ins(PyListObject *self, int where, PyObject *v)
634 if (ins1(self, where, v) != 0)
635 return NULL;
636 Py_INCREF(Py_None);
637 return Py_None;
640 static PyObject *
641 listinsert(PyListObject *self, PyObject *args)
643 int i;
644 PyObject *v;
645 if (!PyArg_ParseTuple(args, "iO:insert", &i, &v))
646 return NULL;
647 return ins(self, i, v);
650 static PyObject *
651 listappend(PyListObject *self, PyObject *v)
653 return ins(self, (int) self->ob_size, v);
656 static int
657 listextend_internal(PyListObject *self, PyObject *b)
659 PyObject **items;
660 int selflen = PyList_GET_SIZE(self);
661 int blen;
662 register int i;
664 if (PyObject_Size(b) == 0) {
665 /* short circuit when b is empty */
666 Py_DECREF(b);
667 return 0;
670 if (self == (PyListObject*)b) {
671 /* as in list_ass_slice() we must special case the
672 * situation: a.extend(a)
674 * XXX: I think this way ought to be faster than using
675 * list_slice() the way list_ass_slice() does.
677 Py_DECREF(b);
678 b = PyList_New(selflen);
679 if (!b)
680 return -1;
681 for (i = 0; i < selflen; i++) {
682 PyObject *o = PyList_GET_ITEM(self, i);
683 Py_INCREF(o);
684 PyList_SET_ITEM(b, i, o);
688 blen = PyObject_Size(b);
690 /* resize a using idiom */
691 items = self->ob_item;
692 NRESIZE(items, PyObject*, selflen + blen);
693 if (items == NULL) {
694 PyErr_NoMemory();
695 Py_DECREF(b);
696 return -1;
699 self->ob_item = items;
701 /* populate the end of self with b's items */
702 for (i = 0; i < blen; i++) {
703 PyObject *o = PySequence_Fast_GET_ITEM(b, i);
704 Py_INCREF(o);
705 PyList_SET_ITEM(self, self->ob_size++, o);
707 Py_DECREF(b);
708 return 0;
712 static PyObject *
713 list_inplace_concat(PyListObject *self, PyObject *other)
715 other = PySequence_Fast(other, "argument to += must be iterable");
716 if (!other)
717 return NULL;
719 if (listextend_internal(self, other) < 0)
720 return NULL;
722 Py_INCREF(self);
723 return (PyObject *)self;
726 static PyObject *
727 listextend(PyListObject *self, PyObject *b)
730 b = PySequence_Fast(b, "list.extend() argument must be iterable");
731 if (!b)
732 return NULL;
734 if (listextend_internal(self, b) < 0)
735 return NULL;
737 Py_INCREF(Py_None);
738 return Py_None;
741 static PyObject *
742 listpop(PyListObject *self, PyObject *args)
744 int i = -1;
745 PyObject *v;
746 if (!PyArg_ParseTuple(args, "|i:pop", &i))
747 return NULL;
748 if (self->ob_size == 0) {
749 /* Special-case most common failure cause */
750 PyErr_SetString(PyExc_IndexError, "pop from empty list");
751 return NULL;
753 if (i < 0)
754 i += self->ob_size;
755 if (i < 0 || i >= self->ob_size) {
756 PyErr_SetString(PyExc_IndexError, "pop index out of range");
757 return NULL;
759 v = self->ob_item[i];
760 Py_INCREF(v);
761 if (list_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) {
762 Py_DECREF(v);
763 return NULL;
765 return v;
768 /* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
769 static void
770 reverse_slice(PyObject **lo, PyObject **hi)
772 assert(lo && hi);
774 --hi;
775 while (lo < hi) {
776 PyObject *t = *lo;
777 *lo = *hi;
778 *hi = t;
779 ++lo;
780 --hi;
784 /* Lots of code for an adaptive, stable, natural mergesort. There are many
785 * pieces to this algorithm; read listsort.txt for overviews and details.
788 /* Comparison function. Takes care of calling a user-supplied
789 * comparison function (any callable Python object), which must not be
790 * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool
791 * with Py_LT if you know it's NULL).
792 * Returns -1 on error, 1 if x < y, 0 if x >= y.
794 static int
795 islt(PyObject *x, PyObject *y, PyObject *compare)
797 PyObject *res;
798 PyObject *args;
799 int i;
801 assert(compare != NULL);
802 /* Call the user's comparison function and translate the 3-way
803 * result into true or false (or error).
805 args = PyTuple_New(2);
806 if (args == NULL)
807 return -1;
808 Py_INCREF(x);
809 Py_INCREF(y);
810 PyTuple_SET_ITEM(args, 0, x);
811 PyTuple_SET_ITEM(args, 1, y);
812 res = PyObject_Call(compare, args, NULL);
813 Py_DECREF(args);
814 if (res == NULL)
815 return -1;
816 if (!PyInt_Check(res)) {
817 Py_DECREF(res);
818 PyErr_SetString(PyExc_TypeError,
819 "comparison function must return int");
820 return -1;
822 i = PyInt_AsLong(res);
823 Py_DECREF(res);
824 return i < 0;
827 /* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
828 * islt. This avoids a layer of function call in the usual case, and
829 * sorting does many comparisons.
830 * Returns -1 on error, 1 if x < y, 0 if x >= y.
832 #define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
833 PyObject_RichCompareBool(X, Y, Py_LT) : \
834 islt(X, Y, COMPARE))
836 /* Compare X to Y via "<". Goto "fail" if the comparison raises an
837 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
838 started. It makes more sense in context <wink>. X and Y are PyObject*s.
840 #define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
841 if (k)
843 /* binarysort is the best method for sorting small arrays: it does
844 few compares, but can do data movement quadratic in the number of
845 elements.
846 [lo, hi) is a contiguous slice of a list, and is sorted via
847 binary insertion. This sort is stable.
848 On entry, must have lo <= start <= hi, and that [lo, start) is already
849 sorted (pass start == lo if you don't know!).
850 If islt() complains return -1, else 0.
851 Even in case of error, the output slice will be some permutation of
852 the input (nothing is lost or duplicated).
854 static int
855 binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
856 /* compare -- comparison function object, or NULL for default */
858 register int k;
859 register PyObject **l, **p, **r;
860 register PyObject *pivot;
862 assert(lo <= start && start <= hi);
863 /* assert [lo, start) is sorted */
864 if (lo == start)
865 ++start;
866 for (; start < hi; ++start) {
867 /* set l to where *start belongs */
868 l = lo;
869 r = start;
870 pivot = *r;
871 /* Invariants:
872 * pivot >= all in [lo, l).
873 * pivot < all in [r, start).
874 * The second is vacuously true at the start.
876 assert(l < r);
877 do {
878 p = l + ((r - l) >> 1);
879 IFLT(pivot, *p)
880 r = p;
881 else
882 l = p+1;
883 } while (l < r);
884 assert(l == r);
885 /* The invariants still hold, so pivot >= all in [lo, l) and
886 pivot < all in [l, start), so pivot belongs at l. Note
887 that if there are elements equal to pivot, l points to the
888 first slot after them -- that's why this sort is stable.
889 Slide over to make room.
890 Caution: using memmove is much slower under MSVC 5;
891 we're not usually moving many slots. */
892 for (p = start; p > l; --p)
893 *p = *(p-1);
894 *l = pivot;
896 return 0;
898 fail:
899 return -1;
903 Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
904 is required on entry. "A run" is the longest ascending sequence, with
906 lo[0] <= lo[1] <= lo[2] <= ...
908 or the longest descending sequence, with
910 lo[0] > lo[1] > lo[2] > ...
912 Boolean *descending is set to 0 in the former case, or to 1 in the latter.
913 For its intended use in a stable mergesort, the strictness of the defn of
914 "descending" is needed so that the caller can safely reverse a descending
915 sequence without violating stability (strict > ensures there are no equal
916 elements to get out of order).
918 Returns -1 in case of error.
920 static int
921 count_run(PyObject **lo, PyObject **hi, PyObject *compare, int *descending)
923 int k;
924 int n;
926 assert(lo < hi);
927 *descending = 0;
928 ++lo;
929 if (lo == hi)
930 return 1;
932 n = 2;
933 IFLT(*lo, *(lo-1)) {
934 *descending = 1;
935 for (lo = lo+1; lo < hi; ++lo, ++n) {
936 IFLT(*lo, *(lo-1))
938 else
939 break;
942 else {
943 for (lo = lo+1; lo < hi; ++lo, ++n) {
944 IFLT(*lo, *(lo-1))
945 break;
949 return n;
950 fail:
951 return -1;
955 Locate the proper position of key in a sorted vector; if the vector contains
956 an element equal to key, return the position immediately to the left of
957 the leftmost equal element. [gallop_right() does the same except returns
958 the position to the right of the rightmost equal element (if any).]
960 "a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
962 "hint" is an index at which to begin the search, 0 <= hint < n. The closer
963 hint is to the final result, the faster this runs.
965 The return value is the int k in 0..n such that
967 a[k-1] < key <= a[k]
969 pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
970 key belongs at index k; or, IOW, the first k elements of a should precede
971 key, and the last n-k should follow key.
973 Returns -1 on error. See listsort.txt for info on the method.
975 static int
976 gallop_left(PyObject *key, PyObject **a, int n, int hint, PyObject *compare)
978 int ofs;
979 int lastofs;
980 int k;
982 assert(key && a && n > 0 && hint >= 0 && hint < n);
984 a += hint;
985 lastofs = 0;
986 ofs = 1;
987 IFLT(*a, key) {
988 /* a[hint] < key -- gallop right, until
989 * a[hint + lastofs] < key <= a[hint + ofs]
991 const int maxofs = n - hint; /* &a[n-1] is highest */
992 while (ofs < maxofs) {
993 IFLT(a[ofs], key) {
994 lastofs = ofs;
995 ofs = (ofs << 1) + 1;
996 if (ofs <= 0) /* int overflow */
997 ofs = maxofs;
999 else /* key <= a[hint + ofs] */
1000 break;
1002 if (ofs > maxofs)
1003 ofs = maxofs;
1004 /* Translate back to offsets relative to &a[0]. */
1005 lastofs += hint;
1006 ofs += hint;
1008 else {
1009 /* key <= a[hint] -- gallop left, until
1010 * a[hint - ofs] < key <= a[hint - lastofs]
1012 const int maxofs = hint + 1; /* &a[0] is lowest */
1013 while (ofs < maxofs) {
1014 IFLT(*(a-ofs), key)
1015 break;
1016 /* key <= a[hint - ofs] */
1017 lastofs = ofs;
1018 ofs = (ofs << 1) + 1;
1019 if (ofs <= 0) /* int overflow */
1020 ofs = maxofs;
1022 if (ofs > maxofs)
1023 ofs = maxofs;
1024 /* Translate back to positive offsets relative to &a[0]. */
1025 k = lastofs;
1026 lastofs = hint - ofs;
1027 ofs = hint - k;
1029 a -= hint;
1031 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1032 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1033 * right of lastofs but no farther right than ofs. Do a binary
1034 * search, with invariant a[lastofs-1] < key <= a[ofs].
1036 ++lastofs;
1037 while (lastofs < ofs) {
1038 int m = lastofs + ((ofs - lastofs) >> 1);
1040 IFLT(a[m], key)
1041 lastofs = m+1; /* a[m] < key */
1042 else
1043 ofs = m; /* key <= a[m] */
1045 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1046 return ofs;
1048 fail:
1049 return -1;
1053 Exactly like gallop_left(), except that if key already exists in a[0:n],
1054 finds the position immediately to the right of the rightmost equal value.
1056 The return value is the int k in 0..n such that
1058 a[k-1] <= key < a[k]
1060 or -1 if error.
1062 The code duplication is massive, but this is enough different given that
1063 we're sticking to "<" comparisons that it's much harder to follow if
1064 written as one routine with yet another "left or right?" flag.
1066 static int
1067 gallop_right(PyObject *key, PyObject **a, int n, int hint, PyObject *compare)
1069 int ofs;
1070 int lastofs;
1071 int k;
1073 assert(key && a && n > 0 && hint >= 0 && hint < n);
1075 a += hint;
1076 lastofs = 0;
1077 ofs = 1;
1078 IFLT(key, *a) {
1079 /* key < a[hint] -- gallop left, until
1080 * a[hint - ofs] <= key < a[hint - lastofs]
1082 const int maxofs = hint + 1; /* &a[0] is lowest */
1083 while (ofs < maxofs) {
1084 IFLT(key, *(a-ofs)) {
1085 lastofs = ofs;
1086 ofs = (ofs << 1) + 1;
1087 if (ofs <= 0) /* int overflow */
1088 ofs = maxofs;
1090 else /* a[hint - ofs] <= key */
1091 break;
1093 if (ofs > maxofs)
1094 ofs = maxofs;
1095 /* Translate back to positive offsets relative to &a[0]. */
1096 k = lastofs;
1097 lastofs = hint - ofs;
1098 ofs = hint - k;
1100 else {
1101 /* a[hint] <= key -- gallop right, until
1102 * a[hint + lastofs] <= key < a[hint + ofs]
1104 const int maxofs = n - hint; /* &a[n-1] is highest */
1105 while (ofs < maxofs) {
1106 IFLT(key, a[ofs])
1107 break;
1108 /* a[hint + ofs] <= key */
1109 lastofs = ofs;
1110 ofs = (ofs << 1) + 1;
1111 if (ofs <= 0) /* int overflow */
1112 ofs = maxofs;
1114 if (ofs > maxofs)
1115 ofs = maxofs;
1116 /* Translate back to offsets relative to &a[0]. */
1117 lastofs += hint;
1118 ofs += hint;
1120 a -= hint;
1122 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1123 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1124 * right of lastofs but no farther right than ofs. Do a binary
1125 * search, with invariant a[lastofs-1] <= key < a[ofs].
1127 ++lastofs;
1128 while (lastofs < ofs) {
1129 int m = lastofs + ((ofs - lastofs) >> 1);
1131 IFLT(key, a[m])
1132 ofs = m; /* key < a[m] */
1133 else
1134 lastofs = m+1; /* a[m] <= key */
1136 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1137 return ofs;
1139 fail:
1140 return -1;
1143 /* The maximum number of entries in a MergeState's pending-runs stack.
1144 * This is enough to sort arrays of size up to about
1145 * 32 * phi ** MAX_MERGE_PENDING
1146 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1147 * with 2**64 elements.
1149 #define MAX_MERGE_PENDING 85
1151 /* When we get into galloping mode, we stay there until both runs win less
1152 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
1154 #define MIN_GALLOP 7
1156 /* Avoid malloc for small temp arrays. */
1157 #define MERGESTATE_TEMP_SIZE 256
1159 /* One MergeState exists on the stack per invocation of mergesort. It's just
1160 * a convenient way to pass state around among the helper functions.
1162 struct s_slice {
1163 PyObject **base;
1164 int len;
1167 typedef struct s_MergeState {
1168 /* The user-supplied comparison function. or NULL if none given. */
1169 PyObject *compare;
1171 /* This controls when we get *into* galloping mode. It's initialized
1172 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1173 * random data, and lower for highly structured data.
1175 int min_gallop;
1177 /* 'a' is temp storage to help with merges. It contains room for
1178 * alloced entries.
1180 PyObject **a; /* may point to temparray below */
1181 int alloced;
1183 /* A stack of n pending runs yet to be merged. Run #i starts at
1184 * address base[i] and extends for len[i] elements. It's always
1185 * true (so long as the indices are in bounds) that
1187 * pending[i].base + pending[i].len == pending[i+1].base
1189 * so we could cut the storage for this, but it's a minor amount,
1190 * and keeping all the info explicit simplifies the code.
1192 int n;
1193 struct s_slice pending[MAX_MERGE_PENDING];
1195 /* 'a' points to this when possible, rather than muck with malloc. */
1196 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1197 } MergeState;
1199 /* Conceptually a MergeState's constructor. */
1200 static void
1201 merge_init(MergeState *ms, PyObject *compare)
1203 assert(ms != NULL);
1204 ms->compare = compare;
1205 ms->a = ms->temparray;
1206 ms->alloced = MERGESTATE_TEMP_SIZE;
1207 ms->n = 0;
1208 ms->min_gallop = MIN_GALLOP;
1211 /* Free all the temp memory owned by the MergeState. This must be called
1212 * when you're done with a MergeState, and may be called before then if
1213 * you want to free the temp memory early.
1215 static void
1216 merge_freemem(MergeState *ms)
1218 assert(ms != NULL);
1219 if (ms->a != ms->temparray)
1220 PyMem_Free(ms->a);
1221 ms->a = ms->temparray;
1222 ms->alloced = MERGESTATE_TEMP_SIZE;
1225 /* Ensure enough temp memory for 'need' array slots is available.
1226 * Returns 0 on success and -1 if the memory can't be gotten.
1228 static int
1229 merge_getmem(MergeState *ms, int need)
1231 assert(ms != NULL);
1232 if (need <= ms->alloced)
1233 return 0;
1234 /* Don't realloc! That can cost cycles to copy the old data, but
1235 * we don't care what's in the block.
1237 merge_freemem(ms);
1238 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1239 if (ms->a) {
1240 ms->alloced = need;
1241 return 0;
1243 PyErr_NoMemory();
1244 merge_freemem(ms); /* reset to sane state */
1245 return -1;
1247 #define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1248 merge_getmem(MS, NEED))
1250 /* Merge the na elements starting at pa with the nb elements starting at pb
1251 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1252 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1253 * merge, and should have na <= nb. See listsort.txt for more info.
1254 * Return 0 if successful, -1 if error.
1256 static int
1257 merge_lo(MergeState *ms, PyObject **pa, int na, PyObject **pb, int nb)
1259 int k;
1260 PyObject *compare;
1261 PyObject **dest;
1262 int result = -1; /* guilty until proved innocent */
1263 int min_gallop = ms->min_gallop;
1265 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1266 if (MERGE_GETMEM(ms, na) < 0)
1267 return -1;
1268 memcpy(ms->a, pa, na * sizeof(PyObject*));
1269 dest = pa;
1270 pa = ms->a;
1272 *dest++ = *pb++;
1273 --nb;
1274 if (nb == 0)
1275 goto Succeed;
1276 if (na == 1)
1277 goto CopyB;
1279 compare = ms->compare;
1280 for (;;) {
1281 int acount = 0; /* # of times A won in a row */
1282 int bcount = 0; /* # of times B won in a row */
1284 /* Do the straightforward thing until (if ever) one run
1285 * appears to win consistently.
1287 for (;;) {
1288 assert(na > 1 && nb > 0);
1289 k = ISLT(*pb, *pa, compare);
1290 if (k) {
1291 if (k < 0)
1292 goto Fail;
1293 *dest++ = *pb++;
1294 ++bcount;
1295 acount = 0;
1296 --nb;
1297 if (nb == 0)
1298 goto Succeed;
1299 if (bcount >= min_gallop)
1300 break;
1302 else {
1303 *dest++ = *pa++;
1304 ++acount;
1305 bcount = 0;
1306 --na;
1307 if (na == 1)
1308 goto CopyB;
1309 if (acount >= min_gallop)
1310 break;
1314 /* One run is winning so consistently that galloping may
1315 * be a huge win. So try that, and continue galloping until
1316 * (if ever) neither run appears to be winning consistently
1317 * anymore.
1319 ++min_gallop;
1320 do {
1321 assert(na > 1 && nb > 0);
1322 min_gallop -= min_gallop > 1;
1323 ms->min_gallop = min_gallop;
1324 k = gallop_right(*pb, pa, na, 0, compare);
1325 acount = k;
1326 if (k) {
1327 if (k < 0)
1328 goto Fail;
1329 memcpy(dest, pa, k * sizeof(PyObject *));
1330 dest += k;
1331 pa += k;
1332 na -= k;
1333 if (na == 1)
1334 goto CopyB;
1335 /* na==0 is impossible now if the comparison
1336 * function is consistent, but we can't assume
1337 * that it is.
1339 if (na == 0)
1340 goto Succeed;
1342 *dest++ = *pb++;
1343 --nb;
1344 if (nb == 0)
1345 goto Succeed;
1347 k = gallop_left(*pa, pb, nb, 0, compare);
1348 bcount = k;
1349 if (k) {
1350 if (k < 0)
1351 goto Fail;
1352 memmove(dest, pb, k * sizeof(PyObject *));
1353 dest += k;
1354 pb += k;
1355 nb -= k;
1356 if (nb == 0)
1357 goto Succeed;
1359 *dest++ = *pa++;
1360 --na;
1361 if (na == 1)
1362 goto CopyB;
1363 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1364 ++min_gallop; /* penalize it for leaving galloping mode */
1365 ms->min_gallop = min_gallop;
1367 Succeed:
1368 result = 0;
1369 Fail:
1370 if (na)
1371 memcpy(dest, pa, na * sizeof(PyObject*));
1372 return result;
1373 CopyB:
1374 assert(na == 1 && nb > 0);
1375 /* The last element of pa belongs at the end of the merge. */
1376 memmove(dest, pb, nb * sizeof(PyObject *));
1377 dest[nb] = *pa;
1378 return 0;
1381 /* Merge the na elements starting at pa with the nb elements starting at pb
1382 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1383 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1384 * merge, and should have na >= nb. See listsort.txt for more info.
1385 * Return 0 if successful, -1 if error.
1387 static int
1388 merge_hi(MergeState *ms, PyObject **pa, int na, PyObject **pb, int nb)
1390 int k;
1391 PyObject *compare;
1392 PyObject **dest;
1393 int result = -1; /* guilty until proved innocent */
1394 PyObject **basea;
1395 PyObject **baseb;
1396 int min_gallop = ms->min_gallop;
1398 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1399 if (MERGE_GETMEM(ms, nb) < 0)
1400 return -1;
1401 dest = pb + nb - 1;
1402 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1403 basea = pa;
1404 baseb = ms->a;
1405 pb = ms->a + nb - 1;
1406 pa += na - 1;
1408 *dest-- = *pa--;
1409 --na;
1410 if (na == 0)
1411 goto Succeed;
1412 if (nb == 1)
1413 goto CopyA;
1415 compare = ms->compare;
1416 for (;;) {
1417 int acount = 0; /* # of times A won in a row */
1418 int bcount = 0; /* # of times B won in a row */
1420 /* Do the straightforward thing until (if ever) one run
1421 * appears to win consistently.
1423 for (;;) {
1424 assert(na > 0 && nb > 1);
1425 k = ISLT(*pb, *pa, compare);
1426 if (k) {
1427 if (k < 0)
1428 goto Fail;
1429 *dest-- = *pa--;
1430 ++acount;
1431 bcount = 0;
1432 --na;
1433 if (na == 0)
1434 goto Succeed;
1435 if (acount >= min_gallop)
1436 break;
1438 else {
1439 *dest-- = *pb--;
1440 ++bcount;
1441 acount = 0;
1442 --nb;
1443 if (nb == 1)
1444 goto CopyA;
1445 if (bcount >= min_gallop)
1446 break;
1450 /* One run is winning so consistently that galloping may
1451 * be a huge win. So try that, and continue galloping until
1452 * (if ever) neither run appears to be winning consistently
1453 * anymore.
1455 ++min_gallop;
1456 do {
1457 assert(na > 0 && nb > 1);
1458 min_gallop -= min_gallop > 1;
1459 ms->min_gallop = min_gallop;
1460 k = gallop_right(*pb, basea, na, na-1, compare);
1461 if (k < 0)
1462 goto Fail;
1463 k = na - k;
1464 acount = k;
1465 if (k) {
1466 dest -= k;
1467 pa -= k;
1468 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1469 na -= k;
1470 if (na == 0)
1471 goto Succeed;
1473 *dest-- = *pb--;
1474 --nb;
1475 if (nb == 1)
1476 goto CopyA;
1478 k = gallop_left(*pa, baseb, nb, nb-1, compare);
1479 if (k < 0)
1480 goto Fail;
1481 k = nb - k;
1482 bcount = k;
1483 if (k) {
1484 dest -= k;
1485 pb -= k;
1486 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1487 nb -= k;
1488 if (nb == 1)
1489 goto CopyA;
1490 /* nb==0 is impossible now if the comparison
1491 * function is consistent, but we can't assume
1492 * that it is.
1494 if (nb == 0)
1495 goto Succeed;
1497 *dest-- = *pa--;
1498 --na;
1499 if (na == 0)
1500 goto Succeed;
1501 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1502 ++min_gallop; /* penalize it for leaving galloping mode */
1503 ms->min_gallop = min_gallop;
1505 Succeed:
1506 result = 0;
1507 Fail:
1508 if (nb)
1509 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1510 return result;
1511 CopyA:
1512 assert(nb == 1 && na > 0);
1513 /* The first element of pb belongs at the front of the merge. */
1514 dest -= na;
1515 pa -= na;
1516 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1517 *dest = *pb;
1518 return 0;
1521 /* Merge the two runs at stack indices i and i+1.
1522 * Returns 0 on success, -1 on error.
1524 static int
1525 merge_at(MergeState *ms, int i)
1527 PyObject **pa, **pb;
1528 int na, nb;
1529 int k;
1530 PyObject *compare;
1532 assert(ms != NULL);
1533 assert(ms->n >= 2);
1534 assert(i >= 0);
1535 assert(i == ms->n - 2 || i == ms->n - 3);
1537 pa = ms->pending[i].base;
1538 na = ms->pending[i].len;
1539 pb = ms->pending[i+1].base;
1540 nb = ms->pending[i+1].len;
1541 assert(na > 0 && nb > 0);
1542 assert(pa + na == pb);
1544 /* Record the length of the combined runs; if i is the 3rd-last
1545 * run now, also slide over the last run (which isn't involved
1546 * in this merge). The current run i+1 goes away in any case.
1548 ms->pending[i].len = na + nb;
1549 if (i == ms->n - 3)
1550 ms->pending[i+1] = ms->pending[i+2];
1551 --ms->n;
1553 /* Where does b start in a? Elements in a before that can be
1554 * ignored (already in place).
1556 compare = ms->compare;
1557 k = gallop_right(*pb, pa, na, 0, compare);
1558 if (k < 0)
1559 return -1;
1560 pa += k;
1561 na -= k;
1562 if (na == 0)
1563 return 0;
1565 /* Where does a end in b? Elements in b after that can be
1566 * ignored (already in place).
1568 nb = gallop_left(pa[na-1], pb, nb, nb-1, compare);
1569 if (nb <= 0)
1570 return nb;
1572 /* Merge what remains of the runs, using a temp array with
1573 * min(na, nb) elements.
1575 if (na <= nb)
1576 return merge_lo(ms, pa, na, pb, nb);
1577 else
1578 return merge_hi(ms, pa, na, pb, nb);
1581 /* Examine the stack of runs waiting to be merged, merging adjacent runs
1582 * until the stack invariants are re-established:
1584 * 1. len[-3] > len[-2] + len[-1]
1585 * 2. len[-2] > len[-1]
1587 * See listsort.txt for more info.
1589 * Returns 0 on success, -1 on error.
1591 static int
1592 merge_collapse(MergeState *ms)
1594 struct s_slice *p = ms->pending;
1596 assert(ms);
1597 while (ms->n > 1) {
1598 int n = ms->n - 2;
1599 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1600 if (p[n-1].len < p[n+1].len)
1601 --n;
1602 if (merge_at(ms, n) < 0)
1603 return -1;
1605 else if (p[n].len <= p[n+1].len) {
1606 if (merge_at(ms, n) < 0)
1607 return -1;
1609 else
1610 break;
1612 return 0;
1615 /* Regardless of invariants, merge all runs on the stack until only one
1616 * remains. This is used at the end of the mergesort.
1618 * Returns 0 on success, -1 on error.
1620 static int
1621 merge_force_collapse(MergeState *ms)
1623 struct s_slice *p = ms->pending;
1625 assert(ms);
1626 while (ms->n > 1) {
1627 int n = ms->n - 2;
1628 if (n > 0 && p[n-1].len < p[n+1].len)
1629 --n;
1630 if (merge_at(ms, n) < 0)
1631 return -1;
1633 return 0;
1636 /* Compute a good value for the minimum run length; natural runs shorter
1637 * than this are boosted artificially via binary insertion.
1639 * If n < 64, return n (it's too small to bother with fancy stuff).
1640 * Else if n is an exact power of 2, return 32.
1641 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1642 * strictly less than, an exact power of 2.
1644 * See listsort.txt for more info.
1646 static int
1647 merge_compute_minrun(int n)
1649 int r = 0; /* becomes 1 if any 1 bits are shifted off */
1651 assert(n >= 0);
1652 while (n >= 64) {
1653 r |= n & 1;
1654 n >>= 1;
1656 return n + r;
1659 /* An adaptive, stable, natural mergesort. See listsort.txt.
1660 * Returns Py_None on success, NULL on error. Even in case of error, the
1661 * list will be some permutation of its input state (nothing is lost or
1662 * duplicated).
1664 static PyObject *
1665 listsort(PyListObject *self, PyObject *args)
1667 MergeState ms;
1668 PyObject **lo, **hi;
1669 int nremaining;
1670 int minrun;
1671 int saved_ob_size;
1672 PyObject **saved_ob_item;
1673 PyObject **empty_ob_item;
1674 PyObject *compare = NULL;
1675 PyObject *result = NULL; /* guilty until proved innocent */
1677 assert(self != NULL);
1678 if (args != NULL) {
1679 if (!PyArg_UnpackTuple(args, "sort", 0, 1, &compare))
1680 return NULL;
1682 if (compare == Py_None)
1683 compare = NULL;
1685 merge_init(&ms, compare);
1687 /* The list is temporarily made empty, so that mutations performed
1688 * by comparison functions can't affect the slice of memory we're
1689 * sorting (allowing mutations during sorting is a core-dump
1690 * factory, since ob_item may change).
1692 saved_ob_size = self->ob_size;
1693 saved_ob_item = self->ob_item;
1694 self->ob_size = 0;
1695 self->ob_item = empty_ob_item = PyMem_NEW(PyObject *, 0);
1697 nremaining = saved_ob_size;
1698 if (nremaining < 2)
1699 goto succeed;
1701 /* March over the array once, left to right, finding natural runs,
1702 * and extending short natural runs to minrun elements.
1704 lo = saved_ob_item;
1705 hi = lo + nremaining;
1706 minrun = merge_compute_minrun(nremaining);
1707 do {
1708 int descending;
1709 int n;
1711 /* Identify next run. */
1712 n = count_run(lo, hi, compare, &descending);
1713 if (n < 0)
1714 goto fail;
1715 if (descending)
1716 reverse_slice(lo, lo + n);
1717 /* If short, extend to min(minrun, nremaining). */
1718 if (n < minrun) {
1719 const int force = nremaining <= minrun ?
1720 nremaining : minrun;
1721 if (binarysort(lo, lo + force, lo + n, compare) < 0)
1722 goto fail;
1723 n = force;
1725 /* Push run onto pending-runs stack, and maybe merge. */
1726 assert(ms.n < MAX_MERGE_PENDING);
1727 ms.pending[ms.n].base = lo;
1728 ms.pending[ms.n].len = n;
1729 ++ms.n;
1730 if (merge_collapse(&ms) < 0)
1731 goto fail;
1732 /* Advance to find next run. */
1733 lo += n;
1734 nremaining -= n;
1735 } while (nremaining);
1736 assert(lo == hi);
1738 if (merge_force_collapse(&ms) < 0)
1739 goto fail;
1740 assert(ms.n == 1);
1741 assert(ms.pending[0].base == saved_ob_item);
1742 assert(ms.pending[0].len == saved_ob_size);
1744 succeed:
1745 result = Py_None;
1746 fail:
1747 if (self->ob_item != empty_ob_item || self->ob_size) {
1748 /* The user mucked with the list during the sort. */
1749 (void)list_ass_slice(self, 0, self->ob_size, (PyObject *)NULL);
1750 if (result != NULL) {
1751 PyErr_SetString(PyExc_ValueError,
1752 "list modified during sort");
1753 result = NULL;
1756 if (self->ob_item == empty_ob_item)
1757 PyMem_FREE(empty_ob_item);
1758 self->ob_size = saved_ob_size;
1759 self->ob_item = saved_ob_item;
1760 merge_freemem(&ms);
1761 Py_XINCREF(result);
1762 return result;
1764 #undef IFLT
1765 #undef ISLT
1768 PyList_Sort(PyObject *v)
1770 if (v == NULL || !PyList_Check(v)) {
1771 PyErr_BadInternalCall();
1772 return -1;
1774 v = listsort((PyListObject *)v, (PyObject *)NULL);
1775 if (v == NULL)
1776 return -1;
1777 Py_DECREF(v);
1778 return 0;
1781 static PyObject *
1782 listreverse(PyListObject *self)
1784 if (self->ob_size > 1)
1785 reverse_slice(self->ob_item, self->ob_item + self->ob_size);
1786 Py_INCREF(Py_None);
1787 return Py_None;
1791 PyList_Reverse(PyObject *v)
1793 PyListObject *self = (PyListObject *)v;
1795 if (v == NULL || !PyList_Check(v)) {
1796 PyErr_BadInternalCall();
1797 return -1;
1799 if (self->ob_size > 1)
1800 reverse_slice(self->ob_item, self->ob_item + self->ob_size);
1801 return 0;
1804 PyObject *
1805 PyList_AsTuple(PyObject *v)
1807 PyObject *w;
1808 PyObject **p;
1809 int n;
1810 if (v == NULL || !PyList_Check(v)) {
1811 PyErr_BadInternalCall();
1812 return NULL;
1814 n = ((PyListObject *)v)->ob_size;
1815 w = PyTuple_New(n);
1816 if (w == NULL)
1817 return NULL;
1818 p = ((PyTupleObject *)w)->ob_item;
1819 memcpy((void *)p,
1820 (void *)((PyListObject *)v)->ob_item,
1821 n*sizeof(PyObject *));
1822 while (--n >= 0) {
1823 Py_INCREF(*p);
1824 p++;
1826 return w;
1829 static PyObject *
1830 listindex(PyListObject *self, PyObject *args)
1832 int i, start=0, stop=self->ob_size;
1833 PyObject *v;
1835 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
1836 _PyEval_SliceIndex, &start,
1837 _PyEval_SliceIndex, &stop))
1838 return NULL;
1839 if (start < 0) {
1840 start += self->ob_size;
1841 if (start < 0)
1842 start = 0;
1844 if (stop < 0) {
1845 stop += self->ob_size;
1846 if (stop < 0)
1847 stop = 0;
1849 else if (stop > self->ob_size)
1850 stop = self->ob_size;
1851 for (i = start; i < stop; i++) {
1852 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
1853 if (cmp > 0)
1854 return PyInt_FromLong((long)i);
1855 else if (cmp < 0)
1856 return NULL;
1858 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
1859 return NULL;
1862 static PyObject *
1863 listcount(PyListObject *self, PyObject *v)
1865 int count = 0;
1866 int i;
1868 for (i = 0; i < self->ob_size; i++) {
1869 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
1870 if (cmp > 0)
1871 count++;
1872 else if (cmp < 0)
1873 return NULL;
1875 return PyInt_FromLong((long)count);
1878 static PyObject *
1879 listremove(PyListObject *self, PyObject *v)
1881 int i;
1883 for (i = 0; i < self->ob_size; i++) {
1884 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
1885 if (cmp > 0) {
1886 if (list_ass_slice(self, i, i+1,
1887 (PyObject *)NULL) != 0)
1888 return NULL;
1889 Py_INCREF(Py_None);
1890 return Py_None;
1892 else if (cmp < 0)
1893 return NULL;
1895 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
1896 return NULL;
1899 static int
1900 list_traverse(PyListObject *o, visitproc visit, void *arg)
1902 int i, err;
1903 PyObject *x;
1905 for (i = o->ob_size; --i >= 0; ) {
1906 x = o->ob_item[i];
1907 if (x != NULL) {
1908 err = visit(x, arg);
1909 if (err)
1910 return err;
1913 return 0;
1916 static int
1917 list_clear(PyListObject *lp)
1919 (void) PyList_SetSlice((PyObject *)lp, 0, lp->ob_size, 0);
1920 return 0;
1923 static PyObject *
1924 list_richcompare(PyObject *v, PyObject *w, int op)
1926 PyListObject *vl, *wl;
1927 int i;
1929 if (!PyList_Check(v) || !PyList_Check(w)) {
1930 Py_INCREF(Py_NotImplemented);
1931 return Py_NotImplemented;
1934 vl = (PyListObject *)v;
1935 wl = (PyListObject *)w;
1937 if (vl->ob_size != wl->ob_size && (op == Py_EQ || op == Py_NE)) {
1938 /* Shortcut: if the lengths differ, the lists differ */
1939 PyObject *res;
1940 if (op == Py_EQ)
1941 res = Py_False;
1942 else
1943 res = Py_True;
1944 Py_INCREF(res);
1945 return res;
1948 /* Search for the first index where items are different */
1949 for (i = 0; i < vl->ob_size && i < wl->ob_size; i++) {
1950 int k = PyObject_RichCompareBool(vl->ob_item[i],
1951 wl->ob_item[i], Py_EQ);
1952 if (k < 0)
1953 return NULL;
1954 if (!k)
1955 break;
1958 if (i >= vl->ob_size || i >= wl->ob_size) {
1959 /* No more items to compare -- compare sizes */
1960 int vs = vl->ob_size;
1961 int ws = wl->ob_size;
1962 int cmp;
1963 PyObject *res;
1964 switch (op) {
1965 case Py_LT: cmp = vs < ws; break;
1966 case Py_LE: cmp = vs <= ws; break;
1967 case Py_EQ: cmp = vs == ws; break;
1968 case Py_NE: cmp = vs != ws; break;
1969 case Py_GT: cmp = vs > ws; break;
1970 case Py_GE: cmp = vs >= ws; break;
1971 default: return NULL; /* cannot happen */
1973 if (cmp)
1974 res = Py_True;
1975 else
1976 res = Py_False;
1977 Py_INCREF(res);
1978 return res;
1981 /* We have an item that differs -- shortcuts for EQ/NE */
1982 if (op == Py_EQ) {
1983 Py_INCREF(Py_False);
1984 return Py_False;
1986 if (op == Py_NE) {
1987 Py_INCREF(Py_True);
1988 return Py_True;
1991 /* Compare the final item again using the proper operator */
1992 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
1995 /* Adapted from newer code by Tim */
1996 static int
1997 list_fill(PyListObject *result, PyObject *v)
1999 PyObject *it; /* iter(v) */
2000 int n; /* guess for result list size */
2001 int i;
2003 n = result->ob_size;
2005 /* Special-case list(a_list), for speed. */
2006 if (PyList_Check(v)) {
2007 if (v == (PyObject *)result)
2008 return 0; /* source is destination, we're done */
2009 return list_ass_slice(result, 0, n, v);
2012 /* Empty previous contents */
2013 if (n != 0) {
2014 if (list_ass_slice(result, 0, n, (PyObject *)NULL) != 0)
2015 return -1;
2018 /* Get iterator. There may be some low-level efficiency to be gained
2019 * by caching the tp_iternext slot instead of using PyIter_Next()
2020 * later, but premature optimization is the root etc.
2022 it = PyObject_GetIter(v);
2023 if (it == NULL)
2024 return -1;
2026 /* Guess a result list size. */
2027 n = -1; /* unknown */
2028 if (PySequence_Check(v) &&
2029 v->ob_type->tp_as_sequence->sq_length) {
2030 n = PySequence_Size(v);
2031 if (n < 0)
2032 PyErr_Clear();
2034 if (n < 0)
2035 n = 8; /* arbitrary */
2036 NRESIZE(result->ob_item, PyObject*, n);
2037 if (result->ob_item == NULL) {
2038 PyErr_NoMemory();
2039 goto error;
2041 memset(result->ob_item, 0, sizeof(*result->ob_item) * n);
2042 result->ob_size = n;
2044 /* Run iterator to exhaustion. */
2045 for (i = 0; ; i++) {
2046 PyObject *item = PyIter_Next(it);
2047 if (item == NULL) {
2048 if (PyErr_Occurred())
2049 goto error;
2050 break;
2052 if (i < n)
2053 PyList_SET_ITEM(result, i, item); /* steals ref */
2054 else {
2055 int status = ins1(result, result->ob_size, item);
2056 Py_DECREF(item); /* append creates a new ref */
2057 if (status < 0)
2058 goto error;
2062 /* Cut back result list if initial guess was too large. */
2063 if (i < n && result != NULL) {
2064 if (list_ass_slice(result, i, n, (PyObject *)NULL) != 0)
2065 goto error;
2067 Py_DECREF(it);
2068 return 0;
2070 error:
2071 Py_DECREF(it);
2072 return -1;
2075 static int
2076 list_init(PyListObject *self, PyObject *args, PyObject *kw)
2078 PyObject *arg = NULL;
2079 static char *kwlist[] = {"sequence", 0};
2081 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2082 return -1;
2083 if (arg != NULL)
2084 return list_fill(self, arg);
2085 if (self->ob_size > 0)
2086 return list_ass_slice(self, 0, self->ob_size, (PyObject*)NULL);
2087 return 0;
2090 static long
2091 list_nohash(PyObject *self)
2093 PyErr_SetString(PyExc_TypeError, "list objects are unhashable");
2094 return -1;
2097 PyDoc_STRVAR(append_doc,
2098 "L.append(object) -- append object to end");
2099 PyDoc_STRVAR(extend_doc,
2100 "L.extend(iterable) -- extend list by appending elements from the iterable");
2101 PyDoc_STRVAR(insert_doc,
2102 "L.insert(index, object) -- insert object before index");
2103 PyDoc_STRVAR(pop_doc,
2104 "L.pop([index]) -> item -- remove and return item at index (default last)");
2105 PyDoc_STRVAR(remove_doc,
2106 "L.remove(value) -- remove first occurrence of value");
2107 PyDoc_STRVAR(index_doc,
2108 "L.index(value, [start, [stop]]) -> integer -- return first index of value");
2109 PyDoc_STRVAR(count_doc,
2110 "L.count(value) -> integer -- return number of occurrences of value");
2111 PyDoc_STRVAR(reverse_doc,
2112 "L.reverse() -- reverse *IN PLACE*");
2113 PyDoc_STRVAR(sort_doc,
2114 "L.sort(cmpfunc=None) -- stable sort *IN PLACE*; cmpfunc(x, y) -> -1, 0, 1");
2116 static PyMethodDef list_methods[] = {
2117 {"append", (PyCFunction)listappend, METH_O, append_doc},
2118 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
2119 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
2120 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
2121 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
2122 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
2123 {"count", (PyCFunction)listcount, METH_O, count_doc},
2124 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
2125 {"sort", (PyCFunction)listsort, METH_VARARGS, sort_doc},
2126 {NULL, NULL} /* sentinel */
2129 static PySequenceMethods list_as_sequence = {
2130 (inquiry)list_length, /* sq_length */
2131 (binaryfunc)list_concat, /* sq_concat */
2132 (intargfunc)list_repeat, /* sq_repeat */
2133 (intargfunc)list_item, /* sq_item */
2134 (intintargfunc)list_slice, /* sq_slice */
2135 (intobjargproc)list_ass_item, /* sq_ass_item */
2136 (intintobjargproc)list_ass_slice, /* sq_ass_slice */
2137 (objobjproc)list_contains, /* sq_contains */
2138 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2139 (intargfunc)list_inplace_repeat, /* sq_inplace_repeat */
2142 PyDoc_STRVAR(list_doc,
2143 "list() -> new list\n"
2144 "list(sequence) -> new list initialized from sequence's items");
2146 static PyObject *list_iter(PyObject *seq);
2148 static PyObject *
2149 list_subscript(PyListObject* self, PyObject* item)
2151 if (PyInt_Check(item)) {
2152 long i = PyInt_AS_LONG(item);
2153 if (i < 0)
2154 i += PyList_GET_SIZE(self);
2155 return list_item(self, i);
2157 else if (PyLong_Check(item)) {
2158 long i = PyLong_AsLong(item);
2159 if (i == -1 && PyErr_Occurred())
2160 return NULL;
2161 if (i < 0)
2162 i += PyList_GET_SIZE(self);
2163 return list_item(self, i);
2165 else if (PySlice_Check(item)) {
2166 int start, stop, step, slicelength, cur, i;
2167 PyObject* result;
2168 PyObject* it;
2170 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
2171 &start, &stop, &step, &slicelength) < 0) {
2172 return NULL;
2175 if (slicelength <= 0) {
2176 return PyList_New(0);
2178 else {
2179 result = PyList_New(slicelength);
2180 if (!result) return NULL;
2182 for (cur = start, i = 0; i < slicelength;
2183 cur += step, i++) {
2184 it = PyList_GET_ITEM(self, cur);
2185 Py_INCREF(it);
2186 PyList_SET_ITEM(result, i, it);
2189 return result;
2192 else {
2193 PyErr_SetString(PyExc_TypeError,
2194 "list indices must be integers");
2195 return NULL;
2199 static int
2200 list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2202 if (PyInt_Check(item)) {
2203 long i = PyInt_AS_LONG(item);
2204 if (i < 0)
2205 i += PyList_GET_SIZE(self);
2206 return list_ass_item(self, i, value);
2208 else if (PyLong_Check(item)) {
2209 long i = PyLong_AsLong(item);
2210 if (i == -1 && PyErr_Occurred())
2211 return -1;
2212 if (i < 0)
2213 i += PyList_GET_SIZE(self);
2214 return list_ass_item(self, i, value);
2216 else if (PySlice_Check(item)) {
2217 int start, stop, step, slicelength;
2219 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
2220 &start, &stop, &step, &slicelength) < 0) {
2221 return -1;
2224 /* treat L[slice(a,b)] = v _exactly_ like L[a:b] = v */
2225 if (step == 1 && ((PySliceObject*)item)->step == Py_None)
2226 return list_ass_slice(self, start, stop, value);
2228 if (value == NULL) {
2229 /* delete slice */
2230 PyObject **garbage, **it;
2231 int cur, i, j;
2233 if (slicelength <= 0)
2234 return 0;
2236 if (step < 0) {
2237 stop = start + 1;
2238 start = stop + step*(slicelength - 1) - 1;
2239 step = -step;
2242 garbage = (PyObject**)
2243 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2245 /* drawing pictures might help
2246 understand these for loops */
2247 for (cur = start, i = 0;
2248 cur < stop;
2249 cur += step, i++) {
2250 int lim = step;
2252 garbage[i] = PyList_GET_ITEM(self, cur);
2254 if (cur + step >= self->ob_size) {
2255 lim = self->ob_size - cur - 1;
2258 for (j = 0; j < lim; j++) {
2259 PyList_SET_ITEM(self, cur + j - i,
2260 PyList_GET_ITEM(self,
2261 cur + j + 1));
2264 for (cur = start + slicelength*step + 1;
2265 cur < self->ob_size; cur++) {
2266 PyList_SET_ITEM(self, cur - slicelength,
2267 PyList_GET_ITEM(self, cur));
2269 self->ob_size -= slicelength;
2270 it = self->ob_item;
2271 NRESIZE(it, PyObject*, self->ob_size);
2272 self->ob_item = it;
2274 for (i = 0; i < slicelength; i++) {
2275 Py_DECREF(garbage[i]);
2277 PyMem_FREE(garbage);
2279 return 0;
2281 else {
2282 /* assign slice */
2283 PyObject **garbage, *ins, *seq;
2284 int cur, i;
2286 /* protect against a[::-1] = a */
2287 if (self == (PyListObject*)value) {
2288 seq = list_slice((PyListObject*)value, 0,
2289 PyList_GET_SIZE(value));
2291 else {
2292 char msg[256];
2293 PyOS_snprintf(msg, sizeof(msg),
2294 "must assign sequence (not \"%.200s\") to extended slice",
2295 value->ob_type->tp_name);
2296 seq = PySequence_Fast(value, msg);
2297 if (!seq)
2298 return -1;
2301 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2302 PyErr_Format(PyExc_ValueError,
2303 "attempt to assign sequence of size %d to extended slice of size %d",
2304 PySequence_Fast_GET_SIZE(seq),
2305 slicelength);
2306 Py_DECREF(seq);
2307 return -1;
2310 if (!slicelength) {
2311 Py_DECREF(seq);
2312 return 0;
2315 garbage = (PyObject**)
2316 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2318 for (cur = start, i = 0; i < slicelength;
2319 cur += step, i++) {
2320 garbage[i] = PyList_GET_ITEM(self, cur);
2322 ins = PySequence_Fast_GET_ITEM(seq, i);
2323 Py_INCREF(ins);
2324 PyList_SET_ITEM(self, cur, ins);
2327 for (i = 0; i < slicelength; i++) {
2328 Py_DECREF(garbage[i]);
2331 PyMem_FREE(garbage);
2332 Py_DECREF(seq);
2334 return 0;
2337 else {
2338 PyErr_SetString(PyExc_TypeError,
2339 "list indices must be integers");
2340 return -1;
2344 static PyMappingMethods list_as_mapping = {
2345 (inquiry)list_length,
2346 (binaryfunc)list_subscript,
2347 (objobjargproc)list_ass_subscript
2350 PyTypeObject PyList_Type = {
2351 PyObject_HEAD_INIT(&PyType_Type)
2353 "list",
2354 sizeof(PyListObject),
2356 (destructor)list_dealloc, /* tp_dealloc */
2357 (printfunc)list_print, /* tp_print */
2358 0, /* tp_getattr */
2359 0, /* tp_setattr */
2360 0, /* tp_compare */
2361 (reprfunc)list_repr, /* tp_repr */
2362 0, /* tp_as_number */
2363 &list_as_sequence, /* tp_as_sequence */
2364 &list_as_mapping, /* tp_as_mapping */
2365 list_nohash, /* tp_hash */
2366 0, /* tp_call */
2367 0, /* tp_str */
2368 PyObject_GenericGetAttr, /* tp_getattro */
2369 0, /* tp_setattro */
2370 0, /* tp_as_buffer */
2371 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2372 Py_TPFLAGS_BASETYPE, /* tp_flags */
2373 list_doc, /* tp_doc */
2374 (traverseproc)list_traverse, /* tp_traverse */
2375 (inquiry)list_clear, /* tp_clear */
2376 list_richcompare, /* tp_richcompare */
2377 0, /* tp_weaklistoffset */
2378 list_iter, /* tp_iter */
2379 0, /* tp_iternext */
2380 list_methods, /* tp_methods */
2381 0, /* tp_members */
2382 0, /* tp_getset */
2383 0, /* tp_base */
2384 0, /* tp_dict */
2385 0, /* tp_descr_get */
2386 0, /* tp_descr_set */
2387 0, /* tp_dictoffset */
2388 (initproc)list_init, /* tp_init */
2389 PyType_GenericAlloc, /* tp_alloc */
2390 PyType_GenericNew, /* tp_new */
2391 PyObject_GC_Del, /* tp_free */
2395 /*********************** List Iterator **************************/
2397 typedef struct {
2398 PyObject_HEAD
2399 long it_index;
2400 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
2401 } listiterobject;
2403 PyTypeObject PyListIter_Type;
2405 static PyObject *
2406 list_iter(PyObject *seq)
2408 listiterobject *it;
2410 if (!PyList_Check(seq)) {
2411 PyErr_BadInternalCall();
2412 return NULL;
2414 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2415 if (it == NULL)
2416 return NULL;
2417 it->it_index = 0;
2418 Py_INCREF(seq);
2419 it->it_seq = (PyListObject *)seq;
2420 _PyObject_GC_TRACK(it);
2421 return (PyObject *)it;
2424 static void
2425 listiter_dealloc(listiterobject *it)
2427 _PyObject_GC_UNTRACK(it);
2428 Py_XDECREF(it->it_seq);
2429 PyObject_GC_Del(it);
2432 static int
2433 listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2435 if (it->it_seq == NULL)
2436 return 0;
2437 return visit((PyObject *)it->it_seq, arg);
2440 static PyObject *
2441 listiter_next(listiterobject *it)
2443 PyListObject *seq;
2444 PyObject *item;
2446 assert(it != NULL);
2447 seq = it->it_seq;
2448 if (seq == NULL)
2449 return NULL;
2450 assert(PyList_Check(seq));
2452 if (it->it_index < PyList_GET_SIZE(seq)) {
2453 item = PyList_GET_ITEM(seq, it->it_index);
2454 ++it->it_index;
2455 Py_INCREF(item);
2456 return item;
2459 Py_DECREF(seq);
2460 it->it_seq = NULL;
2461 return NULL;
2464 PyTypeObject PyListIter_Type = {
2465 PyObject_HEAD_INIT(&PyType_Type)
2466 0, /* ob_size */
2467 "listiterator", /* tp_name */
2468 sizeof(listiterobject), /* tp_basicsize */
2469 0, /* tp_itemsize */
2470 /* methods */
2471 (destructor)listiter_dealloc, /* tp_dealloc */
2472 0, /* tp_print */
2473 0, /* tp_getattr */
2474 0, /* tp_setattr */
2475 0, /* tp_compare */
2476 0, /* tp_repr */
2477 0, /* tp_as_number */
2478 0, /* tp_as_sequence */
2479 0, /* tp_as_mapping */
2480 0, /* tp_hash */
2481 0, /* tp_call */
2482 0, /* tp_str */
2483 PyObject_GenericGetAttr, /* tp_getattro */
2484 0, /* tp_setattro */
2485 0, /* tp_as_buffer */
2486 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2487 0, /* tp_doc */
2488 (traverseproc)listiter_traverse, /* tp_traverse */
2489 0, /* tp_clear */
2490 0, /* tp_richcompare */
2491 0, /* tp_weaklistoffset */
2492 PyObject_SelfIter, /* tp_iter */
2493 (iternextfunc)listiter_next, /* tp_iternext */
2494 0, /* tp_methods */
2495 0, /* tp_members */
2496 0, /* tp_getset */
2497 0, /* tp_base */
2498 0, /* tp_dict */
2499 0, /* tp_descr_get */
2500 0, /* tp_descr_set */