blob: d7103744249f0bddbbf4006cba95e1e5039f7742 [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 }
Gregory P. Smith9d534572008-06-11 07:41:16 +0000129 /* Check for overflow without an actual overflow,
130 * which can cause compiler to optimise out */
Mark Dickinsonac5685e2010-02-14 12:16:43 +0000131 if ((size_t)size > PY_SIZE_MAX / sizeof(PyObject *))
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000132 return PyErr_NoMemory();
Mark Dickinsonac5685e2010-02-14 12:16:43 +0000133 nbytes = size * sizeof(PyObject *);
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)) {
Benjamin Petersone2caf1f2009-11-02 15:06:45 +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");
Benjamin Petersone2caf1f2009-11-02 15:06:45 +0000189 if (indexerr == NULL)
190 return NULL;
191 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000192 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000193 return NULL;
194 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000195 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000196}
197
198int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000199PyList_SetItem(register PyObject *op, register Py_ssize_t i,
Fred Drakea2f55112000-07-09 15:16:51 +0000200 register PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000201{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000202 register PyObject *olditem;
203 register PyObject **p;
204 if (!PyList_Check(op)) {
205 Py_XDECREF(newitem);
206 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000207 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000208 }
Christian Heimese93237d2007-12-19 02:37:44 +0000209 if (i < 0 || i >= Py_SIZE(op)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000210 Py_XDECREF(newitem);
211 PyErr_SetString(PyExc_IndexError,
212 "list assignment index out of range");
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000213 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000214 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000215 p = ((PyListObject *)op) -> ob_item + i;
Guido van Rossum5fe60581995-03-09 12:12:50 +0000216 olditem = *p;
217 *p = newitem;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000218 Py_XDECREF(olditem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000219 return 0;
220}
221
222static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000223ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000224{
Christian Heimese93237d2007-12-19 02:37:44 +0000225 Py_ssize_t i, n = Py_SIZE(self);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000226 PyObject **items;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000227 if (v == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000228 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000229 return -1;
230 }
Martin v. Löwisb1ed7fa2006-04-13 07:52:27 +0000231 if (n == PY_SSIZE_T_MAX) {
Trent Micka5846642000-08-13 22:47:45 +0000232 PyErr_SetString(PyExc_OverflowError,
233 "cannot add more objects to list");
234 return -1;
235 }
Tim Petersb38e2b62004-07-29 02:29:26 +0000236
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000237 if (list_resize(self, n+1) == -1)
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000238 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000239
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000240 if (where < 0) {
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000241 where += n;
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000242 if (where < 0)
243 where = 0;
244 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000245 if (where > n)
246 where = n;
247 items = self->ob_item;
248 for (i = n; --i >= where; )
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000249 items[i+1] = items[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000250 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000251 items[where] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000252 return 0;
253}
254
255int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000256PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000257{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000258 if (!PyList_Check(op)) {
259 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000260 return -1;
261 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000262 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000263}
264
Raymond Hettinger40a03822004-04-12 13:05:09 +0000265static int
266app1(PyListObject *self, PyObject *v)
267{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000268 Py_ssize_t n = PyList_GET_SIZE(self);
Raymond Hettinger40a03822004-04-12 13:05:09 +0000269
270 assert (v != NULL);
Martin v. Löwisb1ed7fa2006-04-13 07:52:27 +0000271 if (n == PY_SSIZE_T_MAX) {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000272 PyErr_SetString(PyExc_OverflowError,
273 "cannot add more objects to list");
274 return -1;
275 }
276
277 if (list_resize(self, n+1) == -1)
278 return -1;
279
280 Py_INCREF(v);
281 PyList_SET_ITEM(self, n, v);
282 return 0;
283}
284
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000285int
Fred Drakea2f55112000-07-09 15:16:51 +0000286PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000287{
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000288 if (PyList_Check(op) && (newitem != NULL))
289 return app1((PyListObject *)op, newitem);
290 PyErr_BadInternalCall();
291 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000292}
293
294/* Methods */
295
296static void
Fred Drakea2f55112000-07-09 15:16:51 +0000297list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000298{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000299 Py_ssize_t i;
Guido van Rossumff413af2002-03-28 20:34:59 +0000300 PyObject_GC_UnTrack(op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000301 Py_TRASHCAN_SAFE_BEGIN(op)
Jack Jansen7874d1f1995-01-19 12:09:27 +0000302 if (op->ob_item != NULL) {
Guido van Rossumfa717011999-06-09 15:19:34 +0000303 /* Do it backwards, for Christian Tismer.
304 There's a simple test case where somehow this reduces
305 thrashing when a *very* large list is created and
306 immediately deleted. */
Christian Heimese93237d2007-12-19 02:37:44 +0000307 i = Py_SIZE(op);
Guido van Rossumfa717011999-06-09 15:19:34 +0000308 while (--i >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000309 Py_XDECREF(op->ob_item[i]);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000310 }
Guido van Rossumb18618d2000-05-03 23:44:39 +0000311 PyMem_FREE(op->ob_item);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000312 }
Christian Heimes5b970ad2008-02-06 13:33:44 +0000313 if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op))
314 free_list[numfree++] = op;
Tim Petersb38e2b62004-07-29 02:29:26 +0000315 else
Christian Heimese93237d2007-12-19 02:37:44 +0000316 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000317 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000318}
319
Guido van Rossum90933611991-06-07 16:10:43 +0000320static int
Fred Drakea2f55112000-07-09 15:16:51 +0000321list_print(PyListObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000322{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000323 int rc;
324 Py_ssize_t i;
Antoine Pitroubeaf6a02009-10-11 21:03:26 +0000325 PyObject *item;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000326
Martin v. Löwis18e16552006-02-15 17:27:45 +0000327 rc = Py_ReprEnter((PyObject*)op);
328 if (rc != 0) {
329 if (rc < 0)
330 return rc;
Brett Cannon01531592007-09-17 03:28:34 +0000331 Py_BEGIN_ALLOW_THREADS
Guido van Rossumfb376de1998-04-10 22:47:27 +0000332 fprintf(fp, "[...]");
Brett Cannon01531592007-09-17 03:28:34 +0000333 Py_END_ALLOW_THREADS
Guido van Rossumfb376de1998-04-10 22:47:27 +0000334 return 0;
335 }
Brett Cannon01531592007-09-17 03:28:34 +0000336 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000337 fprintf(fp, "[");
Brett Cannon01531592007-09-17 03:28:34 +0000338 Py_END_ALLOW_THREADS
Christian Heimese93237d2007-12-19 02:37:44 +0000339 for (i = 0; i < Py_SIZE(op); i++) {
Antoine Pitroubeaf6a02009-10-11 21:03:26 +0000340 item = op->ob_item[i];
341 Py_INCREF(item);
Brett Cannon01531592007-09-17 03:28:34 +0000342 if (i > 0) {
343 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000344 fprintf(fp, ", ");
Brett Cannon01531592007-09-17 03:28:34 +0000345 Py_END_ALLOW_THREADS
346 }
Antoine Pitroubeaf6a02009-10-11 21:03:26 +0000347 if (PyObject_Print(item, fp, 0) != 0) {
348 Py_DECREF(item);
Guido van Rossumfb376de1998-04-10 22:47:27 +0000349 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000350 return -1;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000351 }
Antoine Pitroubeaf6a02009-10-11 21:03:26 +0000352 Py_DECREF(item);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000353 }
Brett Cannon01531592007-09-17 03:28:34 +0000354 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000355 fprintf(fp, "]");
Brett Cannon01531592007-09-17 03:28:34 +0000356 Py_END_ALLOW_THREADS
Guido van Rossumfb376de1998-04-10 22:47:27 +0000357 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000358 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000359}
360
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000361static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000362list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000363{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000364 Py_ssize_t i;
Tim Petersa7259592001-06-16 05:11:17 +0000365 PyObject *s, *temp;
366 PyObject *pieces = NULL, *result = NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000367
368 i = Py_ReprEnter((PyObject*)v);
369 if (i != 0) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000370 return i > 0 ? PyString_FromString("[...]") : NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000371 }
Tim Petersa7259592001-06-16 05:11:17 +0000372
Christian Heimese93237d2007-12-19 02:37:44 +0000373 if (Py_SIZE(v) == 0) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000374 result = PyString_FromString("[]");
Tim Petersa7259592001-06-16 05:11:17 +0000375 goto Done;
376 }
377
378 pieces = PyList_New(0);
379 if (pieces == NULL)
380 goto Done;
381
382 /* Do repr() on each element. Note that this may mutate the list,
383 so must refetch the list size on each iteration. */
Christian Heimese93237d2007-12-19 02:37:44 +0000384 for (i = 0; i < Py_SIZE(v); ++i) {
Tim Petersa7259592001-06-16 05:11:17 +0000385 int status;
Brett Cannona0c05512007-09-10 21:38:27 +0000386 if (Py_EnterRecursiveCall(" while getting the repr of a list"))
387 goto Done;
Tim Petersa7259592001-06-16 05:11:17 +0000388 s = PyObject_Repr(v->ob_item[i]);
Brett Cannona0c05512007-09-10 21:38:27 +0000389 Py_LeaveRecursiveCall();
Tim Petersa7259592001-06-16 05:11:17 +0000390 if (s == NULL)
391 goto Done;
392 status = PyList_Append(pieces, s);
393 Py_DECREF(s); /* append created a new ref */
394 if (status < 0)
395 goto Done;
396 }
397
398 /* Add "[]" decorations to the first and last items. */
399 assert(PyList_GET_SIZE(pieces) > 0);
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000400 s = PyString_FromString("[");
Tim Petersa7259592001-06-16 05:11:17 +0000401 if (s == NULL)
402 goto Done;
403 temp = PyList_GET_ITEM(pieces, 0);
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000404 PyString_ConcatAndDel(&s, temp);
Tim Petersa7259592001-06-16 05:11:17 +0000405 PyList_SET_ITEM(pieces, 0, s);
406 if (s == NULL)
407 goto Done;
408
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000409 s = PyString_FromString("]");
Tim Petersa7259592001-06-16 05:11:17 +0000410 if (s == NULL)
411 goto Done;
412 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000413 PyString_ConcatAndDel(&temp, s);
Tim Petersa7259592001-06-16 05:11:17 +0000414 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
415 if (temp == NULL)
416 goto Done;
417
418 /* Paste them all together with ", " between. */
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000419 s = PyString_FromString(", ");
Tim Petersa7259592001-06-16 05:11:17 +0000420 if (s == NULL)
421 goto Done;
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000422 result = _PyString_Join(s, pieces);
Tim Peters3b01a122002-07-19 02:35:45 +0000423 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +0000424
425Done:
426 Py_XDECREF(pieces);
Guido van Rossumfb376de1998-04-10 22:47:27 +0000427 Py_ReprLeave((PyObject *)v);
Tim Petersa7259592001-06-16 05:11:17 +0000428 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000429}
430
Martin v. Löwis18e16552006-02-15 17:27:45 +0000431static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000432list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000433{
Christian Heimese93237d2007-12-19 02:37:44 +0000434 return Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000435}
436
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000437static int
Fred Drakea2f55112000-07-09 15:16:51 +0000438list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000439{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000440 Py_ssize_t i;
441 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000442
Christian Heimese93237d2007-12-19 02:37:44 +0000443 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
Raymond Hettingeraae59992002-09-05 14:23:49 +0000444 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000445 Py_EQ);
Neal Norwitzbb9c5f52002-09-05 21:32:55 +0000446 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000447}
448
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000449static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000450list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000451{
Christian Heimese93237d2007-12-19 02:37:44 +0000452 if (i < 0 || i >= Py_SIZE(a)) {
Benjamin Petersone2caf1f2009-11-02 15:06:45 +0000453 if (indexerr == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000454 indexerr = PyString_FromString(
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000455 "list index out of range");
Benjamin Petersone2caf1f2009-11-02 15:06:45 +0000456 if (indexerr == NULL)
457 return NULL;
458 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000459 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000460 return NULL;
461 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000462 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000463 return a->ob_item[i];
464}
465
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000466static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000467list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000468{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000469 PyListObject *np;
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000470 PyObject **src, **dest;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000471 Py_ssize_t i, len;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000472 if (ilow < 0)
473 ilow = 0;
Christian Heimese93237d2007-12-19 02:37:44 +0000474 else if (ilow > Py_SIZE(a))
475 ilow = Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000476 if (ihigh < ilow)
477 ihigh = ilow;
Christian Heimese93237d2007-12-19 02:37:44 +0000478 else if (ihigh > Py_SIZE(a))
479 ihigh = Py_SIZE(a);
Raymond Hettinger99842b62004-03-08 05:56:15 +0000480 len = ihigh - ilow;
481 np = (PyListObject *) PyList_New(len);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000482 if (np == NULL)
483 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000484
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000485 src = a->ob_item + ilow;
486 dest = np->ob_item;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000487 for (i = 0; i < len; i++) {
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000488 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000489 Py_INCREF(v);
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000490 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000491 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000492 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000493}
494
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000495PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000496PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000497{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000498 if (!PyList_Check(a)) {
499 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000500 return NULL;
501 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000502 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000503}
504
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000505static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000506list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000507{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000508 Py_ssize_t size;
509 Py_ssize_t i;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000510 PyObject **src, **dest;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000511 PyListObject *np;
512 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000513 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000514 "can only concatenate list (not \"%.200s\") to list",
515 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000516 return NULL;
517 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000518#define b ((PyListObject *)bb)
Christian Heimese93237d2007-12-19 02:37:44 +0000519 size = Py_SIZE(a) + Py_SIZE(b);
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000520 if (size < 0)
521 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000522 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000523 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000524 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000525 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000526 src = a->ob_item;
527 dest = np->ob_item;
Christian Heimese93237d2007-12-19 02:37:44 +0000528 for (i = 0; i < Py_SIZE(a); i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000529 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000530 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000531 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000532 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000533 src = b->ob_item;
Christian Heimese93237d2007-12-19 02:37:44 +0000534 dest = np->ob_item + Py_SIZE(a);
535 for (i = 0; i < Py_SIZE(b); i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000536 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000537 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000538 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000539 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000540 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000541#undef b
542}
543
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000544static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000545list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000546{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000547 Py_ssize_t i, j;
548 Py_ssize_t size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000549 PyListObject *np;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000550 PyObject **p, **items;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000551 PyObject *elem;
Guido van Rossumed98d481991-03-06 13:07:53 +0000552 if (n < 0)
553 n = 0;
Christian Heimese93237d2007-12-19 02:37:44 +0000554 size = Py_SIZE(a) * n;
555 if (n && size/n != Py_SIZE(a))
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000556 return PyErr_NoMemory();
Armin Rigoa1e42e12007-10-17 18:46:37 +0000557 if (size == 0)
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000558 return PyList_New(0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000559 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000560 if (np == NULL)
561 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000562
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000563 items = np->ob_item;
Christian Heimese93237d2007-12-19 02:37:44 +0000564 if (Py_SIZE(a) == 1) {
Raymond Hettinger6624e682003-05-21 05:58:46 +0000565 elem = a->ob_item[0];
566 for (i = 0; i < n; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000567 items[i] = elem;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000568 Py_INCREF(elem);
569 }
570 return (PyObject *) np;
571 }
Guido van Rossumed98d481991-03-06 13:07:53 +0000572 p = np->ob_item;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000573 items = a->ob_item;
Guido van Rossumed98d481991-03-06 13:07:53 +0000574 for (i = 0; i < n; i++) {
Christian Heimese93237d2007-12-19 02:37:44 +0000575 for (j = 0; j < Py_SIZE(a); j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000576 *p = items[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000577 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000578 p++;
579 }
580 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000581 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000582}
583
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000584static int
Armin Rigo93677f02004-07-29 12:40:23 +0000585list_clear(PyListObject *a)
586{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000587 Py_ssize_t i;
Armin Rigo93677f02004-07-29 12:40:23 +0000588 PyObject **item = a->ob_item;
589 if (item != NULL) {
590 /* Because XDECREF can recursively invoke operations on
591 this list, we make it empty first. */
Christian Heimese93237d2007-12-19 02:37:44 +0000592 i = Py_SIZE(a);
593 Py_SIZE(a) = 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000594 a->ob_item = NULL;
595 a->allocated = 0;
596 while (--i >= 0) {
597 Py_XDECREF(item[i]);
598 }
599 PyMem_FREE(item);
600 }
601 /* Never fails; the return value can be ignored.
602 Note that there is no guarantee that the list is actually empty
603 at this point, because XDECREF may have populated it again! */
604 return 0;
605}
606
Tim Peters8fc4a912004-07-31 21:53:19 +0000607/* a[ilow:ihigh] = v if v != NULL.
608 * del a[ilow:ihigh] if v == NULL.
609 *
610 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
611 * guaranteed the call cannot fail.
612 */
Armin Rigo93677f02004-07-29 12:40:23 +0000613static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000614list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000615{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000616 /* Because [X]DECREF can recursively invoke list operations on
617 this list, we must postpone all [X]DECREF activity until
618 after the list is back in its canonical shape. Therefore
619 we must allocate an additional array, 'recycle', into which
620 we temporarily copy the items that are deleted from the
621 list. :-( */
Tim Peters73572222004-07-31 02:54:42 +0000622 PyObject *recycle_on_stack[8];
623 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000624 PyObject **item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000625 PyObject **vitem = NULL;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000626 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000627 Py_ssize_t n; /* # of elements in replacement list */
628 Py_ssize_t norig; /* # of elements in list getting replaced */
629 Py_ssize_t d; /* Change in size */
630 Py_ssize_t k;
Tim Peters8d9eb102004-07-31 02:24:20 +0000631 size_t s;
632 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000633#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000634 if (v == NULL)
635 n = 0;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000636 else {
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000637 if (a == b) {
638 /* Special case "a[i:j] = a" -- copy b first */
Christian Heimese93237d2007-12-19 02:37:44 +0000639 v = list_slice(b, 0, Py_SIZE(b));
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000640 if (v == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000641 return result;
642 result = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000643 Py_DECREF(v);
Tim Peters8d9eb102004-07-31 02:24:20 +0000644 return result;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000645 }
Raymond Hettingerf889e102004-03-09 08:04:33 +0000646 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000647 if(v_as_SF == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000648 goto Error;
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000649 n = PySequence_Fast_GET_SIZE(v_as_SF);
Raymond Hettinger42bec932004-03-12 16:38:17 +0000650 vitem = PySequence_Fast_ITEMS(v_as_SF);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000651 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000652 if (ilow < 0)
653 ilow = 0;
Christian Heimese93237d2007-12-19 02:37:44 +0000654 else if (ilow > Py_SIZE(a))
655 ilow = Py_SIZE(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000656
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000657 if (ihigh < ilow)
658 ihigh = ilow;
Christian Heimese93237d2007-12-19 02:37:44 +0000659 else if (ihigh > Py_SIZE(a))
660 ihigh = Py_SIZE(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000661
Tim Peters8d9eb102004-07-31 02:24:20 +0000662 norig = ihigh - ilow;
663 assert(norig >= 0);
664 d = n - norig;
Christian Heimese93237d2007-12-19 02:37:44 +0000665 if (Py_SIZE(a) + d == 0) {
Armin Rigo93677f02004-07-29 12:40:23 +0000666 Py_XDECREF(v_as_SF);
667 return list_clear(a);
668 }
669 item = a->ob_item;
Tim Peters8d9eb102004-07-31 02:24:20 +0000670 /* recycle the items that we are about to remove */
671 s = norig * sizeof(PyObject *);
Tim Peters73572222004-07-31 02:54:42 +0000672 if (s > sizeof(recycle_on_stack)) {
Armin Rigo1dd04a02004-07-30 11:38:22 +0000673 recycle = (PyObject **)PyMem_MALLOC(s);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000674 if (recycle == NULL) {
675 PyErr_NoMemory();
Tim Peters8d9eb102004-07-31 02:24:20 +0000676 goto Error;
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000677 }
678 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000679 memcpy(recycle, &item[ilow], s);
Tim Peters8d9eb102004-07-31 02:24:20 +0000680
Armin Rigo1dd04a02004-07-30 11:38:22 +0000681 if (d < 0) { /* Delete -d items */
682 memmove(&item[ihigh+d], &item[ihigh],
Christian Heimese93237d2007-12-19 02:37:44 +0000683 (Py_SIZE(a) - ihigh)*sizeof(PyObject *));
684 list_resize(a, Py_SIZE(a) + d);
Armin Rigo1dd04a02004-07-30 11:38:22 +0000685 item = a->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000686 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000687 else if (d > 0) { /* Insert d items */
Christian Heimese93237d2007-12-19 02:37:44 +0000688 k = Py_SIZE(a);
Tim Peters73572222004-07-31 02:54:42 +0000689 if (list_resize(a, k+d) < 0)
Tim Peters8d9eb102004-07-31 02:24:20 +0000690 goto Error;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000691 item = a->ob_item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000692 memmove(&item[ihigh+d], &item[ihigh],
Tim Peters73572222004-07-31 02:54:42 +0000693 (k - ihigh)*sizeof(PyObject *));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000694 }
695 for (k = 0; k < n; k++, ilow++) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000696 PyObject *w = vitem[k];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000697 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000698 item[ilow] = w;
699 }
Tim Peters73572222004-07-31 02:54:42 +0000700 for (k = norig - 1; k >= 0; --k)
701 Py_XDECREF(recycle[k]);
Tim Peters8d9eb102004-07-31 02:24:20 +0000702 result = 0;
703 Error:
Tim Peters73572222004-07-31 02:54:42 +0000704 if (recycle != recycle_on_stack)
Armin Rigo1dd04a02004-07-30 11:38:22 +0000705 PyMem_FREE(recycle);
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000706 Py_XDECREF(v_as_SF);
Tim Peters8d9eb102004-07-31 02:24:20 +0000707 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000708#undef b
709}
710
Guido van Rossum234f9421993-06-17 12:35:49 +0000711int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000712PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000713{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000714 if (!PyList_Check(a)) {
715 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000716 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000717 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000718 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000719}
720
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000721static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000722list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000723{
724 PyObject **items;
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000725 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000726
727
728 size = PyList_GET_SIZE(self);
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000729 if (size == 0 || n == 1) {
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000730 Py_INCREF(self);
731 return (PyObject *)self;
732 }
733
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000734 if (n < 1) {
Armin Rigo93677f02004-07-29 12:40:23 +0000735 (void)list_clear(self);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000736 Py_INCREF(self);
737 return (PyObject *)self;
738 }
739
Thomas Woutersa97744c2008-01-25 21:09:34 +0000740 if (size > PY_SSIZE_T_MAX / n) {
Armin Rigoa1e42e12007-10-17 18:46:37 +0000741 return PyErr_NoMemory();
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000742 }
743
744 if (list_resize(self, size*n) == -1)
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000745 return NULL;
746
747 p = size;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000748 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000749 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
750 for (j = 0; j < size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000751 PyObject *o = items[j];
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000752 Py_INCREF(o);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000753 items[p++] = o;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000754 }
755 }
756 Py_INCREF(self);
757 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000758}
759
Guido van Rossum4a450d01991-04-03 19:05:18 +0000760static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000761list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000762{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000763 PyObject *old_value;
Christian Heimese93237d2007-12-19 02:37:44 +0000764 if (i < 0 || i >= Py_SIZE(a)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000765 PyErr_SetString(PyExc_IndexError,
766 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000767 return -1;
768 }
769 if (v == NULL)
770 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000771 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000772 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000773 a->ob_item[i] = v;
Tim Peters3b01a122002-07-19 02:35:45 +0000774 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000775 return 0;
776}
777
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000778static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000779listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000780{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000781 Py_ssize_t i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000782 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000783 if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000784 return NULL;
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000785 if (ins1(self, i, v) == 0)
786 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000787 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000788}
789
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000790static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000791listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000792{
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000793 if (app1(self, v) == 0)
794 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000795 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000796}
797
Barry Warsawdedf6d61998-10-09 16:37:25 +0000798static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000799listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000800{
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000801 PyObject *it; /* iter(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000802 Py_ssize_t m; /* size of self */
803 Py_ssize_t n; /* guess for size of b */
804 Py_ssize_t mn; /* m + n */
805 Py_ssize_t i;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000806 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000807
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000808 /* Special cases:
Tim Petersb38e2b62004-07-29 02:29:26 +0000809 1) lists and tuples which can use PySequence_Fast ops
810 2) extending self to self requires making a copy first
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000811 */
812 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
Armin Rigo70d172d2004-03-20 22:19:23 +0000813 PyObject **src, **dest;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000814 b = PySequence_Fast(b, "argument must be iterable");
815 if (!b)
816 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000817 n = PySequence_Fast_GET_SIZE(b);
818 if (n == 0) {
819 /* short circuit when b is empty */
820 Py_DECREF(b);
821 Py_RETURN_NONE;
822 }
Christian Heimese93237d2007-12-19 02:37:44 +0000823 m = Py_SIZE(self);
Armin Rigo70d172d2004-03-20 22:19:23 +0000824 if (list_resize(self, m + n) == -1) {
825 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000826 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000827 }
828 /* note that we may still have self == b here for the
829 * situation a.extend(a), but the following code works
830 * in that case too. Just make sure to resize self
831 * before calling PySequence_Fast_ITEMS.
832 */
833 /* populate the end of self with b's items */
834 src = PySequence_Fast_ITEMS(b);
835 dest = self->ob_item + m;
836 for (i = 0; i < n; i++) {
837 PyObject *o = src[i];
838 Py_INCREF(o);
839 dest[i] = o;
840 }
841 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000842 Py_RETURN_NONE;
843 }
844
845 it = PyObject_GetIter(b);
846 if (it == NULL)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000847 return NULL;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000848 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000849
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000850 /* Guess a result list size. */
Raymond Hettinger4e2f7142007-12-06 00:56:53 +0000851 n = _PyObject_LengthHint(b, 8);
Raymond Hettingerb5163702009-02-02 21:50:13 +0000852 if (n == -1) {
853 Py_DECREF(it);
854 return NULL;
855 }
Christian Heimese93237d2007-12-19 02:37:44 +0000856 m = Py_SIZE(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000857 mn = m + n;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000858 if (mn >= m) {
859 /* Make room. */
860 if (list_resize(self, mn) == -1)
861 goto error;
862 /* Make the list sane again. */
Christian Heimese93237d2007-12-19 02:37:44 +0000863 Py_SIZE(self) = m;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000864 }
865 /* Else m + n overflowed; on the chance that n lied, and there really
866 * is enough room, ignore it. If n was telling the truth, we'll
867 * eventually run out of memory during the loop.
868 */
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000869
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000870 /* Run iterator to exhaustion. */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000871 for (;;) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000872 PyObject *item = iternext(it);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000873 if (item == NULL) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000874 if (PyErr_Occurred()) {
875 if (PyErr_ExceptionMatches(PyExc_StopIteration))
876 PyErr_Clear();
877 else
878 goto error;
879 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000880 break;
881 }
Christian Heimese93237d2007-12-19 02:37:44 +0000882 if (Py_SIZE(self) < self->allocated) {
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000883 /* steals ref */
Christian Heimese93237d2007-12-19 02:37:44 +0000884 PyList_SET_ITEM(self, Py_SIZE(self), item);
885 ++Py_SIZE(self);
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000886 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000887 else {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000888 int status = app1(self, item);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000889 Py_DECREF(item); /* append creates a new ref */
890 if (status < 0)
891 goto error;
892 }
893 }
894
895 /* Cut back result list if initial guess was too large. */
Christian Heimese93237d2007-12-19 02:37:44 +0000896 if (Py_SIZE(self) < self->allocated)
897 list_resize(self, Py_SIZE(self)); /* shrinking can't fail */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000898
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000899 Py_DECREF(it);
900 Py_RETURN_NONE;
901
902 error:
903 Py_DECREF(it);
904 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000905}
906
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000907PyObject *
908_PyList_Extend(PyListObject *self, PyObject *b)
909{
910 return listextend(self, b);
911}
912
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000913static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000914list_inplace_concat(PyListObject *self, PyObject *other)
915{
916 PyObject *result;
917
918 result = listextend(self, other);
919 if (result == NULL)
920 return result;
921 Py_DECREF(result);
922 Py_INCREF(self);
923 return (PyObject *)self;
924}
925
926static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000927listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000928{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000929 Py_ssize_t i = -1;
Armin Rigo7ccbca92006-10-04 12:17:45 +0000930 PyObject *v;
Tim Peters8fc4a912004-07-31 21:53:19 +0000931 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000932
Armin Rigo7ccbca92006-10-04 12:17:45 +0000933 if (!PyArg_ParseTuple(args, "|n:pop", &i))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000934 return NULL;
Armin Rigo7ccbca92006-10-04 12:17:45 +0000935
Christian Heimese93237d2007-12-19 02:37:44 +0000936 if (Py_SIZE(self) == 0) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000937 /* Special-case most common failure cause */
938 PyErr_SetString(PyExc_IndexError, "pop from empty list");
939 return NULL;
940 }
941 if (i < 0)
Christian Heimese93237d2007-12-19 02:37:44 +0000942 i += Py_SIZE(self);
943 if (i < 0 || i >= Py_SIZE(self)) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000944 PyErr_SetString(PyExc_IndexError, "pop index out of range");
945 return NULL;
946 }
947 v = self->ob_item[i];
Christian Heimese93237d2007-12-19 02:37:44 +0000948 if (i == Py_SIZE(self) - 1) {
949 status = list_resize(self, Py_SIZE(self) - 1);
Tim Peters8fc4a912004-07-31 21:53:19 +0000950 assert(status >= 0);
951 return v; /* and v now owns the reference the list had */
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000952 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000953 Py_INCREF(v);
Tim Peters8fc4a912004-07-31 21:53:19 +0000954 status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
955 assert(status >= 0);
956 /* Use status, so that in a release build compilers don't
957 * complain about the unused name.
958 */
Brett Cannon651dd522004-08-08 21:21:18 +0000959 (void) status;
960
961 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000962}
963
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000964/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
965static void
966reverse_slice(PyObject **lo, PyObject **hi)
967{
968 assert(lo && hi);
969
970 --hi;
971 while (lo < hi) {
972 PyObject *t = *lo;
973 *lo = *hi;
974 *hi = t;
975 ++lo;
976 --hi;
977 }
978}
979
Tim Petersa64dc242002-08-01 02:13:36 +0000980/* Lots of code for an adaptive, stable, natural mergesort. There are many
981 * pieces to this algorithm; read listsort.txt for overviews and details.
982 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000983
Guido van Rossum3f236de1996-12-10 23:55:39 +0000984/* Comparison function. Takes care of calling a user-supplied
Tim Peters66860f62002-08-04 17:47:26 +0000985 * comparison function (any callable Python object), which must not be
986 * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool
987 * with Py_LT if you know it's NULL).
Tim Petersa64dc242002-08-01 02:13:36 +0000988 * Returns -1 on error, 1 if x < y, 0 if x >= y.
989 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000990static int
Tim Petersa8c974c2002-07-19 03:30:57 +0000991islt(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000992{
Tim Petersf2a04732002-07-11 21:46:16 +0000993 PyObject *res;
994 PyObject *args;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000995 Py_ssize_t i;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000996
Tim Peters66860f62002-08-04 17:47:26 +0000997 assert(compare != NULL);
Tim Petersa8c974c2002-07-19 03:30:57 +0000998 /* Call the user's comparison function and translate the 3-way
999 * result into true or false (or error).
1000 */
Tim Petersf2a04732002-07-11 21:46:16 +00001001 args = PyTuple_New(2);
Guido van Rossum3f236de1996-12-10 23:55:39 +00001002 if (args == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +00001003 return -1;
Tim Petersf2a04732002-07-11 21:46:16 +00001004 Py_INCREF(x);
1005 Py_INCREF(y);
1006 PyTuple_SET_ITEM(args, 0, x);
1007 PyTuple_SET_ITEM(args, 1, y);
Tim Peters58cf3612002-07-15 05:16:13 +00001008 res = PyObject_Call(compare, args, NULL);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001009 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +00001010 if (res == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +00001011 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001012 if (!PyInt_Check(res)) {
Georg Brandl283a1352006-11-19 08:48:30 +00001013 PyErr_Format(PyExc_TypeError,
1014 "comparison function must return int, not %.200s",
1015 res->ob_type->tp_name);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001016 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +00001017 return -1;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001018 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001019 i = PyInt_AsLong(res);
1020 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +00001021 return i < 0;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001022}
1023
Tim Peters66860f62002-08-04 17:47:26 +00001024/* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
1025 * islt. This avoids a layer of function call in the usual case, and
1026 * sorting does many comparisons.
1027 * Returns -1 on error, 1 if x < y, 0 if x >= y.
1028 */
1029#define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
1030 PyObject_RichCompareBool(X, Y, Py_LT) : \
1031 islt(X, Y, COMPARE))
1032
1033/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +00001034 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
1035 started. It makes more sense in context <wink>. X and Y are PyObject*s.
1036*/
Tim Peters66860f62002-08-04 17:47:26 +00001037#define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
Tim Petersa8c974c2002-07-19 03:30:57 +00001038 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001039
1040/* binarysort is the best method for sorting small arrays: it does
1041 few compares, but can do data movement quadratic in the number of
1042 elements.
Guido van Rossum42812581998-06-17 14:15:44 +00001043 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +00001044 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001045 On entry, must have lo <= start <= hi, and that [lo, start) is already
1046 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +00001047 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001048 Even in case of error, the output slice will be some permutation of
1049 the input (nothing is lost or duplicated).
1050*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00001051static int
Fred Drakea2f55112000-07-09 15:16:51 +00001052binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
1053 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001054{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001055 register Py_ssize_t k;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001056 register PyObject **l, **p, **r;
1057 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001058
Tim Petersa8c974c2002-07-19 03:30:57 +00001059 assert(lo <= start && start <= hi);
1060 /* assert [lo, start) is sorted */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001061 if (lo == start)
1062 ++start;
1063 for (; start < hi; ++start) {
1064 /* set l to where *start belongs */
1065 l = lo;
1066 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001067 pivot = *r;
Tim Peters0fe977c2002-07-19 06:12:32 +00001068 /* Invariants:
1069 * pivot >= all in [lo, l).
1070 * pivot < all in [r, start).
1071 * The second is vacuously true at the start.
1072 */
1073 assert(l < r);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001074 do {
1075 p = l + ((r - l) >> 1);
Tim Petersa8c974c2002-07-19 03:30:57 +00001076 IFLT(pivot, *p)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001077 r = p;
1078 else
Tim Peters0fe977c2002-07-19 06:12:32 +00001079 l = p+1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001080 } while (l < r);
Tim Peters0fe977c2002-07-19 06:12:32 +00001081 assert(l == r);
1082 /* The invariants still hold, so pivot >= all in [lo, l) and
1083 pivot < all in [l, start), so pivot belongs at l. Note
1084 that if there are elements equal to pivot, l points to the
1085 first slot after them -- that's why this sort is stable.
1086 Slide over to make room.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001087 Caution: using memmove is much slower under MSVC 5;
1088 we're not usually moving many slots. */
1089 for (p = start; p > l; --p)
1090 *p = *(p-1);
1091 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001092 }
Guido van Rossum3f236de1996-12-10 23:55:39 +00001093 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001094
1095 fail:
1096 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001097}
1098
Tim Petersa64dc242002-08-01 02:13:36 +00001099/*
1100Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1101is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001102
Tim Petersa64dc242002-08-01 02:13:36 +00001103 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001104
Tim Petersa64dc242002-08-01 02:13:36 +00001105or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001106
Tim Petersa64dc242002-08-01 02:13:36 +00001107 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001108
Tim Petersa64dc242002-08-01 02:13:36 +00001109Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1110For its intended use in a stable mergesort, the strictness of the defn of
1111"descending" is needed so that the caller can safely reverse a descending
1112sequence without violating stability (strict > ensures there are no equal
1113elements to get out of order).
1114
1115Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001116*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001117static Py_ssize_t
Tim Petersa64dc242002-08-01 02:13:36 +00001118count_run(PyObject **lo, PyObject **hi, PyObject *compare, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001119{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001120 Py_ssize_t k;
1121 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001122
Tim Petersa64dc242002-08-01 02:13:36 +00001123 assert(lo < hi);
1124 *descending = 0;
1125 ++lo;
1126 if (lo == hi)
1127 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001128
Tim Petersa64dc242002-08-01 02:13:36 +00001129 n = 2;
1130 IFLT(*lo, *(lo-1)) {
1131 *descending = 1;
1132 for (lo = lo+1; lo < hi; ++lo, ++n) {
1133 IFLT(*lo, *(lo-1))
1134 ;
1135 else
1136 break;
1137 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001138 }
Tim Petersa64dc242002-08-01 02:13:36 +00001139 else {
1140 for (lo = lo+1; lo < hi; ++lo, ++n) {
1141 IFLT(*lo, *(lo-1))
1142 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001143 }
1144 }
1145
Tim Petersa64dc242002-08-01 02:13:36 +00001146 return n;
1147fail:
1148 return -1;
1149}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001150
Tim Petersa64dc242002-08-01 02:13:36 +00001151/*
1152Locate the proper position of key in a sorted vector; if the vector contains
1153an element equal to key, return the position immediately to the left of
1154the leftmost equal element. [gallop_right() does the same except returns
1155the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001156
Tim Petersa64dc242002-08-01 02:13:36 +00001157"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001158
Tim Petersa64dc242002-08-01 02:13:36 +00001159"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1160hint is to the final result, the faster this runs.
1161
1162The return value is the int k in 0..n such that
1163
1164 a[k-1] < key <= a[k]
1165
1166pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1167key belongs at index k; or, IOW, the first k elements of a should precede
1168key, and the last n-k should follow key.
1169
1170Returns -1 on error. See listsort.txt for info on the method.
1171*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001172static Py_ssize_t
1173gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
Tim Petersa64dc242002-08-01 02:13:36 +00001174{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001175 Py_ssize_t ofs;
1176 Py_ssize_t lastofs;
1177 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001178
1179 assert(key && a && n > 0 && hint >= 0 && hint < n);
1180
1181 a += hint;
1182 lastofs = 0;
1183 ofs = 1;
1184 IFLT(*a, key) {
1185 /* a[hint] < key -- gallop right, until
1186 * a[hint + lastofs] < key <= a[hint + ofs]
1187 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001188 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001189 while (ofs < maxofs) {
1190 IFLT(a[ofs], key) {
1191 lastofs = ofs;
1192 ofs = (ofs << 1) + 1;
1193 if (ofs <= 0) /* int overflow */
1194 ofs = maxofs;
1195 }
1196 else /* key <= a[hint + ofs] */
1197 break;
1198 }
1199 if (ofs > maxofs)
1200 ofs = maxofs;
1201 /* Translate back to offsets relative to &a[0]. */
1202 lastofs += hint;
1203 ofs += hint;
1204 }
1205 else {
1206 /* key <= a[hint] -- gallop left, until
1207 * a[hint - ofs] < key <= a[hint - lastofs]
1208 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001209 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001210 while (ofs < maxofs) {
1211 IFLT(*(a-ofs), key)
1212 break;
1213 /* key <= a[hint - ofs] */
1214 lastofs = ofs;
1215 ofs = (ofs << 1) + 1;
1216 if (ofs <= 0) /* int overflow */
1217 ofs = maxofs;
1218 }
1219 if (ofs > maxofs)
1220 ofs = maxofs;
1221 /* Translate back to positive offsets relative to &a[0]. */
1222 k = lastofs;
1223 lastofs = hint - ofs;
1224 ofs = hint - k;
1225 }
1226 a -= hint;
1227
1228 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1229 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1230 * right of lastofs but no farther right than ofs. Do a binary
1231 * search, with invariant a[lastofs-1] < key <= a[ofs].
1232 */
1233 ++lastofs;
1234 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001235 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001236
1237 IFLT(a[m], key)
1238 lastofs = m+1; /* a[m] < key */
1239 else
1240 ofs = m; /* key <= a[m] */
1241 }
1242 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1243 return ofs;
1244
1245fail:
1246 return -1;
1247}
1248
1249/*
1250Exactly like gallop_left(), except that if key already exists in a[0:n],
1251finds the position immediately to the right of the rightmost equal value.
1252
1253The return value is the int k in 0..n such that
1254
1255 a[k-1] <= key < a[k]
1256
1257or -1 if error.
1258
1259The code duplication is massive, but this is enough different given that
1260we're sticking to "<" comparisons that it's much harder to follow if
1261written as one routine with yet another "left or right?" flag.
1262*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001263static Py_ssize_t
1264gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
Tim Petersa64dc242002-08-01 02:13:36 +00001265{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001266 Py_ssize_t ofs;
1267 Py_ssize_t lastofs;
1268 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001269
1270 assert(key && a && n > 0 && hint >= 0 && hint < n);
1271
1272 a += hint;
1273 lastofs = 0;
1274 ofs = 1;
1275 IFLT(key, *a) {
1276 /* key < a[hint] -- gallop left, until
1277 * a[hint - ofs] <= key < a[hint - lastofs]
1278 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001279 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001280 while (ofs < maxofs) {
1281 IFLT(key, *(a-ofs)) {
1282 lastofs = ofs;
1283 ofs = (ofs << 1) + 1;
1284 if (ofs <= 0) /* int overflow */
1285 ofs = maxofs;
1286 }
1287 else /* a[hint - ofs] <= key */
1288 break;
1289 }
1290 if (ofs > maxofs)
1291 ofs = maxofs;
1292 /* Translate back to positive offsets relative to &a[0]. */
1293 k = lastofs;
1294 lastofs = hint - ofs;
1295 ofs = hint - k;
1296 }
1297 else {
1298 /* a[hint] <= key -- gallop right, until
1299 * a[hint + lastofs] <= key < a[hint + ofs]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001300 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001301 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001302 while (ofs < maxofs) {
1303 IFLT(key, a[ofs])
1304 break;
1305 /* a[hint + ofs] <= key */
1306 lastofs = ofs;
1307 ofs = (ofs << 1) + 1;
1308 if (ofs <= 0) /* int overflow */
1309 ofs = maxofs;
1310 }
1311 if (ofs > maxofs)
1312 ofs = maxofs;
1313 /* Translate back to offsets relative to &a[0]. */
1314 lastofs += hint;
1315 ofs += hint;
1316 }
1317 a -= hint;
1318
1319 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1320 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1321 * right of lastofs but no farther right than ofs. Do a binary
1322 * search, with invariant a[lastofs-1] <= key < a[ofs].
1323 */
1324 ++lastofs;
1325 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001326 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001327
1328 IFLT(key, a[m])
1329 ofs = m; /* key < a[m] */
1330 else
1331 lastofs = m+1; /* a[m] <= key */
1332 }
1333 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1334 return ofs;
1335
1336fail:
1337 return -1;
1338}
1339
1340/* The maximum number of entries in a MergeState's pending-runs stack.
1341 * This is enough to sort arrays of size up to about
1342 * 32 * phi ** MAX_MERGE_PENDING
1343 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1344 * with 2**64 elements.
1345 */
1346#define MAX_MERGE_PENDING 85
1347
Tim Peterse05f65a2002-08-10 05:21:15 +00001348/* When we get into galloping mode, we stay there until both runs win less
1349 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001350 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001351#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001352
1353/* Avoid malloc for small temp arrays. */
1354#define MERGESTATE_TEMP_SIZE 256
1355
1356/* One MergeState exists on the stack per invocation of mergesort. It's just
1357 * a convenient way to pass state around among the helper functions.
1358 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001359struct s_slice {
1360 PyObject **base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001361 Py_ssize_t len;
Tim Peterse05f65a2002-08-10 05:21:15 +00001362};
1363
Tim Petersa64dc242002-08-01 02:13:36 +00001364typedef struct s_MergeState {
1365 /* The user-supplied comparison function. or NULL if none given. */
1366 PyObject *compare;
1367
Tim Peterse05f65a2002-08-10 05:21:15 +00001368 /* This controls when we get *into* galloping mode. It's initialized
1369 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1370 * random data, and lower for highly structured data.
1371 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001372 Py_ssize_t min_gallop;
Tim Peterse05f65a2002-08-10 05:21:15 +00001373
Tim Petersa64dc242002-08-01 02:13:36 +00001374 /* 'a' is temp storage to help with merges. It contains room for
1375 * alloced entries.
1376 */
1377 PyObject **a; /* may point to temparray below */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001378 Py_ssize_t alloced;
Tim Petersa64dc242002-08-01 02:13:36 +00001379
1380 /* A stack of n pending runs yet to be merged. Run #i starts at
1381 * address base[i] and extends for len[i] elements. It's always
1382 * true (so long as the indices are in bounds) that
1383 *
Tim Peterse05f65a2002-08-10 05:21:15 +00001384 * pending[i].base + pending[i].len == pending[i+1].base
Tim Petersa64dc242002-08-01 02:13:36 +00001385 *
1386 * so we could cut the storage for this, but it's a minor amount,
1387 * and keeping all the info explicit simplifies the code.
1388 */
1389 int n;
Tim Peterse05f65a2002-08-10 05:21:15 +00001390 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001391
1392 /* 'a' points to this when possible, rather than muck with malloc. */
1393 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1394} MergeState;
1395
1396/* Conceptually a MergeState's constructor. */
1397static void
1398merge_init(MergeState *ms, PyObject *compare)
1399{
1400 assert(ms != NULL);
1401 ms->compare = compare;
1402 ms->a = ms->temparray;
1403 ms->alloced = MERGESTATE_TEMP_SIZE;
1404 ms->n = 0;
Tim Peterse05f65a2002-08-10 05:21:15 +00001405 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001406}
1407
1408/* Free all the temp memory owned by the MergeState. This must be called
1409 * when you're done with a MergeState, and may be called before then if
1410 * you want to free the temp memory early.
1411 */
1412static void
1413merge_freemem(MergeState *ms)
1414{
1415 assert(ms != NULL);
1416 if (ms->a != ms->temparray)
1417 PyMem_Free(ms->a);
1418 ms->a = ms->temparray;
1419 ms->alloced = MERGESTATE_TEMP_SIZE;
1420}
1421
1422/* Ensure enough temp memory for 'need' array slots is available.
1423 * Returns 0 on success and -1 if the memory can't be gotten.
1424 */
1425static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001426merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001427{
1428 assert(ms != NULL);
1429 if (need <= ms->alloced)
1430 return 0;
1431 /* Don't realloc! That can cost cycles to copy the old data, but
1432 * we don't care what's in the block.
1433 */
1434 merge_freemem(ms);
Mark Dickinsonac5685e2010-02-14 12:16:43 +00001435 if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject*)) {
Gregory P. Smith9d534572008-06-11 07:41:16 +00001436 PyErr_NoMemory();
1437 return -1;
1438 }
Tim Petersa64dc242002-08-01 02:13:36 +00001439 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1440 if (ms->a) {
1441 ms->alloced = need;
1442 return 0;
1443 }
1444 PyErr_NoMemory();
1445 merge_freemem(ms); /* reset to sane state */
1446 return -1;
1447}
1448#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1449 merge_getmem(MS, NEED))
1450
1451/* Merge the na elements starting at pa with the nb elements starting at pb
1452 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1453 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1454 * merge, and should have na <= nb. See listsort.txt for more info.
1455 * Return 0 if successful, -1 if error.
1456 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001457static Py_ssize_t
1458merge_lo(MergeState *ms, PyObject **pa, Py_ssize_t na,
1459 PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001460{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001461 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001462 PyObject *compare;
1463 PyObject **dest;
1464 int result = -1; /* guilty until proved innocent */
Neal Norwitz7fd96072006-08-19 04:28:55 +00001465 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001466
1467 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1468 if (MERGE_GETMEM(ms, na) < 0)
1469 return -1;
1470 memcpy(ms->a, pa, na * sizeof(PyObject*));
1471 dest = pa;
1472 pa = ms->a;
1473
1474 *dest++ = *pb++;
1475 --nb;
1476 if (nb == 0)
1477 goto Succeed;
1478 if (na == 1)
1479 goto CopyB;
1480
Neal Norwitz7fd96072006-08-19 04:28:55 +00001481 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001482 compare = ms->compare;
1483 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001484 Py_ssize_t acount = 0; /* # of times A won in a row */
1485 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001486
1487 /* Do the straightforward thing until (if ever) one run
1488 * appears to win consistently.
1489 */
1490 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001491 assert(na > 1 && nb > 0);
Tim Peters66860f62002-08-04 17:47:26 +00001492 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001493 if (k) {
1494 if (k < 0)
1495 goto Fail;
1496 *dest++ = *pb++;
1497 ++bcount;
1498 acount = 0;
1499 --nb;
1500 if (nb == 0)
1501 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001502 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001503 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001504 }
1505 else {
Tim Petersa64dc242002-08-01 02:13:36 +00001506 *dest++ = *pa++;
1507 ++acount;
1508 bcount = 0;
1509 --na;
1510 if (na == 1)
1511 goto CopyB;
Tim Peterse05f65a2002-08-10 05:21:15 +00001512 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001513 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001514 }
Tim Petersa64dc242002-08-01 02:13:36 +00001515 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001516
Tim Petersa64dc242002-08-01 02:13:36 +00001517 /* One run is winning so consistently that galloping may
1518 * be a huge win. So try that, and continue galloping until
1519 * (if ever) neither run appears to be winning consistently
1520 * anymore.
1521 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001522 ++min_gallop;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001523 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001524 assert(na > 1 && nb > 0);
1525 min_gallop -= min_gallop > 1;
1526 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001527 k = gallop_right(*pb, pa, na, 0, compare);
1528 acount = k;
1529 if (k) {
1530 if (k < 0)
1531 goto Fail;
1532 memcpy(dest, pa, k * sizeof(PyObject *));
1533 dest += k;
1534 pa += k;
1535 na -= k;
1536 if (na == 1)
1537 goto CopyB;
1538 /* na==0 is impossible now if the comparison
1539 * function is consistent, but we can't assume
1540 * that it is.
1541 */
1542 if (na == 0)
1543 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001544 }
Tim Petersa64dc242002-08-01 02:13:36 +00001545 *dest++ = *pb++;
1546 --nb;
1547 if (nb == 0)
1548 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001549
Tim Petersa64dc242002-08-01 02:13:36 +00001550 k = gallop_left(*pa, pb, nb, 0, compare);
1551 bcount = k;
1552 if (k) {
1553 if (k < 0)
1554 goto Fail;
1555 memmove(dest, pb, k * sizeof(PyObject *));
1556 dest += k;
1557 pb += k;
1558 nb -= k;
1559 if (nb == 0)
1560 goto Succeed;
1561 }
1562 *dest++ = *pa++;
1563 --na;
1564 if (na == 1)
1565 goto CopyB;
1566 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001567 ++min_gallop; /* penalize it for leaving galloping mode */
1568 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001569 }
1570Succeed:
1571 result = 0;
1572Fail:
1573 if (na)
1574 memcpy(dest, pa, na * sizeof(PyObject*));
1575 return result;
1576CopyB:
1577 assert(na == 1 && nb > 0);
1578 /* The last element of pa belongs at the end of the merge. */
1579 memmove(dest, pb, nb * sizeof(PyObject *));
1580 dest[nb] = *pa;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001581 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001582}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001583
Tim Petersa64dc242002-08-01 02:13:36 +00001584/* Merge the na elements starting at pa with the nb elements starting at pb
1585 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1586 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1587 * merge, and should have na >= nb. See listsort.txt for more info.
1588 * Return 0 if successful, -1 if error.
1589 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001590static Py_ssize_t
1591merge_hi(MergeState *ms, PyObject **pa, Py_ssize_t na, PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001592{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001593 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001594 PyObject *compare;
1595 PyObject **dest;
1596 int result = -1; /* guilty until proved innocent */
1597 PyObject **basea;
1598 PyObject **baseb;
Neal Norwitz7fd96072006-08-19 04:28:55 +00001599 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001600
1601 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1602 if (MERGE_GETMEM(ms, nb) < 0)
1603 return -1;
1604 dest = pb + nb - 1;
1605 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1606 basea = pa;
1607 baseb = ms->a;
1608 pb = ms->a + nb - 1;
1609 pa += na - 1;
1610
1611 *dest-- = *pa--;
1612 --na;
1613 if (na == 0)
1614 goto Succeed;
1615 if (nb == 1)
1616 goto CopyA;
1617
Neal Norwitz7fd96072006-08-19 04:28:55 +00001618 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001619 compare = ms->compare;
1620 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001621 Py_ssize_t acount = 0; /* # of times A won in a row */
1622 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001623
1624 /* Do the straightforward thing until (if ever) one run
1625 * appears to win consistently.
1626 */
1627 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001628 assert(na > 0 && nb > 1);
Tim Peters66860f62002-08-04 17:47:26 +00001629 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001630 if (k) {
1631 if (k < 0)
1632 goto Fail;
1633 *dest-- = *pa--;
1634 ++acount;
1635 bcount = 0;
1636 --na;
1637 if (na == 0)
1638 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001639 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001640 break;
1641 }
1642 else {
1643 *dest-- = *pb--;
1644 ++bcount;
1645 acount = 0;
1646 --nb;
1647 if (nb == 1)
1648 goto CopyA;
Tim Peterse05f65a2002-08-10 05:21:15 +00001649 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001650 break;
1651 }
1652 }
1653
1654 /* One run is winning so consistently that galloping may
1655 * be a huge win. So try that, and continue galloping until
1656 * (if ever) neither run appears to be winning consistently
1657 * anymore.
1658 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001659 ++min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001660 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001661 assert(na > 0 && nb > 1);
1662 min_gallop -= min_gallop > 1;
1663 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001664 k = gallop_right(*pb, basea, na, na-1, compare);
1665 if (k < 0)
1666 goto Fail;
1667 k = na - k;
1668 acount = k;
1669 if (k) {
1670 dest -= k;
1671 pa -= k;
1672 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1673 na -= k;
1674 if (na == 0)
1675 goto Succeed;
1676 }
1677 *dest-- = *pb--;
1678 --nb;
1679 if (nb == 1)
1680 goto CopyA;
1681
1682 k = gallop_left(*pa, baseb, nb, nb-1, compare);
1683 if (k < 0)
1684 goto Fail;
1685 k = nb - k;
1686 bcount = k;
1687 if (k) {
1688 dest -= k;
1689 pb -= k;
1690 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1691 nb -= k;
1692 if (nb == 1)
1693 goto CopyA;
1694 /* nb==0 is impossible now if the comparison
1695 * function is consistent, but we can't assume
1696 * that it is.
1697 */
1698 if (nb == 0)
1699 goto Succeed;
1700 }
1701 *dest-- = *pa--;
1702 --na;
1703 if (na == 0)
1704 goto Succeed;
1705 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001706 ++min_gallop; /* penalize it for leaving galloping mode */
1707 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001708 }
1709Succeed:
1710 result = 0;
1711Fail:
1712 if (nb)
1713 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1714 return result;
1715CopyA:
1716 assert(nb == 1 && na > 0);
1717 /* The first element of pb belongs at the front of the merge. */
1718 dest -= na;
1719 pa -= na;
1720 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1721 *dest = *pb;
1722 return 0;
1723}
1724
1725/* Merge the two runs at stack indices i and i+1.
1726 * Returns 0 on success, -1 on error.
1727 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001728static Py_ssize_t
1729merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001730{
1731 PyObject **pa, **pb;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001732 Py_ssize_t na, nb;
1733 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001734 PyObject *compare;
1735
1736 assert(ms != NULL);
1737 assert(ms->n >= 2);
1738 assert(i >= 0);
1739 assert(i == ms->n - 2 || i == ms->n - 3);
1740
Tim Peterse05f65a2002-08-10 05:21:15 +00001741 pa = ms->pending[i].base;
1742 na = ms->pending[i].len;
1743 pb = ms->pending[i+1].base;
1744 nb = ms->pending[i+1].len;
Tim Petersa64dc242002-08-01 02:13:36 +00001745 assert(na > 0 && nb > 0);
1746 assert(pa + na == pb);
1747
1748 /* Record the length of the combined runs; if i is the 3rd-last
1749 * run now, also slide over the last run (which isn't involved
1750 * in this merge). The current run i+1 goes away in any case.
1751 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001752 ms->pending[i].len = na + nb;
1753 if (i == ms->n - 3)
1754 ms->pending[i+1] = ms->pending[i+2];
Tim Petersa64dc242002-08-01 02:13:36 +00001755 --ms->n;
1756
1757 /* Where does b start in a? Elements in a before that can be
1758 * ignored (already in place).
1759 */
1760 compare = ms->compare;
1761 k = gallop_right(*pb, pa, na, 0, compare);
1762 if (k < 0)
1763 return -1;
1764 pa += k;
1765 na -= k;
1766 if (na == 0)
1767 return 0;
1768
1769 /* Where does a end in b? Elements in b after that can be
1770 * ignored (already in place).
1771 */
1772 nb = gallop_left(pa[na-1], pb, nb, nb-1, compare);
1773 if (nb <= 0)
1774 return nb;
1775
1776 /* Merge what remains of the runs, using a temp array with
1777 * min(na, nb) elements.
1778 */
1779 if (na <= nb)
1780 return merge_lo(ms, pa, na, pb, nb);
1781 else
1782 return merge_hi(ms, pa, na, pb, nb);
1783}
1784
1785/* Examine the stack of runs waiting to be merged, merging adjacent runs
1786 * until the stack invariants are re-established:
1787 *
1788 * 1. len[-3] > len[-2] + len[-1]
1789 * 2. len[-2] > len[-1]
1790 *
1791 * See listsort.txt for more info.
1792 *
1793 * Returns 0 on success, -1 on error.
1794 */
1795static int
1796merge_collapse(MergeState *ms)
1797{
Tim Peterse05f65a2002-08-10 05:21:15 +00001798 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001799
1800 assert(ms);
1801 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001802 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001803 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1804 if (p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001805 --n;
1806 if (merge_at(ms, n) < 0)
1807 return -1;
1808 }
Tim Peterse05f65a2002-08-10 05:21:15 +00001809 else if (p[n].len <= p[n+1].len) {
Tim Petersa64dc242002-08-01 02:13:36 +00001810 if (merge_at(ms, n) < 0)
1811 return -1;
1812 }
1813 else
1814 break;
1815 }
1816 return 0;
1817}
1818
1819/* Regardless of invariants, merge all runs on the stack until only one
1820 * remains. This is used at the end of the mergesort.
1821 *
1822 * Returns 0 on success, -1 on error.
1823 */
1824static int
1825merge_force_collapse(MergeState *ms)
1826{
Tim Peterse05f65a2002-08-10 05:21:15 +00001827 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001828
1829 assert(ms);
1830 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001831 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001832 if (n > 0 && p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001833 --n;
1834 if (merge_at(ms, n) < 0)
1835 return -1;
1836 }
1837 return 0;
1838}
1839
1840/* Compute a good value for the minimum run length; natural runs shorter
1841 * than this are boosted artificially via binary insertion.
1842 *
1843 * If n < 64, return n (it's too small to bother with fancy stuff).
1844 * Else if n is an exact power of 2, return 32.
1845 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1846 * strictly less than, an exact power of 2.
1847 *
1848 * See listsort.txt for more info.
1849 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001850static Py_ssize_t
1851merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001852{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001853 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001854
1855 assert(n >= 0);
1856 while (n >= 64) {
1857 r |= n & 1;
1858 n >>= 1;
1859 }
1860 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001861}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001862
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001863/* Special wrapper to support stable sorting using the decorate-sort-undecorate
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001864 pattern. Holds a key which is used for comparisons and the original record
Tim Petersb38e2b62004-07-29 02:29:26 +00001865 which is returned during the undecorate phase. By exposing only the key
1866 during comparisons, the underlying sort stability characteristics are left
1867 unchanged. Also, if a custom comparison function is used, it will only see
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001868 the key instead of a full record. */
1869
1870typedef struct {
1871 PyObject_HEAD
1872 PyObject *key;
1873 PyObject *value;
1874} sortwrapperobject;
1875
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001876PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
Anthony Baxter377be112006-04-11 06:54:30 +00001877static PyObject *
1878sortwrapper_richcompare(sortwrapperobject *, sortwrapperobject *, int);
1879static void
1880sortwrapper_dealloc(sortwrapperobject *);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001881
1882static PyTypeObject sortwrapper_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001883 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001884 "sortwrapper", /* tp_name */
1885 sizeof(sortwrapperobject), /* tp_basicsize */
1886 0, /* tp_itemsize */
1887 /* methods */
1888 (destructor)sortwrapper_dealloc, /* tp_dealloc */
1889 0, /* tp_print */
1890 0, /* tp_getattr */
1891 0, /* tp_setattr */
1892 0, /* tp_compare */
1893 0, /* tp_repr */
1894 0, /* tp_as_number */
1895 0, /* tp_as_sequence */
1896 0, /* tp_as_mapping */
1897 0, /* tp_hash */
1898 0, /* tp_call */
1899 0, /* tp_str */
1900 PyObject_GenericGetAttr, /* tp_getattro */
1901 0, /* tp_setattro */
1902 0, /* tp_as_buffer */
Tim Petersb38e2b62004-07-29 02:29:26 +00001903 Py_TPFLAGS_DEFAULT |
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001904 Py_TPFLAGS_HAVE_RICHCOMPARE, /* tp_flags */
1905 sortwrapper_doc, /* tp_doc */
1906 0, /* tp_traverse */
1907 0, /* tp_clear */
1908 (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
1909};
1910
Anthony Baxter377be112006-04-11 06:54:30 +00001911
1912static PyObject *
1913sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
1914{
1915 if (!PyObject_TypeCheck(b, &sortwrapper_type)) {
1916 PyErr_SetString(PyExc_TypeError,
1917 "expected a sortwrapperobject");
1918 return NULL;
1919 }
1920 return PyObject_RichCompare(a->key, b->key, op);
1921}
1922
1923static void
1924sortwrapper_dealloc(sortwrapperobject *so)
1925{
1926 Py_XDECREF(so->key);
1927 Py_XDECREF(so->value);
1928 PyObject_Del(so);
1929}
1930
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001931/* Returns a new reference to a sortwrapper.
1932 Consumes the references to the two underlying objects. */
1933
1934static PyObject *
1935build_sortwrapper(PyObject *key, PyObject *value)
1936{
1937 sortwrapperobject *so;
Tim Petersb38e2b62004-07-29 02:29:26 +00001938
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001939 so = PyObject_New(sortwrapperobject, &sortwrapper_type);
1940 if (so == NULL)
1941 return NULL;
1942 so->key = key;
1943 so->value = value;
1944 return (PyObject *)so;
1945}
1946
1947/* Returns a new reference to the value underlying the wrapper. */
1948static PyObject *
1949sortwrapper_getvalue(PyObject *so)
1950{
1951 PyObject *value;
1952
1953 if (!PyObject_TypeCheck(so, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001954 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001955 "expected a sortwrapperobject");
1956 return NULL;
1957 }
1958 value = ((sortwrapperobject *)so)->value;
1959 Py_INCREF(value);
1960 return value;
1961}
1962
1963/* Wrapper for user specified cmp functions in combination with a
1964 specified key function. Makes sure the cmp function is presented
1965 with the actual key instead of the sortwrapper */
1966
1967typedef struct {
1968 PyObject_HEAD
1969 PyObject *func;
1970} cmpwrapperobject;
1971
1972static void
1973cmpwrapper_dealloc(cmpwrapperobject *co)
1974{
1975 Py_XDECREF(co->func);
1976 PyObject_Del(co);
1977}
1978
1979static PyObject *
1980cmpwrapper_call(cmpwrapperobject *co, PyObject *args, PyObject *kwds)
1981{
1982 PyObject *x, *y, *xx, *yy;
1983
1984 if (!PyArg_UnpackTuple(args, "", 2, 2, &x, &y))
1985 return NULL;
1986 if (!PyObject_TypeCheck(x, &sortwrapper_type) ||
Raymond Hettingerae4a2992003-10-16 17:16:30 +00001987 !PyObject_TypeCheck(y, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001988 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001989 "expected a sortwrapperobject");
1990 return NULL;
1991 }
1992 xx = ((sortwrapperobject *)x)->key;
1993 yy = ((sortwrapperobject *)y)->key;
1994 return PyObject_CallFunctionObjArgs(co->func, xx, yy, NULL);
1995}
1996
1997PyDoc_STRVAR(cmpwrapper_doc, "cmp() wrapper for sort with custom keys.");
1998
1999static PyTypeObject cmpwrapper_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002000 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002001 "cmpwrapper", /* tp_name */
2002 sizeof(cmpwrapperobject), /* tp_basicsize */
2003 0, /* tp_itemsize */
2004 /* methods */
2005 (destructor)cmpwrapper_dealloc, /* tp_dealloc */
2006 0, /* tp_print */
2007 0, /* tp_getattr */
2008 0, /* tp_setattr */
2009 0, /* tp_compare */
2010 0, /* tp_repr */
2011 0, /* tp_as_number */
2012 0, /* tp_as_sequence */
2013 0, /* tp_as_mapping */
2014 0, /* tp_hash */
2015 (ternaryfunc)cmpwrapper_call, /* tp_call */
2016 0, /* tp_str */
2017 PyObject_GenericGetAttr, /* tp_getattro */
2018 0, /* tp_setattro */
2019 0, /* tp_as_buffer */
2020 Py_TPFLAGS_DEFAULT, /* tp_flags */
2021 cmpwrapper_doc, /* tp_doc */
2022};
2023
2024static PyObject *
2025build_cmpwrapper(PyObject *cmpfunc)
2026{
2027 cmpwrapperobject *co;
Tim Petersb38e2b62004-07-29 02:29:26 +00002028
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002029 co = PyObject_New(cmpwrapperobject, &cmpwrapper_type);
2030 if (co == NULL)
2031 return NULL;
2032 Py_INCREF(cmpfunc);
2033 co->func = cmpfunc;
2034 return (PyObject *)co;
2035}
2036
Tim Petersa64dc242002-08-01 02:13:36 +00002037/* An adaptive, stable, natural mergesort. See listsort.txt.
2038 * Returns Py_None on success, NULL on error. Even in case of error, the
2039 * list will be some permutation of its input state (nothing is lost or
2040 * duplicated).
2041 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002042static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002043listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00002044{
Tim Petersa64dc242002-08-01 02:13:36 +00002045 MergeState ms;
2046 PyObject **lo, **hi;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002047 Py_ssize_t nremaining;
2048 Py_ssize_t minrun;
2049 Py_ssize_t saved_ob_size, saved_allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00002050 PyObject **saved_ob_item;
Armin Rigo93677f02004-07-29 12:40:23 +00002051 PyObject **final_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00002052 PyObject *compare = NULL;
2053 PyObject *result = NULL; /* guilty until proved innocent */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002054 int reverse = 0;
2055 PyObject *keyfunc = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002056 Py_ssize_t i;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002057 PyObject *key, *value, *kvpair;
Martin v. Löwis15e62742006-02-27 16:46:16 +00002058 static char *kwlist[] = {"cmp", "key", "reverse", 0};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002059
Tim Petersa64dc242002-08-01 02:13:36 +00002060 assert(self != NULL);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002061 assert (PyList_Check(self));
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002062 if (args != NULL) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002063 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:sort",
2064 kwlist, &compare, &keyfunc, &reverse))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002065 return NULL;
2066 }
Skip Montanaro4abd5f02003-01-02 20:51:08 +00002067 if (compare == Py_None)
2068 compare = NULL;
Raymond Hettinger05387862008-03-19 17:45:19 +00002069 if (compare != NULL &&
Benjamin Petersonf19a7b92008-04-27 18:40:21 +00002070 PyErr_WarnPy3k("the cmp argument is not supported in 3.x", 1) < 0)
Raymond Hettinger6c0ff8a2008-03-18 23:33:08 +00002071 return NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002072 if (keyfunc == Py_None)
2073 keyfunc = NULL;
2074 if (compare != NULL && keyfunc != NULL) {
2075 compare = build_cmpwrapper(compare);
2076 if (compare == NULL)
Hye-Shik Chang19cb1932003-12-10 07:31:08 +00002077 return NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002078 } else
2079 Py_XINCREF(compare);
2080
Tim Petersb9099c32002-11-12 22:08:10 +00002081 /* The list is temporarily made empty, so that mutations performed
2082 * by comparison functions can't affect the slice of memory we're
2083 * sorting (allowing mutations during sorting is a core-dump
2084 * factory, since ob_item may change).
2085 */
Christian Heimese93237d2007-12-19 02:37:44 +00002086 saved_ob_size = Py_SIZE(self);
Tim Petersb9099c32002-11-12 22:08:10 +00002087 saved_ob_item = self->ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002088 saved_allocated = self->allocated;
Christian Heimese93237d2007-12-19 02:37:44 +00002089 Py_SIZE(self) = 0;
Tim Peters51b4ade2004-07-29 04:07:15 +00002090 self->ob_item = NULL;
Armin Rigo93677f02004-07-29 12:40:23 +00002091 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00002092
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002093 if (keyfunc != NULL) {
2094 for (i=0 ; i < saved_ob_size ; i++) {
2095 value = saved_ob_item[i];
Tim Petersb38e2b62004-07-29 02:29:26 +00002096 key = PyObject_CallFunctionObjArgs(keyfunc, value,
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002097 NULL);
2098 if (key == NULL) {
2099 for (i=i-1 ; i>=0 ; i--) {
2100 kvpair = saved_ob_item[i];
2101 value = sortwrapper_getvalue(kvpair);
2102 saved_ob_item[i] = value;
2103 Py_DECREF(kvpair);
2104 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002105 goto dsu_fail;
2106 }
2107 kvpair = build_sortwrapper(key, value);
2108 if (kvpair == NULL)
2109 goto dsu_fail;
2110 saved_ob_item[i] = kvpair;
2111 }
2112 }
2113
2114 /* Reverse sort stability achieved by initially reversing the list,
2115 applying a stable forward sort, then reversing the final result. */
2116 if (reverse && saved_ob_size > 1)
2117 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2118
2119 merge_init(&ms, compare);
2120
Tim Petersb9099c32002-11-12 22:08:10 +00002121 nremaining = saved_ob_size;
Tim Petersa64dc242002-08-01 02:13:36 +00002122 if (nremaining < 2)
2123 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00002124
Tim Petersa64dc242002-08-01 02:13:36 +00002125 /* March over the array once, left to right, finding natural runs,
2126 * and extending short natural runs to minrun elements.
2127 */
Tim Petersb9099c32002-11-12 22:08:10 +00002128 lo = saved_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00002129 hi = lo + nremaining;
2130 minrun = merge_compute_minrun(nremaining);
2131 do {
2132 int descending;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002133 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00002134
Tim Petersa64dc242002-08-01 02:13:36 +00002135 /* Identify next run. */
2136 n = count_run(lo, hi, compare, &descending);
2137 if (n < 0)
2138 goto fail;
2139 if (descending)
2140 reverse_slice(lo, lo + n);
2141 /* If short, extend to min(minrun, nremaining). */
2142 if (n < minrun) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002143 const Py_ssize_t force = nremaining <= minrun ?
Tim Petersa64dc242002-08-01 02:13:36 +00002144 nremaining : minrun;
2145 if (binarysort(lo, lo + force, lo + n, compare) < 0)
2146 goto fail;
2147 n = force;
2148 }
2149 /* Push run onto pending-runs stack, and maybe merge. */
2150 assert(ms.n < MAX_MERGE_PENDING);
Tim Peterse05f65a2002-08-10 05:21:15 +00002151 ms.pending[ms.n].base = lo;
2152 ms.pending[ms.n].len = n;
Tim Petersa64dc242002-08-01 02:13:36 +00002153 ++ms.n;
2154 if (merge_collapse(&ms) < 0)
2155 goto fail;
2156 /* Advance to find next run. */
2157 lo += n;
2158 nremaining -= n;
2159 } while (nremaining);
2160 assert(lo == hi);
Tim Peters330f9e92002-07-19 07:05:44 +00002161
Tim Petersa64dc242002-08-01 02:13:36 +00002162 if (merge_force_collapse(&ms) < 0)
2163 goto fail;
2164 assert(ms.n == 1);
Tim Petersb9099c32002-11-12 22:08:10 +00002165 assert(ms.pending[0].base == saved_ob_item);
2166 assert(ms.pending[0].len == saved_ob_size);
Tim Petersa64dc242002-08-01 02:13:36 +00002167
2168succeed:
2169 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002170fail:
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002171 if (keyfunc != NULL) {
2172 for (i=0 ; i < saved_ob_size ; i++) {
2173 kvpair = saved_ob_item[i];
2174 value = sortwrapper_getvalue(kvpair);
2175 saved_ob_item[i] = value;
2176 Py_DECREF(kvpair);
2177 }
2178 }
2179
Armin Rigo93677f02004-07-29 12:40:23 +00002180 if (self->allocated != -1 && result != NULL) {
Tim Peters51b4ade2004-07-29 04:07:15 +00002181 /* The user mucked with the list during the sort,
2182 * and we don't already have another error to report.
2183 */
2184 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2185 result = NULL;
Tim Petersb9099c32002-11-12 22:08:10 +00002186 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002187
2188 if (reverse && saved_ob_size > 1)
2189 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2190
2191 merge_freemem(&ms);
2192
2193dsu_fail:
Armin Rigo93677f02004-07-29 12:40:23 +00002194 final_ob_item = self->ob_item;
Christian Heimese93237d2007-12-19 02:37:44 +00002195 i = Py_SIZE(self);
2196 Py_SIZE(self) = saved_ob_size;
Tim Petersb9099c32002-11-12 22:08:10 +00002197 self->ob_item = saved_ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002198 self->allocated = saved_allocated;
Armin Rigo93677f02004-07-29 12:40:23 +00002199 if (final_ob_item != NULL) {
2200 /* we cannot use list_clear() for this because it does not
2201 guarantee that the list is really empty when it returns */
2202 while (--i >= 0) {
2203 Py_XDECREF(final_ob_item[i]);
2204 }
2205 PyMem_FREE(final_ob_item);
2206 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002207 Py_XDECREF(compare);
Tim Petersa64dc242002-08-01 02:13:36 +00002208 Py_XINCREF(result);
2209 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002210}
Tim Peters330f9e92002-07-19 07:05:44 +00002211#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002212#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002213
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002214int
Fred Drakea2f55112000-07-09 15:16:51 +00002215PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002216{
2217 if (v == NULL || !PyList_Check(v)) {
2218 PyErr_BadInternalCall();
2219 return -1;
2220 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002221 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002222 if (v == NULL)
2223 return -1;
2224 Py_DECREF(v);
2225 return 0;
2226}
2227
Guido van Rossumb86c5492001-02-12 22:06:02 +00002228static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002229listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002230{
Christian Heimese93237d2007-12-19 02:37:44 +00002231 if (Py_SIZE(self) > 1)
2232 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002233 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002234}
2235
Guido van Rossum84c76f51990-10-30 13:32:20 +00002236int
Fred Drakea2f55112000-07-09 15:16:51 +00002237PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002238{
Tim Peters6063e262002-08-08 01:06:39 +00002239 PyListObject *self = (PyListObject *)v;
2240
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002241 if (v == NULL || !PyList_Check(v)) {
2242 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002243 return -1;
2244 }
Christian Heimese93237d2007-12-19 02:37:44 +00002245 if (Py_SIZE(self) > 1)
2246 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002247 return 0;
2248}
2249
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002250PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002251PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002252{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002253 PyObject *w;
Raymond Hettinger6c87af52007-12-15 00:07:25 +00002254 PyObject **p, **q;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002255 Py_ssize_t n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002256 if (v == NULL || !PyList_Check(v)) {
2257 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002258 return NULL;
2259 }
Christian Heimese93237d2007-12-19 02:37:44 +00002260 n = Py_SIZE(v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002261 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002262 if (w == NULL)
2263 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002264 p = ((PyTupleObject *)w)->ob_item;
Raymond Hettinger6c87af52007-12-15 00:07:25 +00002265 q = ((PyListObject *)v)->ob_item;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002266 while (--n >= 0) {
Raymond Hettinger6c87af52007-12-15 00:07:25 +00002267 Py_INCREF(*q);
2268 *p = *q;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002269 p++;
Raymond Hettinger6c87af52007-12-15 00:07:25 +00002270 q++;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002271 }
2272 return w;
2273}
2274
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002275static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002276listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002277{
Christian Heimese93237d2007-12-19 02:37:44 +00002278 Py_ssize_t i, start=0, stop=Py_SIZE(self);
Benjamin Petersonc45a0cf2009-11-02 16:14:19 +00002279 PyObject *v, *format_tuple, *err_string;
2280 static PyObject *err_format = NULL;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002281
Walter Dörwalde8049bef2003-06-17 19:27:39 +00002282 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2283 _PyEval_SliceIndex, &start,
2284 _PyEval_SliceIndex, &stop))
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002285 return NULL;
Guido van Rossum2743d872003-06-17 14:25:14 +00002286 if (start < 0) {
Christian Heimese93237d2007-12-19 02:37:44 +00002287 start += Py_SIZE(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002288 if (start < 0)
2289 start = 0;
2290 }
2291 if (stop < 0) {
Christian Heimese93237d2007-12-19 02:37:44 +00002292 stop += Py_SIZE(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002293 if (stop < 0)
2294 stop = 0;
2295 }
Christian Heimese93237d2007-12-19 02:37:44 +00002296 for (i = start; i < stop && i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002297 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2298 if (cmp > 0)
Martin v. Löwis18e16552006-02-15 17:27:45 +00002299 return PyInt_FromSsize_t(i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002300 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002301 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002302 }
Benjamin Petersonc45a0cf2009-11-02 16:14:19 +00002303 if (err_format == NULL) {
2304 err_format = PyString_FromString("%r is not in list");
2305 if (err_format == NULL)
2306 return NULL;
2307 }
2308 format_tuple = PyTuple_Pack(1, v);
2309 if (format_tuple == NULL)
2310 return NULL;
2311 err_string = PyString_Format(err_format, format_tuple);
2312 Py_DECREF(format_tuple);
2313 if (err_string == NULL)
2314 return NULL;
2315 PyErr_SetObject(PyExc_ValueError, err_string);
2316 Py_DECREF(err_string);
Guido van Rossumed98d481991-03-06 13:07:53 +00002317 return NULL;
2318}
2319
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002320static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002321listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002322{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002323 Py_ssize_t count = 0;
2324 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002325
Christian Heimese93237d2007-12-19 02:37:44 +00002326 for (i = 0; i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002327 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2328 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002329 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002330 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002331 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00002332 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002333 return PyInt_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002334}
2335
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002336static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002337listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002338{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002339 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002340
Christian Heimese93237d2007-12-19 02:37:44 +00002341 for (i = 0; i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002342 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2343 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002344 if (list_ass_slice(self, i, i+1,
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002345 (PyObject *)NULL) == 0)
2346 Py_RETURN_NONE;
2347 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002348 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002349 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002350 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002351 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002352 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002353 return NULL;
2354}
2355
Jeremy Hylton8caad492000-06-23 14:18:11 +00002356static int
2357list_traverse(PyListObject *o, visitproc visit, void *arg)
2358{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002359 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002360
Christian Heimese93237d2007-12-19 02:37:44 +00002361 for (i = Py_SIZE(o); --i >= 0; )
Thomas Woutersc6e55062006-04-15 21:47:09 +00002362 Py_VISIT(o->ob_item[i]);
Jeremy Hylton8caad492000-06-23 14:18:11 +00002363 return 0;
2364}
2365
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002366static PyObject *
2367list_richcompare(PyObject *v, PyObject *w, int op)
2368{
2369 PyListObject *vl, *wl;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002370 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002371
2372 if (!PyList_Check(v) || !PyList_Check(w)) {
2373 Py_INCREF(Py_NotImplemented);
2374 return Py_NotImplemented;
2375 }
2376
2377 vl = (PyListObject *)v;
2378 wl = (PyListObject *)w;
2379
Christian Heimese93237d2007-12-19 02:37:44 +00002380 if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002381 /* Shortcut: if the lengths differ, the lists differ */
2382 PyObject *res;
2383 if (op == Py_EQ)
2384 res = Py_False;
2385 else
2386 res = Py_True;
2387 Py_INCREF(res);
2388 return res;
2389 }
2390
2391 /* Search for the first index where items are different */
Christian Heimese93237d2007-12-19 02:37:44 +00002392 for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002393 int k = PyObject_RichCompareBool(vl->ob_item[i],
2394 wl->ob_item[i], Py_EQ);
2395 if (k < 0)
2396 return NULL;
2397 if (!k)
2398 break;
2399 }
2400
Christian Heimese93237d2007-12-19 02:37:44 +00002401 if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002402 /* No more items to compare -- compare sizes */
Christian Heimese93237d2007-12-19 02:37:44 +00002403 Py_ssize_t vs = Py_SIZE(vl);
2404 Py_ssize_t ws = Py_SIZE(wl);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002405 int cmp;
2406 PyObject *res;
2407 switch (op) {
2408 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00002409 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002410 case Py_EQ: cmp = vs == ws; break;
2411 case Py_NE: cmp = vs != ws; break;
2412 case Py_GT: cmp = vs > ws; break;
2413 case Py_GE: cmp = vs >= ws; break;
2414 default: return NULL; /* cannot happen */
2415 }
2416 if (cmp)
2417 res = Py_True;
2418 else
2419 res = Py_False;
2420 Py_INCREF(res);
2421 return res;
2422 }
2423
2424 /* We have an item that differs -- shortcuts for EQ/NE */
2425 if (op == Py_EQ) {
2426 Py_INCREF(Py_False);
2427 return Py_False;
2428 }
2429 if (op == Py_NE) {
2430 Py_INCREF(Py_True);
2431 return Py_True;
2432 }
2433
2434 /* Compare the final item again using the proper operator */
2435 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
2436}
2437
Tim Peters6d6c1a32001-08-02 04:15:00 +00002438static int
2439list_init(PyListObject *self, PyObject *args, PyObject *kw)
2440{
2441 PyObject *arg = NULL;
Martin v. Löwis15e62742006-02-27 16:46:16 +00002442 static char *kwlist[] = {"sequence", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002443
2444 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2445 return -1;
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002446
2447 /* Verify list invariants established by PyType_GenericAlloc() */
Christian Heimese93237d2007-12-19 02:37:44 +00002448 assert(0 <= Py_SIZE(self));
2449 assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
Armin Rigoa37bbf22004-07-30 11:20:18 +00002450 assert(self->ob_item != NULL ||
2451 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002452
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002453 /* Empty previous contents */
Armin Rigo93677f02004-07-29 12:40:23 +00002454 if (self->ob_item != NULL) {
2455 (void)list_clear(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002456 }
2457 if (arg != NULL) {
2458 PyObject *rv = listextend(self, arg);
2459 if (rv == NULL)
2460 return -1;
2461 Py_DECREF(rv);
2462 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002463 return 0;
2464}
2465
Robert Schuppenies51df0642008-06-01 16:16:17 +00002466static PyObject *
2467list_sizeof(PyListObject *self)
2468{
2469 Py_ssize_t res;
2470
2471 res = sizeof(PyListObject) + self->allocated * sizeof(void*);
2472 return PyInt_FromSsize_t(res);
2473}
2474
Raymond Hettinger1021c442003-11-07 15:38:09 +00002475static PyObject *list_iter(PyObject *seq);
2476static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2477
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002478PyDoc_STRVAR(getitem_doc,
2479"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002480PyDoc_STRVAR(reversed_doc,
2481"L.__reversed__() -- return a reverse iterator over the list");
Robert Schuppenies51df0642008-06-01 16:16:17 +00002482PyDoc_STRVAR(sizeof_doc,
Georg Brandl7a6de8b2008-06-01 16:42:16 +00002483"L.__sizeof__() -- size of L in memory, in bytes");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002484PyDoc_STRVAR(append_doc,
2485"L.append(object) -- append object to end");
2486PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002487"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002488PyDoc_STRVAR(insert_doc,
2489"L.insert(index, object) -- insert object before index");
2490PyDoc_STRVAR(pop_doc,
Andrew M. Kuchlingd810cdf2008-10-04 01:04:24 +00002491"L.pop([index]) -> item -- remove and return item at index (default last).\n"
2492"Raises IndexError if list is empty or index is out of range.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002493PyDoc_STRVAR(remove_doc,
Andrew M. Kuchlingd810cdf2008-10-04 01:04:24 +00002494"L.remove(value) -- remove first occurrence of value.\n"
2495"Raises ValueError if the value is not present.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002496PyDoc_STRVAR(index_doc,
Andrew M. Kuchlingd810cdf2008-10-04 01:04:24 +00002497"L.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
2498"Raises ValueError if the value is not present.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002499PyDoc_STRVAR(count_doc,
2500"L.count(value) -> integer -- return number of occurrences of value");
2501PyDoc_STRVAR(reverse_doc,
2502"L.reverse() -- reverse *IN PLACE*");
2503PyDoc_STRVAR(sort_doc,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002504"L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n\
2505cmp(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002506
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002507static PyObject *list_subscript(PyListObject*, PyObject*);
2508
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002509static PyMethodDef list_methods[] = {
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002510 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
Raymond Hettinger1021c442003-11-07 15:38:09 +00002511 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
Robert Schuppenies51df0642008-06-01 16:16:17 +00002512 {"__sizeof__", (PyCFunction)list_sizeof, METH_NOARGS, sizeof_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002513 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002514 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002515 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002516 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002517 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002518 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002519 {"count", (PyCFunction)listcount, METH_O, count_doc},
2520 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002521 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
Tim Petersa64dc242002-08-01 02:13:36 +00002522 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002523};
2524
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002525static PySequenceMethods list_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002526 (lenfunc)list_length, /* sq_length */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002527 (binaryfunc)list_concat, /* sq_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002528 (ssizeargfunc)list_repeat, /* sq_repeat */
2529 (ssizeargfunc)list_item, /* sq_item */
2530 (ssizessizeargfunc)list_slice, /* sq_slice */
2531 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
2532 (ssizessizeobjargproc)list_ass_slice, /* sq_ass_slice */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002533 (objobjproc)list_contains, /* sq_contains */
2534 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002535 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002536};
2537
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002538PyDoc_STRVAR(list_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002539"list() -> new list\n"
Georg Brandlbca11692010-02-28 18:19:17 +00002540"list(iterable) -> new list initialized from iterable's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002541
Guido van Rossum38fff8c2006-03-07 18:50:55 +00002542
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002543static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002544list_subscript(PyListObject* self, PyObject* item)
2545{
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00002546 if (PyIndex_Check(item)) {
2547 Py_ssize_t i;
2548 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002549 if (i == -1 && PyErr_Occurred())
2550 return NULL;
2551 if (i < 0)
2552 i += PyList_GET_SIZE(self);
2553 return list_item(self, i);
2554 }
2555 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002556 Py_ssize_t start, stop, step, slicelength, cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002557 PyObject* result;
2558 PyObject* it;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002559 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002560
Christian Heimese93237d2007-12-19 02:37:44 +00002561 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002562 &start, &stop, &step, &slicelength) < 0) {
2563 return NULL;
2564 }
2565
2566 if (slicelength <= 0) {
2567 return PyList_New(0);
2568 }
Thomas Wouters3ccec682007-08-28 15:28:19 +00002569 else if (step == 1) {
2570 return list_slice(self, start, stop);
2571 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002572 else {
2573 result = PyList_New(slicelength);
2574 if (!result) return NULL;
2575
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002576 src = self->ob_item;
2577 dest = ((PyListObject *)result)->ob_item;
Tim Peters3b01a122002-07-19 02:35:45 +00002578 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002579 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002580 it = src[cur];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002581 Py_INCREF(it);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002582 dest[i] = it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002583 }
Tim Peters3b01a122002-07-19 02:35:45 +00002584
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002585 return result;
2586 }
2587 }
2588 else {
Georg Brandl283a1352006-11-19 08:48:30 +00002589 PyErr_Format(PyExc_TypeError,
2590 "list indices must be integers, not %.200s",
2591 item->ob_type->tp_name);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002592 return NULL;
2593 }
2594}
2595
Tim Peters3b01a122002-07-19 02:35:45 +00002596static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002597list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2598{
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00002599 if (PyIndex_Check(item)) {
2600 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002601 if (i == -1 && PyErr_Occurred())
2602 return -1;
2603 if (i < 0)
2604 i += PyList_GET_SIZE(self);
2605 return list_ass_item(self, i, value);
2606 }
2607 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002608 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002609
Christian Heimese93237d2007-12-19 02:37:44 +00002610 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002611 &start, &stop, &step, &slicelength) < 0) {
2612 return -1;
2613 }
2614
Thomas Wouters3ccec682007-08-28 15:28:19 +00002615 if (step == 1)
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002616 return list_ass_slice(self, start, stop, value);
2617
Thomas Wouters3ccec682007-08-28 15:28:19 +00002618 /* Make sure s[5:2] = [..] inserts at the right place:
2619 before 5, not before 2. */
2620 if ((step < 0 && start < stop) ||
2621 (step > 0 && start > stop))
2622 stop = start;
2623
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002624 if (value == NULL) {
2625 /* delete slice */
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002626 PyObject **garbage;
Mark Dickinson36ecd672010-01-29 17:11:39 +00002627 size_t cur;
2628 Py_ssize_t i;
Tim Peters3b01a122002-07-19 02:35:45 +00002629
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002630 if (slicelength <= 0)
2631 return 0;
2632
2633 if (step < 0) {
2634 stop = start + 1;
2635 start = stop + step*(slicelength - 1) - 1;
2636 step = -step;
2637 }
2638
Mark Dickinsonac5685e2010-02-14 12:16:43 +00002639 assert((size_t)slicelength <=
2640 PY_SIZE_MAX / sizeof(PyObject*));
Gregory P. Smith9d534572008-06-11 07:41:16 +00002641
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002642 garbage = (PyObject**)
2643 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Neal Norwitzb88cfad2006-08-12 03:16:54 +00002644 if (!garbage) {
2645 PyErr_NoMemory();
2646 return -1;
2647 }
Tim Peters3b01a122002-07-19 02:35:45 +00002648
Thomas Wouters3ccec682007-08-28 15:28:19 +00002649 /* drawing pictures might help understand these for
2650 loops. Basically, we memmove the parts of the
2651 list that are *not* part of the slice: step-1
2652 items for each item that is part of the slice,
2653 and then tail end of the list that was not
2654 covered by the slice */
Guido van Rossum75a20b12002-06-11 12:22:28 +00002655 for (cur = start, i = 0;
Mark Dickinsonac5685e2010-02-14 12:16:43 +00002656 cur < (size_t)stop;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002657 cur += step, i++) {
Thomas Wouters3ccec682007-08-28 15:28:19 +00002658 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002659
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002660 garbage[i] = PyList_GET_ITEM(self, cur);
2661
Mark Dickinsonac5685e2010-02-14 12:16:43 +00002662 if (cur + step >= (size_t)Py_SIZE(self)) {
Christian Heimese93237d2007-12-19 02:37:44 +00002663 lim = Py_SIZE(self) - cur - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002664 }
2665
Tim Petersb38e2b62004-07-29 02:29:26 +00002666 memmove(self->ob_item + cur - i,
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002667 self->ob_item + cur + 1,
2668 lim * sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002669 }
Thomas Wouters3ccec682007-08-28 15:28:19 +00002670 cur = start + slicelength*step;
Mark Dickinsonac5685e2010-02-14 12:16:43 +00002671 if (cur < (size_t)Py_SIZE(self)) {
Thomas Wouters3ccec682007-08-28 15:28:19 +00002672 memmove(self->ob_item + cur - slicelength,
2673 self->ob_item + cur,
Christian Heimese93237d2007-12-19 02:37:44 +00002674 (Py_SIZE(self) - cur) *
Thomas Wouters3ccec682007-08-28 15:28:19 +00002675 sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002676 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002677
Christian Heimese93237d2007-12-19 02:37:44 +00002678 Py_SIZE(self) -= slicelength;
2679 list_resize(self, Py_SIZE(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002680
2681 for (i = 0; i < slicelength; i++) {
2682 Py_DECREF(garbage[i]);
2683 }
2684 PyMem_FREE(garbage);
2685
2686 return 0;
2687 }
2688 else {
2689 /* assign slice */
Thomas Wouters3ccec682007-08-28 15:28:19 +00002690 PyObject *ins, *seq;
2691 PyObject **garbage, **seqitems, **selfitems;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002692 Py_ssize_t cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002693
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002694 /* protect against a[::-1] = a */
Tim Peters3b01a122002-07-19 02:35:45 +00002695 if (self == (PyListObject*)value) {
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002696 seq = list_slice((PyListObject*)value, 0,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002697 PyList_GET_SIZE(value));
Tim Peters3b01a122002-07-19 02:35:45 +00002698 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002699 else {
Tim Petersb38e2b62004-07-29 02:29:26 +00002700 seq = PySequence_Fast(value,
Thomas Wouters3ccec682007-08-28 15:28:19 +00002701 "must assign iterable "
2702 "to extended slice");
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002703 }
Neal Norwitzb88cfad2006-08-12 03:16:54 +00002704 if (!seq)
2705 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002706
2707 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2708 PyErr_Format(PyExc_ValueError,
Thomas Wouters3ccec682007-08-28 15:28:19 +00002709 "attempt to assign sequence of "
2710 "size %zd to extended slice of "
2711 "size %zd",
Martin v. Löwise0e89f72006-02-16 06:59:22 +00002712 PySequence_Fast_GET_SIZE(seq),
2713 slicelength);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002714 Py_DECREF(seq);
2715 return -1;
2716 }
2717
2718 if (!slicelength) {
2719 Py_DECREF(seq);
2720 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002721 }
2722
2723 garbage = (PyObject**)
2724 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Neal Norwitze7e4e2d2006-10-28 21:20:12 +00002725 if (!garbage) {
2726 Py_DECREF(seq);
2727 PyErr_NoMemory();
2728 return -1;
2729 }
Tim Peters3b01a122002-07-19 02:35:45 +00002730
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002731 selfitems = self->ob_item;
Raymond Hettinger42bec932004-03-12 16:38:17 +00002732 seqitems = PySequence_Fast_ITEMS(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002733 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002734 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002735 garbage[i] = selfitems[cur];
2736 ins = seqitems[i];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002737 Py_INCREF(ins);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002738 selfitems[cur] = ins;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002739 }
2740
2741 for (i = 0; i < slicelength; i++) {
2742 Py_DECREF(garbage[i]);
2743 }
Tim Peters3b01a122002-07-19 02:35:45 +00002744
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002745 PyMem_FREE(garbage);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002746 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002747
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002748 return 0;
2749 }
Tim Peters3b01a122002-07-19 02:35:45 +00002750 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002751 else {
Georg Brandl283a1352006-11-19 08:48:30 +00002752 PyErr_Format(PyExc_TypeError,
2753 "list indices must be integers, not %.200s",
2754 item->ob_type->tp_name);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002755 return -1;
2756 }
2757}
2758
2759static PyMappingMethods list_as_mapping = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002760 (lenfunc)list_length,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002761 (binaryfunc)list_subscript,
2762 (objobjargproc)list_ass_subscript
2763};
2764
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002765PyTypeObject PyList_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002766 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002767 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002768 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002769 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002770 (destructor)list_dealloc, /* tp_dealloc */
2771 (printfunc)list_print, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002772 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002773 0, /* tp_setattr */
2774 0, /* tp_compare */
2775 (reprfunc)list_repr, /* tp_repr */
2776 0, /* tp_as_number */
2777 &list_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002778 &list_as_mapping, /* tp_as_mapping */
Nick Coghlan53663a62008-07-15 14:27:37 +00002779 (hashfunc)PyObject_HashNotImplemented, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002780 0, /* tp_call */
2781 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002782 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002783 0, /* tp_setattro */
2784 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002785 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Neal Norwitzee3a1b52007-02-25 19:44:48 +00002786 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002787 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002788 (traverseproc)list_traverse, /* tp_traverse */
2789 (inquiry)list_clear, /* tp_clear */
2790 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002791 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002792 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002793 0, /* tp_iternext */
2794 list_methods, /* tp_methods */
2795 0, /* tp_members */
2796 0, /* tp_getset */
2797 0, /* tp_base */
2798 0, /* tp_dict */
2799 0, /* tp_descr_get */
2800 0, /* tp_descr_set */
2801 0, /* tp_dictoffset */
2802 (initproc)list_init, /* tp_init */
2803 PyType_GenericAlloc, /* tp_alloc */
2804 PyType_GenericNew, /* tp_new */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002805 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002806};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002807
2808
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002809/*********************** List Iterator **************************/
2810
2811typedef struct {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002812 PyObject_HEAD
2813 long it_index;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002814 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002815} listiterobject;
2816
Anthony Baxter377be112006-04-11 06:54:30 +00002817static PyObject *list_iter(PyObject *);
2818static void listiter_dealloc(listiterobject *);
2819static int listiter_traverse(listiterobject *, visitproc, void *);
2820static PyObject *listiter_next(listiterobject *);
2821static PyObject *listiter_len(listiterobject *);
2822
2823PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
2824
2825static PyMethodDef listiter_methods[] = {
2826 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
2827 {NULL, NULL} /* sentinel */
2828};
2829
2830PyTypeObject PyListIter_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002831 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Anthony Baxter377be112006-04-11 06:54:30 +00002832 "listiterator", /* tp_name */
2833 sizeof(listiterobject), /* tp_basicsize */
2834 0, /* tp_itemsize */
2835 /* methods */
2836 (destructor)listiter_dealloc, /* tp_dealloc */
2837 0, /* tp_print */
2838 0, /* tp_getattr */
2839 0, /* tp_setattr */
2840 0, /* tp_compare */
2841 0, /* tp_repr */
2842 0, /* tp_as_number */
2843 0, /* tp_as_sequence */
2844 0, /* tp_as_mapping */
2845 0, /* tp_hash */
2846 0, /* tp_call */
2847 0, /* tp_str */
2848 PyObject_GenericGetAttr, /* tp_getattro */
2849 0, /* tp_setattro */
2850 0, /* tp_as_buffer */
2851 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2852 0, /* tp_doc */
2853 (traverseproc)listiter_traverse, /* tp_traverse */
2854 0, /* tp_clear */
2855 0, /* tp_richcompare */
2856 0, /* tp_weaklistoffset */
2857 PyObject_SelfIter, /* tp_iter */
2858 (iternextfunc)listiter_next, /* tp_iternext */
2859 listiter_methods, /* tp_methods */
2860 0, /* tp_members */
2861};
2862
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002863
Guido van Rossum5086e492002-07-16 15:56:52 +00002864static PyObject *
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002865list_iter(PyObject *seq)
2866{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002867 listiterobject *it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002868
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002869 if (!PyList_Check(seq)) {
2870 PyErr_BadInternalCall();
2871 return NULL;
2872 }
2873 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2874 if (it == NULL)
2875 return NULL;
2876 it->it_index = 0;
2877 Py_INCREF(seq);
2878 it->it_seq = (PyListObject *)seq;
2879 _PyObject_GC_TRACK(it);
2880 return (PyObject *)it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002881}
2882
2883static void
2884listiter_dealloc(listiterobject *it)
2885{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002886 _PyObject_GC_UNTRACK(it);
Guido van Rossum86103ae2002-07-16 20:07:32 +00002887 Py_XDECREF(it->it_seq);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002888 PyObject_GC_Del(it);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002889}
2890
2891static int
2892listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2893{
Thomas Woutersc6e55062006-04-15 21:47:09 +00002894 Py_VISIT(it->it_seq);
2895 return 0;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002896}
2897
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002898static PyObject *
Tim Peters93b2cc42002-06-01 05:22:55 +00002899listiter_next(listiterobject *it)
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002900{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002901 PyListObject *seq;
2902 PyObject *item;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002903
Tim Peters93b2cc42002-06-01 05:22:55 +00002904 assert(it != NULL);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002905 seq = it->it_seq;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002906 if (seq == NULL)
2907 return NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002908 assert(PyList_Check(seq));
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002909
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002910 if (it->it_index < PyList_GET_SIZE(seq)) {
Tim Peters93b2cc42002-06-01 05:22:55 +00002911 item = PyList_GET_ITEM(seq, it->it_index);
2912 ++it->it_index;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002913 Py_INCREF(item);
2914 return item;
2915 }
Guido van Rossum86103ae2002-07-16 20:07:32 +00002916
2917 Py_DECREF(seq);
2918 it->it_seq = NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002919 return NULL;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002920}
2921
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002922static PyObject *
Raymond Hettinger435bf582004-03-18 22:43:10 +00002923listiter_len(listiterobject *it)
2924{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002925 Py_ssize_t len;
Raymond Hettinger40a03822004-04-12 13:05:09 +00002926 if (it->it_seq) {
2927 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2928 if (len >= 0)
Martin v. Löwis18e16552006-02-15 17:27:45 +00002929 return PyInt_FromSsize_t(len);
Raymond Hettinger40a03822004-04-12 13:05:09 +00002930 }
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002931 return PyInt_FromLong(0);
Raymond Hettinger435bf582004-03-18 22:43:10 +00002932}
Anthony Baxter377be112006-04-11 06:54:30 +00002933/*********************** List Reverse Iterator **************************/
Raymond Hettinger435bf582004-03-18 22:43:10 +00002934
Anthony Baxter377be112006-04-11 06:54:30 +00002935typedef struct {
2936 PyObject_HEAD
2937 Py_ssize_t it_index;
2938 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
2939} listreviterobject;
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002940
Anthony Baxter377be112006-04-11 06:54:30 +00002941static PyObject *list_reversed(PyListObject *, PyObject *);
2942static void listreviter_dealloc(listreviterobject *);
2943static int listreviter_traverse(listreviterobject *, visitproc, void *);
2944static PyObject *listreviter_next(listreviterobject *);
Raymond Hettinger7989a4d2008-12-03 15:42:10 +00002945static PyObject *listreviter_len(listreviterobject *);
Anthony Baxter377be112006-04-11 06:54:30 +00002946
Raymond Hettinger7989a4d2008-12-03 15:42:10 +00002947static PyMethodDef listreviter_methods[] = {
2948 {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc},
2949 {NULL, NULL} /* sentinel */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002950};
2951
Anthony Baxter377be112006-04-11 06:54:30 +00002952PyTypeObject PyListRevIter_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002953 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Anthony Baxter377be112006-04-11 06:54:30 +00002954 "listreverseiterator", /* tp_name */
2955 sizeof(listreviterobject), /* tp_basicsize */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002956 0, /* tp_itemsize */
2957 /* methods */
Anthony Baxter377be112006-04-11 06:54:30 +00002958 (destructor)listreviter_dealloc, /* tp_dealloc */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002959 0, /* tp_print */
2960 0, /* tp_getattr */
2961 0, /* tp_setattr */
2962 0, /* tp_compare */
2963 0, /* tp_repr */
2964 0, /* tp_as_number */
Raymond Hettinger7989a4d2008-12-03 15:42:10 +00002965 0, /* tp_as_sequence */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002966 0, /* tp_as_mapping */
2967 0, /* tp_hash */
2968 0, /* tp_call */
2969 0, /* tp_str */
2970 PyObject_GenericGetAttr, /* tp_getattro */
2971 0, /* tp_setattro */
2972 0, /* tp_as_buffer */
2973 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2974 0, /* tp_doc */
Anthony Baxter377be112006-04-11 06:54:30 +00002975 (traverseproc)listreviter_traverse, /* tp_traverse */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002976 0, /* tp_clear */
2977 0, /* tp_richcompare */
2978 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00002979 PyObject_SelfIter, /* tp_iter */
Anthony Baxter377be112006-04-11 06:54:30 +00002980 (iternextfunc)listreviter_next, /* tp_iternext */
Raymond Hettinger7989a4d2008-12-03 15:42:10 +00002981 listreviter_methods, /* tp_methods */
Anthony Baxter377be112006-04-11 06:54:30 +00002982 0,
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002983};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002984
Raymond Hettinger1021c442003-11-07 15:38:09 +00002985static PyObject *
2986list_reversed(PyListObject *seq, PyObject *unused)
2987{
2988 listreviterobject *it;
2989
2990 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2991 if (it == NULL)
2992 return NULL;
2993 assert(PyList_Check(seq));
2994 it->it_index = PyList_GET_SIZE(seq) - 1;
2995 Py_INCREF(seq);
2996 it->it_seq = seq;
2997 PyObject_GC_Track(it);
2998 return (PyObject *)it;
2999}
3000
3001static void
3002listreviter_dealloc(listreviterobject *it)
3003{
3004 PyObject_GC_UnTrack(it);
3005 Py_XDECREF(it->it_seq);
3006 PyObject_GC_Del(it);
3007}
3008
3009static int
3010listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
3011{
Thomas Woutersc6e55062006-04-15 21:47:09 +00003012 Py_VISIT(it->it_seq);
3013 return 0;
Raymond Hettinger1021c442003-11-07 15:38:09 +00003014}
3015
3016static PyObject *
3017listreviter_next(listreviterobject *it)
3018{
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003019 PyObject *item;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00003020 Py_ssize_t index = it->it_index;
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003021 PyListObject *seq = it->it_seq;
Raymond Hettinger1021c442003-11-07 15:38:09 +00003022
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003023 if (index>=0 && index < PyList_GET_SIZE(seq)) {
3024 item = PyList_GET_ITEM(seq, index);
Raymond Hettinger1021c442003-11-07 15:38:09 +00003025 it->it_index--;
3026 Py_INCREF(item);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003027 return item;
Raymond Hettinger1021c442003-11-07 15:38:09 +00003028 }
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003029 it->it_index = -1;
3030 if (seq != NULL) {
3031 it->it_seq = NULL;
3032 Py_DECREF(seq);
3033 }
3034 return NULL;
Raymond Hettinger1021c442003-11-07 15:38:09 +00003035}
3036
Raymond Hettinger7989a4d2008-12-03 15:42:10 +00003037static PyObject *
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003038listreviter_len(listreviterobject *it)
3039{
Martin v. Löwis18e16552006-02-15 17:27:45 +00003040 Py_ssize_t len = it->it_index + 1;
Raymond Hettinger40a03822004-04-12 13:05:09 +00003041 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
Raymond Hettinger7989a4d2008-12-03 15:42:10 +00003042 len = 0;
3043 return PyLong_FromSsize_t(len);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003044}