blob: c5b147580292c55ccca97509d3f0b23482c3303c [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* List object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
4
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00005#ifdef STDC_HEADERS
6#include <stddef.h>
7#else
8#include <sys/types.h> /* For size_t */
9#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000010
Tim Peters8d9eb102004-07-31 02:24:20 +000011/* Ensure ob_item has room for at least newsize elements, and set
12 * ob_size to newsize. If newsize > ob_size on entry, the content
13 * of the new slots at exit is undefined heap trash; it's the caller's
14 * responsiblity to overwrite them with sane values.
15 * The number of allocated elements may grow, shrink, or stay the same.
16 * Failure is impossible if newsize <= self.allocated on entry, although
17 * that partly relies on an assumption that the system realloc() never
18 * fails when passed a number of bytes <= the number of bytes last
19 * allocated (the C standard doesn't guarantee this, but it's hard to
20 * imagine a realloc implementation where it wouldn't be true).
21 * Note that self->ob_item may change, and even if newsize is less
22 * than ob_size on entry.
23 */
Guido van Rossuma46d51d1995-01-26 22:59:43 +000024static int
Martin v. Löwis18e16552006-02-15 17:27:45 +000025list_resize(PyListObject *self, Py_ssize_t newsize)
Guido van Rossuma46d51d1995-01-26 22:59:43 +000026{
Raymond Hettinger4bb95402004-02-13 11:36:39 +000027 PyObject **items;
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000028 size_t new_allocated;
Martin v. Löwis18e16552006-02-15 17:27:45 +000029 Py_ssize_t allocated = self->allocated;
Tim Peters65b8b842001-05-26 05:28:40 +000030
Raymond Hettinger4bb95402004-02-13 11:36:39 +000031 /* Bypass realloc() when a previous overallocation is large enough
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000032 to accommodate the newsize. If the newsize falls lower than half
33 the allocated size, then proceed with the realloc() to shrink the list.
Raymond Hettinger4bb95402004-02-13 11:36:39 +000034 */
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000035 if (allocated >= newsize && newsize >= (allocated >> 1)) {
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +000036 assert(self->ob_item != NULL || newsize == 0);
Christian Heimese93237d2007-12-19 02:37:44 +000037 Py_SIZE(self) = newsize;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000038 return 0;
39 }
40
41 /* This over-allocates proportional to the list size, making room
Tim Peters65b8b842001-05-26 05:28:40 +000042 * for additional growth. The over-allocation is mild, but is
43 * enough to give linear-time amortized behavior over a long
44 * sequence of appends() in the presence of a poorly-performing
Raymond Hettingerab517d22004-02-14 18:34:46 +000045 * system realloc().
46 * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
Tim Peters65b8b842001-05-26 05:28:40 +000047 */
Gregory P. Smith9d534572008-06-11 07:41:16 +000048 new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6);
49
50 /* check for integer overflow */
51 if (new_allocated > PY_SIZE_MAX - newsize) {
52 PyErr_NoMemory();
53 return -1;
54 } else {
55 new_allocated += newsize;
56 }
57
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000058 if (newsize == 0)
59 new_allocated = 0;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000060 items = self->ob_item;
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000061 if (new_allocated <= ((~(size_t)0) / sizeof(PyObject *)))
62 PyMem_RESIZE(items, PyObject *, new_allocated);
Raymond Hettinger4bb95402004-02-13 11:36:39 +000063 else
64 items = NULL;
65 if (items == NULL) {
66 PyErr_NoMemory();
67 return -1;
68 }
69 self->ob_item = items;
Christian Heimese93237d2007-12-19 02:37:44 +000070 Py_SIZE(self) = newsize;
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000071 self->allocated = new_allocated;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000072 return 0;
73}
Guido van Rossuma46d51d1995-01-26 22:59:43 +000074
Christian Heimesb4ee4a12008-02-07 17:15:30 +000075/* Debug statistic to compare allocations with reuse through the free list */
76#undef SHOW_ALLOC_COUNT
77#ifdef SHOW_ALLOC_COUNT
78static size_t count_alloc = 0;
79static size_t count_reuse = 0;
80
81static void
82show_alloc(void)
83{
Christian Heimes09bde042008-02-24 12:26:16 +000084 fprintf(stderr, "List allocations: %" PY_FORMAT_SIZE_T "d\n",
85 count_alloc);
86 fprintf(stderr, "List reuse through freelist: %" PY_FORMAT_SIZE_T
87 "d\n", count_reuse);
Christian Heimesb4ee4a12008-02-07 17:15:30 +000088 fprintf(stderr, "%.2f%% reuse rate\n\n",
89 (100.0*count_reuse/(count_alloc+count_reuse)));
90}
91#endif
92
Raymond Hettinger0468e412004-05-05 05:37:53 +000093/* Empty list reuse scheme to save calls to malloc and free */
Christian Heimes5b970ad2008-02-06 13:33:44 +000094#ifndef PyList_MAXFREELIST
95#define PyList_MAXFREELIST 80
96#endif
97static PyListObject *free_list[PyList_MAXFREELIST];
98static int numfree = 0;
Raymond Hettinger0468e412004-05-05 05:37:53 +000099
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000100void
101PyList_Fini(void)
102{
103 PyListObject *op;
104
Christian Heimes5b970ad2008-02-06 13:33:44 +0000105 while (numfree) {
Christian Heimes48397d62008-02-08 00:14:34 +0000106 op = free_list[--numfree];
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000107 assert(PyList_CheckExact(op));
108 PyObject_GC_Del(op);
109 }
110}
111
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000112PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000113PyList_New(Py_ssize_t size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000114{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000115 PyListObject *op;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +0000116 size_t nbytes;
Christian Heimesb4ee4a12008-02-07 17:15:30 +0000117#ifdef SHOW_ALLOC_COUNT
118 static int initialized = 0;
119 if (!initialized) {
120 Py_AtExit(show_alloc);
121 initialized = 1;
122 }
123#endif
Tim Peters3986d4e2004-07-29 02:28:42 +0000124
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000125 if (size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000126 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000127 return NULL;
128 }
Tim Peters7049d812004-01-18 20:31:02 +0000129 nbytes = size * sizeof(PyObject *);
Gregory P. Smith9d534572008-06-11 07:41:16 +0000130 /* Check for overflow without an actual overflow,
131 * which can cause compiler to optimise out */
132 if (size > PY_SIZE_MAX / sizeof(PyObject *))
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000133 return PyErr_NoMemory();
Christian Heimes5b970ad2008-02-06 13:33:44 +0000134 if (numfree) {
135 numfree--;
136 op = free_list[numfree];
Raymond Hettinger0468e412004-05-05 05:37:53 +0000137 _Py_NewReference((PyObject *)op);
Christian Heimesb4ee4a12008-02-07 17:15:30 +0000138#ifdef SHOW_ALLOC_COUNT
139 count_reuse++;
140#endif
Raymond Hettinger0468e412004-05-05 05:37:53 +0000141 } else {
142 op = PyObject_GC_New(PyListObject, &PyList_Type);
143 if (op == NULL)
144 return NULL;
Christian Heimesb4ee4a12008-02-07 17:15:30 +0000145#ifdef SHOW_ALLOC_COUNT
146 count_alloc++;
147#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000148 }
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000149 if (size <= 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000150 op->ob_item = NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000151 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +0000152 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
Neal Norwitza00c0b92006-06-12 02:08:41 +0000153 if (op->ob_item == NULL) {
154 Py_DECREF(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000155 return PyErr_NoMemory();
Neal Norwitza00c0b92006-06-12 02:08:41 +0000156 }
Tim Peters3986d4e2004-07-29 02:28:42 +0000157 memset(op->ob_item, 0, nbytes);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000158 }
Christian Heimese93237d2007-12-19 02:37:44 +0000159 Py_SIZE(op) = size;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000160 op->allocated = size;
Neil Schemenauere83c00e2001-08-29 23:54:21 +0000161 _PyObject_GC_TRACK(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000162 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000163}
164
Martin v. Löwis18e16552006-02-15 17:27:45 +0000165Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000166PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000167{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000168 if (!PyList_Check(op)) {
169 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000170 return -1;
171 }
172 else
Christian Heimese93237d2007-12-19 02:37:44 +0000173 return Py_SIZE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000174}
175
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000176static PyObject *indexerr = NULL;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000177
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000178PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000179PyList_GetItem(PyObject *op, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000180{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000181 if (!PyList_Check(op)) {
182 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000183 return NULL;
184 }
Christian Heimese93237d2007-12-19 02:37:44 +0000185 if (i < 0 || i >= Py_SIZE(op)) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000186 if (indexerr == NULL)
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000187 indexerr = PyString_FromString(
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000188 "list index out of range");
189 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000190 return NULL;
191 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000192 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000193}
194
195int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000196PyList_SetItem(register PyObject *op, register Py_ssize_t i,
Fred Drakea2f55112000-07-09 15:16:51 +0000197 register PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000198{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000199 register PyObject *olditem;
200 register PyObject **p;
201 if (!PyList_Check(op)) {
202 Py_XDECREF(newitem);
203 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000204 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000205 }
Christian Heimese93237d2007-12-19 02:37:44 +0000206 if (i < 0 || i >= Py_SIZE(op)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000207 Py_XDECREF(newitem);
208 PyErr_SetString(PyExc_IndexError,
209 "list assignment index out of range");
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000210 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000211 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000212 p = ((PyListObject *)op) -> ob_item + i;
Guido van Rossum5fe60581995-03-09 12:12:50 +0000213 olditem = *p;
214 *p = newitem;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000215 Py_XDECREF(olditem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000216 return 0;
217}
218
219static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000220ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000221{
Christian Heimese93237d2007-12-19 02:37:44 +0000222 Py_ssize_t i, n = Py_SIZE(self);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000223 PyObject **items;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000224 if (v == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000225 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000226 return -1;
227 }
Martin v. Löwisb1ed7fa2006-04-13 07:52:27 +0000228 if (n == PY_SSIZE_T_MAX) {
Trent Micka5846642000-08-13 22:47:45 +0000229 PyErr_SetString(PyExc_OverflowError,
230 "cannot add more objects to list");
231 return -1;
232 }
Tim Petersb38e2b62004-07-29 02:29:26 +0000233
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000234 if (list_resize(self, n+1) == -1)
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000235 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000236
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000237 if (where < 0) {
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000238 where += n;
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000239 if (where < 0)
240 where = 0;
241 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000242 if (where > n)
243 where = n;
244 items = self->ob_item;
245 for (i = n; --i >= where; )
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000246 items[i+1] = items[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000247 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000248 items[where] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000249 return 0;
250}
251
252int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000253PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000254{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000255 if (!PyList_Check(op)) {
256 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000257 return -1;
258 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000259 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000260}
261
Raymond Hettinger40a03822004-04-12 13:05:09 +0000262static int
263app1(PyListObject *self, PyObject *v)
264{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000265 Py_ssize_t n = PyList_GET_SIZE(self);
Raymond Hettinger40a03822004-04-12 13:05:09 +0000266
267 assert (v != NULL);
Martin v. Löwisb1ed7fa2006-04-13 07:52:27 +0000268 if (n == PY_SSIZE_T_MAX) {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000269 PyErr_SetString(PyExc_OverflowError,
270 "cannot add more objects to list");
271 return -1;
272 }
273
274 if (list_resize(self, n+1) == -1)
275 return -1;
276
277 Py_INCREF(v);
278 PyList_SET_ITEM(self, n, v);
279 return 0;
280}
281
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000282int
Fred Drakea2f55112000-07-09 15:16:51 +0000283PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000284{
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000285 if (PyList_Check(op) && (newitem != NULL))
286 return app1((PyListObject *)op, newitem);
287 PyErr_BadInternalCall();
288 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000289}
290
291/* Methods */
292
293static void
Fred Drakea2f55112000-07-09 15:16:51 +0000294list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000295{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000296 Py_ssize_t i;
Guido van Rossumff413af2002-03-28 20:34:59 +0000297 PyObject_GC_UnTrack(op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000298 Py_TRASHCAN_SAFE_BEGIN(op)
Jack Jansen7874d1f1995-01-19 12:09:27 +0000299 if (op->ob_item != NULL) {
Guido van Rossumfa717011999-06-09 15:19:34 +0000300 /* Do it backwards, for Christian Tismer.
301 There's a simple test case where somehow this reduces
302 thrashing when a *very* large list is created and
303 immediately deleted. */
Christian Heimese93237d2007-12-19 02:37:44 +0000304 i = Py_SIZE(op);
Guido van Rossumfa717011999-06-09 15:19:34 +0000305 while (--i >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000306 Py_XDECREF(op->ob_item[i]);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000307 }
Guido van Rossumb18618d2000-05-03 23:44:39 +0000308 PyMem_FREE(op->ob_item);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000309 }
Christian Heimes5b970ad2008-02-06 13:33:44 +0000310 if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op))
311 free_list[numfree++] = op;
Tim Petersb38e2b62004-07-29 02:29:26 +0000312 else
Christian Heimese93237d2007-12-19 02:37:44 +0000313 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000314 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000315}
316
Guido van Rossum90933611991-06-07 16:10:43 +0000317static int
Fred Drakea2f55112000-07-09 15:16:51 +0000318list_print(PyListObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000319{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000320 int rc;
321 Py_ssize_t i;
Antoine Pitroubeaf6a02009-10-11 21:03:26 +0000322 PyObject *item;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000323
Martin v. Löwis18e16552006-02-15 17:27:45 +0000324 rc = Py_ReprEnter((PyObject*)op);
325 if (rc != 0) {
326 if (rc < 0)
327 return rc;
Brett Cannon01531592007-09-17 03:28:34 +0000328 Py_BEGIN_ALLOW_THREADS
Guido van Rossumfb376de1998-04-10 22:47:27 +0000329 fprintf(fp, "[...]");
Brett Cannon01531592007-09-17 03:28:34 +0000330 Py_END_ALLOW_THREADS
Guido van Rossumfb376de1998-04-10 22:47:27 +0000331 return 0;
332 }
Brett Cannon01531592007-09-17 03:28:34 +0000333 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000334 fprintf(fp, "[");
Brett Cannon01531592007-09-17 03:28:34 +0000335 Py_END_ALLOW_THREADS
Christian Heimese93237d2007-12-19 02:37:44 +0000336 for (i = 0; i < Py_SIZE(op); i++) {
Antoine Pitroubeaf6a02009-10-11 21:03:26 +0000337 item = op->ob_item[i];
338 Py_INCREF(item);
Brett Cannon01531592007-09-17 03:28:34 +0000339 if (i > 0) {
340 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000341 fprintf(fp, ", ");
Brett Cannon01531592007-09-17 03:28:34 +0000342 Py_END_ALLOW_THREADS
343 }
Antoine Pitroubeaf6a02009-10-11 21:03:26 +0000344 if (PyObject_Print(item, fp, 0) != 0) {
345 Py_DECREF(item);
Guido van Rossumfb376de1998-04-10 22:47:27 +0000346 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000347 return -1;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000348 }
Antoine Pitroubeaf6a02009-10-11 21:03:26 +0000349 Py_DECREF(item);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000350 }
Brett Cannon01531592007-09-17 03:28:34 +0000351 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000352 fprintf(fp, "]");
Brett Cannon01531592007-09-17 03:28:34 +0000353 Py_END_ALLOW_THREADS
Guido van Rossumfb376de1998-04-10 22:47:27 +0000354 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000355 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000356}
357
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000358static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000359list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000360{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000361 Py_ssize_t i;
Tim Petersa7259592001-06-16 05:11:17 +0000362 PyObject *s, *temp;
363 PyObject *pieces = NULL, *result = NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000364
365 i = Py_ReprEnter((PyObject*)v);
366 if (i != 0) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000367 return i > 0 ? PyString_FromString("[...]") : NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000368 }
Tim Petersa7259592001-06-16 05:11:17 +0000369
Christian Heimese93237d2007-12-19 02:37:44 +0000370 if (Py_SIZE(v) == 0) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000371 result = PyString_FromString("[]");
Tim Petersa7259592001-06-16 05:11:17 +0000372 goto Done;
373 }
374
375 pieces = PyList_New(0);
376 if (pieces == NULL)
377 goto Done;
378
379 /* Do repr() on each element. Note that this may mutate the list,
380 so must refetch the list size on each iteration. */
Christian Heimese93237d2007-12-19 02:37:44 +0000381 for (i = 0; i < Py_SIZE(v); ++i) {
Tim Petersa7259592001-06-16 05:11:17 +0000382 int status;
Brett Cannona0c05512007-09-10 21:38:27 +0000383 if (Py_EnterRecursiveCall(" while getting the repr of a list"))
384 goto Done;
Tim Petersa7259592001-06-16 05:11:17 +0000385 s = PyObject_Repr(v->ob_item[i]);
Brett Cannona0c05512007-09-10 21:38:27 +0000386 Py_LeaveRecursiveCall();
Tim Petersa7259592001-06-16 05:11:17 +0000387 if (s == NULL)
388 goto Done;
389 status = PyList_Append(pieces, s);
390 Py_DECREF(s); /* append created a new ref */
391 if (status < 0)
392 goto Done;
393 }
394
395 /* Add "[]" decorations to the first and last items. */
396 assert(PyList_GET_SIZE(pieces) > 0);
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000397 s = PyString_FromString("[");
Tim Petersa7259592001-06-16 05:11:17 +0000398 if (s == NULL)
399 goto Done;
400 temp = PyList_GET_ITEM(pieces, 0);
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000401 PyString_ConcatAndDel(&s, temp);
Tim Petersa7259592001-06-16 05:11:17 +0000402 PyList_SET_ITEM(pieces, 0, s);
403 if (s == NULL)
404 goto Done;
405
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000406 s = PyString_FromString("]");
Tim Petersa7259592001-06-16 05:11:17 +0000407 if (s == NULL)
408 goto Done;
409 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000410 PyString_ConcatAndDel(&temp, s);
Tim Petersa7259592001-06-16 05:11:17 +0000411 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
412 if (temp == NULL)
413 goto Done;
414
415 /* Paste them all together with ", " between. */
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000416 s = PyString_FromString(", ");
Tim Petersa7259592001-06-16 05:11:17 +0000417 if (s == NULL)
418 goto Done;
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000419 result = _PyString_Join(s, pieces);
Tim Peters3b01a122002-07-19 02:35:45 +0000420 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +0000421
422Done:
423 Py_XDECREF(pieces);
Guido van Rossumfb376de1998-04-10 22:47:27 +0000424 Py_ReprLeave((PyObject *)v);
Tim Petersa7259592001-06-16 05:11:17 +0000425 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000426}
427
Martin v. Löwis18e16552006-02-15 17:27:45 +0000428static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000429list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000430{
Christian Heimese93237d2007-12-19 02:37:44 +0000431 return Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000432}
433
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000434static int
Fred Drakea2f55112000-07-09 15:16:51 +0000435list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000436{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000437 Py_ssize_t i;
438 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000439
Christian Heimese93237d2007-12-19 02:37:44 +0000440 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
Raymond Hettingeraae59992002-09-05 14:23:49 +0000441 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000442 Py_EQ);
Neal Norwitzbb9c5f52002-09-05 21:32:55 +0000443 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000444}
445
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000446static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000447list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000448{
Christian Heimese93237d2007-12-19 02:37:44 +0000449 if (i < 0 || i >= Py_SIZE(a)) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000450 if (indexerr == NULL)
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000451 indexerr = PyString_FromString(
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000452 "list index out of range");
453 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000454 return NULL;
455 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000456 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000457 return a->ob_item[i];
458}
459
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000460static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000461list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000462{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000463 PyListObject *np;
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000464 PyObject **src, **dest;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000465 Py_ssize_t i, len;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000466 if (ilow < 0)
467 ilow = 0;
Christian Heimese93237d2007-12-19 02:37:44 +0000468 else if (ilow > Py_SIZE(a))
469 ilow = Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000470 if (ihigh < ilow)
471 ihigh = ilow;
Christian Heimese93237d2007-12-19 02:37:44 +0000472 else if (ihigh > Py_SIZE(a))
473 ihigh = Py_SIZE(a);
Raymond Hettinger99842b62004-03-08 05:56:15 +0000474 len = ihigh - ilow;
475 np = (PyListObject *) PyList_New(len);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000476 if (np == NULL)
477 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000478
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000479 src = a->ob_item + ilow;
480 dest = np->ob_item;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000481 for (i = 0; i < len; i++) {
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000482 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000483 Py_INCREF(v);
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000484 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000485 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000486 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000487}
488
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000489PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000490PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000491{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000492 if (!PyList_Check(a)) {
493 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000494 return NULL;
495 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000496 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000497}
498
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000499static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000500list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000501{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000502 Py_ssize_t size;
503 Py_ssize_t i;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000504 PyObject **src, **dest;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000505 PyListObject *np;
506 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000507 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000508 "can only concatenate list (not \"%.200s\") to list",
509 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000510 return NULL;
511 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000512#define b ((PyListObject *)bb)
Christian Heimese93237d2007-12-19 02:37:44 +0000513 size = Py_SIZE(a) + Py_SIZE(b);
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000514 if (size < 0)
515 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000516 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000517 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000518 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000519 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000520 src = a->ob_item;
521 dest = np->ob_item;
Christian Heimese93237d2007-12-19 02:37:44 +0000522 for (i = 0; i < Py_SIZE(a); i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000523 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000524 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000525 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000526 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000527 src = b->ob_item;
Christian Heimese93237d2007-12-19 02:37:44 +0000528 dest = np->ob_item + Py_SIZE(a);
529 for (i = 0; i < Py_SIZE(b); i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000530 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000531 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000532 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000533 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000534 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000535#undef b
536}
537
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000538static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000539list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000540{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000541 Py_ssize_t i, j;
542 Py_ssize_t size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000543 PyListObject *np;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000544 PyObject **p, **items;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000545 PyObject *elem;
Guido van Rossumed98d481991-03-06 13:07:53 +0000546 if (n < 0)
547 n = 0;
Christian Heimese93237d2007-12-19 02:37:44 +0000548 size = Py_SIZE(a) * n;
549 if (n && size/n != Py_SIZE(a))
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000550 return PyErr_NoMemory();
Armin Rigoa1e42e12007-10-17 18:46:37 +0000551 if (size == 0)
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000552 return PyList_New(0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000553 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000554 if (np == NULL)
555 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000556
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000557 items = np->ob_item;
Christian Heimese93237d2007-12-19 02:37:44 +0000558 if (Py_SIZE(a) == 1) {
Raymond Hettinger6624e682003-05-21 05:58:46 +0000559 elem = a->ob_item[0];
560 for (i = 0; i < n; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000561 items[i] = elem;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000562 Py_INCREF(elem);
563 }
564 return (PyObject *) np;
565 }
Guido van Rossumed98d481991-03-06 13:07:53 +0000566 p = np->ob_item;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000567 items = a->ob_item;
Guido van Rossumed98d481991-03-06 13:07:53 +0000568 for (i = 0; i < n; i++) {
Christian Heimese93237d2007-12-19 02:37:44 +0000569 for (j = 0; j < Py_SIZE(a); j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000570 *p = items[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000571 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000572 p++;
573 }
574 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000575 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000576}
577
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000578static int
Armin Rigo93677f02004-07-29 12:40:23 +0000579list_clear(PyListObject *a)
580{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000581 Py_ssize_t i;
Armin Rigo93677f02004-07-29 12:40:23 +0000582 PyObject **item = a->ob_item;
583 if (item != NULL) {
584 /* Because XDECREF can recursively invoke operations on
585 this list, we make it empty first. */
Christian Heimese93237d2007-12-19 02:37:44 +0000586 i = Py_SIZE(a);
587 Py_SIZE(a) = 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000588 a->ob_item = NULL;
589 a->allocated = 0;
590 while (--i >= 0) {
591 Py_XDECREF(item[i]);
592 }
593 PyMem_FREE(item);
594 }
595 /* Never fails; the return value can be ignored.
596 Note that there is no guarantee that the list is actually empty
597 at this point, because XDECREF may have populated it again! */
598 return 0;
599}
600
Tim Peters8fc4a912004-07-31 21:53:19 +0000601/* a[ilow:ihigh] = v if v != NULL.
602 * del a[ilow:ihigh] if v == NULL.
603 *
604 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
605 * guaranteed the call cannot fail.
606 */
Armin Rigo93677f02004-07-29 12:40:23 +0000607static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000608list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000609{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000610 /* Because [X]DECREF can recursively invoke list operations on
611 this list, we must postpone all [X]DECREF activity until
612 after the list is back in its canonical shape. Therefore
613 we must allocate an additional array, 'recycle', into which
614 we temporarily copy the items that are deleted from the
615 list. :-( */
Tim Peters73572222004-07-31 02:54:42 +0000616 PyObject *recycle_on_stack[8];
617 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000618 PyObject **item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000619 PyObject **vitem = NULL;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000620 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000621 Py_ssize_t n; /* # of elements in replacement list */
622 Py_ssize_t norig; /* # of elements in list getting replaced */
623 Py_ssize_t d; /* Change in size */
624 Py_ssize_t k;
Tim Peters8d9eb102004-07-31 02:24:20 +0000625 size_t s;
626 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000627#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000628 if (v == NULL)
629 n = 0;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000630 else {
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000631 if (a == b) {
632 /* Special case "a[i:j] = a" -- copy b first */
Christian Heimese93237d2007-12-19 02:37:44 +0000633 v = list_slice(b, 0, Py_SIZE(b));
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000634 if (v == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000635 return result;
636 result = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000637 Py_DECREF(v);
Tim Peters8d9eb102004-07-31 02:24:20 +0000638 return result;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000639 }
Raymond Hettingerf889e102004-03-09 08:04:33 +0000640 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000641 if(v_as_SF == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000642 goto Error;
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000643 n = PySequence_Fast_GET_SIZE(v_as_SF);
Raymond Hettinger42bec932004-03-12 16:38:17 +0000644 vitem = PySequence_Fast_ITEMS(v_as_SF);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000645 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000646 if (ilow < 0)
647 ilow = 0;
Christian Heimese93237d2007-12-19 02:37:44 +0000648 else if (ilow > Py_SIZE(a))
649 ilow = Py_SIZE(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000650
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000651 if (ihigh < ilow)
652 ihigh = ilow;
Christian Heimese93237d2007-12-19 02:37:44 +0000653 else if (ihigh > Py_SIZE(a))
654 ihigh = Py_SIZE(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000655
Tim Peters8d9eb102004-07-31 02:24:20 +0000656 norig = ihigh - ilow;
657 assert(norig >= 0);
658 d = n - norig;
Christian Heimese93237d2007-12-19 02:37:44 +0000659 if (Py_SIZE(a) + d == 0) {
Armin Rigo93677f02004-07-29 12:40:23 +0000660 Py_XDECREF(v_as_SF);
661 return list_clear(a);
662 }
663 item = a->ob_item;
Tim Peters8d9eb102004-07-31 02:24:20 +0000664 /* recycle the items that we are about to remove */
665 s = norig * sizeof(PyObject *);
Tim Peters73572222004-07-31 02:54:42 +0000666 if (s > sizeof(recycle_on_stack)) {
Armin Rigo1dd04a02004-07-30 11:38:22 +0000667 recycle = (PyObject **)PyMem_MALLOC(s);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000668 if (recycle == NULL) {
669 PyErr_NoMemory();
Tim Peters8d9eb102004-07-31 02:24:20 +0000670 goto Error;
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000671 }
672 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000673 memcpy(recycle, &item[ilow], s);
Tim Peters8d9eb102004-07-31 02:24:20 +0000674
Armin Rigo1dd04a02004-07-30 11:38:22 +0000675 if (d < 0) { /* Delete -d items */
676 memmove(&item[ihigh+d], &item[ihigh],
Christian Heimese93237d2007-12-19 02:37:44 +0000677 (Py_SIZE(a) - ihigh)*sizeof(PyObject *));
678 list_resize(a, Py_SIZE(a) + d);
Armin Rigo1dd04a02004-07-30 11:38:22 +0000679 item = a->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000680 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000681 else if (d > 0) { /* Insert d items */
Christian Heimese93237d2007-12-19 02:37:44 +0000682 k = Py_SIZE(a);
Tim Peters73572222004-07-31 02:54:42 +0000683 if (list_resize(a, k+d) < 0)
Tim Peters8d9eb102004-07-31 02:24:20 +0000684 goto Error;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000685 item = a->ob_item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000686 memmove(&item[ihigh+d], &item[ihigh],
Tim Peters73572222004-07-31 02:54:42 +0000687 (k - ihigh)*sizeof(PyObject *));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000688 }
689 for (k = 0; k < n; k++, ilow++) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000690 PyObject *w = vitem[k];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000691 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000692 item[ilow] = w;
693 }
Tim Peters73572222004-07-31 02:54:42 +0000694 for (k = norig - 1; k >= 0; --k)
695 Py_XDECREF(recycle[k]);
Tim Peters8d9eb102004-07-31 02:24:20 +0000696 result = 0;
697 Error:
Tim Peters73572222004-07-31 02:54:42 +0000698 if (recycle != recycle_on_stack)
Armin Rigo1dd04a02004-07-30 11:38:22 +0000699 PyMem_FREE(recycle);
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000700 Py_XDECREF(v_as_SF);
Tim Peters8d9eb102004-07-31 02:24:20 +0000701 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000702#undef b
703}
704
Guido van Rossum234f9421993-06-17 12:35:49 +0000705int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000706PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000707{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000708 if (!PyList_Check(a)) {
709 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000710 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000711 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000712 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000713}
714
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000715static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000716list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000717{
718 PyObject **items;
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000719 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000720
721
722 size = PyList_GET_SIZE(self);
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000723 if (size == 0 || n == 1) {
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000724 Py_INCREF(self);
725 return (PyObject *)self;
726 }
727
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000728 if (n < 1) {
Armin Rigo93677f02004-07-29 12:40:23 +0000729 (void)list_clear(self);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000730 Py_INCREF(self);
731 return (PyObject *)self;
732 }
733
Thomas Woutersa97744c2008-01-25 21:09:34 +0000734 if (size > PY_SSIZE_T_MAX / n) {
Armin Rigoa1e42e12007-10-17 18:46:37 +0000735 return PyErr_NoMemory();
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000736 }
737
738 if (list_resize(self, size*n) == -1)
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000739 return NULL;
740
741 p = size;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000742 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000743 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
744 for (j = 0; j < size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000745 PyObject *o = items[j];
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000746 Py_INCREF(o);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000747 items[p++] = o;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000748 }
749 }
750 Py_INCREF(self);
751 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000752}
753
Guido van Rossum4a450d01991-04-03 19:05:18 +0000754static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000755list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000756{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000757 PyObject *old_value;
Christian Heimese93237d2007-12-19 02:37:44 +0000758 if (i < 0 || i >= Py_SIZE(a)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000759 PyErr_SetString(PyExc_IndexError,
760 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000761 return -1;
762 }
763 if (v == NULL)
764 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000765 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000766 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000767 a->ob_item[i] = v;
Tim Peters3b01a122002-07-19 02:35:45 +0000768 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000769 return 0;
770}
771
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000772static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000773listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000774{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000775 Py_ssize_t i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000776 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000777 if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000778 return NULL;
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000779 if (ins1(self, i, v) == 0)
780 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000781 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000782}
783
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000784static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000785listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000786{
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000787 if (app1(self, v) == 0)
788 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000789 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000790}
791
Barry Warsawdedf6d61998-10-09 16:37:25 +0000792static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000793listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000794{
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000795 PyObject *it; /* iter(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000796 Py_ssize_t m; /* size of self */
797 Py_ssize_t n; /* guess for size of b */
798 Py_ssize_t mn; /* m + n */
799 Py_ssize_t i;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000800 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000801
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000802 /* Special cases:
Tim Petersb38e2b62004-07-29 02:29:26 +0000803 1) lists and tuples which can use PySequence_Fast ops
804 2) extending self to self requires making a copy first
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000805 */
806 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
Armin Rigo70d172d2004-03-20 22:19:23 +0000807 PyObject **src, **dest;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000808 b = PySequence_Fast(b, "argument must be iterable");
809 if (!b)
810 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000811 n = PySequence_Fast_GET_SIZE(b);
812 if (n == 0) {
813 /* short circuit when b is empty */
814 Py_DECREF(b);
815 Py_RETURN_NONE;
816 }
Christian Heimese93237d2007-12-19 02:37:44 +0000817 m = Py_SIZE(self);
Armin Rigo70d172d2004-03-20 22:19:23 +0000818 if (list_resize(self, m + n) == -1) {
819 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000820 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000821 }
822 /* note that we may still have self == b here for the
823 * situation a.extend(a), but the following code works
824 * in that case too. Just make sure to resize self
825 * before calling PySequence_Fast_ITEMS.
826 */
827 /* populate the end of self with b's items */
828 src = PySequence_Fast_ITEMS(b);
829 dest = self->ob_item + m;
830 for (i = 0; i < n; i++) {
831 PyObject *o = src[i];
832 Py_INCREF(o);
833 dest[i] = o;
834 }
835 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000836 Py_RETURN_NONE;
837 }
838
839 it = PyObject_GetIter(b);
840 if (it == NULL)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000841 return NULL;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000842 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000843
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000844 /* Guess a result list size. */
Raymond Hettinger4e2f7142007-12-06 00:56:53 +0000845 n = _PyObject_LengthHint(b, 8);
Raymond Hettingerb5163702009-02-02 21:50:13 +0000846 if (n == -1) {
847 Py_DECREF(it);
848 return NULL;
849 }
Christian Heimese93237d2007-12-19 02:37:44 +0000850 m = Py_SIZE(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000851 mn = m + n;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000852 if (mn >= m) {
853 /* Make room. */
854 if (list_resize(self, mn) == -1)
855 goto error;
856 /* Make the list sane again. */
Christian Heimese93237d2007-12-19 02:37:44 +0000857 Py_SIZE(self) = m;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000858 }
859 /* Else m + n overflowed; on the chance that n lied, and there really
860 * is enough room, ignore it. If n was telling the truth, we'll
861 * eventually run out of memory during the loop.
862 */
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000863
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000864 /* Run iterator to exhaustion. */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000865 for (;;) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000866 PyObject *item = iternext(it);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000867 if (item == NULL) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000868 if (PyErr_Occurred()) {
869 if (PyErr_ExceptionMatches(PyExc_StopIteration))
870 PyErr_Clear();
871 else
872 goto error;
873 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000874 break;
875 }
Christian Heimese93237d2007-12-19 02:37:44 +0000876 if (Py_SIZE(self) < self->allocated) {
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000877 /* steals ref */
Christian Heimese93237d2007-12-19 02:37:44 +0000878 PyList_SET_ITEM(self, Py_SIZE(self), item);
879 ++Py_SIZE(self);
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000880 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000881 else {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000882 int status = app1(self, item);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000883 Py_DECREF(item); /* append creates a new ref */
884 if (status < 0)
885 goto error;
886 }
887 }
888
889 /* Cut back result list if initial guess was too large. */
Christian Heimese93237d2007-12-19 02:37:44 +0000890 if (Py_SIZE(self) < self->allocated)
891 list_resize(self, Py_SIZE(self)); /* shrinking can't fail */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000892
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000893 Py_DECREF(it);
894 Py_RETURN_NONE;
895
896 error:
897 Py_DECREF(it);
898 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000899}
900
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000901PyObject *
902_PyList_Extend(PyListObject *self, PyObject *b)
903{
904 return listextend(self, b);
905}
906
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000907static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000908list_inplace_concat(PyListObject *self, PyObject *other)
909{
910 PyObject *result;
911
912 result = listextend(self, other);
913 if (result == NULL)
914 return result;
915 Py_DECREF(result);
916 Py_INCREF(self);
917 return (PyObject *)self;
918}
919
920static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000921listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000922{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000923 Py_ssize_t i = -1;
Armin Rigo7ccbca92006-10-04 12:17:45 +0000924 PyObject *v;
Tim Peters8fc4a912004-07-31 21:53:19 +0000925 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000926
Armin Rigo7ccbca92006-10-04 12:17:45 +0000927 if (!PyArg_ParseTuple(args, "|n:pop", &i))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000928 return NULL;
Armin Rigo7ccbca92006-10-04 12:17:45 +0000929
Christian Heimese93237d2007-12-19 02:37:44 +0000930 if (Py_SIZE(self) == 0) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000931 /* Special-case most common failure cause */
932 PyErr_SetString(PyExc_IndexError, "pop from empty list");
933 return NULL;
934 }
935 if (i < 0)
Christian Heimese93237d2007-12-19 02:37:44 +0000936 i += Py_SIZE(self);
937 if (i < 0 || i >= Py_SIZE(self)) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000938 PyErr_SetString(PyExc_IndexError, "pop index out of range");
939 return NULL;
940 }
941 v = self->ob_item[i];
Christian Heimese93237d2007-12-19 02:37:44 +0000942 if (i == Py_SIZE(self) - 1) {
943 status = list_resize(self, Py_SIZE(self) - 1);
Tim Peters8fc4a912004-07-31 21:53:19 +0000944 assert(status >= 0);
945 return v; /* and v now owns the reference the list had */
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000946 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000947 Py_INCREF(v);
Tim Peters8fc4a912004-07-31 21:53:19 +0000948 status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
949 assert(status >= 0);
950 /* Use status, so that in a release build compilers don't
951 * complain about the unused name.
952 */
Brett Cannon651dd522004-08-08 21:21:18 +0000953 (void) status;
954
955 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000956}
957
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000958/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
959static void
960reverse_slice(PyObject **lo, PyObject **hi)
961{
962 assert(lo && hi);
963
964 --hi;
965 while (lo < hi) {
966 PyObject *t = *lo;
967 *lo = *hi;
968 *hi = t;
969 ++lo;
970 --hi;
971 }
972}
973
Tim Petersa64dc242002-08-01 02:13:36 +0000974/* Lots of code for an adaptive, stable, natural mergesort. There are many
975 * pieces to this algorithm; read listsort.txt for overviews and details.
976 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000977
Guido van Rossum3f236de1996-12-10 23:55:39 +0000978/* Comparison function. Takes care of calling a user-supplied
Tim Peters66860f62002-08-04 17:47:26 +0000979 * comparison function (any callable Python object), which must not be
980 * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool
981 * with Py_LT if you know it's NULL).
Tim Petersa64dc242002-08-01 02:13:36 +0000982 * Returns -1 on error, 1 if x < y, 0 if x >= y.
983 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000984static int
Tim Petersa8c974c2002-07-19 03:30:57 +0000985islt(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000986{
Tim Petersf2a04732002-07-11 21:46:16 +0000987 PyObject *res;
988 PyObject *args;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000989 Py_ssize_t i;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000990
Tim Peters66860f62002-08-04 17:47:26 +0000991 assert(compare != NULL);
Tim Petersa8c974c2002-07-19 03:30:57 +0000992 /* Call the user's comparison function and translate the 3-way
993 * result into true or false (or error).
994 */
Tim Petersf2a04732002-07-11 21:46:16 +0000995 args = PyTuple_New(2);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000996 if (args == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000997 return -1;
Tim Petersf2a04732002-07-11 21:46:16 +0000998 Py_INCREF(x);
999 Py_INCREF(y);
1000 PyTuple_SET_ITEM(args, 0, x);
1001 PyTuple_SET_ITEM(args, 1, y);
Tim Peters58cf3612002-07-15 05:16:13 +00001002 res = PyObject_Call(compare, args, NULL);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001003 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +00001004 if (res == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +00001005 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001006 if (!PyInt_Check(res)) {
Georg Brandl283a1352006-11-19 08:48:30 +00001007 PyErr_Format(PyExc_TypeError,
1008 "comparison function must return int, not %.200s",
1009 res->ob_type->tp_name);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001010 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +00001011 return -1;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001012 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001013 i = PyInt_AsLong(res);
1014 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +00001015 return i < 0;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001016}
1017
Tim Peters66860f62002-08-04 17:47:26 +00001018/* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
1019 * islt. This avoids a layer of function call in the usual case, and
1020 * sorting does many comparisons.
1021 * Returns -1 on error, 1 if x < y, 0 if x >= y.
1022 */
1023#define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
1024 PyObject_RichCompareBool(X, Y, Py_LT) : \
1025 islt(X, Y, COMPARE))
1026
1027/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +00001028 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
1029 started. It makes more sense in context <wink>. X and Y are PyObject*s.
1030*/
Tim Peters66860f62002-08-04 17:47:26 +00001031#define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
Tim Petersa8c974c2002-07-19 03:30:57 +00001032 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001033
1034/* binarysort is the best method for sorting small arrays: it does
1035 few compares, but can do data movement quadratic in the number of
1036 elements.
Guido van Rossum42812581998-06-17 14:15:44 +00001037 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +00001038 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001039 On entry, must have lo <= start <= hi, and that [lo, start) is already
1040 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +00001041 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001042 Even in case of error, the output slice will be some permutation of
1043 the input (nothing is lost or duplicated).
1044*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00001045static int
Fred Drakea2f55112000-07-09 15:16:51 +00001046binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
1047 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001048{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001049 register Py_ssize_t k;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001050 register PyObject **l, **p, **r;
1051 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001052
Tim Petersa8c974c2002-07-19 03:30:57 +00001053 assert(lo <= start && start <= hi);
1054 /* assert [lo, start) is sorted */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001055 if (lo == start)
1056 ++start;
1057 for (; start < hi; ++start) {
1058 /* set l to where *start belongs */
1059 l = lo;
1060 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001061 pivot = *r;
Tim Peters0fe977c2002-07-19 06:12:32 +00001062 /* Invariants:
1063 * pivot >= all in [lo, l).
1064 * pivot < all in [r, start).
1065 * The second is vacuously true at the start.
1066 */
1067 assert(l < r);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001068 do {
1069 p = l + ((r - l) >> 1);
Tim Petersa8c974c2002-07-19 03:30:57 +00001070 IFLT(pivot, *p)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001071 r = p;
1072 else
Tim Peters0fe977c2002-07-19 06:12:32 +00001073 l = p+1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001074 } while (l < r);
Tim Peters0fe977c2002-07-19 06:12:32 +00001075 assert(l == r);
1076 /* The invariants still hold, so pivot >= all in [lo, l) and
1077 pivot < all in [l, start), so pivot belongs at l. Note
1078 that if there are elements equal to pivot, l points to the
1079 first slot after them -- that's why this sort is stable.
1080 Slide over to make room.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001081 Caution: using memmove is much slower under MSVC 5;
1082 we're not usually moving many slots. */
1083 for (p = start; p > l; --p)
1084 *p = *(p-1);
1085 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001086 }
Guido van Rossum3f236de1996-12-10 23:55:39 +00001087 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001088
1089 fail:
1090 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001091}
1092
Tim Petersa64dc242002-08-01 02:13:36 +00001093/*
1094Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1095is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001096
Tim Petersa64dc242002-08-01 02:13:36 +00001097 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001098
Tim Petersa64dc242002-08-01 02:13:36 +00001099or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001100
Tim Petersa64dc242002-08-01 02:13:36 +00001101 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001102
Tim Petersa64dc242002-08-01 02:13:36 +00001103Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1104For its intended use in a stable mergesort, the strictness of the defn of
1105"descending" is needed so that the caller can safely reverse a descending
1106sequence without violating stability (strict > ensures there are no equal
1107elements to get out of order).
1108
1109Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001110*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001111static Py_ssize_t
Tim Petersa64dc242002-08-01 02:13:36 +00001112count_run(PyObject **lo, PyObject **hi, PyObject *compare, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001113{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001114 Py_ssize_t k;
1115 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001116
Tim Petersa64dc242002-08-01 02:13:36 +00001117 assert(lo < hi);
1118 *descending = 0;
1119 ++lo;
1120 if (lo == hi)
1121 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001122
Tim Petersa64dc242002-08-01 02:13:36 +00001123 n = 2;
1124 IFLT(*lo, *(lo-1)) {
1125 *descending = 1;
1126 for (lo = lo+1; lo < hi; ++lo, ++n) {
1127 IFLT(*lo, *(lo-1))
1128 ;
1129 else
1130 break;
1131 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001132 }
Tim Petersa64dc242002-08-01 02:13:36 +00001133 else {
1134 for (lo = lo+1; lo < hi; ++lo, ++n) {
1135 IFLT(*lo, *(lo-1))
1136 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001137 }
1138 }
1139
Tim Petersa64dc242002-08-01 02:13:36 +00001140 return n;
1141fail:
1142 return -1;
1143}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001144
Tim Petersa64dc242002-08-01 02:13:36 +00001145/*
1146Locate the proper position of key in a sorted vector; if the vector contains
1147an element equal to key, return the position immediately to the left of
1148the leftmost equal element. [gallop_right() does the same except returns
1149the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001150
Tim Petersa64dc242002-08-01 02:13:36 +00001151"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001152
Tim Petersa64dc242002-08-01 02:13:36 +00001153"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1154hint is to the final result, the faster this runs.
1155
1156The return value is the int k in 0..n such that
1157
1158 a[k-1] < key <= a[k]
1159
1160pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1161key belongs at index k; or, IOW, the first k elements of a should precede
1162key, and the last n-k should follow key.
1163
1164Returns -1 on error. See listsort.txt for info on the method.
1165*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001166static Py_ssize_t
1167gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
Tim Petersa64dc242002-08-01 02:13:36 +00001168{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001169 Py_ssize_t ofs;
1170 Py_ssize_t lastofs;
1171 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001172
1173 assert(key && a && n > 0 && hint >= 0 && hint < n);
1174
1175 a += hint;
1176 lastofs = 0;
1177 ofs = 1;
1178 IFLT(*a, key) {
1179 /* a[hint] < key -- gallop right, until
1180 * a[hint + lastofs] < key <= a[hint + ofs]
1181 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001182 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001183 while (ofs < maxofs) {
1184 IFLT(a[ofs], key) {
1185 lastofs = ofs;
1186 ofs = (ofs << 1) + 1;
1187 if (ofs <= 0) /* int overflow */
1188 ofs = maxofs;
1189 }
1190 else /* key <= a[hint + ofs] */
1191 break;
1192 }
1193 if (ofs > maxofs)
1194 ofs = maxofs;
1195 /* Translate back to offsets relative to &a[0]. */
1196 lastofs += hint;
1197 ofs += hint;
1198 }
1199 else {
1200 /* key <= a[hint] -- gallop left, until
1201 * a[hint - ofs] < key <= a[hint - lastofs]
1202 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001203 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001204 while (ofs < maxofs) {
1205 IFLT(*(a-ofs), key)
1206 break;
1207 /* key <= a[hint - ofs] */
1208 lastofs = ofs;
1209 ofs = (ofs << 1) + 1;
1210 if (ofs <= 0) /* int overflow */
1211 ofs = maxofs;
1212 }
1213 if (ofs > maxofs)
1214 ofs = maxofs;
1215 /* Translate back to positive offsets relative to &a[0]. */
1216 k = lastofs;
1217 lastofs = hint - ofs;
1218 ofs = hint - k;
1219 }
1220 a -= hint;
1221
1222 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1223 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1224 * right of lastofs but no farther right than ofs. Do a binary
1225 * search, with invariant a[lastofs-1] < key <= a[ofs].
1226 */
1227 ++lastofs;
1228 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001229 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001230
1231 IFLT(a[m], key)
1232 lastofs = m+1; /* a[m] < key */
1233 else
1234 ofs = m; /* key <= a[m] */
1235 }
1236 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1237 return ofs;
1238
1239fail:
1240 return -1;
1241}
1242
1243/*
1244Exactly like gallop_left(), except that if key already exists in a[0:n],
1245finds the position immediately to the right of the rightmost equal value.
1246
1247The return value is the int k in 0..n such that
1248
1249 a[k-1] <= key < a[k]
1250
1251or -1 if error.
1252
1253The code duplication is massive, but this is enough different given that
1254we're sticking to "<" comparisons that it's much harder to follow if
1255written as one routine with yet another "left or right?" flag.
1256*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001257static Py_ssize_t
1258gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
Tim Petersa64dc242002-08-01 02:13:36 +00001259{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001260 Py_ssize_t ofs;
1261 Py_ssize_t lastofs;
1262 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001263
1264 assert(key && a && n > 0 && hint >= 0 && hint < n);
1265
1266 a += hint;
1267 lastofs = 0;
1268 ofs = 1;
1269 IFLT(key, *a) {
1270 /* key < a[hint] -- gallop left, until
1271 * a[hint - ofs] <= key < a[hint - lastofs]
1272 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001273 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001274 while (ofs < maxofs) {
1275 IFLT(key, *(a-ofs)) {
1276 lastofs = ofs;
1277 ofs = (ofs << 1) + 1;
1278 if (ofs <= 0) /* int overflow */
1279 ofs = maxofs;
1280 }
1281 else /* a[hint - ofs] <= key */
1282 break;
1283 }
1284 if (ofs > maxofs)
1285 ofs = maxofs;
1286 /* Translate back to positive offsets relative to &a[0]. */
1287 k = lastofs;
1288 lastofs = hint - ofs;
1289 ofs = hint - k;
1290 }
1291 else {
1292 /* a[hint] <= key -- gallop right, until
1293 * a[hint + lastofs] <= key < a[hint + ofs]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001294 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001295 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001296 while (ofs < maxofs) {
1297 IFLT(key, a[ofs])
1298 break;
1299 /* a[hint + ofs] <= key */
1300 lastofs = ofs;
1301 ofs = (ofs << 1) + 1;
1302 if (ofs <= 0) /* int overflow */
1303 ofs = maxofs;
1304 }
1305 if (ofs > maxofs)
1306 ofs = maxofs;
1307 /* Translate back to offsets relative to &a[0]. */
1308 lastofs += hint;
1309 ofs += hint;
1310 }
1311 a -= hint;
1312
1313 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1314 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1315 * right of lastofs but no farther right than ofs. Do a binary
1316 * search, with invariant a[lastofs-1] <= key < a[ofs].
1317 */
1318 ++lastofs;
1319 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001320 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001321
1322 IFLT(key, a[m])
1323 ofs = m; /* key < a[m] */
1324 else
1325 lastofs = m+1; /* a[m] <= key */
1326 }
1327 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1328 return ofs;
1329
1330fail:
1331 return -1;
1332}
1333
1334/* The maximum number of entries in a MergeState's pending-runs stack.
1335 * This is enough to sort arrays of size up to about
1336 * 32 * phi ** MAX_MERGE_PENDING
1337 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1338 * with 2**64 elements.
1339 */
1340#define MAX_MERGE_PENDING 85
1341
Tim Peterse05f65a2002-08-10 05:21:15 +00001342/* When we get into galloping mode, we stay there until both runs win less
1343 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001344 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001345#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001346
1347/* Avoid malloc for small temp arrays. */
1348#define MERGESTATE_TEMP_SIZE 256
1349
1350/* One MergeState exists on the stack per invocation of mergesort. It's just
1351 * a convenient way to pass state around among the helper functions.
1352 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001353struct s_slice {
1354 PyObject **base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001355 Py_ssize_t len;
Tim Peterse05f65a2002-08-10 05:21:15 +00001356};
1357
Tim Petersa64dc242002-08-01 02:13:36 +00001358typedef struct s_MergeState {
1359 /* The user-supplied comparison function. or NULL if none given. */
1360 PyObject *compare;
1361
Tim Peterse05f65a2002-08-10 05:21:15 +00001362 /* This controls when we get *into* galloping mode. It's initialized
1363 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1364 * random data, and lower for highly structured data.
1365 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001366 Py_ssize_t min_gallop;
Tim Peterse05f65a2002-08-10 05:21:15 +00001367
Tim Petersa64dc242002-08-01 02:13:36 +00001368 /* 'a' is temp storage to help with merges. It contains room for
1369 * alloced entries.
1370 */
1371 PyObject **a; /* may point to temparray below */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001372 Py_ssize_t alloced;
Tim Petersa64dc242002-08-01 02:13:36 +00001373
1374 /* A stack of n pending runs yet to be merged. Run #i starts at
1375 * address base[i] and extends for len[i] elements. It's always
1376 * true (so long as the indices are in bounds) that
1377 *
Tim Peterse05f65a2002-08-10 05:21:15 +00001378 * pending[i].base + pending[i].len == pending[i+1].base
Tim Petersa64dc242002-08-01 02:13:36 +00001379 *
1380 * so we could cut the storage for this, but it's a minor amount,
1381 * and keeping all the info explicit simplifies the code.
1382 */
1383 int n;
Tim Peterse05f65a2002-08-10 05:21:15 +00001384 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001385
1386 /* 'a' points to this when possible, rather than muck with malloc. */
1387 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1388} MergeState;
1389
1390/* Conceptually a MergeState's constructor. */
1391static void
1392merge_init(MergeState *ms, PyObject *compare)
1393{
1394 assert(ms != NULL);
1395 ms->compare = compare;
1396 ms->a = ms->temparray;
1397 ms->alloced = MERGESTATE_TEMP_SIZE;
1398 ms->n = 0;
Tim Peterse05f65a2002-08-10 05:21:15 +00001399 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001400}
1401
1402/* Free all the temp memory owned by the MergeState. This must be called
1403 * when you're done with a MergeState, and may be called before then if
1404 * you want to free the temp memory early.
1405 */
1406static void
1407merge_freemem(MergeState *ms)
1408{
1409 assert(ms != NULL);
1410 if (ms->a != ms->temparray)
1411 PyMem_Free(ms->a);
1412 ms->a = ms->temparray;
1413 ms->alloced = MERGESTATE_TEMP_SIZE;
1414}
1415
1416/* Ensure enough temp memory for 'need' array slots is available.
1417 * Returns 0 on success and -1 if the memory can't be gotten.
1418 */
1419static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001420merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001421{
1422 assert(ms != NULL);
1423 if (need <= ms->alloced)
1424 return 0;
1425 /* Don't realloc! That can cost cycles to copy the old data, but
1426 * we don't care what's in the block.
1427 */
1428 merge_freemem(ms);
Gregory P. Smith9d534572008-06-11 07:41:16 +00001429 if (need > PY_SSIZE_T_MAX / sizeof(PyObject*)) {
1430 PyErr_NoMemory();
1431 return -1;
1432 }
Tim Petersa64dc242002-08-01 02:13:36 +00001433 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1434 if (ms->a) {
1435 ms->alloced = need;
1436 return 0;
1437 }
1438 PyErr_NoMemory();
1439 merge_freemem(ms); /* reset to sane state */
1440 return -1;
1441}
1442#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1443 merge_getmem(MS, NEED))
1444
1445/* Merge the na elements starting at pa with the nb elements starting at pb
1446 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1447 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1448 * merge, and should have na <= nb. See listsort.txt for more info.
1449 * Return 0 if successful, -1 if error.
1450 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001451static Py_ssize_t
1452merge_lo(MergeState *ms, PyObject **pa, Py_ssize_t na,
1453 PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001454{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001455 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001456 PyObject *compare;
1457 PyObject **dest;
1458 int result = -1; /* guilty until proved innocent */
Neal Norwitz7fd96072006-08-19 04:28:55 +00001459 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001460
1461 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1462 if (MERGE_GETMEM(ms, na) < 0)
1463 return -1;
1464 memcpy(ms->a, pa, na * sizeof(PyObject*));
1465 dest = pa;
1466 pa = ms->a;
1467
1468 *dest++ = *pb++;
1469 --nb;
1470 if (nb == 0)
1471 goto Succeed;
1472 if (na == 1)
1473 goto CopyB;
1474
Neal Norwitz7fd96072006-08-19 04:28:55 +00001475 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001476 compare = ms->compare;
1477 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001478 Py_ssize_t acount = 0; /* # of times A won in a row */
1479 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001480
1481 /* Do the straightforward thing until (if ever) one run
1482 * appears to win consistently.
1483 */
1484 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001485 assert(na > 1 && nb > 0);
Tim Peters66860f62002-08-04 17:47:26 +00001486 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001487 if (k) {
1488 if (k < 0)
1489 goto Fail;
1490 *dest++ = *pb++;
1491 ++bcount;
1492 acount = 0;
1493 --nb;
1494 if (nb == 0)
1495 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001496 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001497 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001498 }
1499 else {
Tim Petersa64dc242002-08-01 02:13:36 +00001500 *dest++ = *pa++;
1501 ++acount;
1502 bcount = 0;
1503 --na;
1504 if (na == 1)
1505 goto CopyB;
Tim Peterse05f65a2002-08-10 05:21:15 +00001506 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001507 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001508 }
Tim Petersa64dc242002-08-01 02:13:36 +00001509 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001510
Tim Petersa64dc242002-08-01 02:13:36 +00001511 /* One run is winning so consistently that galloping may
1512 * be a huge win. So try that, and continue galloping until
1513 * (if ever) neither run appears to be winning consistently
1514 * anymore.
1515 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001516 ++min_gallop;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001517 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001518 assert(na > 1 && nb > 0);
1519 min_gallop -= min_gallop > 1;
1520 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001521 k = gallop_right(*pb, pa, na, 0, compare);
1522 acount = k;
1523 if (k) {
1524 if (k < 0)
1525 goto Fail;
1526 memcpy(dest, pa, k * sizeof(PyObject *));
1527 dest += k;
1528 pa += k;
1529 na -= k;
1530 if (na == 1)
1531 goto CopyB;
1532 /* na==0 is impossible now if the comparison
1533 * function is consistent, but we can't assume
1534 * that it is.
1535 */
1536 if (na == 0)
1537 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001538 }
Tim Petersa64dc242002-08-01 02:13:36 +00001539 *dest++ = *pb++;
1540 --nb;
1541 if (nb == 0)
1542 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001543
Tim Petersa64dc242002-08-01 02:13:36 +00001544 k = gallop_left(*pa, pb, nb, 0, compare);
1545 bcount = k;
1546 if (k) {
1547 if (k < 0)
1548 goto Fail;
1549 memmove(dest, pb, k * sizeof(PyObject *));
1550 dest += k;
1551 pb += k;
1552 nb -= k;
1553 if (nb == 0)
1554 goto Succeed;
1555 }
1556 *dest++ = *pa++;
1557 --na;
1558 if (na == 1)
1559 goto CopyB;
1560 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001561 ++min_gallop; /* penalize it for leaving galloping mode */
1562 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001563 }
1564Succeed:
1565 result = 0;
1566Fail:
1567 if (na)
1568 memcpy(dest, pa, na * sizeof(PyObject*));
1569 return result;
1570CopyB:
1571 assert(na == 1 && nb > 0);
1572 /* The last element of pa belongs at the end of the merge. */
1573 memmove(dest, pb, nb * sizeof(PyObject *));
1574 dest[nb] = *pa;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001575 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001576}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001577
Tim Petersa64dc242002-08-01 02:13:36 +00001578/* Merge the na elements starting at pa with the nb elements starting at pb
1579 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1580 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1581 * merge, and should have na >= nb. See listsort.txt for more info.
1582 * Return 0 if successful, -1 if error.
1583 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001584static Py_ssize_t
1585merge_hi(MergeState *ms, PyObject **pa, Py_ssize_t na, PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001586{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001587 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001588 PyObject *compare;
1589 PyObject **dest;
1590 int result = -1; /* guilty until proved innocent */
1591 PyObject **basea;
1592 PyObject **baseb;
Neal Norwitz7fd96072006-08-19 04:28:55 +00001593 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001594
1595 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1596 if (MERGE_GETMEM(ms, nb) < 0)
1597 return -1;
1598 dest = pb + nb - 1;
1599 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1600 basea = pa;
1601 baseb = ms->a;
1602 pb = ms->a + nb - 1;
1603 pa += na - 1;
1604
1605 *dest-- = *pa--;
1606 --na;
1607 if (na == 0)
1608 goto Succeed;
1609 if (nb == 1)
1610 goto CopyA;
1611
Neal Norwitz7fd96072006-08-19 04:28:55 +00001612 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001613 compare = ms->compare;
1614 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001615 Py_ssize_t acount = 0; /* # of times A won in a row */
1616 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001617
1618 /* Do the straightforward thing until (if ever) one run
1619 * appears to win consistently.
1620 */
1621 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001622 assert(na > 0 && nb > 1);
Tim Peters66860f62002-08-04 17:47:26 +00001623 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001624 if (k) {
1625 if (k < 0)
1626 goto Fail;
1627 *dest-- = *pa--;
1628 ++acount;
1629 bcount = 0;
1630 --na;
1631 if (na == 0)
1632 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001633 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001634 break;
1635 }
1636 else {
1637 *dest-- = *pb--;
1638 ++bcount;
1639 acount = 0;
1640 --nb;
1641 if (nb == 1)
1642 goto CopyA;
Tim Peterse05f65a2002-08-10 05:21:15 +00001643 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001644 break;
1645 }
1646 }
1647
1648 /* One run is winning so consistently that galloping may
1649 * be a huge win. So try that, and continue galloping until
1650 * (if ever) neither run appears to be winning consistently
1651 * anymore.
1652 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001653 ++min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001654 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001655 assert(na > 0 && nb > 1);
1656 min_gallop -= min_gallop > 1;
1657 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001658 k = gallop_right(*pb, basea, na, na-1, compare);
1659 if (k < 0)
1660 goto Fail;
1661 k = na - k;
1662 acount = k;
1663 if (k) {
1664 dest -= k;
1665 pa -= k;
1666 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1667 na -= k;
1668 if (na == 0)
1669 goto Succeed;
1670 }
1671 *dest-- = *pb--;
1672 --nb;
1673 if (nb == 1)
1674 goto CopyA;
1675
1676 k = gallop_left(*pa, baseb, nb, nb-1, compare);
1677 if (k < 0)
1678 goto Fail;
1679 k = nb - k;
1680 bcount = k;
1681 if (k) {
1682 dest -= k;
1683 pb -= k;
1684 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1685 nb -= k;
1686 if (nb == 1)
1687 goto CopyA;
1688 /* nb==0 is impossible now if the comparison
1689 * function is consistent, but we can't assume
1690 * that it is.
1691 */
1692 if (nb == 0)
1693 goto Succeed;
1694 }
1695 *dest-- = *pa--;
1696 --na;
1697 if (na == 0)
1698 goto Succeed;
1699 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001700 ++min_gallop; /* penalize it for leaving galloping mode */
1701 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001702 }
1703Succeed:
1704 result = 0;
1705Fail:
1706 if (nb)
1707 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1708 return result;
1709CopyA:
1710 assert(nb == 1 && na > 0);
1711 /* The first element of pb belongs at the front of the merge. */
1712 dest -= na;
1713 pa -= na;
1714 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1715 *dest = *pb;
1716 return 0;
1717}
1718
1719/* Merge the two runs at stack indices i and i+1.
1720 * Returns 0 on success, -1 on error.
1721 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001722static Py_ssize_t
1723merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001724{
1725 PyObject **pa, **pb;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001726 Py_ssize_t na, nb;
1727 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001728 PyObject *compare;
1729
1730 assert(ms != NULL);
1731 assert(ms->n >= 2);
1732 assert(i >= 0);
1733 assert(i == ms->n - 2 || i == ms->n - 3);
1734
Tim Peterse05f65a2002-08-10 05:21:15 +00001735 pa = ms->pending[i].base;
1736 na = ms->pending[i].len;
1737 pb = ms->pending[i+1].base;
1738 nb = ms->pending[i+1].len;
Tim Petersa64dc242002-08-01 02:13:36 +00001739 assert(na > 0 && nb > 0);
1740 assert(pa + na == pb);
1741
1742 /* Record the length of the combined runs; if i is the 3rd-last
1743 * run now, also slide over the last run (which isn't involved
1744 * in this merge). The current run i+1 goes away in any case.
1745 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001746 ms->pending[i].len = na + nb;
1747 if (i == ms->n - 3)
1748 ms->pending[i+1] = ms->pending[i+2];
Tim Petersa64dc242002-08-01 02:13:36 +00001749 --ms->n;
1750
1751 /* Where does b start in a? Elements in a before that can be
1752 * ignored (already in place).
1753 */
1754 compare = ms->compare;
1755 k = gallop_right(*pb, pa, na, 0, compare);
1756 if (k < 0)
1757 return -1;
1758 pa += k;
1759 na -= k;
1760 if (na == 0)
1761 return 0;
1762
1763 /* Where does a end in b? Elements in b after that can be
1764 * ignored (already in place).
1765 */
1766 nb = gallop_left(pa[na-1], pb, nb, nb-1, compare);
1767 if (nb <= 0)
1768 return nb;
1769
1770 /* Merge what remains of the runs, using a temp array with
1771 * min(na, nb) elements.
1772 */
1773 if (na <= nb)
1774 return merge_lo(ms, pa, na, pb, nb);
1775 else
1776 return merge_hi(ms, pa, na, pb, nb);
1777}
1778
1779/* Examine the stack of runs waiting to be merged, merging adjacent runs
1780 * until the stack invariants are re-established:
1781 *
1782 * 1. len[-3] > len[-2] + len[-1]
1783 * 2. len[-2] > len[-1]
1784 *
1785 * See listsort.txt for more info.
1786 *
1787 * Returns 0 on success, -1 on error.
1788 */
1789static int
1790merge_collapse(MergeState *ms)
1791{
Tim Peterse05f65a2002-08-10 05:21:15 +00001792 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001793
1794 assert(ms);
1795 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001796 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001797 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1798 if (p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001799 --n;
1800 if (merge_at(ms, n) < 0)
1801 return -1;
1802 }
Tim Peterse05f65a2002-08-10 05:21:15 +00001803 else if (p[n].len <= p[n+1].len) {
Tim Petersa64dc242002-08-01 02:13:36 +00001804 if (merge_at(ms, n) < 0)
1805 return -1;
1806 }
1807 else
1808 break;
1809 }
1810 return 0;
1811}
1812
1813/* Regardless of invariants, merge all runs on the stack until only one
1814 * remains. This is used at the end of the mergesort.
1815 *
1816 * Returns 0 on success, -1 on error.
1817 */
1818static int
1819merge_force_collapse(MergeState *ms)
1820{
Tim Peterse05f65a2002-08-10 05:21:15 +00001821 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001822
1823 assert(ms);
1824 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001825 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001826 if (n > 0 && p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001827 --n;
1828 if (merge_at(ms, n) < 0)
1829 return -1;
1830 }
1831 return 0;
1832}
1833
1834/* Compute a good value for the minimum run length; natural runs shorter
1835 * than this are boosted artificially via binary insertion.
1836 *
1837 * If n < 64, return n (it's too small to bother with fancy stuff).
1838 * Else if n is an exact power of 2, return 32.
1839 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1840 * strictly less than, an exact power of 2.
1841 *
1842 * See listsort.txt for more info.
1843 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001844static Py_ssize_t
1845merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001846{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001847 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001848
1849 assert(n >= 0);
1850 while (n >= 64) {
1851 r |= n & 1;
1852 n >>= 1;
1853 }
1854 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001855}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001856
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001857/* Special wrapper to support stable sorting using the decorate-sort-undecorate
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001858 pattern. Holds a key which is used for comparisons and the original record
Tim Petersb38e2b62004-07-29 02:29:26 +00001859 which is returned during the undecorate phase. By exposing only the key
1860 during comparisons, the underlying sort stability characteristics are left
1861 unchanged. Also, if a custom comparison function is used, it will only see
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001862 the key instead of a full record. */
1863
1864typedef struct {
1865 PyObject_HEAD
1866 PyObject *key;
1867 PyObject *value;
1868} sortwrapperobject;
1869
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001870PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
Anthony Baxter377be112006-04-11 06:54:30 +00001871static PyObject *
1872sortwrapper_richcompare(sortwrapperobject *, sortwrapperobject *, int);
1873static void
1874sortwrapper_dealloc(sortwrapperobject *);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001875
1876static PyTypeObject sortwrapper_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001877 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001878 "sortwrapper", /* tp_name */
1879 sizeof(sortwrapperobject), /* tp_basicsize */
1880 0, /* tp_itemsize */
1881 /* methods */
1882 (destructor)sortwrapper_dealloc, /* tp_dealloc */
1883 0, /* tp_print */
1884 0, /* tp_getattr */
1885 0, /* tp_setattr */
1886 0, /* tp_compare */
1887 0, /* tp_repr */
1888 0, /* tp_as_number */
1889 0, /* tp_as_sequence */
1890 0, /* tp_as_mapping */
1891 0, /* tp_hash */
1892 0, /* tp_call */
1893 0, /* tp_str */
1894 PyObject_GenericGetAttr, /* tp_getattro */
1895 0, /* tp_setattro */
1896 0, /* tp_as_buffer */
Tim Petersb38e2b62004-07-29 02:29:26 +00001897 Py_TPFLAGS_DEFAULT |
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001898 Py_TPFLAGS_HAVE_RICHCOMPARE, /* tp_flags */
1899 sortwrapper_doc, /* tp_doc */
1900 0, /* tp_traverse */
1901 0, /* tp_clear */
1902 (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
1903};
1904
Anthony Baxter377be112006-04-11 06:54:30 +00001905
1906static PyObject *
1907sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
1908{
1909 if (!PyObject_TypeCheck(b, &sortwrapper_type)) {
1910 PyErr_SetString(PyExc_TypeError,
1911 "expected a sortwrapperobject");
1912 return NULL;
1913 }
1914 return PyObject_RichCompare(a->key, b->key, op);
1915}
1916
1917static void
1918sortwrapper_dealloc(sortwrapperobject *so)
1919{
1920 Py_XDECREF(so->key);
1921 Py_XDECREF(so->value);
1922 PyObject_Del(so);
1923}
1924
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001925/* Returns a new reference to a sortwrapper.
1926 Consumes the references to the two underlying objects. */
1927
1928static PyObject *
1929build_sortwrapper(PyObject *key, PyObject *value)
1930{
1931 sortwrapperobject *so;
Tim Petersb38e2b62004-07-29 02:29:26 +00001932
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001933 so = PyObject_New(sortwrapperobject, &sortwrapper_type);
1934 if (so == NULL)
1935 return NULL;
1936 so->key = key;
1937 so->value = value;
1938 return (PyObject *)so;
1939}
1940
1941/* Returns a new reference to the value underlying the wrapper. */
1942static PyObject *
1943sortwrapper_getvalue(PyObject *so)
1944{
1945 PyObject *value;
1946
1947 if (!PyObject_TypeCheck(so, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001948 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001949 "expected a sortwrapperobject");
1950 return NULL;
1951 }
1952 value = ((sortwrapperobject *)so)->value;
1953 Py_INCREF(value);
1954 return value;
1955}
1956
1957/* Wrapper for user specified cmp functions in combination with a
1958 specified key function. Makes sure the cmp function is presented
1959 with the actual key instead of the sortwrapper */
1960
1961typedef struct {
1962 PyObject_HEAD
1963 PyObject *func;
1964} cmpwrapperobject;
1965
1966static void
1967cmpwrapper_dealloc(cmpwrapperobject *co)
1968{
1969 Py_XDECREF(co->func);
1970 PyObject_Del(co);
1971}
1972
1973static PyObject *
1974cmpwrapper_call(cmpwrapperobject *co, PyObject *args, PyObject *kwds)
1975{
1976 PyObject *x, *y, *xx, *yy;
1977
1978 if (!PyArg_UnpackTuple(args, "", 2, 2, &x, &y))
1979 return NULL;
1980 if (!PyObject_TypeCheck(x, &sortwrapper_type) ||
Raymond Hettingerae4a2992003-10-16 17:16:30 +00001981 !PyObject_TypeCheck(y, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001982 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001983 "expected a sortwrapperobject");
1984 return NULL;
1985 }
1986 xx = ((sortwrapperobject *)x)->key;
1987 yy = ((sortwrapperobject *)y)->key;
1988 return PyObject_CallFunctionObjArgs(co->func, xx, yy, NULL);
1989}
1990
1991PyDoc_STRVAR(cmpwrapper_doc, "cmp() wrapper for sort with custom keys.");
1992
1993static PyTypeObject cmpwrapper_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001994 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001995 "cmpwrapper", /* tp_name */
1996 sizeof(cmpwrapperobject), /* tp_basicsize */
1997 0, /* tp_itemsize */
1998 /* methods */
1999 (destructor)cmpwrapper_dealloc, /* tp_dealloc */
2000 0, /* tp_print */
2001 0, /* tp_getattr */
2002 0, /* tp_setattr */
2003 0, /* tp_compare */
2004 0, /* tp_repr */
2005 0, /* tp_as_number */
2006 0, /* tp_as_sequence */
2007 0, /* tp_as_mapping */
2008 0, /* tp_hash */
2009 (ternaryfunc)cmpwrapper_call, /* tp_call */
2010 0, /* tp_str */
2011 PyObject_GenericGetAttr, /* tp_getattro */
2012 0, /* tp_setattro */
2013 0, /* tp_as_buffer */
2014 Py_TPFLAGS_DEFAULT, /* tp_flags */
2015 cmpwrapper_doc, /* tp_doc */
2016};
2017
2018static PyObject *
2019build_cmpwrapper(PyObject *cmpfunc)
2020{
2021 cmpwrapperobject *co;
Tim Petersb38e2b62004-07-29 02:29:26 +00002022
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002023 co = PyObject_New(cmpwrapperobject, &cmpwrapper_type);
2024 if (co == NULL)
2025 return NULL;
2026 Py_INCREF(cmpfunc);
2027 co->func = cmpfunc;
2028 return (PyObject *)co;
2029}
2030
Tim Petersa64dc242002-08-01 02:13:36 +00002031/* An adaptive, stable, natural mergesort. See listsort.txt.
2032 * Returns Py_None on success, NULL on error. Even in case of error, the
2033 * list will be some permutation of its input state (nothing is lost or
2034 * duplicated).
2035 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002036static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002037listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00002038{
Tim Petersa64dc242002-08-01 02:13:36 +00002039 MergeState ms;
2040 PyObject **lo, **hi;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002041 Py_ssize_t nremaining;
2042 Py_ssize_t minrun;
2043 Py_ssize_t saved_ob_size, saved_allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00002044 PyObject **saved_ob_item;
Armin Rigo93677f02004-07-29 12:40:23 +00002045 PyObject **final_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00002046 PyObject *compare = NULL;
2047 PyObject *result = NULL; /* guilty until proved innocent */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002048 int reverse = 0;
2049 PyObject *keyfunc = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002050 Py_ssize_t i;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002051 PyObject *key, *value, *kvpair;
Martin v. Löwis15e62742006-02-27 16:46:16 +00002052 static char *kwlist[] = {"cmp", "key", "reverse", 0};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002053
Tim Petersa64dc242002-08-01 02:13:36 +00002054 assert(self != NULL);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002055 assert (PyList_Check(self));
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002056 if (args != NULL) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002057 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:sort",
2058 kwlist, &compare, &keyfunc, &reverse))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002059 return NULL;
2060 }
Skip Montanaro4abd5f02003-01-02 20:51:08 +00002061 if (compare == Py_None)
2062 compare = NULL;
Raymond Hettinger05387862008-03-19 17:45:19 +00002063 if (compare != NULL &&
Benjamin Petersonf19a7b92008-04-27 18:40:21 +00002064 PyErr_WarnPy3k("the cmp argument is not supported in 3.x", 1) < 0)
Raymond Hettinger6c0ff8a2008-03-18 23:33:08 +00002065 return NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002066 if (keyfunc == Py_None)
2067 keyfunc = NULL;
2068 if (compare != NULL && keyfunc != NULL) {
2069 compare = build_cmpwrapper(compare);
2070 if (compare == NULL)
Hye-Shik Chang19cb1932003-12-10 07:31:08 +00002071 return NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002072 } else
2073 Py_XINCREF(compare);
2074
Tim Petersb9099c32002-11-12 22:08:10 +00002075 /* The list is temporarily made empty, so that mutations performed
2076 * by comparison functions can't affect the slice of memory we're
2077 * sorting (allowing mutations during sorting is a core-dump
2078 * factory, since ob_item may change).
2079 */
Christian Heimese93237d2007-12-19 02:37:44 +00002080 saved_ob_size = Py_SIZE(self);
Tim Petersb9099c32002-11-12 22:08:10 +00002081 saved_ob_item = self->ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002082 saved_allocated = self->allocated;
Christian Heimese93237d2007-12-19 02:37:44 +00002083 Py_SIZE(self) = 0;
Tim Peters51b4ade2004-07-29 04:07:15 +00002084 self->ob_item = NULL;
Armin Rigo93677f02004-07-29 12:40:23 +00002085 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00002086
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002087 if (keyfunc != NULL) {
2088 for (i=0 ; i < saved_ob_size ; i++) {
2089 value = saved_ob_item[i];
Tim Petersb38e2b62004-07-29 02:29:26 +00002090 key = PyObject_CallFunctionObjArgs(keyfunc, value,
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002091 NULL);
2092 if (key == NULL) {
2093 for (i=i-1 ; i>=0 ; i--) {
2094 kvpair = saved_ob_item[i];
2095 value = sortwrapper_getvalue(kvpair);
2096 saved_ob_item[i] = value;
2097 Py_DECREF(kvpair);
2098 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002099 goto dsu_fail;
2100 }
2101 kvpair = build_sortwrapper(key, value);
2102 if (kvpair == NULL)
2103 goto dsu_fail;
2104 saved_ob_item[i] = kvpair;
2105 }
2106 }
2107
2108 /* Reverse sort stability achieved by initially reversing the list,
2109 applying a stable forward sort, then reversing the final result. */
2110 if (reverse && saved_ob_size > 1)
2111 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2112
2113 merge_init(&ms, compare);
2114
Tim Petersb9099c32002-11-12 22:08:10 +00002115 nremaining = saved_ob_size;
Tim Petersa64dc242002-08-01 02:13:36 +00002116 if (nremaining < 2)
2117 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00002118
Tim Petersa64dc242002-08-01 02:13:36 +00002119 /* March over the array once, left to right, finding natural runs,
2120 * and extending short natural runs to minrun elements.
2121 */
Tim Petersb9099c32002-11-12 22:08:10 +00002122 lo = saved_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00002123 hi = lo + nremaining;
2124 minrun = merge_compute_minrun(nremaining);
2125 do {
2126 int descending;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002127 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00002128
Tim Petersa64dc242002-08-01 02:13:36 +00002129 /* Identify next run. */
2130 n = count_run(lo, hi, compare, &descending);
2131 if (n < 0)
2132 goto fail;
2133 if (descending)
2134 reverse_slice(lo, lo + n);
2135 /* If short, extend to min(minrun, nremaining). */
2136 if (n < minrun) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002137 const Py_ssize_t force = nremaining <= minrun ?
Tim Petersa64dc242002-08-01 02:13:36 +00002138 nremaining : minrun;
2139 if (binarysort(lo, lo + force, lo + n, compare) < 0)
2140 goto fail;
2141 n = force;
2142 }
2143 /* Push run onto pending-runs stack, and maybe merge. */
2144 assert(ms.n < MAX_MERGE_PENDING);
Tim Peterse05f65a2002-08-10 05:21:15 +00002145 ms.pending[ms.n].base = lo;
2146 ms.pending[ms.n].len = n;
Tim Petersa64dc242002-08-01 02:13:36 +00002147 ++ms.n;
2148 if (merge_collapse(&ms) < 0)
2149 goto fail;
2150 /* Advance to find next run. */
2151 lo += n;
2152 nremaining -= n;
2153 } while (nremaining);
2154 assert(lo == hi);
Tim Peters330f9e92002-07-19 07:05:44 +00002155
Tim Petersa64dc242002-08-01 02:13:36 +00002156 if (merge_force_collapse(&ms) < 0)
2157 goto fail;
2158 assert(ms.n == 1);
Tim Petersb9099c32002-11-12 22:08:10 +00002159 assert(ms.pending[0].base == saved_ob_item);
2160 assert(ms.pending[0].len == saved_ob_size);
Tim Petersa64dc242002-08-01 02:13:36 +00002161
2162succeed:
2163 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002164fail:
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002165 if (keyfunc != NULL) {
2166 for (i=0 ; i < saved_ob_size ; i++) {
2167 kvpair = saved_ob_item[i];
2168 value = sortwrapper_getvalue(kvpair);
2169 saved_ob_item[i] = value;
2170 Py_DECREF(kvpair);
2171 }
2172 }
2173
Armin Rigo93677f02004-07-29 12:40:23 +00002174 if (self->allocated != -1 && result != NULL) {
Tim Peters51b4ade2004-07-29 04:07:15 +00002175 /* The user mucked with the list during the sort,
2176 * and we don't already have another error to report.
2177 */
2178 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2179 result = NULL;
Tim Petersb9099c32002-11-12 22:08:10 +00002180 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002181
2182 if (reverse && saved_ob_size > 1)
2183 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2184
2185 merge_freemem(&ms);
2186
2187dsu_fail:
Armin Rigo93677f02004-07-29 12:40:23 +00002188 final_ob_item = self->ob_item;
Christian Heimese93237d2007-12-19 02:37:44 +00002189 i = Py_SIZE(self);
2190 Py_SIZE(self) = saved_ob_size;
Tim Petersb9099c32002-11-12 22:08:10 +00002191 self->ob_item = saved_ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002192 self->allocated = saved_allocated;
Armin Rigo93677f02004-07-29 12:40:23 +00002193 if (final_ob_item != NULL) {
2194 /* we cannot use list_clear() for this because it does not
2195 guarantee that the list is really empty when it returns */
2196 while (--i >= 0) {
2197 Py_XDECREF(final_ob_item[i]);
2198 }
2199 PyMem_FREE(final_ob_item);
2200 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002201 Py_XDECREF(compare);
Tim Petersa64dc242002-08-01 02:13:36 +00002202 Py_XINCREF(result);
2203 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002204}
Tim Peters330f9e92002-07-19 07:05:44 +00002205#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002206#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002207
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002208int
Fred Drakea2f55112000-07-09 15:16:51 +00002209PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002210{
2211 if (v == NULL || !PyList_Check(v)) {
2212 PyErr_BadInternalCall();
2213 return -1;
2214 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002215 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002216 if (v == NULL)
2217 return -1;
2218 Py_DECREF(v);
2219 return 0;
2220}
2221
Guido van Rossumb86c5492001-02-12 22:06:02 +00002222static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002223listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002224{
Christian Heimese93237d2007-12-19 02:37:44 +00002225 if (Py_SIZE(self) > 1)
2226 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002227 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002228}
2229
Guido van Rossum84c76f51990-10-30 13:32:20 +00002230int
Fred Drakea2f55112000-07-09 15:16:51 +00002231PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002232{
Tim Peters6063e262002-08-08 01:06:39 +00002233 PyListObject *self = (PyListObject *)v;
2234
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002235 if (v == NULL || !PyList_Check(v)) {
2236 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002237 return -1;
2238 }
Christian Heimese93237d2007-12-19 02:37:44 +00002239 if (Py_SIZE(self) > 1)
2240 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002241 return 0;
2242}
2243
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002244PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002245PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002246{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002247 PyObject *w;
Raymond Hettinger6c87af52007-12-15 00:07:25 +00002248 PyObject **p, **q;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002249 Py_ssize_t n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002250 if (v == NULL || !PyList_Check(v)) {
2251 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002252 return NULL;
2253 }
Christian Heimese93237d2007-12-19 02:37:44 +00002254 n = Py_SIZE(v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002255 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002256 if (w == NULL)
2257 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002258 p = ((PyTupleObject *)w)->ob_item;
Raymond Hettinger6c87af52007-12-15 00:07:25 +00002259 q = ((PyListObject *)v)->ob_item;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002260 while (--n >= 0) {
Raymond Hettinger6c87af52007-12-15 00:07:25 +00002261 Py_INCREF(*q);
2262 *p = *q;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002263 p++;
Raymond Hettinger6c87af52007-12-15 00:07:25 +00002264 q++;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002265 }
2266 return w;
2267}
2268
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002269static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002270listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002271{
Christian Heimese93237d2007-12-19 02:37:44 +00002272 Py_ssize_t i, start=0, stop=Py_SIZE(self);
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002273 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002274
Walter Dörwalde8049bef2003-06-17 19:27:39 +00002275 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2276 _PyEval_SliceIndex, &start,
2277 _PyEval_SliceIndex, &stop))
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002278 return NULL;
Guido van Rossum2743d872003-06-17 14:25:14 +00002279 if (start < 0) {
Christian Heimese93237d2007-12-19 02:37:44 +00002280 start += Py_SIZE(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002281 if (start < 0)
2282 start = 0;
2283 }
2284 if (stop < 0) {
Christian Heimese93237d2007-12-19 02:37:44 +00002285 stop += Py_SIZE(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002286 if (stop < 0)
2287 stop = 0;
2288 }
Christian Heimese93237d2007-12-19 02:37:44 +00002289 for (i = start; i < stop && i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002290 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2291 if (cmp > 0)
Martin v. Löwis18e16552006-02-15 17:27:45 +00002292 return PyInt_FromSsize_t(i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002293 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002294 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002295 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002296 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002297 return NULL;
2298}
2299
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002300static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002301listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002302{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002303 Py_ssize_t count = 0;
2304 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002305
Christian Heimese93237d2007-12-19 02:37:44 +00002306 for (i = 0; i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002307 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2308 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002309 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002310 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002311 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00002312 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002313 return PyInt_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002314}
2315
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002316static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002317listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002318{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002319 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002320
Christian Heimese93237d2007-12-19 02:37:44 +00002321 for (i = 0; i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002322 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2323 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002324 if (list_ass_slice(self, i, i+1,
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002325 (PyObject *)NULL) == 0)
2326 Py_RETURN_NONE;
2327 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002328 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002329 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002330 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002331 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002332 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002333 return NULL;
2334}
2335
Jeremy Hylton8caad492000-06-23 14:18:11 +00002336static int
2337list_traverse(PyListObject *o, visitproc visit, void *arg)
2338{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002339 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002340
Christian Heimese93237d2007-12-19 02:37:44 +00002341 for (i = Py_SIZE(o); --i >= 0; )
Thomas Woutersc6e55062006-04-15 21:47:09 +00002342 Py_VISIT(o->ob_item[i]);
Jeremy Hylton8caad492000-06-23 14:18:11 +00002343 return 0;
2344}
2345
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002346static PyObject *
2347list_richcompare(PyObject *v, PyObject *w, int op)
2348{
2349 PyListObject *vl, *wl;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002350 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002351
2352 if (!PyList_Check(v) || !PyList_Check(w)) {
2353 Py_INCREF(Py_NotImplemented);
2354 return Py_NotImplemented;
2355 }
2356
2357 vl = (PyListObject *)v;
2358 wl = (PyListObject *)w;
2359
Christian Heimese93237d2007-12-19 02:37:44 +00002360 if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002361 /* Shortcut: if the lengths differ, the lists differ */
2362 PyObject *res;
2363 if (op == Py_EQ)
2364 res = Py_False;
2365 else
2366 res = Py_True;
2367 Py_INCREF(res);
2368 return res;
2369 }
2370
2371 /* Search for the first index where items are different */
Christian Heimese93237d2007-12-19 02:37:44 +00002372 for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002373 int k = PyObject_RichCompareBool(vl->ob_item[i],
2374 wl->ob_item[i], Py_EQ);
2375 if (k < 0)
2376 return NULL;
2377 if (!k)
2378 break;
2379 }
2380
Christian Heimese93237d2007-12-19 02:37:44 +00002381 if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002382 /* No more items to compare -- compare sizes */
Christian Heimese93237d2007-12-19 02:37:44 +00002383 Py_ssize_t vs = Py_SIZE(vl);
2384 Py_ssize_t ws = Py_SIZE(wl);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002385 int cmp;
2386 PyObject *res;
2387 switch (op) {
2388 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00002389 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002390 case Py_EQ: cmp = vs == ws; break;
2391 case Py_NE: cmp = vs != ws; break;
2392 case Py_GT: cmp = vs > ws; break;
2393 case Py_GE: cmp = vs >= ws; break;
2394 default: return NULL; /* cannot happen */
2395 }
2396 if (cmp)
2397 res = Py_True;
2398 else
2399 res = Py_False;
2400 Py_INCREF(res);
2401 return res;
2402 }
2403
2404 /* We have an item that differs -- shortcuts for EQ/NE */
2405 if (op == Py_EQ) {
2406 Py_INCREF(Py_False);
2407 return Py_False;
2408 }
2409 if (op == Py_NE) {
2410 Py_INCREF(Py_True);
2411 return Py_True;
2412 }
2413
2414 /* Compare the final item again using the proper operator */
2415 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
2416}
2417
Tim Peters6d6c1a32001-08-02 04:15:00 +00002418static int
2419list_init(PyListObject *self, PyObject *args, PyObject *kw)
2420{
2421 PyObject *arg = NULL;
Martin v. Löwis15e62742006-02-27 16:46:16 +00002422 static char *kwlist[] = {"sequence", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002423
2424 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2425 return -1;
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002426
2427 /* Verify list invariants established by PyType_GenericAlloc() */
Christian Heimese93237d2007-12-19 02:37:44 +00002428 assert(0 <= Py_SIZE(self));
2429 assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
Armin Rigoa37bbf22004-07-30 11:20:18 +00002430 assert(self->ob_item != NULL ||
2431 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002432
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002433 /* Empty previous contents */
Armin Rigo93677f02004-07-29 12:40:23 +00002434 if (self->ob_item != NULL) {
2435 (void)list_clear(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002436 }
2437 if (arg != NULL) {
2438 PyObject *rv = listextend(self, arg);
2439 if (rv == NULL)
2440 return -1;
2441 Py_DECREF(rv);
2442 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002443 return 0;
2444}
2445
Robert Schuppenies51df0642008-06-01 16:16:17 +00002446static PyObject *
2447list_sizeof(PyListObject *self)
2448{
2449 Py_ssize_t res;
2450
2451 res = sizeof(PyListObject) + self->allocated * sizeof(void*);
2452 return PyInt_FromSsize_t(res);
2453}
2454
Raymond Hettinger1021c442003-11-07 15:38:09 +00002455static PyObject *list_iter(PyObject *seq);
2456static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2457
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002458PyDoc_STRVAR(getitem_doc,
2459"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002460PyDoc_STRVAR(reversed_doc,
2461"L.__reversed__() -- return a reverse iterator over the list");
Robert Schuppenies51df0642008-06-01 16:16:17 +00002462PyDoc_STRVAR(sizeof_doc,
Georg Brandl7a6de8b2008-06-01 16:42:16 +00002463"L.__sizeof__() -- size of L in memory, in bytes");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002464PyDoc_STRVAR(append_doc,
2465"L.append(object) -- append object to end");
2466PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002467"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002468PyDoc_STRVAR(insert_doc,
2469"L.insert(index, object) -- insert object before index");
2470PyDoc_STRVAR(pop_doc,
Andrew M. Kuchlingd810cdf2008-10-04 01:04:24 +00002471"L.pop([index]) -> item -- remove and return item at index (default last).\n"
2472"Raises IndexError if list is empty or index is out of range.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002473PyDoc_STRVAR(remove_doc,
Andrew M. Kuchlingd810cdf2008-10-04 01:04:24 +00002474"L.remove(value) -- remove first occurrence of value.\n"
2475"Raises ValueError if the value is not present.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002476PyDoc_STRVAR(index_doc,
Andrew M. Kuchlingd810cdf2008-10-04 01:04:24 +00002477"L.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
2478"Raises ValueError if the value is not present.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002479PyDoc_STRVAR(count_doc,
2480"L.count(value) -> integer -- return number of occurrences of value");
2481PyDoc_STRVAR(reverse_doc,
2482"L.reverse() -- reverse *IN PLACE*");
2483PyDoc_STRVAR(sort_doc,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002484"L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n\
2485cmp(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002486
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002487static PyObject *list_subscript(PyListObject*, PyObject*);
2488
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002489static PyMethodDef list_methods[] = {
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002490 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
Raymond Hettinger1021c442003-11-07 15:38:09 +00002491 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
Robert Schuppenies51df0642008-06-01 16:16:17 +00002492 {"__sizeof__", (PyCFunction)list_sizeof, METH_NOARGS, sizeof_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002493 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002494 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002495 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002496 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002497 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002498 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002499 {"count", (PyCFunction)listcount, METH_O, count_doc},
2500 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002501 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
Tim Petersa64dc242002-08-01 02:13:36 +00002502 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002503};
2504
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002505static PySequenceMethods list_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002506 (lenfunc)list_length, /* sq_length */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002507 (binaryfunc)list_concat, /* sq_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002508 (ssizeargfunc)list_repeat, /* sq_repeat */
2509 (ssizeargfunc)list_item, /* sq_item */
2510 (ssizessizeargfunc)list_slice, /* sq_slice */
2511 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
2512 (ssizessizeobjargproc)list_ass_slice, /* sq_ass_slice */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002513 (objobjproc)list_contains, /* sq_contains */
2514 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002515 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002516};
2517
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002518PyDoc_STRVAR(list_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002519"list() -> new list\n"
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002520"list(sequence) -> new list initialized from sequence's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002521
Guido van Rossum38fff8c2006-03-07 18:50:55 +00002522
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002523static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002524list_subscript(PyListObject* self, PyObject* item)
2525{
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00002526 if (PyIndex_Check(item)) {
2527 Py_ssize_t i;
2528 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002529 if (i == -1 && PyErr_Occurred())
2530 return NULL;
2531 if (i < 0)
2532 i += PyList_GET_SIZE(self);
2533 return list_item(self, i);
2534 }
2535 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002536 Py_ssize_t start, stop, step, slicelength, cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002537 PyObject* result;
2538 PyObject* it;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002539 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002540
Christian Heimese93237d2007-12-19 02:37:44 +00002541 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002542 &start, &stop, &step, &slicelength) < 0) {
2543 return NULL;
2544 }
2545
2546 if (slicelength <= 0) {
2547 return PyList_New(0);
2548 }
Thomas Wouters3ccec682007-08-28 15:28:19 +00002549 else if (step == 1) {
2550 return list_slice(self, start, stop);
2551 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002552 else {
2553 result = PyList_New(slicelength);
2554 if (!result) return NULL;
2555
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002556 src = self->ob_item;
2557 dest = ((PyListObject *)result)->ob_item;
Tim Peters3b01a122002-07-19 02:35:45 +00002558 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002559 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002560 it = src[cur];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002561 Py_INCREF(it);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002562 dest[i] = it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002563 }
Tim Peters3b01a122002-07-19 02:35:45 +00002564
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002565 return result;
2566 }
2567 }
2568 else {
Georg Brandl283a1352006-11-19 08:48:30 +00002569 PyErr_Format(PyExc_TypeError,
2570 "list indices must be integers, not %.200s",
2571 item->ob_type->tp_name);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002572 return NULL;
2573 }
2574}
2575
Tim Peters3b01a122002-07-19 02:35:45 +00002576static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002577list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2578{
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00002579 if (PyIndex_Check(item)) {
2580 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002581 if (i == -1 && PyErr_Occurred())
2582 return -1;
2583 if (i < 0)
2584 i += PyList_GET_SIZE(self);
2585 return list_ass_item(self, i, value);
2586 }
2587 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002588 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002589
Christian Heimese93237d2007-12-19 02:37:44 +00002590 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002591 &start, &stop, &step, &slicelength) < 0) {
2592 return -1;
2593 }
2594
Thomas Wouters3ccec682007-08-28 15:28:19 +00002595 if (step == 1)
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002596 return list_ass_slice(self, start, stop, value);
2597
Thomas Wouters3ccec682007-08-28 15:28:19 +00002598 /* Make sure s[5:2] = [..] inserts at the right place:
2599 before 5, not before 2. */
2600 if ((step < 0 && start < stop) ||
2601 (step > 0 && start > stop))
2602 stop = start;
2603
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002604 if (value == NULL) {
2605 /* delete slice */
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002606 PyObject **garbage;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002607 Py_ssize_t cur, i;
Tim Peters3b01a122002-07-19 02:35:45 +00002608
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002609 if (slicelength <= 0)
2610 return 0;
2611
2612 if (step < 0) {
2613 stop = start + 1;
2614 start = stop + step*(slicelength - 1) - 1;
2615 step = -step;
2616 }
2617
Gregory P. Smith9d534572008-06-11 07:41:16 +00002618 assert(slicelength <= PY_SIZE_MAX / sizeof(PyObject*));
2619
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002620 garbage = (PyObject**)
2621 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Neal Norwitzb88cfad2006-08-12 03:16:54 +00002622 if (!garbage) {
2623 PyErr_NoMemory();
2624 return -1;
2625 }
Tim Peters3b01a122002-07-19 02:35:45 +00002626
Thomas Wouters3ccec682007-08-28 15:28:19 +00002627 /* drawing pictures might help understand these for
2628 loops. Basically, we memmove the parts of the
2629 list that are *not* part of the slice: step-1
2630 items for each item that is part of the slice,
2631 and then tail end of the list that was not
2632 covered by the slice */
Guido van Rossum75a20b12002-06-11 12:22:28 +00002633 for (cur = start, i = 0;
2634 cur < stop;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002635 cur += step, i++) {
Thomas Wouters3ccec682007-08-28 15:28:19 +00002636 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002637
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002638 garbage[i] = PyList_GET_ITEM(self, cur);
2639
Christian Heimese93237d2007-12-19 02:37:44 +00002640 if (cur + step >= Py_SIZE(self)) {
2641 lim = Py_SIZE(self) - cur - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002642 }
2643
Tim Petersb38e2b62004-07-29 02:29:26 +00002644 memmove(self->ob_item + cur - i,
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002645 self->ob_item + cur + 1,
2646 lim * sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002647 }
Thomas Wouters3ccec682007-08-28 15:28:19 +00002648 cur = start + slicelength*step;
Christian Heimese93237d2007-12-19 02:37:44 +00002649 if (cur < Py_SIZE(self)) {
Thomas Wouters3ccec682007-08-28 15:28:19 +00002650 memmove(self->ob_item + cur - slicelength,
2651 self->ob_item + cur,
Christian Heimese93237d2007-12-19 02:37:44 +00002652 (Py_SIZE(self) - cur) *
Thomas Wouters3ccec682007-08-28 15:28:19 +00002653 sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002654 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002655
Christian Heimese93237d2007-12-19 02:37:44 +00002656 Py_SIZE(self) -= slicelength;
2657 list_resize(self, Py_SIZE(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002658
2659 for (i = 0; i < slicelength; i++) {
2660 Py_DECREF(garbage[i]);
2661 }
2662 PyMem_FREE(garbage);
2663
2664 return 0;
2665 }
2666 else {
2667 /* assign slice */
Thomas Wouters3ccec682007-08-28 15:28:19 +00002668 PyObject *ins, *seq;
2669 PyObject **garbage, **seqitems, **selfitems;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002670 Py_ssize_t cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002671
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002672 /* protect against a[::-1] = a */
Tim Peters3b01a122002-07-19 02:35:45 +00002673 if (self == (PyListObject*)value) {
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002674 seq = list_slice((PyListObject*)value, 0,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002675 PyList_GET_SIZE(value));
Tim Peters3b01a122002-07-19 02:35:45 +00002676 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002677 else {
Tim Petersb38e2b62004-07-29 02:29:26 +00002678 seq = PySequence_Fast(value,
Thomas Wouters3ccec682007-08-28 15:28:19 +00002679 "must assign iterable "
2680 "to extended slice");
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002681 }
Neal Norwitzb88cfad2006-08-12 03:16:54 +00002682 if (!seq)
2683 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002684
2685 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2686 PyErr_Format(PyExc_ValueError,
Thomas Wouters3ccec682007-08-28 15:28:19 +00002687 "attempt to assign sequence of "
2688 "size %zd to extended slice of "
2689 "size %zd",
Martin v. Löwise0e89f72006-02-16 06:59:22 +00002690 PySequence_Fast_GET_SIZE(seq),
2691 slicelength);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002692 Py_DECREF(seq);
2693 return -1;
2694 }
2695
2696 if (!slicelength) {
2697 Py_DECREF(seq);
2698 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002699 }
2700
2701 garbage = (PyObject**)
2702 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Neal Norwitze7e4e2d2006-10-28 21:20:12 +00002703 if (!garbage) {
2704 Py_DECREF(seq);
2705 PyErr_NoMemory();
2706 return -1;
2707 }
Tim Peters3b01a122002-07-19 02:35:45 +00002708
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002709 selfitems = self->ob_item;
Raymond Hettinger42bec932004-03-12 16:38:17 +00002710 seqitems = PySequence_Fast_ITEMS(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002711 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002712 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002713 garbage[i] = selfitems[cur];
2714 ins = seqitems[i];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002715 Py_INCREF(ins);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002716 selfitems[cur] = ins;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002717 }
2718
2719 for (i = 0; i < slicelength; i++) {
2720 Py_DECREF(garbage[i]);
2721 }
Tim Peters3b01a122002-07-19 02:35:45 +00002722
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002723 PyMem_FREE(garbage);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002724 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002725
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002726 return 0;
2727 }
Tim Peters3b01a122002-07-19 02:35:45 +00002728 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002729 else {
Georg Brandl283a1352006-11-19 08:48:30 +00002730 PyErr_Format(PyExc_TypeError,
2731 "list indices must be integers, not %.200s",
2732 item->ob_type->tp_name);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002733 return -1;
2734 }
2735}
2736
2737static PyMappingMethods list_as_mapping = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002738 (lenfunc)list_length,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002739 (binaryfunc)list_subscript,
2740 (objobjargproc)list_ass_subscript
2741};
2742
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002743PyTypeObject PyList_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002744 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002745 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002746 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002747 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002748 (destructor)list_dealloc, /* tp_dealloc */
2749 (printfunc)list_print, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002750 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002751 0, /* tp_setattr */
2752 0, /* tp_compare */
2753 (reprfunc)list_repr, /* tp_repr */
2754 0, /* tp_as_number */
2755 &list_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002756 &list_as_mapping, /* tp_as_mapping */
Nick Coghlan53663a62008-07-15 14:27:37 +00002757 (hashfunc)PyObject_HashNotImplemented, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002758 0, /* tp_call */
2759 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002760 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002761 0, /* tp_setattro */
2762 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002763 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Neal Norwitzee3a1b52007-02-25 19:44:48 +00002764 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002765 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002766 (traverseproc)list_traverse, /* tp_traverse */
2767 (inquiry)list_clear, /* tp_clear */
2768 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002769 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002770 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002771 0, /* tp_iternext */
2772 list_methods, /* tp_methods */
2773 0, /* tp_members */
2774 0, /* tp_getset */
2775 0, /* tp_base */
2776 0, /* tp_dict */
2777 0, /* tp_descr_get */
2778 0, /* tp_descr_set */
2779 0, /* tp_dictoffset */
2780 (initproc)list_init, /* tp_init */
2781 PyType_GenericAlloc, /* tp_alloc */
2782 PyType_GenericNew, /* tp_new */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002783 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002784};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002785
2786
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002787/*********************** List Iterator **************************/
2788
2789typedef struct {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002790 PyObject_HEAD
2791 long it_index;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002792 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002793} listiterobject;
2794
Anthony Baxter377be112006-04-11 06:54:30 +00002795static PyObject *list_iter(PyObject *);
2796static void listiter_dealloc(listiterobject *);
2797static int listiter_traverse(listiterobject *, visitproc, void *);
2798static PyObject *listiter_next(listiterobject *);
2799static PyObject *listiter_len(listiterobject *);
2800
2801PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
2802
2803static PyMethodDef listiter_methods[] = {
2804 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
2805 {NULL, NULL} /* sentinel */
2806};
2807
2808PyTypeObject PyListIter_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002809 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Anthony Baxter377be112006-04-11 06:54:30 +00002810 "listiterator", /* tp_name */
2811 sizeof(listiterobject), /* tp_basicsize */
2812 0, /* tp_itemsize */
2813 /* methods */
2814 (destructor)listiter_dealloc, /* tp_dealloc */
2815 0, /* tp_print */
2816 0, /* tp_getattr */
2817 0, /* tp_setattr */
2818 0, /* tp_compare */
2819 0, /* tp_repr */
2820 0, /* tp_as_number */
2821 0, /* tp_as_sequence */
2822 0, /* tp_as_mapping */
2823 0, /* tp_hash */
2824 0, /* tp_call */
2825 0, /* tp_str */
2826 PyObject_GenericGetAttr, /* tp_getattro */
2827 0, /* tp_setattro */
2828 0, /* tp_as_buffer */
2829 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2830 0, /* tp_doc */
2831 (traverseproc)listiter_traverse, /* tp_traverse */
2832 0, /* tp_clear */
2833 0, /* tp_richcompare */
2834 0, /* tp_weaklistoffset */
2835 PyObject_SelfIter, /* tp_iter */
2836 (iternextfunc)listiter_next, /* tp_iternext */
2837 listiter_methods, /* tp_methods */
2838 0, /* tp_members */
2839};
2840
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002841
Guido van Rossum5086e492002-07-16 15:56:52 +00002842static PyObject *
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002843list_iter(PyObject *seq)
2844{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002845 listiterobject *it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002846
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002847 if (!PyList_Check(seq)) {
2848 PyErr_BadInternalCall();
2849 return NULL;
2850 }
2851 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2852 if (it == NULL)
2853 return NULL;
2854 it->it_index = 0;
2855 Py_INCREF(seq);
2856 it->it_seq = (PyListObject *)seq;
2857 _PyObject_GC_TRACK(it);
2858 return (PyObject *)it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002859}
2860
2861static void
2862listiter_dealloc(listiterobject *it)
2863{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002864 _PyObject_GC_UNTRACK(it);
Guido van Rossum86103ae2002-07-16 20:07:32 +00002865 Py_XDECREF(it->it_seq);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002866 PyObject_GC_Del(it);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002867}
2868
2869static int
2870listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2871{
Thomas Woutersc6e55062006-04-15 21:47:09 +00002872 Py_VISIT(it->it_seq);
2873 return 0;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002874}
2875
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002876static PyObject *
Tim Peters93b2cc42002-06-01 05:22:55 +00002877listiter_next(listiterobject *it)
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002878{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002879 PyListObject *seq;
2880 PyObject *item;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002881
Tim Peters93b2cc42002-06-01 05:22:55 +00002882 assert(it != NULL);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002883 seq = it->it_seq;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002884 if (seq == NULL)
2885 return NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002886 assert(PyList_Check(seq));
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002887
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002888 if (it->it_index < PyList_GET_SIZE(seq)) {
Tim Peters93b2cc42002-06-01 05:22:55 +00002889 item = PyList_GET_ITEM(seq, it->it_index);
2890 ++it->it_index;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002891 Py_INCREF(item);
2892 return item;
2893 }
Guido van Rossum86103ae2002-07-16 20:07:32 +00002894
2895 Py_DECREF(seq);
2896 it->it_seq = NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002897 return NULL;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002898}
2899
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002900static PyObject *
Raymond Hettinger435bf582004-03-18 22:43:10 +00002901listiter_len(listiterobject *it)
2902{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002903 Py_ssize_t len;
Raymond Hettinger40a03822004-04-12 13:05:09 +00002904 if (it->it_seq) {
2905 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2906 if (len >= 0)
Martin v. Löwis18e16552006-02-15 17:27:45 +00002907 return PyInt_FromSsize_t(len);
Raymond Hettinger40a03822004-04-12 13:05:09 +00002908 }
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002909 return PyInt_FromLong(0);
Raymond Hettinger435bf582004-03-18 22:43:10 +00002910}
Anthony Baxter377be112006-04-11 06:54:30 +00002911/*********************** List Reverse Iterator **************************/
Raymond Hettinger435bf582004-03-18 22:43:10 +00002912
Anthony Baxter377be112006-04-11 06:54:30 +00002913typedef struct {
2914 PyObject_HEAD
2915 Py_ssize_t it_index;
2916 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
2917} listreviterobject;
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002918
Anthony Baxter377be112006-04-11 06:54:30 +00002919static PyObject *list_reversed(PyListObject *, PyObject *);
2920static void listreviter_dealloc(listreviterobject *);
2921static int listreviter_traverse(listreviterobject *, visitproc, void *);
2922static PyObject *listreviter_next(listreviterobject *);
Raymond Hettinger7989a4d2008-12-03 15:42:10 +00002923static PyObject *listreviter_len(listreviterobject *);
Anthony Baxter377be112006-04-11 06:54:30 +00002924
Raymond Hettinger7989a4d2008-12-03 15:42:10 +00002925static PyMethodDef listreviter_methods[] = {
2926 {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc},
2927 {NULL, NULL} /* sentinel */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002928};
2929
Anthony Baxter377be112006-04-11 06:54:30 +00002930PyTypeObject PyListRevIter_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002931 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Anthony Baxter377be112006-04-11 06:54:30 +00002932 "listreverseiterator", /* tp_name */
2933 sizeof(listreviterobject), /* tp_basicsize */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002934 0, /* tp_itemsize */
2935 /* methods */
Anthony Baxter377be112006-04-11 06:54:30 +00002936 (destructor)listreviter_dealloc, /* tp_dealloc */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002937 0, /* tp_print */
2938 0, /* tp_getattr */
2939 0, /* tp_setattr */
2940 0, /* tp_compare */
2941 0, /* tp_repr */
2942 0, /* tp_as_number */
Raymond Hettinger7989a4d2008-12-03 15:42:10 +00002943 0, /* tp_as_sequence */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002944 0, /* tp_as_mapping */
2945 0, /* tp_hash */
2946 0, /* tp_call */
2947 0, /* tp_str */
2948 PyObject_GenericGetAttr, /* tp_getattro */
2949 0, /* tp_setattro */
2950 0, /* tp_as_buffer */
2951 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2952 0, /* tp_doc */
Anthony Baxter377be112006-04-11 06:54:30 +00002953 (traverseproc)listreviter_traverse, /* tp_traverse */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002954 0, /* tp_clear */
2955 0, /* tp_richcompare */
2956 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00002957 PyObject_SelfIter, /* tp_iter */
Anthony Baxter377be112006-04-11 06:54:30 +00002958 (iternextfunc)listreviter_next, /* tp_iternext */
Raymond Hettinger7989a4d2008-12-03 15:42:10 +00002959 listreviter_methods, /* tp_methods */
Anthony Baxter377be112006-04-11 06:54:30 +00002960 0,
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002961};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002962
Raymond Hettinger1021c442003-11-07 15:38:09 +00002963static PyObject *
2964list_reversed(PyListObject *seq, PyObject *unused)
2965{
2966 listreviterobject *it;
2967
2968 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2969 if (it == NULL)
2970 return NULL;
2971 assert(PyList_Check(seq));
2972 it->it_index = PyList_GET_SIZE(seq) - 1;
2973 Py_INCREF(seq);
2974 it->it_seq = seq;
2975 PyObject_GC_Track(it);
2976 return (PyObject *)it;
2977}
2978
2979static void
2980listreviter_dealloc(listreviterobject *it)
2981{
2982 PyObject_GC_UnTrack(it);
2983 Py_XDECREF(it->it_seq);
2984 PyObject_GC_Del(it);
2985}
2986
2987static int
2988listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2989{
Thomas Woutersc6e55062006-04-15 21:47:09 +00002990 Py_VISIT(it->it_seq);
2991 return 0;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002992}
2993
2994static PyObject *
2995listreviter_next(listreviterobject *it)
2996{
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002997 PyObject *item;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002998 Py_ssize_t index = it->it_index;
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002999 PyListObject *seq = it->it_seq;
Raymond Hettinger1021c442003-11-07 15:38:09 +00003000
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003001 if (index>=0 && index < PyList_GET_SIZE(seq)) {
3002 item = PyList_GET_ITEM(seq, index);
Raymond Hettinger1021c442003-11-07 15:38:09 +00003003 it->it_index--;
3004 Py_INCREF(item);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003005 return item;
Raymond Hettinger1021c442003-11-07 15:38:09 +00003006 }
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003007 it->it_index = -1;
3008 if (seq != NULL) {
3009 it->it_seq = NULL;
3010 Py_DECREF(seq);
3011 }
3012 return NULL;
Raymond Hettinger1021c442003-11-07 15:38:09 +00003013}
3014
Raymond Hettinger7989a4d2008-12-03 15:42:10 +00003015static PyObject *
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003016listreviter_len(listreviterobject *it)
3017{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003018 Py_ssize_t len = it->it_index + 1;
Raymond Hettinger40a03822004-04-12 13:05:09 +00003019 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
Raymond Hettinger7989a4d2008-12-03 15:42:10 +00003020 len = 0;
3021 return PyLong_FromSsize_t(len);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003022}