blob: 98d7e473549e0a2c557a0754fc0ea64ac38fbf3a [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;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000322
Martin v. Löwis18e16552006-02-15 17:27:45 +0000323 rc = Py_ReprEnter((PyObject*)op);
324 if (rc != 0) {
325 if (rc < 0)
326 return rc;
Brett Cannon01531592007-09-17 03:28:34 +0000327 Py_BEGIN_ALLOW_THREADS
Guido van Rossumfb376de1998-04-10 22:47:27 +0000328 fprintf(fp, "[...]");
Brett Cannon01531592007-09-17 03:28:34 +0000329 Py_END_ALLOW_THREADS
Guido van Rossumfb376de1998-04-10 22:47:27 +0000330 return 0;
331 }
Brett Cannon01531592007-09-17 03:28:34 +0000332 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000333 fprintf(fp, "[");
Brett Cannon01531592007-09-17 03:28:34 +0000334 Py_END_ALLOW_THREADS
Christian Heimese93237d2007-12-19 02:37:44 +0000335 for (i = 0; i < Py_SIZE(op); i++) {
Brett Cannon01531592007-09-17 03:28:34 +0000336 if (i > 0) {
337 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000338 fprintf(fp, ", ");
Brett Cannon01531592007-09-17 03:28:34 +0000339 Py_END_ALLOW_THREADS
340 }
Guido van Rossumfb376de1998-04-10 22:47:27 +0000341 if (PyObject_Print(op->ob_item[i], fp, 0) != 0) {
342 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000343 return -1;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000344 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000345 }
Brett Cannon01531592007-09-17 03:28:34 +0000346 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000347 fprintf(fp, "]");
Brett Cannon01531592007-09-17 03:28:34 +0000348 Py_END_ALLOW_THREADS
Guido van Rossumfb376de1998-04-10 22:47:27 +0000349 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000350 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000351}
352
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000353static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000354list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000355{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000356 Py_ssize_t i;
Tim Petersa7259592001-06-16 05:11:17 +0000357 PyObject *s, *temp;
358 PyObject *pieces = NULL, *result = NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000359
360 i = Py_ReprEnter((PyObject*)v);
361 if (i != 0) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000362 return i > 0 ? PyString_FromString("[...]") : NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000363 }
Tim Petersa7259592001-06-16 05:11:17 +0000364
Christian Heimese93237d2007-12-19 02:37:44 +0000365 if (Py_SIZE(v) == 0) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000366 result = PyString_FromString("[]");
Tim Petersa7259592001-06-16 05:11:17 +0000367 goto Done;
368 }
369
370 pieces = PyList_New(0);
371 if (pieces == NULL)
372 goto Done;
373
374 /* Do repr() on each element. Note that this may mutate the list,
375 so must refetch the list size on each iteration. */
Christian Heimese93237d2007-12-19 02:37:44 +0000376 for (i = 0; i < Py_SIZE(v); ++i) {
Tim Petersa7259592001-06-16 05:11:17 +0000377 int status;
Brett Cannona0c05512007-09-10 21:38:27 +0000378 if (Py_EnterRecursiveCall(" while getting the repr of a list"))
379 goto Done;
Tim Petersa7259592001-06-16 05:11:17 +0000380 s = PyObject_Repr(v->ob_item[i]);
Brett Cannona0c05512007-09-10 21:38:27 +0000381 Py_LeaveRecursiveCall();
Tim Petersa7259592001-06-16 05:11:17 +0000382 if (s == NULL)
383 goto Done;
384 status = PyList_Append(pieces, s);
385 Py_DECREF(s); /* append created a new ref */
386 if (status < 0)
387 goto Done;
388 }
389
390 /* Add "[]" decorations to the first and last items. */
391 assert(PyList_GET_SIZE(pieces) > 0);
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000392 s = PyString_FromString("[");
Tim Petersa7259592001-06-16 05:11:17 +0000393 if (s == NULL)
394 goto Done;
395 temp = PyList_GET_ITEM(pieces, 0);
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000396 PyString_ConcatAndDel(&s, temp);
Tim Petersa7259592001-06-16 05:11:17 +0000397 PyList_SET_ITEM(pieces, 0, s);
398 if (s == NULL)
399 goto Done;
400
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000401 s = PyString_FromString("]");
Tim Petersa7259592001-06-16 05:11:17 +0000402 if (s == NULL)
403 goto Done;
404 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000405 PyString_ConcatAndDel(&temp, s);
Tim Petersa7259592001-06-16 05:11:17 +0000406 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
407 if (temp == NULL)
408 goto Done;
409
410 /* Paste them all together with ", " between. */
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000411 s = PyString_FromString(", ");
Tim Petersa7259592001-06-16 05:11:17 +0000412 if (s == NULL)
413 goto Done;
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000414 result = _PyString_Join(s, pieces);
Tim Peters3b01a122002-07-19 02:35:45 +0000415 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +0000416
417Done:
418 Py_XDECREF(pieces);
Guido van Rossumfb376de1998-04-10 22:47:27 +0000419 Py_ReprLeave((PyObject *)v);
Tim Petersa7259592001-06-16 05:11:17 +0000420 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000421}
422
Martin v. Löwis18e16552006-02-15 17:27:45 +0000423static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000424list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000425{
Christian Heimese93237d2007-12-19 02:37:44 +0000426 return Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000427}
428
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000429static int
Fred Drakea2f55112000-07-09 15:16:51 +0000430list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000431{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000432 Py_ssize_t i;
433 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000434
Christian Heimese93237d2007-12-19 02:37:44 +0000435 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
Raymond Hettingeraae59992002-09-05 14:23:49 +0000436 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000437 Py_EQ);
Neal Norwitzbb9c5f52002-09-05 21:32:55 +0000438 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000439}
440
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000441static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000442list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000443{
Christian Heimese93237d2007-12-19 02:37:44 +0000444 if (i < 0 || i >= Py_SIZE(a)) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000445 if (indexerr == NULL)
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000446 indexerr = PyString_FromString(
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000447 "list index out of range");
448 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000449 return NULL;
450 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000451 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000452 return a->ob_item[i];
453}
454
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000455static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000456list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000457{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000458 PyListObject *np;
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000459 PyObject **src, **dest;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000460 Py_ssize_t i, len;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000461 if (ilow < 0)
462 ilow = 0;
Christian Heimese93237d2007-12-19 02:37:44 +0000463 else if (ilow > Py_SIZE(a))
464 ilow = Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000465 if (ihigh < ilow)
466 ihigh = ilow;
Christian Heimese93237d2007-12-19 02:37:44 +0000467 else if (ihigh > Py_SIZE(a))
468 ihigh = Py_SIZE(a);
Raymond Hettinger99842b62004-03-08 05:56:15 +0000469 len = ihigh - ilow;
470 np = (PyListObject *) PyList_New(len);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000471 if (np == NULL)
472 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000473
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000474 src = a->ob_item + ilow;
475 dest = np->ob_item;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000476 for (i = 0; i < len; i++) {
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000477 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000478 Py_INCREF(v);
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000479 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000480 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000481 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000482}
483
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000484PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000485PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000486{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000487 if (!PyList_Check(a)) {
488 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000489 return NULL;
490 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000491 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000492}
493
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000494static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000495list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000496{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000497 Py_ssize_t size;
498 Py_ssize_t i;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000499 PyObject **src, **dest;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000500 PyListObject *np;
501 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000502 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000503 "can only concatenate list (not \"%.200s\") to list",
504 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000505 return NULL;
506 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000507#define b ((PyListObject *)bb)
Christian Heimese93237d2007-12-19 02:37:44 +0000508 size = Py_SIZE(a) + Py_SIZE(b);
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000509 if (size < 0)
510 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000511 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000512 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000513 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000514 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000515 src = a->ob_item;
516 dest = np->ob_item;
Christian Heimese93237d2007-12-19 02:37:44 +0000517 for (i = 0; i < Py_SIZE(a); i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000518 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000519 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000520 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000521 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000522 src = b->ob_item;
Christian Heimese93237d2007-12-19 02:37:44 +0000523 dest = np->ob_item + Py_SIZE(a);
524 for (i = 0; i < Py_SIZE(b); i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000525 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000526 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000527 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000528 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000529 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000530#undef b
531}
532
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000533static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000534list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000535{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000536 Py_ssize_t i, j;
537 Py_ssize_t size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000538 PyListObject *np;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000539 PyObject **p, **items;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000540 PyObject *elem;
Guido van Rossumed98d481991-03-06 13:07:53 +0000541 if (n < 0)
542 n = 0;
Christian Heimese93237d2007-12-19 02:37:44 +0000543 size = Py_SIZE(a) * n;
544 if (n && size/n != Py_SIZE(a))
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000545 return PyErr_NoMemory();
Armin Rigoa1e42e12007-10-17 18:46:37 +0000546 if (size == 0)
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000547 return PyList_New(0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000548 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000549 if (np == NULL)
550 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000551
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000552 items = np->ob_item;
Christian Heimese93237d2007-12-19 02:37:44 +0000553 if (Py_SIZE(a) == 1) {
Raymond Hettinger6624e682003-05-21 05:58:46 +0000554 elem = a->ob_item[0];
555 for (i = 0; i < n; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000556 items[i] = elem;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000557 Py_INCREF(elem);
558 }
559 return (PyObject *) np;
560 }
Guido van Rossumed98d481991-03-06 13:07:53 +0000561 p = np->ob_item;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000562 items = a->ob_item;
Guido van Rossumed98d481991-03-06 13:07:53 +0000563 for (i = 0; i < n; i++) {
Christian Heimese93237d2007-12-19 02:37:44 +0000564 for (j = 0; j < Py_SIZE(a); j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000565 *p = items[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000566 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000567 p++;
568 }
569 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000570 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000571}
572
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000573static int
Armin Rigo93677f02004-07-29 12:40:23 +0000574list_clear(PyListObject *a)
575{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000576 Py_ssize_t i;
Armin Rigo93677f02004-07-29 12:40:23 +0000577 PyObject **item = a->ob_item;
578 if (item != NULL) {
579 /* Because XDECREF can recursively invoke operations on
580 this list, we make it empty first. */
Christian Heimese93237d2007-12-19 02:37:44 +0000581 i = Py_SIZE(a);
582 Py_SIZE(a) = 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000583 a->ob_item = NULL;
584 a->allocated = 0;
585 while (--i >= 0) {
586 Py_XDECREF(item[i]);
587 }
588 PyMem_FREE(item);
589 }
590 /* Never fails; the return value can be ignored.
591 Note that there is no guarantee that the list is actually empty
592 at this point, because XDECREF may have populated it again! */
593 return 0;
594}
595
Tim Peters8fc4a912004-07-31 21:53:19 +0000596/* a[ilow:ihigh] = v if v != NULL.
597 * del a[ilow:ihigh] if v == NULL.
598 *
599 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
600 * guaranteed the call cannot fail.
601 */
Armin Rigo93677f02004-07-29 12:40:23 +0000602static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000603list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000604{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000605 /* Because [X]DECREF can recursively invoke list operations on
606 this list, we must postpone all [X]DECREF activity until
607 after the list is back in its canonical shape. Therefore
608 we must allocate an additional array, 'recycle', into which
609 we temporarily copy the items that are deleted from the
610 list. :-( */
Tim Peters73572222004-07-31 02:54:42 +0000611 PyObject *recycle_on_stack[8];
612 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000613 PyObject **item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000614 PyObject **vitem = NULL;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000615 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000616 Py_ssize_t n; /* # of elements in replacement list */
617 Py_ssize_t norig; /* # of elements in list getting replaced */
618 Py_ssize_t d; /* Change in size */
619 Py_ssize_t k;
Tim Peters8d9eb102004-07-31 02:24:20 +0000620 size_t s;
621 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000622#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000623 if (v == NULL)
624 n = 0;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000625 else {
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000626 if (a == b) {
627 /* Special case "a[i:j] = a" -- copy b first */
Christian Heimese93237d2007-12-19 02:37:44 +0000628 v = list_slice(b, 0, Py_SIZE(b));
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000629 if (v == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000630 return result;
631 result = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000632 Py_DECREF(v);
Tim Peters8d9eb102004-07-31 02:24:20 +0000633 return result;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000634 }
Raymond Hettingerf889e102004-03-09 08:04:33 +0000635 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000636 if(v_as_SF == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000637 goto Error;
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000638 n = PySequence_Fast_GET_SIZE(v_as_SF);
Raymond Hettinger42bec932004-03-12 16:38:17 +0000639 vitem = PySequence_Fast_ITEMS(v_as_SF);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000640 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000641 if (ilow < 0)
642 ilow = 0;
Christian Heimese93237d2007-12-19 02:37:44 +0000643 else if (ilow > Py_SIZE(a))
644 ilow = Py_SIZE(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000645
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000646 if (ihigh < ilow)
647 ihigh = ilow;
Christian Heimese93237d2007-12-19 02:37:44 +0000648 else if (ihigh > Py_SIZE(a))
649 ihigh = Py_SIZE(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000650
Tim Peters8d9eb102004-07-31 02:24:20 +0000651 norig = ihigh - ilow;
652 assert(norig >= 0);
653 d = n - norig;
Christian Heimese93237d2007-12-19 02:37:44 +0000654 if (Py_SIZE(a) + d == 0) {
Armin Rigo93677f02004-07-29 12:40:23 +0000655 Py_XDECREF(v_as_SF);
656 return list_clear(a);
657 }
658 item = a->ob_item;
Tim Peters8d9eb102004-07-31 02:24:20 +0000659 /* recycle the items that we are about to remove */
660 s = norig * sizeof(PyObject *);
Tim Peters73572222004-07-31 02:54:42 +0000661 if (s > sizeof(recycle_on_stack)) {
Armin Rigo1dd04a02004-07-30 11:38:22 +0000662 recycle = (PyObject **)PyMem_MALLOC(s);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000663 if (recycle == NULL) {
664 PyErr_NoMemory();
Tim Peters8d9eb102004-07-31 02:24:20 +0000665 goto Error;
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000666 }
667 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000668 memcpy(recycle, &item[ilow], s);
Tim Peters8d9eb102004-07-31 02:24:20 +0000669
Armin Rigo1dd04a02004-07-30 11:38:22 +0000670 if (d < 0) { /* Delete -d items */
671 memmove(&item[ihigh+d], &item[ihigh],
Christian Heimese93237d2007-12-19 02:37:44 +0000672 (Py_SIZE(a) - ihigh)*sizeof(PyObject *));
673 list_resize(a, Py_SIZE(a) + d);
Armin Rigo1dd04a02004-07-30 11:38:22 +0000674 item = a->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000675 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000676 else if (d > 0) { /* Insert d items */
Christian Heimese93237d2007-12-19 02:37:44 +0000677 k = Py_SIZE(a);
Tim Peters73572222004-07-31 02:54:42 +0000678 if (list_resize(a, k+d) < 0)
Tim Peters8d9eb102004-07-31 02:24:20 +0000679 goto Error;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000680 item = a->ob_item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000681 memmove(&item[ihigh+d], &item[ihigh],
Tim Peters73572222004-07-31 02:54:42 +0000682 (k - ihigh)*sizeof(PyObject *));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000683 }
684 for (k = 0; k < n; k++, ilow++) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000685 PyObject *w = vitem[k];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000686 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000687 item[ilow] = w;
688 }
Tim Peters73572222004-07-31 02:54:42 +0000689 for (k = norig - 1; k >= 0; --k)
690 Py_XDECREF(recycle[k]);
Tim Peters8d9eb102004-07-31 02:24:20 +0000691 result = 0;
692 Error:
Tim Peters73572222004-07-31 02:54:42 +0000693 if (recycle != recycle_on_stack)
Armin Rigo1dd04a02004-07-30 11:38:22 +0000694 PyMem_FREE(recycle);
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000695 Py_XDECREF(v_as_SF);
Tim Peters8d9eb102004-07-31 02:24:20 +0000696 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000697#undef b
698}
699
Guido van Rossum234f9421993-06-17 12:35:49 +0000700int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000701PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000702{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000703 if (!PyList_Check(a)) {
704 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000705 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000706 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000707 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000708}
709
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000710static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000711list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000712{
713 PyObject **items;
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000714 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000715
716
717 size = PyList_GET_SIZE(self);
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000718 if (size == 0 || n == 1) {
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000719 Py_INCREF(self);
720 return (PyObject *)self;
721 }
722
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000723 if (n < 1) {
Armin Rigo93677f02004-07-29 12:40:23 +0000724 (void)list_clear(self);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000725 Py_INCREF(self);
726 return (PyObject *)self;
727 }
728
Thomas Woutersa97744c2008-01-25 21:09:34 +0000729 if (size > PY_SSIZE_T_MAX / n) {
Armin Rigoa1e42e12007-10-17 18:46:37 +0000730 return PyErr_NoMemory();
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000731 }
732
733 if (list_resize(self, size*n) == -1)
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000734 return NULL;
735
736 p = size;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000737 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000738 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
739 for (j = 0; j < size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000740 PyObject *o = items[j];
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000741 Py_INCREF(o);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000742 items[p++] = o;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000743 }
744 }
745 Py_INCREF(self);
746 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000747}
748
Guido van Rossum4a450d01991-04-03 19:05:18 +0000749static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000750list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000751{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000752 PyObject *old_value;
Christian Heimese93237d2007-12-19 02:37:44 +0000753 if (i < 0 || i >= Py_SIZE(a)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000754 PyErr_SetString(PyExc_IndexError,
755 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000756 return -1;
757 }
758 if (v == NULL)
759 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000760 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000761 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000762 a->ob_item[i] = v;
Tim Peters3b01a122002-07-19 02:35:45 +0000763 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000764 return 0;
765}
766
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000767static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000768listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000769{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000770 Py_ssize_t i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000771 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000772 if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000773 return NULL;
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000774 if (ins1(self, i, v) == 0)
775 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000776 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000777}
778
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000779static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000780listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000781{
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000782 if (app1(self, v) == 0)
783 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000784 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000785}
786
Barry Warsawdedf6d61998-10-09 16:37:25 +0000787static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000788listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000789{
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000790 PyObject *it; /* iter(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000791 Py_ssize_t m; /* size of self */
792 Py_ssize_t n; /* guess for size of b */
793 Py_ssize_t mn; /* m + n */
794 Py_ssize_t i;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000795 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000796
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000797 /* Special cases:
Tim Petersb38e2b62004-07-29 02:29:26 +0000798 1) lists and tuples which can use PySequence_Fast ops
799 2) extending self to self requires making a copy first
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000800 */
801 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
Armin Rigo70d172d2004-03-20 22:19:23 +0000802 PyObject **src, **dest;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000803 b = PySequence_Fast(b, "argument must be iterable");
804 if (!b)
805 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000806 n = PySequence_Fast_GET_SIZE(b);
807 if (n == 0) {
808 /* short circuit when b is empty */
809 Py_DECREF(b);
810 Py_RETURN_NONE;
811 }
Christian Heimese93237d2007-12-19 02:37:44 +0000812 m = Py_SIZE(self);
Armin Rigo70d172d2004-03-20 22:19:23 +0000813 if (list_resize(self, m + n) == -1) {
814 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000815 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000816 }
817 /* note that we may still have self == b here for the
818 * situation a.extend(a), but the following code works
819 * in that case too. Just make sure to resize self
820 * before calling PySequence_Fast_ITEMS.
821 */
822 /* populate the end of self with b's items */
823 src = PySequence_Fast_ITEMS(b);
824 dest = self->ob_item + m;
825 for (i = 0; i < n; i++) {
826 PyObject *o = src[i];
827 Py_INCREF(o);
828 dest[i] = o;
829 }
830 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000831 Py_RETURN_NONE;
832 }
833
834 it = PyObject_GetIter(b);
835 if (it == NULL)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000836 return NULL;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000837 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000838
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000839 /* Guess a result list size. */
Raymond Hettinger4e2f7142007-12-06 00:56:53 +0000840 n = _PyObject_LengthHint(b, 8);
Raymond Hettingerb5163702009-02-02 21:50:13 +0000841 if (n == -1) {
842 Py_DECREF(it);
843 return NULL;
844 }
Christian Heimese93237d2007-12-19 02:37:44 +0000845 m = Py_SIZE(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000846 mn = m + n;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000847 if (mn >= m) {
848 /* Make room. */
849 if (list_resize(self, mn) == -1)
850 goto error;
851 /* Make the list sane again. */
Christian Heimese93237d2007-12-19 02:37:44 +0000852 Py_SIZE(self) = m;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000853 }
854 /* Else m + n overflowed; on the chance that n lied, and there really
855 * is enough room, ignore it. If n was telling the truth, we'll
856 * eventually run out of memory during the loop.
857 */
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000858
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000859 /* Run iterator to exhaustion. */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000860 for (;;) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000861 PyObject *item = iternext(it);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000862 if (item == NULL) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000863 if (PyErr_Occurred()) {
864 if (PyErr_ExceptionMatches(PyExc_StopIteration))
865 PyErr_Clear();
866 else
867 goto error;
868 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000869 break;
870 }
Christian Heimese93237d2007-12-19 02:37:44 +0000871 if (Py_SIZE(self) < self->allocated) {
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000872 /* steals ref */
Christian Heimese93237d2007-12-19 02:37:44 +0000873 PyList_SET_ITEM(self, Py_SIZE(self), item);
874 ++Py_SIZE(self);
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000875 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000876 else {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000877 int status = app1(self, item);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000878 Py_DECREF(item); /* append creates a new ref */
879 if (status < 0)
880 goto error;
881 }
882 }
883
884 /* Cut back result list if initial guess was too large. */
Christian Heimese93237d2007-12-19 02:37:44 +0000885 if (Py_SIZE(self) < self->allocated)
886 list_resize(self, Py_SIZE(self)); /* shrinking can't fail */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000887
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000888 Py_DECREF(it);
889 Py_RETURN_NONE;
890
891 error:
892 Py_DECREF(it);
893 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000894}
895
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000896PyObject *
897_PyList_Extend(PyListObject *self, PyObject *b)
898{
899 return listextend(self, b);
900}
901
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000902static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000903list_inplace_concat(PyListObject *self, PyObject *other)
904{
905 PyObject *result;
906
907 result = listextend(self, other);
908 if (result == NULL)
909 return result;
910 Py_DECREF(result);
911 Py_INCREF(self);
912 return (PyObject *)self;
913}
914
915static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000916listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000917{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000918 Py_ssize_t i = -1;
Armin Rigo7ccbca92006-10-04 12:17:45 +0000919 PyObject *v;
Tim Peters8fc4a912004-07-31 21:53:19 +0000920 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000921
Armin Rigo7ccbca92006-10-04 12:17:45 +0000922 if (!PyArg_ParseTuple(args, "|n:pop", &i))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000923 return NULL;
Armin Rigo7ccbca92006-10-04 12:17:45 +0000924
Christian Heimese93237d2007-12-19 02:37:44 +0000925 if (Py_SIZE(self) == 0) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000926 /* Special-case most common failure cause */
927 PyErr_SetString(PyExc_IndexError, "pop from empty list");
928 return NULL;
929 }
930 if (i < 0)
Christian Heimese93237d2007-12-19 02:37:44 +0000931 i += Py_SIZE(self);
932 if (i < 0 || i >= Py_SIZE(self)) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000933 PyErr_SetString(PyExc_IndexError, "pop index out of range");
934 return NULL;
935 }
936 v = self->ob_item[i];
Christian Heimese93237d2007-12-19 02:37:44 +0000937 if (i == Py_SIZE(self) - 1) {
938 status = list_resize(self, Py_SIZE(self) - 1);
Tim Peters8fc4a912004-07-31 21:53:19 +0000939 assert(status >= 0);
940 return v; /* and v now owns the reference the list had */
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000941 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000942 Py_INCREF(v);
Tim Peters8fc4a912004-07-31 21:53:19 +0000943 status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
944 assert(status >= 0);
945 /* Use status, so that in a release build compilers don't
946 * complain about the unused name.
947 */
Brett Cannon651dd522004-08-08 21:21:18 +0000948 (void) status;
949
950 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000951}
952
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000953/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
954static void
955reverse_slice(PyObject **lo, PyObject **hi)
956{
957 assert(lo && hi);
958
959 --hi;
960 while (lo < hi) {
961 PyObject *t = *lo;
962 *lo = *hi;
963 *hi = t;
964 ++lo;
965 --hi;
966 }
967}
968
Tim Petersa64dc242002-08-01 02:13:36 +0000969/* Lots of code for an adaptive, stable, natural mergesort. There are many
970 * pieces to this algorithm; read listsort.txt for overviews and details.
971 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000972
Guido van Rossum3f236de1996-12-10 23:55:39 +0000973/* Comparison function. Takes care of calling a user-supplied
Tim Peters66860f62002-08-04 17:47:26 +0000974 * comparison function (any callable Python object), which must not be
975 * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool
976 * with Py_LT if you know it's NULL).
Tim Petersa64dc242002-08-01 02:13:36 +0000977 * Returns -1 on error, 1 if x < y, 0 if x >= y.
978 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000979static int
Tim Petersa8c974c2002-07-19 03:30:57 +0000980islt(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000981{
Tim Petersf2a04732002-07-11 21:46:16 +0000982 PyObject *res;
983 PyObject *args;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000984 Py_ssize_t i;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000985
Tim Peters66860f62002-08-04 17:47:26 +0000986 assert(compare != NULL);
Tim Petersa8c974c2002-07-19 03:30:57 +0000987 /* Call the user's comparison function and translate the 3-way
988 * result into true or false (or error).
989 */
Tim Petersf2a04732002-07-11 21:46:16 +0000990 args = PyTuple_New(2);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000991 if (args == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000992 return -1;
Tim Petersf2a04732002-07-11 21:46:16 +0000993 Py_INCREF(x);
994 Py_INCREF(y);
995 PyTuple_SET_ITEM(args, 0, x);
996 PyTuple_SET_ITEM(args, 1, y);
Tim Peters58cf3612002-07-15 05:16:13 +0000997 res = PyObject_Call(compare, args, NULL);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000998 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000999 if (res == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +00001000 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001001 if (!PyInt_Check(res)) {
Georg Brandl283a1352006-11-19 08:48:30 +00001002 PyErr_Format(PyExc_TypeError,
1003 "comparison function must return int, not %.200s",
1004 res->ob_type->tp_name);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001005 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +00001006 return -1;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001007 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001008 i = PyInt_AsLong(res);
1009 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +00001010 return i < 0;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001011}
1012
Tim Peters66860f62002-08-04 17:47:26 +00001013/* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
1014 * islt. This avoids a layer of function call in the usual case, and
1015 * sorting does many comparisons.
1016 * Returns -1 on error, 1 if x < y, 0 if x >= y.
1017 */
1018#define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
1019 PyObject_RichCompareBool(X, Y, Py_LT) : \
1020 islt(X, Y, COMPARE))
1021
1022/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +00001023 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
1024 started. It makes more sense in context <wink>. X and Y are PyObject*s.
1025*/
Tim Peters66860f62002-08-04 17:47:26 +00001026#define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
Tim Petersa8c974c2002-07-19 03:30:57 +00001027 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001028
1029/* binarysort is the best method for sorting small arrays: it does
1030 few compares, but can do data movement quadratic in the number of
1031 elements.
Guido van Rossum42812581998-06-17 14:15:44 +00001032 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +00001033 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001034 On entry, must have lo <= start <= hi, and that [lo, start) is already
1035 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +00001036 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001037 Even in case of error, the output slice will be some permutation of
1038 the input (nothing is lost or duplicated).
1039*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00001040static int
Fred Drakea2f55112000-07-09 15:16:51 +00001041binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
1042 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001043{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001044 register Py_ssize_t k;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001045 register PyObject **l, **p, **r;
1046 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001047
Tim Petersa8c974c2002-07-19 03:30:57 +00001048 assert(lo <= start && start <= hi);
1049 /* assert [lo, start) is sorted */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001050 if (lo == start)
1051 ++start;
1052 for (; start < hi; ++start) {
1053 /* set l to where *start belongs */
1054 l = lo;
1055 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001056 pivot = *r;
Tim Peters0fe977c2002-07-19 06:12:32 +00001057 /* Invariants:
1058 * pivot >= all in [lo, l).
1059 * pivot < all in [r, start).
1060 * The second is vacuously true at the start.
1061 */
1062 assert(l < r);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001063 do {
1064 p = l + ((r - l) >> 1);
Tim Petersa8c974c2002-07-19 03:30:57 +00001065 IFLT(pivot, *p)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001066 r = p;
1067 else
Tim Peters0fe977c2002-07-19 06:12:32 +00001068 l = p+1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001069 } while (l < r);
Tim Peters0fe977c2002-07-19 06:12:32 +00001070 assert(l == r);
1071 /* The invariants still hold, so pivot >= all in [lo, l) and
1072 pivot < all in [l, start), so pivot belongs at l. Note
1073 that if there are elements equal to pivot, l points to the
1074 first slot after them -- that's why this sort is stable.
1075 Slide over to make room.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001076 Caution: using memmove is much slower under MSVC 5;
1077 we're not usually moving many slots. */
1078 for (p = start; p > l; --p)
1079 *p = *(p-1);
1080 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001081 }
Guido van Rossum3f236de1996-12-10 23:55:39 +00001082 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001083
1084 fail:
1085 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001086}
1087
Tim Petersa64dc242002-08-01 02:13:36 +00001088/*
1089Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1090is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001091
Tim Petersa64dc242002-08-01 02:13:36 +00001092 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001093
Tim Petersa64dc242002-08-01 02:13:36 +00001094or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001095
Tim Petersa64dc242002-08-01 02:13:36 +00001096 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001097
Tim Petersa64dc242002-08-01 02:13:36 +00001098Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1099For its intended use in a stable mergesort, the strictness of the defn of
1100"descending" is needed so that the caller can safely reverse a descending
1101sequence without violating stability (strict > ensures there are no equal
1102elements to get out of order).
1103
1104Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001105*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001106static Py_ssize_t
Tim Petersa64dc242002-08-01 02:13:36 +00001107count_run(PyObject **lo, PyObject **hi, PyObject *compare, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001108{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001109 Py_ssize_t k;
1110 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001111
Tim Petersa64dc242002-08-01 02:13:36 +00001112 assert(lo < hi);
1113 *descending = 0;
1114 ++lo;
1115 if (lo == hi)
1116 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001117
Tim Petersa64dc242002-08-01 02:13:36 +00001118 n = 2;
1119 IFLT(*lo, *(lo-1)) {
1120 *descending = 1;
1121 for (lo = lo+1; lo < hi; ++lo, ++n) {
1122 IFLT(*lo, *(lo-1))
1123 ;
1124 else
1125 break;
1126 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001127 }
Tim Petersa64dc242002-08-01 02:13:36 +00001128 else {
1129 for (lo = lo+1; lo < hi; ++lo, ++n) {
1130 IFLT(*lo, *(lo-1))
1131 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001132 }
1133 }
1134
Tim Petersa64dc242002-08-01 02:13:36 +00001135 return n;
1136fail:
1137 return -1;
1138}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001139
Tim Petersa64dc242002-08-01 02:13:36 +00001140/*
1141Locate the proper position of key in a sorted vector; if the vector contains
1142an element equal to key, return the position immediately to the left of
1143the leftmost equal element. [gallop_right() does the same except returns
1144the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001145
Tim Petersa64dc242002-08-01 02:13:36 +00001146"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001147
Tim Petersa64dc242002-08-01 02:13:36 +00001148"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1149hint is to the final result, the faster this runs.
1150
1151The return value is the int k in 0..n such that
1152
1153 a[k-1] < key <= a[k]
1154
1155pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1156key belongs at index k; or, IOW, the first k elements of a should precede
1157key, and the last n-k should follow key.
1158
1159Returns -1 on error. See listsort.txt for info on the method.
1160*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001161static Py_ssize_t
1162gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
Tim Petersa64dc242002-08-01 02:13:36 +00001163{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001164 Py_ssize_t ofs;
1165 Py_ssize_t lastofs;
1166 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001167
1168 assert(key && a && n > 0 && hint >= 0 && hint < n);
1169
1170 a += hint;
1171 lastofs = 0;
1172 ofs = 1;
1173 IFLT(*a, key) {
1174 /* a[hint] < key -- gallop right, until
1175 * a[hint + lastofs] < key <= a[hint + ofs]
1176 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001177 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001178 while (ofs < maxofs) {
1179 IFLT(a[ofs], key) {
1180 lastofs = ofs;
1181 ofs = (ofs << 1) + 1;
1182 if (ofs <= 0) /* int overflow */
1183 ofs = maxofs;
1184 }
1185 else /* key <= a[hint + ofs] */
1186 break;
1187 }
1188 if (ofs > maxofs)
1189 ofs = maxofs;
1190 /* Translate back to offsets relative to &a[0]. */
1191 lastofs += hint;
1192 ofs += hint;
1193 }
1194 else {
1195 /* key <= a[hint] -- gallop left, until
1196 * a[hint - ofs] < key <= a[hint - lastofs]
1197 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001198 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001199 while (ofs < maxofs) {
1200 IFLT(*(a-ofs), key)
1201 break;
1202 /* key <= a[hint - ofs] */
1203 lastofs = ofs;
1204 ofs = (ofs << 1) + 1;
1205 if (ofs <= 0) /* int overflow */
1206 ofs = maxofs;
1207 }
1208 if (ofs > maxofs)
1209 ofs = maxofs;
1210 /* Translate back to positive offsets relative to &a[0]. */
1211 k = lastofs;
1212 lastofs = hint - ofs;
1213 ofs = hint - k;
1214 }
1215 a -= hint;
1216
1217 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1218 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1219 * right of lastofs but no farther right than ofs. Do a binary
1220 * search, with invariant a[lastofs-1] < key <= a[ofs].
1221 */
1222 ++lastofs;
1223 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001224 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001225
1226 IFLT(a[m], key)
1227 lastofs = m+1; /* a[m] < key */
1228 else
1229 ofs = m; /* key <= a[m] */
1230 }
1231 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1232 return ofs;
1233
1234fail:
1235 return -1;
1236}
1237
1238/*
1239Exactly like gallop_left(), except that if key already exists in a[0:n],
1240finds the position immediately to the right of the rightmost equal value.
1241
1242The return value is the int k in 0..n such that
1243
1244 a[k-1] <= key < a[k]
1245
1246or -1 if error.
1247
1248The code duplication is massive, but this is enough different given that
1249we're sticking to "<" comparisons that it's much harder to follow if
1250written as one routine with yet another "left or right?" flag.
1251*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001252static Py_ssize_t
1253gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
Tim Petersa64dc242002-08-01 02:13:36 +00001254{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001255 Py_ssize_t ofs;
1256 Py_ssize_t lastofs;
1257 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001258
1259 assert(key && a && n > 0 && hint >= 0 && hint < n);
1260
1261 a += hint;
1262 lastofs = 0;
1263 ofs = 1;
1264 IFLT(key, *a) {
1265 /* key < a[hint] -- gallop left, until
1266 * a[hint - ofs] <= key < a[hint - lastofs]
1267 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001268 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001269 while (ofs < maxofs) {
1270 IFLT(key, *(a-ofs)) {
1271 lastofs = ofs;
1272 ofs = (ofs << 1) + 1;
1273 if (ofs <= 0) /* int overflow */
1274 ofs = maxofs;
1275 }
1276 else /* a[hint - ofs] <= key */
1277 break;
1278 }
1279 if (ofs > maxofs)
1280 ofs = maxofs;
1281 /* Translate back to positive offsets relative to &a[0]. */
1282 k = lastofs;
1283 lastofs = hint - ofs;
1284 ofs = hint - k;
1285 }
1286 else {
1287 /* a[hint] <= key -- gallop right, until
1288 * a[hint + lastofs] <= key < a[hint + ofs]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001289 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001290 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001291 while (ofs < maxofs) {
1292 IFLT(key, a[ofs])
1293 break;
1294 /* a[hint + ofs] <= key */
1295 lastofs = ofs;
1296 ofs = (ofs << 1) + 1;
1297 if (ofs <= 0) /* int overflow */
1298 ofs = maxofs;
1299 }
1300 if (ofs > maxofs)
1301 ofs = maxofs;
1302 /* Translate back to offsets relative to &a[0]. */
1303 lastofs += hint;
1304 ofs += hint;
1305 }
1306 a -= hint;
1307
1308 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1309 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1310 * right of lastofs but no farther right than ofs. Do a binary
1311 * search, with invariant a[lastofs-1] <= key < a[ofs].
1312 */
1313 ++lastofs;
1314 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001315 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001316
1317 IFLT(key, a[m])
1318 ofs = m; /* key < a[m] */
1319 else
1320 lastofs = m+1; /* a[m] <= key */
1321 }
1322 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1323 return ofs;
1324
1325fail:
1326 return -1;
1327}
1328
1329/* The maximum number of entries in a MergeState's pending-runs stack.
1330 * This is enough to sort arrays of size up to about
1331 * 32 * phi ** MAX_MERGE_PENDING
1332 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1333 * with 2**64 elements.
1334 */
1335#define MAX_MERGE_PENDING 85
1336
Tim Peterse05f65a2002-08-10 05:21:15 +00001337/* When we get into galloping mode, we stay there until both runs win less
1338 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001339 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001340#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001341
1342/* Avoid malloc for small temp arrays. */
1343#define MERGESTATE_TEMP_SIZE 256
1344
1345/* One MergeState exists on the stack per invocation of mergesort. It's just
1346 * a convenient way to pass state around among the helper functions.
1347 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001348struct s_slice {
1349 PyObject **base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001350 Py_ssize_t len;
Tim Peterse05f65a2002-08-10 05:21:15 +00001351};
1352
Tim Petersa64dc242002-08-01 02:13:36 +00001353typedef struct s_MergeState {
1354 /* The user-supplied comparison function. or NULL if none given. */
1355 PyObject *compare;
1356
Tim Peterse05f65a2002-08-10 05:21:15 +00001357 /* This controls when we get *into* galloping mode. It's initialized
1358 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1359 * random data, and lower for highly structured data.
1360 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001361 Py_ssize_t min_gallop;
Tim Peterse05f65a2002-08-10 05:21:15 +00001362
Tim Petersa64dc242002-08-01 02:13:36 +00001363 /* 'a' is temp storage to help with merges. It contains room for
1364 * alloced entries.
1365 */
1366 PyObject **a; /* may point to temparray below */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001367 Py_ssize_t alloced;
Tim Petersa64dc242002-08-01 02:13:36 +00001368
1369 /* A stack of n pending runs yet to be merged. Run #i starts at
1370 * address base[i] and extends for len[i] elements. It's always
1371 * true (so long as the indices are in bounds) that
1372 *
Tim Peterse05f65a2002-08-10 05:21:15 +00001373 * pending[i].base + pending[i].len == pending[i+1].base
Tim Petersa64dc242002-08-01 02:13:36 +00001374 *
1375 * so we could cut the storage for this, but it's a minor amount,
1376 * and keeping all the info explicit simplifies the code.
1377 */
1378 int n;
Tim Peterse05f65a2002-08-10 05:21:15 +00001379 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001380
1381 /* 'a' points to this when possible, rather than muck with malloc. */
1382 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1383} MergeState;
1384
1385/* Conceptually a MergeState's constructor. */
1386static void
1387merge_init(MergeState *ms, PyObject *compare)
1388{
1389 assert(ms != NULL);
1390 ms->compare = compare;
1391 ms->a = ms->temparray;
1392 ms->alloced = MERGESTATE_TEMP_SIZE;
1393 ms->n = 0;
Tim Peterse05f65a2002-08-10 05:21:15 +00001394 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001395}
1396
1397/* Free all the temp memory owned by the MergeState. This must be called
1398 * when you're done with a MergeState, and may be called before then if
1399 * you want to free the temp memory early.
1400 */
1401static void
1402merge_freemem(MergeState *ms)
1403{
1404 assert(ms != NULL);
1405 if (ms->a != ms->temparray)
1406 PyMem_Free(ms->a);
1407 ms->a = ms->temparray;
1408 ms->alloced = MERGESTATE_TEMP_SIZE;
1409}
1410
1411/* Ensure enough temp memory for 'need' array slots is available.
1412 * Returns 0 on success and -1 if the memory can't be gotten.
1413 */
1414static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001415merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001416{
1417 assert(ms != NULL);
1418 if (need <= ms->alloced)
1419 return 0;
1420 /* Don't realloc! That can cost cycles to copy the old data, but
1421 * we don't care what's in the block.
1422 */
1423 merge_freemem(ms);
Gregory P. Smith9d534572008-06-11 07:41:16 +00001424 if (need > PY_SSIZE_T_MAX / sizeof(PyObject*)) {
1425 PyErr_NoMemory();
1426 return -1;
1427 }
Tim Petersa64dc242002-08-01 02:13:36 +00001428 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1429 if (ms->a) {
1430 ms->alloced = need;
1431 return 0;
1432 }
1433 PyErr_NoMemory();
1434 merge_freemem(ms); /* reset to sane state */
1435 return -1;
1436}
1437#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1438 merge_getmem(MS, NEED))
1439
1440/* Merge the na elements starting at pa with the nb elements starting at pb
1441 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1442 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1443 * merge, and should have na <= nb. See listsort.txt for more info.
1444 * Return 0 if successful, -1 if error.
1445 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001446static Py_ssize_t
1447merge_lo(MergeState *ms, PyObject **pa, Py_ssize_t na,
1448 PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001449{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001450 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001451 PyObject *compare;
1452 PyObject **dest;
1453 int result = -1; /* guilty until proved innocent */
Neal Norwitz7fd96072006-08-19 04:28:55 +00001454 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001455
1456 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1457 if (MERGE_GETMEM(ms, na) < 0)
1458 return -1;
1459 memcpy(ms->a, pa, na * sizeof(PyObject*));
1460 dest = pa;
1461 pa = ms->a;
1462
1463 *dest++ = *pb++;
1464 --nb;
1465 if (nb == 0)
1466 goto Succeed;
1467 if (na == 1)
1468 goto CopyB;
1469
Neal Norwitz7fd96072006-08-19 04:28:55 +00001470 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001471 compare = ms->compare;
1472 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001473 Py_ssize_t acount = 0; /* # of times A won in a row */
1474 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001475
1476 /* Do the straightforward thing until (if ever) one run
1477 * appears to win consistently.
1478 */
1479 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001480 assert(na > 1 && nb > 0);
Tim Peters66860f62002-08-04 17:47:26 +00001481 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001482 if (k) {
1483 if (k < 0)
1484 goto Fail;
1485 *dest++ = *pb++;
1486 ++bcount;
1487 acount = 0;
1488 --nb;
1489 if (nb == 0)
1490 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001491 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001492 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001493 }
1494 else {
Tim Petersa64dc242002-08-01 02:13:36 +00001495 *dest++ = *pa++;
1496 ++acount;
1497 bcount = 0;
1498 --na;
1499 if (na == 1)
1500 goto CopyB;
Tim Peterse05f65a2002-08-10 05:21:15 +00001501 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001502 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001503 }
Tim Petersa64dc242002-08-01 02:13:36 +00001504 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001505
Tim Petersa64dc242002-08-01 02:13:36 +00001506 /* One run is winning so consistently that galloping may
1507 * be a huge win. So try that, and continue galloping until
1508 * (if ever) neither run appears to be winning consistently
1509 * anymore.
1510 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001511 ++min_gallop;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001512 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001513 assert(na > 1 && nb > 0);
1514 min_gallop -= min_gallop > 1;
1515 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001516 k = gallop_right(*pb, pa, na, 0, compare);
1517 acount = k;
1518 if (k) {
1519 if (k < 0)
1520 goto Fail;
1521 memcpy(dest, pa, k * sizeof(PyObject *));
1522 dest += k;
1523 pa += k;
1524 na -= k;
1525 if (na == 1)
1526 goto CopyB;
1527 /* na==0 is impossible now if the comparison
1528 * function is consistent, but we can't assume
1529 * that it is.
1530 */
1531 if (na == 0)
1532 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001533 }
Tim Petersa64dc242002-08-01 02:13:36 +00001534 *dest++ = *pb++;
1535 --nb;
1536 if (nb == 0)
1537 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001538
Tim Petersa64dc242002-08-01 02:13:36 +00001539 k = gallop_left(*pa, pb, nb, 0, compare);
1540 bcount = k;
1541 if (k) {
1542 if (k < 0)
1543 goto Fail;
1544 memmove(dest, pb, k * sizeof(PyObject *));
1545 dest += k;
1546 pb += k;
1547 nb -= k;
1548 if (nb == 0)
1549 goto Succeed;
1550 }
1551 *dest++ = *pa++;
1552 --na;
1553 if (na == 1)
1554 goto CopyB;
1555 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001556 ++min_gallop; /* penalize it for leaving galloping mode */
1557 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001558 }
1559Succeed:
1560 result = 0;
1561Fail:
1562 if (na)
1563 memcpy(dest, pa, na * sizeof(PyObject*));
1564 return result;
1565CopyB:
1566 assert(na == 1 && nb > 0);
1567 /* The last element of pa belongs at the end of the merge. */
1568 memmove(dest, pb, nb * sizeof(PyObject *));
1569 dest[nb] = *pa;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001570 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001571}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001572
Tim Petersa64dc242002-08-01 02:13:36 +00001573/* Merge the na elements starting at pa with the nb elements starting at pb
1574 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1575 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1576 * merge, and should have na >= nb. See listsort.txt for more info.
1577 * Return 0 if successful, -1 if error.
1578 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001579static Py_ssize_t
1580merge_hi(MergeState *ms, PyObject **pa, Py_ssize_t na, PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001581{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001582 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001583 PyObject *compare;
1584 PyObject **dest;
1585 int result = -1; /* guilty until proved innocent */
1586 PyObject **basea;
1587 PyObject **baseb;
Neal Norwitz7fd96072006-08-19 04:28:55 +00001588 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001589
1590 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1591 if (MERGE_GETMEM(ms, nb) < 0)
1592 return -1;
1593 dest = pb + nb - 1;
1594 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1595 basea = pa;
1596 baseb = ms->a;
1597 pb = ms->a + nb - 1;
1598 pa += na - 1;
1599
1600 *dest-- = *pa--;
1601 --na;
1602 if (na == 0)
1603 goto Succeed;
1604 if (nb == 1)
1605 goto CopyA;
1606
Neal Norwitz7fd96072006-08-19 04:28:55 +00001607 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001608 compare = ms->compare;
1609 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001610 Py_ssize_t acount = 0; /* # of times A won in a row */
1611 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001612
1613 /* Do the straightforward thing until (if ever) one run
1614 * appears to win consistently.
1615 */
1616 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001617 assert(na > 0 && nb > 1);
Tim Peters66860f62002-08-04 17:47:26 +00001618 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001619 if (k) {
1620 if (k < 0)
1621 goto Fail;
1622 *dest-- = *pa--;
1623 ++acount;
1624 bcount = 0;
1625 --na;
1626 if (na == 0)
1627 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001628 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001629 break;
1630 }
1631 else {
1632 *dest-- = *pb--;
1633 ++bcount;
1634 acount = 0;
1635 --nb;
1636 if (nb == 1)
1637 goto CopyA;
Tim Peterse05f65a2002-08-10 05:21:15 +00001638 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001639 break;
1640 }
1641 }
1642
1643 /* One run is winning so consistently that galloping may
1644 * be a huge win. So try that, and continue galloping until
1645 * (if ever) neither run appears to be winning consistently
1646 * anymore.
1647 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001648 ++min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001649 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001650 assert(na > 0 && nb > 1);
1651 min_gallop -= min_gallop > 1;
1652 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001653 k = gallop_right(*pb, basea, na, na-1, compare);
1654 if (k < 0)
1655 goto Fail;
1656 k = na - k;
1657 acount = k;
1658 if (k) {
1659 dest -= k;
1660 pa -= k;
1661 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1662 na -= k;
1663 if (na == 0)
1664 goto Succeed;
1665 }
1666 *dest-- = *pb--;
1667 --nb;
1668 if (nb == 1)
1669 goto CopyA;
1670
1671 k = gallop_left(*pa, baseb, nb, nb-1, compare);
1672 if (k < 0)
1673 goto Fail;
1674 k = nb - k;
1675 bcount = k;
1676 if (k) {
1677 dest -= k;
1678 pb -= k;
1679 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1680 nb -= k;
1681 if (nb == 1)
1682 goto CopyA;
1683 /* nb==0 is impossible now if the comparison
1684 * function is consistent, but we can't assume
1685 * that it is.
1686 */
1687 if (nb == 0)
1688 goto Succeed;
1689 }
1690 *dest-- = *pa--;
1691 --na;
1692 if (na == 0)
1693 goto Succeed;
1694 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001695 ++min_gallop; /* penalize it for leaving galloping mode */
1696 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001697 }
1698Succeed:
1699 result = 0;
1700Fail:
1701 if (nb)
1702 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1703 return result;
1704CopyA:
1705 assert(nb == 1 && na > 0);
1706 /* The first element of pb belongs at the front of the merge. */
1707 dest -= na;
1708 pa -= na;
1709 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1710 *dest = *pb;
1711 return 0;
1712}
1713
1714/* Merge the two runs at stack indices i and i+1.
1715 * Returns 0 on success, -1 on error.
1716 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001717static Py_ssize_t
1718merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001719{
1720 PyObject **pa, **pb;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001721 Py_ssize_t na, nb;
1722 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001723 PyObject *compare;
1724
1725 assert(ms != NULL);
1726 assert(ms->n >= 2);
1727 assert(i >= 0);
1728 assert(i == ms->n - 2 || i == ms->n - 3);
1729
Tim Peterse05f65a2002-08-10 05:21:15 +00001730 pa = ms->pending[i].base;
1731 na = ms->pending[i].len;
1732 pb = ms->pending[i+1].base;
1733 nb = ms->pending[i+1].len;
Tim Petersa64dc242002-08-01 02:13:36 +00001734 assert(na > 0 && nb > 0);
1735 assert(pa + na == pb);
1736
1737 /* Record the length of the combined runs; if i is the 3rd-last
1738 * run now, also slide over the last run (which isn't involved
1739 * in this merge). The current run i+1 goes away in any case.
1740 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001741 ms->pending[i].len = na + nb;
1742 if (i == ms->n - 3)
1743 ms->pending[i+1] = ms->pending[i+2];
Tim Petersa64dc242002-08-01 02:13:36 +00001744 --ms->n;
1745
1746 /* Where does b start in a? Elements in a before that can be
1747 * ignored (already in place).
1748 */
1749 compare = ms->compare;
1750 k = gallop_right(*pb, pa, na, 0, compare);
1751 if (k < 0)
1752 return -1;
1753 pa += k;
1754 na -= k;
1755 if (na == 0)
1756 return 0;
1757
1758 /* Where does a end in b? Elements in b after that can be
1759 * ignored (already in place).
1760 */
1761 nb = gallop_left(pa[na-1], pb, nb, nb-1, compare);
1762 if (nb <= 0)
1763 return nb;
1764
1765 /* Merge what remains of the runs, using a temp array with
1766 * min(na, nb) elements.
1767 */
1768 if (na <= nb)
1769 return merge_lo(ms, pa, na, pb, nb);
1770 else
1771 return merge_hi(ms, pa, na, pb, nb);
1772}
1773
1774/* Examine the stack of runs waiting to be merged, merging adjacent runs
1775 * until the stack invariants are re-established:
1776 *
1777 * 1. len[-3] > len[-2] + len[-1]
1778 * 2. len[-2] > len[-1]
1779 *
1780 * See listsort.txt for more info.
1781 *
1782 * Returns 0 on success, -1 on error.
1783 */
1784static int
1785merge_collapse(MergeState *ms)
1786{
Tim Peterse05f65a2002-08-10 05:21:15 +00001787 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001788
1789 assert(ms);
1790 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001791 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001792 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1793 if (p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001794 --n;
1795 if (merge_at(ms, n) < 0)
1796 return -1;
1797 }
Tim Peterse05f65a2002-08-10 05:21:15 +00001798 else if (p[n].len <= p[n+1].len) {
Tim Petersa64dc242002-08-01 02:13:36 +00001799 if (merge_at(ms, n) < 0)
1800 return -1;
1801 }
1802 else
1803 break;
1804 }
1805 return 0;
1806}
1807
1808/* Regardless of invariants, merge all runs on the stack until only one
1809 * remains. This is used at the end of the mergesort.
1810 *
1811 * Returns 0 on success, -1 on error.
1812 */
1813static int
1814merge_force_collapse(MergeState *ms)
1815{
Tim Peterse05f65a2002-08-10 05:21:15 +00001816 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001817
1818 assert(ms);
1819 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001820 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001821 if (n > 0 && p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001822 --n;
1823 if (merge_at(ms, n) < 0)
1824 return -1;
1825 }
1826 return 0;
1827}
1828
1829/* Compute a good value for the minimum run length; natural runs shorter
1830 * than this are boosted artificially via binary insertion.
1831 *
1832 * If n < 64, return n (it's too small to bother with fancy stuff).
1833 * Else if n is an exact power of 2, return 32.
1834 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1835 * strictly less than, an exact power of 2.
1836 *
1837 * See listsort.txt for more info.
1838 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001839static Py_ssize_t
1840merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001841{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001842 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001843
1844 assert(n >= 0);
1845 while (n >= 64) {
1846 r |= n & 1;
1847 n >>= 1;
1848 }
1849 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001850}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001851
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001852/* Special wrapper to support stable sorting using the decorate-sort-undecorate
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001853 pattern. Holds a key which is used for comparisons and the original record
Tim Petersb38e2b62004-07-29 02:29:26 +00001854 which is returned during the undecorate phase. By exposing only the key
1855 during comparisons, the underlying sort stability characteristics are left
1856 unchanged. Also, if a custom comparison function is used, it will only see
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001857 the key instead of a full record. */
1858
1859typedef struct {
1860 PyObject_HEAD
1861 PyObject *key;
1862 PyObject *value;
1863} sortwrapperobject;
1864
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001865PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
Anthony Baxter377be112006-04-11 06:54:30 +00001866static PyObject *
1867sortwrapper_richcompare(sortwrapperobject *, sortwrapperobject *, int);
1868static void
1869sortwrapper_dealloc(sortwrapperobject *);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001870
1871static PyTypeObject sortwrapper_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001872 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001873 "sortwrapper", /* tp_name */
1874 sizeof(sortwrapperobject), /* tp_basicsize */
1875 0, /* tp_itemsize */
1876 /* methods */
1877 (destructor)sortwrapper_dealloc, /* tp_dealloc */
1878 0, /* tp_print */
1879 0, /* tp_getattr */
1880 0, /* tp_setattr */
1881 0, /* tp_compare */
1882 0, /* tp_repr */
1883 0, /* tp_as_number */
1884 0, /* tp_as_sequence */
1885 0, /* tp_as_mapping */
1886 0, /* tp_hash */
1887 0, /* tp_call */
1888 0, /* tp_str */
1889 PyObject_GenericGetAttr, /* tp_getattro */
1890 0, /* tp_setattro */
1891 0, /* tp_as_buffer */
Tim Petersb38e2b62004-07-29 02:29:26 +00001892 Py_TPFLAGS_DEFAULT |
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001893 Py_TPFLAGS_HAVE_RICHCOMPARE, /* tp_flags */
1894 sortwrapper_doc, /* tp_doc */
1895 0, /* tp_traverse */
1896 0, /* tp_clear */
1897 (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
1898};
1899
Anthony Baxter377be112006-04-11 06:54:30 +00001900
1901static PyObject *
1902sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
1903{
1904 if (!PyObject_TypeCheck(b, &sortwrapper_type)) {
1905 PyErr_SetString(PyExc_TypeError,
1906 "expected a sortwrapperobject");
1907 return NULL;
1908 }
1909 return PyObject_RichCompare(a->key, b->key, op);
1910}
1911
1912static void
1913sortwrapper_dealloc(sortwrapperobject *so)
1914{
1915 Py_XDECREF(so->key);
1916 Py_XDECREF(so->value);
1917 PyObject_Del(so);
1918}
1919
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001920/* Returns a new reference to a sortwrapper.
1921 Consumes the references to the two underlying objects. */
1922
1923static PyObject *
1924build_sortwrapper(PyObject *key, PyObject *value)
1925{
1926 sortwrapperobject *so;
Tim Petersb38e2b62004-07-29 02:29:26 +00001927
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001928 so = PyObject_New(sortwrapperobject, &sortwrapper_type);
1929 if (so == NULL)
1930 return NULL;
1931 so->key = key;
1932 so->value = value;
1933 return (PyObject *)so;
1934}
1935
1936/* Returns a new reference to the value underlying the wrapper. */
1937static PyObject *
1938sortwrapper_getvalue(PyObject *so)
1939{
1940 PyObject *value;
1941
1942 if (!PyObject_TypeCheck(so, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001943 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001944 "expected a sortwrapperobject");
1945 return NULL;
1946 }
1947 value = ((sortwrapperobject *)so)->value;
1948 Py_INCREF(value);
1949 return value;
1950}
1951
1952/* Wrapper for user specified cmp functions in combination with a
1953 specified key function. Makes sure the cmp function is presented
1954 with the actual key instead of the sortwrapper */
1955
1956typedef struct {
1957 PyObject_HEAD
1958 PyObject *func;
1959} cmpwrapperobject;
1960
1961static void
1962cmpwrapper_dealloc(cmpwrapperobject *co)
1963{
1964 Py_XDECREF(co->func);
1965 PyObject_Del(co);
1966}
1967
1968static PyObject *
1969cmpwrapper_call(cmpwrapperobject *co, PyObject *args, PyObject *kwds)
1970{
1971 PyObject *x, *y, *xx, *yy;
1972
1973 if (!PyArg_UnpackTuple(args, "", 2, 2, &x, &y))
1974 return NULL;
1975 if (!PyObject_TypeCheck(x, &sortwrapper_type) ||
Raymond Hettingerae4a2992003-10-16 17:16:30 +00001976 !PyObject_TypeCheck(y, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001977 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001978 "expected a sortwrapperobject");
1979 return NULL;
1980 }
1981 xx = ((sortwrapperobject *)x)->key;
1982 yy = ((sortwrapperobject *)y)->key;
1983 return PyObject_CallFunctionObjArgs(co->func, xx, yy, NULL);
1984}
1985
1986PyDoc_STRVAR(cmpwrapper_doc, "cmp() wrapper for sort with custom keys.");
1987
1988static PyTypeObject cmpwrapper_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001989 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001990 "cmpwrapper", /* tp_name */
1991 sizeof(cmpwrapperobject), /* tp_basicsize */
1992 0, /* tp_itemsize */
1993 /* methods */
1994 (destructor)cmpwrapper_dealloc, /* tp_dealloc */
1995 0, /* tp_print */
1996 0, /* tp_getattr */
1997 0, /* tp_setattr */
1998 0, /* tp_compare */
1999 0, /* tp_repr */
2000 0, /* tp_as_number */
2001 0, /* tp_as_sequence */
2002 0, /* tp_as_mapping */
2003 0, /* tp_hash */
2004 (ternaryfunc)cmpwrapper_call, /* tp_call */
2005 0, /* tp_str */
2006 PyObject_GenericGetAttr, /* tp_getattro */
2007 0, /* tp_setattro */
2008 0, /* tp_as_buffer */
2009 Py_TPFLAGS_DEFAULT, /* tp_flags */
2010 cmpwrapper_doc, /* tp_doc */
2011};
2012
2013static PyObject *
2014build_cmpwrapper(PyObject *cmpfunc)
2015{
2016 cmpwrapperobject *co;
Tim Petersb38e2b62004-07-29 02:29:26 +00002017
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002018 co = PyObject_New(cmpwrapperobject, &cmpwrapper_type);
2019 if (co == NULL)
2020 return NULL;
2021 Py_INCREF(cmpfunc);
2022 co->func = cmpfunc;
2023 return (PyObject *)co;
2024}
2025
Tim Petersa64dc242002-08-01 02:13:36 +00002026/* An adaptive, stable, natural mergesort. See listsort.txt.
2027 * Returns Py_None on success, NULL on error. Even in case of error, the
2028 * list will be some permutation of its input state (nothing is lost or
2029 * duplicated).
2030 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002031static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002032listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00002033{
Tim Petersa64dc242002-08-01 02:13:36 +00002034 MergeState ms;
2035 PyObject **lo, **hi;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002036 Py_ssize_t nremaining;
2037 Py_ssize_t minrun;
2038 Py_ssize_t saved_ob_size, saved_allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00002039 PyObject **saved_ob_item;
Armin Rigo93677f02004-07-29 12:40:23 +00002040 PyObject **final_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00002041 PyObject *compare = NULL;
2042 PyObject *result = NULL; /* guilty until proved innocent */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002043 int reverse = 0;
2044 PyObject *keyfunc = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002045 Py_ssize_t i;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002046 PyObject *key, *value, *kvpair;
Martin v. Löwis15e62742006-02-27 16:46:16 +00002047 static char *kwlist[] = {"cmp", "key", "reverse", 0};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002048
Tim Petersa64dc242002-08-01 02:13:36 +00002049 assert(self != NULL);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002050 assert (PyList_Check(self));
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002051 if (args != NULL) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002052 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:sort",
2053 kwlist, &compare, &keyfunc, &reverse))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002054 return NULL;
2055 }
Skip Montanaro4abd5f02003-01-02 20:51:08 +00002056 if (compare == Py_None)
2057 compare = NULL;
Raymond Hettinger05387862008-03-19 17:45:19 +00002058 if (compare != NULL &&
Benjamin Petersonf19a7b92008-04-27 18:40:21 +00002059 PyErr_WarnPy3k("the cmp argument is not supported in 3.x", 1) < 0)
Raymond Hettinger6c0ff8a2008-03-18 23:33:08 +00002060 return NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002061 if (keyfunc == Py_None)
2062 keyfunc = NULL;
2063 if (compare != NULL && keyfunc != NULL) {
2064 compare = build_cmpwrapper(compare);
2065 if (compare == NULL)
Hye-Shik Chang19cb1932003-12-10 07:31:08 +00002066 return NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002067 } else
2068 Py_XINCREF(compare);
2069
Tim Petersb9099c32002-11-12 22:08:10 +00002070 /* The list is temporarily made empty, so that mutations performed
2071 * by comparison functions can't affect the slice of memory we're
2072 * sorting (allowing mutations during sorting is a core-dump
2073 * factory, since ob_item may change).
2074 */
Christian Heimese93237d2007-12-19 02:37:44 +00002075 saved_ob_size = Py_SIZE(self);
Tim Petersb9099c32002-11-12 22:08:10 +00002076 saved_ob_item = self->ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002077 saved_allocated = self->allocated;
Christian Heimese93237d2007-12-19 02:37:44 +00002078 Py_SIZE(self) = 0;
Tim Peters51b4ade2004-07-29 04:07:15 +00002079 self->ob_item = NULL;
Armin Rigo93677f02004-07-29 12:40:23 +00002080 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00002081
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002082 if (keyfunc != NULL) {
2083 for (i=0 ; i < saved_ob_size ; i++) {
2084 value = saved_ob_item[i];
Tim Petersb38e2b62004-07-29 02:29:26 +00002085 key = PyObject_CallFunctionObjArgs(keyfunc, value,
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002086 NULL);
2087 if (key == NULL) {
2088 for (i=i-1 ; i>=0 ; i--) {
2089 kvpair = saved_ob_item[i];
2090 value = sortwrapper_getvalue(kvpair);
2091 saved_ob_item[i] = value;
2092 Py_DECREF(kvpair);
2093 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002094 goto dsu_fail;
2095 }
2096 kvpair = build_sortwrapper(key, value);
2097 if (kvpair == NULL)
2098 goto dsu_fail;
2099 saved_ob_item[i] = kvpair;
2100 }
2101 }
2102
2103 /* Reverse sort stability achieved by initially reversing the list,
2104 applying a stable forward sort, then reversing the final result. */
2105 if (reverse && saved_ob_size > 1)
2106 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2107
2108 merge_init(&ms, compare);
2109
Tim Petersb9099c32002-11-12 22:08:10 +00002110 nremaining = saved_ob_size;
Tim Petersa64dc242002-08-01 02:13:36 +00002111 if (nremaining < 2)
2112 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00002113
Tim Petersa64dc242002-08-01 02:13:36 +00002114 /* March over the array once, left to right, finding natural runs,
2115 * and extending short natural runs to minrun elements.
2116 */
Tim Petersb9099c32002-11-12 22:08:10 +00002117 lo = saved_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00002118 hi = lo + nremaining;
2119 minrun = merge_compute_minrun(nremaining);
2120 do {
2121 int descending;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002122 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00002123
Tim Petersa64dc242002-08-01 02:13:36 +00002124 /* Identify next run. */
2125 n = count_run(lo, hi, compare, &descending);
2126 if (n < 0)
2127 goto fail;
2128 if (descending)
2129 reverse_slice(lo, lo + n);
2130 /* If short, extend to min(minrun, nremaining). */
2131 if (n < minrun) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002132 const Py_ssize_t force = nremaining <= minrun ?
Tim Petersa64dc242002-08-01 02:13:36 +00002133 nremaining : minrun;
2134 if (binarysort(lo, lo + force, lo + n, compare) < 0)
2135 goto fail;
2136 n = force;
2137 }
2138 /* Push run onto pending-runs stack, and maybe merge. */
2139 assert(ms.n < MAX_MERGE_PENDING);
Tim Peterse05f65a2002-08-10 05:21:15 +00002140 ms.pending[ms.n].base = lo;
2141 ms.pending[ms.n].len = n;
Tim Petersa64dc242002-08-01 02:13:36 +00002142 ++ms.n;
2143 if (merge_collapse(&ms) < 0)
2144 goto fail;
2145 /* Advance to find next run. */
2146 lo += n;
2147 nremaining -= n;
2148 } while (nremaining);
2149 assert(lo == hi);
Tim Peters330f9e92002-07-19 07:05:44 +00002150
Tim Petersa64dc242002-08-01 02:13:36 +00002151 if (merge_force_collapse(&ms) < 0)
2152 goto fail;
2153 assert(ms.n == 1);
Tim Petersb9099c32002-11-12 22:08:10 +00002154 assert(ms.pending[0].base == saved_ob_item);
2155 assert(ms.pending[0].len == saved_ob_size);
Tim Petersa64dc242002-08-01 02:13:36 +00002156
2157succeed:
2158 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002159fail:
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002160 if (keyfunc != NULL) {
2161 for (i=0 ; i < saved_ob_size ; i++) {
2162 kvpair = saved_ob_item[i];
2163 value = sortwrapper_getvalue(kvpair);
2164 saved_ob_item[i] = value;
2165 Py_DECREF(kvpair);
2166 }
2167 }
2168
Armin Rigo93677f02004-07-29 12:40:23 +00002169 if (self->allocated != -1 && result != NULL) {
Tim Peters51b4ade2004-07-29 04:07:15 +00002170 /* The user mucked with the list during the sort,
2171 * and we don't already have another error to report.
2172 */
2173 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2174 result = NULL;
Tim Petersb9099c32002-11-12 22:08:10 +00002175 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002176
2177 if (reverse && saved_ob_size > 1)
2178 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2179
2180 merge_freemem(&ms);
2181
2182dsu_fail:
Armin Rigo93677f02004-07-29 12:40:23 +00002183 final_ob_item = self->ob_item;
Christian Heimese93237d2007-12-19 02:37:44 +00002184 i = Py_SIZE(self);
2185 Py_SIZE(self) = saved_ob_size;
Tim Petersb9099c32002-11-12 22:08:10 +00002186 self->ob_item = saved_ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002187 self->allocated = saved_allocated;
Armin Rigo93677f02004-07-29 12:40:23 +00002188 if (final_ob_item != NULL) {
2189 /* we cannot use list_clear() for this because it does not
2190 guarantee that the list is really empty when it returns */
2191 while (--i >= 0) {
2192 Py_XDECREF(final_ob_item[i]);
2193 }
2194 PyMem_FREE(final_ob_item);
2195 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002196 Py_XDECREF(compare);
Tim Petersa64dc242002-08-01 02:13:36 +00002197 Py_XINCREF(result);
2198 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002199}
Tim Peters330f9e92002-07-19 07:05:44 +00002200#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002201#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002202
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002203int
Fred Drakea2f55112000-07-09 15:16:51 +00002204PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002205{
2206 if (v == NULL || !PyList_Check(v)) {
2207 PyErr_BadInternalCall();
2208 return -1;
2209 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002210 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002211 if (v == NULL)
2212 return -1;
2213 Py_DECREF(v);
2214 return 0;
2215}
2216
Guido van Rossumb86c5492001-02-12 22:06:02 +00002217static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002218listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002219{
Christian Heimese93237d2007-12-19 02:37:44 +00002220 if (Py_SIZE(self) > 1)
2221 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002222 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002223}
2224
Guido van Rossum84c76f51990-10-30 13:32:20 +00002225int
Fred Drakea2f55112000-07-09 15:16:51 +00002226PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002227{
Tim Peters6063e262002-08-08 01:06:39 +00002228 PyListObject *self = (PyListObject *)v;
2229
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002230 if (v == NULL || !PyList_Check(v)) {
2231 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002232 return -1;
2233 }
Christian Heimese93237d2007-12-19 02:37:44 +00002234 if (Py_SIZE(self) > 1)
2235 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002236 return 0;
2237}
2238
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002239PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002240PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002241{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002242 PyObject *w;
Raymond Hettinger6c87af52007-12-15 00:07:25 +00002243 PyObject **p, **q;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002244 Py_ssize_t n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002245 if (v == NULL || !PyList_Check(v)) {
2246 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002247 return NULL;
2248 }
Christian Heimese93237d2007-12-19 02:37:44 +00002249 n = Py_SIZE(v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002250 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002251 if (w == NULL)
2252 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002253 p = ((PyTupleObject *)w)->ob_item;
Raymond Hettinger6c87af52007-12-15 00:07:25 +00002254 q = ((PyListObject *)v)->ob_item;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002255 while (--n >= 0) {
Raymond Hettinger6c87af52007-12-15 00:07:25 +00002256 Py_INCREF(*q);
2257 *p = *q;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002258 p++;
Raymond Hettinger6c87af52007-12-15 00:07:25 +00002259 q++;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002260 }
2261 return w;
2262}
2263
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002264static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002265listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002266{
Christian Heimese93237d2007-12-19 02:37:44 +00002267 Py_ssize_t i, start=0, stop=Py_SIZE(self);
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002268 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002269
Walter Dörwalde8049bef2003-06-17 19:27:39 +00002270 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2271 _PyEval_SliceIndex, &start,
2272 _PyEval_SliceIndex, &stop))
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002273 return NULL;
Guido van Rossum2743d872003-06-17 14:25:14 +00002274 if (start < 0) {
Christian Heimese93237d2007-12-19 02:37:44 +00002275 start += Py_SIZE(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002276 if (start < 0)
2277 start = 0;
2278 }
2279 if (stop < 0) {
Christian Heimese93237d2007-12-19 02:37:44 +00002280 stop += Py_SIZE(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002281 if (stop < 0)
2282 stop = 0;
2283 }
Christian Heimese93237d2007-12-19 02:37:44 +00002284 for (i = start; i < stop && i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002285 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2286 if (cmp > 0)
Martin v. Löwis18e16552006-02-15 17:27:45 +00002287 return PyInt_FromSsize_t(i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002288 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002289 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002290 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002291 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002292 return NULL;
2293}
2294
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002295static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002296listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002297{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002298 Py_ssize_t count = 0;
2299 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002300
Christian Heimese93237d2007-12-19 02:37:44 +00002301 for (i = 0; i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002302 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2303 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002304 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002305 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002306 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00002307 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002308 return PyInt_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002309}
2310
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002311static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002312listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002313{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002314 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002315
Christian Heimese93237d2007-12-19 02:37:44 +00002316 for (i = 0; i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002317 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2318 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002319 if (list_ass_slice(self, i, i+1,
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002320 (PyObject *)NULL) == 0)
2321 Py_RETURN_NONE;
2322 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002323 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002324 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002325 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002326 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002327 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002328 return NULL;
2329}
2330
Jeremy Hylton8caad492000-06-23 14:18:11 +00002331static int
2332list_traverse(PyListObject *o, visitproc visit, void *arg)
2333{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002334 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002335
Christian Heimese93237d2007-12-19 02:37:44 +00002336 for (i = Py_SIZE(o); --i >= 0; )
Thomas Woutersc6e55062006-04-15 21:47:09 +00002337 Py_VISIT(o->ob_item[i]);
Jeremy Hylton8caad492000-06-23 14:18:11 +00002338 return 0;
2339}
2340
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002341static PyObject *
2342list_richcompare(PyObject *v, PyObject *w, int op)
2343{
2344 PyListObject *vl, *wl;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002345 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002346
2347 if (!PyList_Check(v) || !PyList_Check(w)) {
2348 Py_INCREF(Py_NotImplemented);
2349 return Py_NotImplemented;
2350 }
2351
2352 vl = (PyListObject *)v;
2353 wl = (PyListObject *)w;
2354
Christian Heimese93237d2007-12-19 02:37:44 +00002355 if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002356 /* Shortcut: if the lengths differ, the lists differ */
2357 PyObject *res;
2358 if (op == Py_EQ)
2359 res = Py_False;
2360 else
2361 res = Py_True;
2362 Py_INCREF(res);
2363 return res;
2364 }
2365
2366 /* Search for the first index where items are different */
Christian Heimese93237d2007-12-19 02:37:44 +00002367 for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002368 int k = PyObject_RichCompareBool(vl->ob_item[i],
2369 wl->ob_item[i], Py_EQ);
2370 if (k < 0)
2371 return NULL;
2372 if (!k)
2373 break;
2374 }
2375
Christian Heimese93237d2007-12-19 02:37:44 +00002376 if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002377 /* No more items to compare -- compare sizes */
Christian Heimese93237d2007-12-19 02:37:44 +00002378 Py_ssize_t vs = Py_SIZE(vl);
2379 Py_ssize_t ws = Py_SIZE(wl);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002380 int cmp;
2381 PyObject *res;
2382 switch (op) {
2383 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00002384 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002385 case Py_EQ: cmp = vs == ws; break;
2386 case Py_NE: cmp = vs != ws; break;
2387 case Py_GT: cmp = vs > ws; break;
2388 case Py_GE: cmp = vs >= ws; break;
2389 default: return NULL; /* cannot happen */
2390 }
2391 if (cmp)
2392 res = Py_True;
2393 else
2394 res = Py_False;
2395 Py_INCREF(res);
2396 return res;
2397 }
2398
2399 /* We have an item that differs -- shortcuts for EQ/NE */
2400 if (op == Py_EQ) {
2401 Py_INCREF(Py_False);
2402 return Py_False;
2403 }
2404 if (op == Py_NE) {
2405 Py_INCREF(Py_True);
2406 return Py_True;
2407 }
2408
2409 /* Compare the final item again using the proper operator */
2410 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
2411}
2412
Tim Peters6d6c1a32001-08-02 04:15:00 +00002413static int
2414list_init(PyListObject *self, PyObject *args, PyObject *kw)
2415{
2416 PyObject *arg = NULL;
Martin v. Löwis15e62742006-02-27 16:46:16 +00002417 static char *kwlist[] = {"sequence", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002418
2419 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2420 return -1;
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002421
2422 /* Verify list invariants established by PyType_GenericAlloc() */
Christian Heimese93237d2007-12-19 02:37:44 +00002423 assert(0 <= Py_SIZE(self));
2424 assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
Armin Rigoa37bbf22004-07-30 11:20:18 +00002425 assert(self->ob_item != NULL ||
2426 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002427
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002428 /* Empty previous contents */
Armin Rigo93677f02004-07-29 12:40:23 +00002429 if (self->ob_item != NULL) {
2430 (void)list_clear(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002431 }
2432 if (arg != NULL) {
2433 PyObject *rv = listextend(self, arg);
2434 if (rv == NULL)
2435 return -1;
2436 Py_DECREF(rv);
2437 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002438 return 0;
2439}
2440
Robert Schuppenies51df0642008-06-01 16:16:17 +00002441static PyObject *
2442list_sizeof(PyListObject *self)
2443{
2444 Py_ssize_t res;
2445
2446 res = sizeof(PyListObject) + self->allocated * sizeof(void*);
2447 return PyInt_FromSsize_t(res);
2448}
2449
Raymond Hettinger1021c442003-11-07 15:38:09 +00002450static PyObject *list_iter(PyObject *seq);
2451static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2452
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002453PyDoc_STRVAR(getitem_doc,
2454"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002455PyDoc_STRVAR(reversed_doc,
2456"L.__reversed__() -- return a reverse iterator over the list");
Robert Schuppenies51df0642008-06-01 16:16:17 +00002457PyDoc_STRVAR(sizeof_doc,
Georg Brandl7a6de8b2008-06-01 16:42:16 +00002458"L.__sizeof__() -- size of L in memory, in bytes");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002459PyDoc_STRVAR(append_doc,
2460"L.append(object) -- append object to end");
2461PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002462"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002463PyDoc_STRVAR(insert_doc,
2464"L.insert(index, object) -- insert object before index");
2465PyDoc_STRVAR(pop_doc,
Andrew M. Kuchlingd810cdf2008-10-04 01:04:24 +00002466"L.pop([index]) -> item -- remove and return item at index (default last).\n"
2467"Raises IndexError if list is empty or index is out of range.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002468PyDoc_STRVAR(remove_doc,
Andrew M. Kuchlingd810cdf2008-10-04 01:04:24 +00002469"L.remove(value) -- remove first occurrence of value.\n"
2470"Raises ValueError if the value is not present.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002471PyDoc_STRVAR(index_doc,
Andrew M. Kuchlingd810cdf2008-10-04 01:04:24 +00002472"L.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
2473"Raises ValueError if the value is not present.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002474PyDoc_STRVAR(count_doc,
2475"L.count(value) -> integer -- return number of occurrences of value");
2476PyDoc_STRVAR(reverse_doc,
2477"L.reverse() -- reverse *IN PLACE*");
2478PyDoc_STRVAR(sort_doc,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002479"L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n\
2480cmp(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002481
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002482static PyObject *list_subscript(PyListObject*, PyObject*);
2483
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002484static PyMethodDef list_methods[] = {
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002485 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
Raymond Hettinger1021c442003-11-07 15:38:09 +00002486 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
Robert Schuppenies51df0642008-06-01 16:16:17 +00002487 {"__sizeof__", (PyCFunction)list_sizeof, METH_NOARGS, sizeof_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002488 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002489 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002490 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002491 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002492 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002493 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002494 {"count", (PyCFunction)listcount, METH_O, count_doc},
2495 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002496 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
Tim Petersa64dc242002-08-01 02:13:36 +00002497 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002498};
2499
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002500static PySequenceMethods list_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002501 (lenfunc)list_length, /* sq_length */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002502 (binaryfunc)list_concat, /* sq_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002503 (ssizeargfunc)list_repeat, /* sq_repeat */
2504 (ssizeargfunc)list_item, /* sq_item */
2505 (ssizessizeargfunc)list_slice, /* sq_slice */
2506 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
2507 (ssizessizeobjargproc)list_ass_slice, /* sq_ass_slice */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002508 (objobjproc)list_contains, /* sq_contains */
2509 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002510 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002511};
2512
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002513PyDoc_STRVAR(list_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002514"list() -> new list\n"
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002515"list(sequence) -> new list initialized from sequence's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002516
Guido van Rossum38fff8c2006-03-07 18:50:55 +00002517
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002518static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002519list_subscript(PyListObject* self, PyObject* item)
2520{
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00002521 if (PyIndex_Check(item)) {
2522 Py_ssize_t i;
2523 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002524 if (i == -1 && PyErr_Occurred())
2525 return NULL;
2526 if (i < 0)
2527 i += PyList_GET_SIZE(self);
2528 return list_item(self, i);
2529 }
2530 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002531 Py_ssize_t start, stop, step, slicelength, cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002532 PyObject* result;
2533 PyObject* it;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002534 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002535
Christian Heimese93237d2007-12-19 02:37:44 +00002536 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002537 &start, &stop, &step, &slicelength) < 0) {
2538 return NULL;
2539 }
2540
2541 if (slicelength <= 0) {
2542 return PyList_New(0);
2543 }
Thomas Wouters3ccec682007-08-28 15:28:19 +00002544 else if (step == 1) {
2545 return list_slice(self, start, stop);
2546 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002547 else {
2548 result = PyList_New(slicelength);
2549 if (!result) return NULL;
2550
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002551 src = self->ob_item;
2552 dest = ((PyListObject *)result)->ob_item;
Tim Peters3b01a122002-07-19 02:35:45 +00002553 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002554 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002555 it = src[cur];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002556 Py_INCREF(it);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002557 dest[i] = it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002558 }
Tim Peters3b01a122002-07-19 02:35:45 +00002559
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002560 return result;
2561 }
2562 }
2563 else {
Georg Brandl283a1352006-11-19 08:48:30 +00002564 PyErr_Format(PyExc_TypeError,
2565 "list indices must be integers, not %.200s",
2566 item->ob_type->tp_name);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002567 return NULL;
2568 }
2569}
2570
Tim Peters3b01a122002-07-19 02:35:45 +00002571static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002572list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2573{
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00002574 if (PyIndex_Check(item)) {
2575 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002576 if (i == -1 && PyErr_Occurred())
2577 return -1;
2578 if (i < 0)
2579 i += PyList_GET_SIZE(self);
2580 return list_ass_item(self, i, value);
2581 }
2582 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002583 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002584
Christian Heimese93237d2007-12-19 02:37:44 +00002585 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002586 &start, &stop, &step, &slicelength) < 0) {
2587 return -1;
2588 }
2589
Thomas Wouters3ccec682007-08-28 15:28:19 +00002590 if (step == 1)
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002591 return list_ass_slice(self, start, stop, value);
2592
Thomas Wouters3ccec682007-08-28 15:28:19 +00002593 /* Make sure s[5:2] = [..] inserts at the right place:
2594 before 5, not before 2. */
2595 if ((step < 0 && start < stop) ||
2596 (step > 0 && start > stop))
2597 stop = start;
2598
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002599 if (value == NULL) {
2600 /* delete slice */
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002601 PyObject **garbage;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002602 Py_ssize_t cur, i;
Tim Peters3b01a122002-07-19 02:35:45 +00002603
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002604 if (slicelength <= 0)
2605 return 0;
2606
2607 if (step < 0) {
2608 stop = start + 1;
2609 start = stop + step*(slicelength - 1) - 1;
2610 step = -step;
2611 }
2612
Gregory P. Smith9d534572008-06-11 07:41:16 +00002613 assert(slicelength <= PY_SIZE_MAX / sizeof(PyObject*));
2614
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002615 garbage = (PyObject**)
2616 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Neal Norwitzb88cfad2006-08-12 03:16:54 +00002617 if (!garbage) {
2618 PyErr_NoMemory();
2619 return -1;
2620 }
Tim Peters3b01a122002-07-19 02:35:45 +00002621
Thomas Wouters3ccec682007-08-28 15:28:19 +00002622 /* drawing pictures might help understand these for
2623 loops. Basically, we memmove the parts of the
2624 list that are *not* part of the slice: step-1
2625 items for each item that is part of the slice,
2626 and then tail end of the list that was not
2627 covered by the slice */
Guido van Rossum75a20b12002-06-11 12:22:28 +00002628 for (cur = start, i = 0;
2629 cur < stop;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002630 cur += step, i++) {
Thomas Wouters3ccec682007-08-28 15:28:19 +00002631 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002632
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002633 garbage[i] = PyList_GET_ITEM(self, cur);
2634
Christian Heimese93237d2007-12-19 02:37:44 +00002635 if (cur + step >= Py_SIZE(self)) {
2636 lim = Py_SIZE(self) - cur - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002637 }
2638
Tim Petersb38e2b62004-07-29 02:29:26 +00002639 memmove(self->ob_item + cur - i,
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002640 self->ob_item + cur + 1,
2641 lim * sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002642 }
Thomas Wouters3ccec682007-08-28 15:28:19 +00002643 cur = start + slicelength*step;
Christian Heimese93237d2007-12-19 02:37:44 +00002644 if (cur < Py_SIZE(self)) {
Thomas Wouters3ccec682007-08-28 15:28:19 +00002645 memmove(self->ob_item + cur - slicelength,
2646 self->ob_item + cur,
Christian Heimese93237d2007-12-19 02:37:44 +00002647 (Py_SIZE(self) - cur) *
Thomas Wouters3ccec682007-08-28 15:28:19 +00002648 sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002649 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002650
Christian Heimese93237d2007-12-19 02:37:44 +00002651 Py_SIZE(self) -= slicelength;
2652 list_resize(self, Py_SIZE(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002653
2654 for (i = 0; i < slicelength; i++) {
2655 Py_DECREF(garbage[i]);
2656 }
2657 PyMem_FREE(garbage);
2658
2659 return 0;
2660 }
2661 else {
2662 /* assign slice */
Thomas Wouters3ccec682007-08-28 15:28:19 +00002663 PyObject *ins, *seq;
2664 PyObject **garbage, **seqitems, **selfitems;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002665 Py_ssize_t cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002666
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002667 /* protect against a[::-1] = a */
Tim Peters3b01a122002-07-19 02:35:45 +00002668 if (self == (PyListObject*)value) {
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002669 seq = list_slice((PyListObject*)value, 0,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002670 PyList_GET_SIZE(value));
Tim Peters3b01a122002-07-19 02:35:45 +00002671 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002672 else {
Tim Petersb38e2b62004-07-29 02:29:26 +00002673 seq = PySequence_Fast(value,
Thomas Wouters3ccec682007-08-28 15:28:19 +00002674 "must assign iterable "
2675 "to extended slice");
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002676 }
Neal Norwitzb88cfad2006-08-12 03:16:54 +00002677 if (!seq)
2678 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002679
2680 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2681 PyErr_Format(PyExc_ValueError,
Thomas Wouters3ccec682007-08-28 15:28:19 +00002682 "attempt to assign sequence of "
2683 "size %zd to extended slice of "
2684 "size %zd",
Martin v. Löwise0e89f72006-02-16 06:59:22 +00002685 PySequence_Fast_GET_SIZE(seq),
2686 slicelength);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002687 Py_DECREF(seq);
2688 return -1;
2689 }
2690
2691 if (!slicelength) {
2692 Py_DECREF(seq);
2693 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002694 }
2695
2696 garbage = (PyObject**)
2697 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Neal Norwitze7e4e2d2006-10-28 21:20:12 +00002698 if (!garbage) {
2699 Py_DECREF(seq);
2700 PyErr_NoMemory();
2701 return -1;
2702 }
Tim Peters3b01a122002-07-19 02:35:45 +00002703
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002704 selfitems = self->ob_item;
Raymond Hettinger42bec932004-03-12 16:38:17 +00002705 seqitems = PySequence_Fast_ITEMS(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002706 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002707 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002708 garbage[i] = selfitems[cur];
2709 ins = seqitems[i];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002710 Py_INCREF(ins);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002711 selfitems[cur] = ins;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002712 }
2713
2714 for (i = 0; i < slicelength; i++) {
2715 Py_DECREF(garbage[i]);
2716 }
Tim Peters3b01a122002-07-19 02:35:45 +00002717
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002718 PyMem_FREE(garbage);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002719 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002720
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002721 return 0;
2722 }
Tim Peters3b01a122002-07-19 02:35:45 +00002723 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002724 else {
Georg Brandl283a1352006-11-19 08:48:30 +00002725 PyErr_Format(PyExc_TypeError,
2726 "list indices must be integers, not %.200s",
2727 item->ob_type->tp_name);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002728 return -1;
2729 }
2730}
2731
2732static PyMappingMethods list_as_mapping = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002733 (lenfunc)list_length,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002734 (binaryfunc)list_subscript,
2735 (objobjargproc)list_ass_subscript
2736};
2737
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002738PyTypeObject PyList_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002739 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002740 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002741 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002742 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002743 (destructor)list_dealloc, /* tp_dealloc */
2744 (printfunc)list_print, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002745 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002746 0, /* tp_setattr */
2747 0, /* tp_compare */
2748 (reprfunc)list_repr, /* tp_repr */
2749 0, /* tp_as_number */
2750 &list_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002751 &list_as_mapping, /* tp_as_mapping */
Nick Coghlan53663a62008-07-15 14:27:37 +00002752 (hashfunc)PyObject_HashNotImplemented, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002753 0, /* tp_call */
2754 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002755 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002756 0, /* tp_setattro */
2757 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002758 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Neal Norwitzee3a1b52007-02-25 19:44:48 +00002759 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002760 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002761 (traverseproc)list_traverse, /* tp_traverse */
2762 (inquiry)list_clear, /* tp_clear */
2763 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002764 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002765 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002766 0, /* tp_iternext */
2767 list_methods, /* tp_methods */
2768 0, /* tp_members */
2769 0, /* tp_getset */
2770 0, /* tp_base */
2771 0, /* tp_dict */
2772 0, /* tp_descr_get */
2773 0, /* tp_descr_set */
2774 0, /* tp_dictoffset */
2775 (initproc)list_init, /* tp_init */
2776 PyType_GenericAlloc, /* tp_alloc */
2777 PyType_GenericNew, /* tp_new */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002778 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002779};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002780
2781
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002782/*********************** List Iterator **************************/
2783
2784typedef struct {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002785 PyObject_HEAD
2786 long it_index;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002787 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002788} listiterobject;
2789
Anthony Baxter377be112006-04-11 06:54:30 +00002790static PyObject *list_iter(PyObject *);
2791static void listiter_dealloc(listiterobject *);
2792static int listiter_traverse(listiterobject *, visitproc, void *);
2793static PyObject *listiter_next(listiterobject *);
2794static PyObject *listiter_len(listiterobject *);
2795
2796PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
2797
2798static PyMethodDef listiter_methods[] = {
2799 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
2800 {NULL, NULL} /* sentinel */
2801};
2802
2803PyTypeObject PyListIter_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002804 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Anthony Baxter377be112006-04-11 06:54:30 +00002805 "listiterator", /* tp_name */
2806 sizeof(listiterobject), /* tp_basicsize */
2807 0, /* tp_itemsize */
2808 /* methods */
2809 (destructor)listiter_dealloc, /* tp_dealloc */
2810 0, /* tp_print */
2811 0, /* tp_getattr */
2812 0, /* tp_setattr */
2813 0, /* tp_compare */
2814 0, /* tp_repr */
2815 0, /* tp_as_number */
2816 0, /* tp_as_sequence */
2817 0, /* tp_as_mapping */
2818 0, /* tp_hash */
2819 0, /* tp_call */
2820 0, /* tp_str */
2821 PyObject_GenericGetAttr, /* tp_getattro */
2822 0, /* tp_setattro */
2823 0, /* tp_as_buffer */
2824 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2825 0, /* tp_doc */
2826 (traverseproc)listiter_traverse, /* tp_traverse */
2827 0, /* tp_clear */
2828 0, /* tp_richcompare */
2829 0, /* tp_weaklistoffset */
2830 PyObject_SelfIter, /* tp_iter */
2831 (iternextfunc)listiter_next, /* tp_iternext */
2832 listiter_methods, /* tp_methods */
2833 0, /* tp_members */
2834};
2835
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002836
Guido van Rossum5086e492002-07-16 15:56:52 +00002837static PyObject *
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002838list_iter(PyObject *seq)
2839{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002840 listiterobject *it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002841
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002842 if (!PyList_Check(seq)) {
2843 PyErr_BadInternalCall();
2844 return NULL;
2845 }
2846 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2847 if (it == NULL)
2848 return NULL;
2849 it->it_index = 0;
2850 Py_INCREF(seq);
2851 it->it_seq = (PyListObject *)seq;
2852 _PyObject_GC_TRACK(it);
2853 return (PyObject *)it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002854}
2855
2856static void
2857listiter_dealloc(listiterobject *it)
2858{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002859 _PyObject_GC_UNTRACK(it);
Guido van Rossum86103ae2002-07-16 20:07:32 +00002860 Py_XDECREF(it->it_seq);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002861 PyObject_GC_Del(it);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002862}
2863
2864static int
2865listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2866{
Thomas Woutersc6e55062006-04-15 21:47:09 +00002867 Py_VISIT(it->it_seq);
2868 return 0;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002869}
2870
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002871static PyObject *
Tim Peters93b2cc42002-06-01 05:22:55 +00002872listiter_next(listiterobject *it)
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002873{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002874 PyListObject *seq;
2875 PyObject *item;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002876
Tim Peters93b2cc42002-06-01 05:22:55 +00002877 assert(it != NULL);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002878 seq = it->it_seq;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002879 if (seq == NULL)
2880 return NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002881 assert(PyList_Check(seq));
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002882
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002883 if (it->it_index < PyList_GET_SIZE(seq)) {
Tim Peters93b2cc42002-06-01 05:22:55 +00002884 item = PyList_GET_ITEM(seq, it->it_index);
2885 ++it->it_index;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002886 Py_INCREF(item);
2887 return item;
2888 }
Guido van Rossum86103ae2002-07-16 20:07:32 +00002889
2890 Py_DECREF(seq);
2891 it->it_seq = NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002892 return NULL;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002893}
2894
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002895static PyObject *
Raymond Hettinger435bf582004-03-18 22:43:10 +00002896listiter_len(listiterobject *it)
2897{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002898 Py_ssize_t len;
Raymond Hettinger40a03822004-04-12 13:05:09 +00002899 if (it->it_seq) {
2900 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2901 if (len >= 0)
Martin v. Löwis18e16552006-02-15 17:27:45 +00002902 return PyInt_FromSsize_t(len);
Raymond Hettinger40a03822004-04-12 13:05:09 +00002903 }
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002904 return PyInt_FromLong(0);
Raymond Hettinger435bf582004-03-18 22:43:10 +00002905}
Anthony Baxter377be112006-04-11 06:54:30 +00002906/*********************** List Reverse Iterator **************************/
Raymond Hettinger435bf582004-03-18 22:43:10 +00002907
Anthony Baxter377be112006-04-11 06:54:30 +00002908typedef struct {
2909 PyObject_HEAD
2910 Py_ssize_t it_index;
2911 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
2912} listreviterobject;
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002913
Anthony Baxter377be112006-04-11 06:54:30 +00002914static PyObject *list_reversed(PyListObject *, PyObject *);
2915static void listreviter_dealloc(listreviterobject *);
2916static int listreviter_traverse(listreviterobject *, visitproc, void *);
2917static PyObject *listreviter_next(listreviterobject *);
Raymond Hettinger7989a4d2008-12-03 15:42:10 +00002918static PyObject *listreviter_len(listreviterobject *);
Anthony Baxter377be112006-04-11 06:54:30 +00002919
Raymond Hettinger7989a4d2008-12-03 15:42:10 +00002920static PyMethodDef listreviter_methods[] = {
2921 {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc},
2922 {NULL, NULL} /* sentinel */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002923};
2924
Anthony Baxter377be112006-04-11 06:54:30 +00002925PyTypeObject PyListRevIter_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002926 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Anthony Baxter377be112006-04-11 06:54:30 +00002927 "listreverseiterator", /* tp_name */
2928 sizeof(listreviterobject), /* tp_basicsize */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002929 0, /* tp_itemsize */
2930 /* methods */
Anthony Baxter377be112006-04-11 06:54:30 +00002931 (destructor)listreviter_dealloc, /* tp_dealloc */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002932 0, /* tp_print */
2933 0, /* tp_getattr */
2934 0, /* tp_setattr */
2935 0, /* tp_compare */
2936 0, /* tp_repr */
2937 0, /* tp_as_number */
Raymond Hettinger7989a4d2008-12-03 15:42:10 +00002938 0, /* tp_as_sequence */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002939 0, /* tp_as_mapping */
2940 0, /* tp_hash */
2941 0, /* tp_call */
2942 0, /* tp_str */
2943 PyObject_GenericGetAttr, /* tp_getattro */
2944 0, /* tp_setattro */
2945 0, /* tp_as_buffer */
2946 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2947 0, /* tp_doc */
Anthony Baxter377be112006-04-11 06:54:30 +00002948 (traverseproc)listreviter_traverse, /* tp_traverse */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002949 0, /* tp_clear */
2950 0, /* tp_richcompare */
2951 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00002952 PyObject_SelfIter, /* tp_iter */
Anthony Baxter377be112006-04-11 06:54:30 +00002953 (iternextfunc)listreviter_next, /* tp_iternext */
Raymond Hettinger7989a4d2008-12-03 15:42:10 +00002954 listreviter_methods, /* tp_methods */
Anthony Baxter377be112006-04-11 06:54:30 +00002955 0,
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002956};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002957
Raymond Hettinger1021c442003-11-07 15:38:09 +00002958static PyObject *
2959list_reversed(PyListObject *seq, PyObject *unused)
2960{
2961 listreviterobject *it;
2962
2963 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2964 if (it == NULL)
2965 return NULL;
2966 assert(PyList_Check(seq));
2967 it->it_index = PyList_GET_SIZE(seq) - 1;
2968 Py_INCREF(seq);
2969 it->it_seq = seq;
2970 PyObject_GC_Track(it);
2971 return (PyObject *)it;
2972}
2973
2974static void
2975listreviter_dealloc(listreviterobject *it)
2976{
2977 PyObject_GC_UnTrack(it);
2978 Py_XDECREF(it->it_seq);
2979 PyObject_GC_Del(it);
2980}
2981
2982static int
2983listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2984{
Thomas Woutersc6e55062006-04-15 21:47:09 +00002985 Py_VISIT(it->it_seq);
2986 return 0;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002987}
2988
2989static PyObject *
2990listreviter_next(listreviterobject *it)
2991{
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002992 PyObject *item;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002993 Py_ssize_t index = it->it_index;
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002994 PyListObject *seq = it->it_seq;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002995
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002996 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2997 item = PyList_GET_ITEM(seq, index);
Raymond Hettinger1021c442003-11-07 15:38:09 +00002998 it->it_index--;
2999 Py_INCREF(item);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003000 return item;
Raymond Hettinger1021c442003-11-07 15:38:09 +00003001 }
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003002 it->it_index = -1;
3003 if (seq != NULL) {
3004 it->it_seq = NULL;
3005 Py_DECREF(seq);
3006 }
3007 return NULL;
Raymond Hettinger1021c442003-11-07 15:38:09 +00003008}
3009
Raymond Hettinger7989a4d2008-12-03 15:42:10 +00003010static PyObject *
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003011listreviter_len(listreviterobject *it)
3012{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003013 Py_ssize_t len = it->it_index + 1;
Raymond Hettinger40a03822004-04-12 13:05:09 +00003014 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
Raymond Hettinger7989a4d2008-12-03 15:42:10 +00003015 len = 0;
3016 return PyLong_FromSsize_t(len);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003017}