blob: 78e8da4b3de0502ba007f00dc58514ead4b92110 [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 */
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000048 new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6) + newsize;
49 if (newsize == 0)
50 new_allocated = 0;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000051 items = self->ob_item;
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000052 if (new_allocated <= ((~(size_t)0) / sizeof(PyObject *)))
53 PyMem_RESIZE(items, PyObject *, new_allocated);
Raymond Hettinger4bb95402004-02-13 11:36:39 +000054 else
55 items = NULL;
56 if (items == NULL) {
57 PyErr_NoMemory();
58 return -1;
59 }
60 self->ob_item = items;
Christian Heimese93237d2007-12-19 02:37:44 +000061 Py_SIZE(self) = newsize;
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000062 self->allocated = new_allocated;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000063 return 0;
64}
Guido van Rossuma46d51d1995-01-26 22:59:43 +000065
Raymond Hettinger0468e412004-05-05 05:37:53 +000066/* Empty list reuse scheme to save calls to malloc and free */
67#define MAXFREELISTS 80
68static PyListObject *free_lists[MAXFREELISTS];
69static int num_free_lists = 0;
70
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +000071void
72PyList_Fini(void)
73{
74 PyListObject *op;
75
76 while (num_free_lists) {
77 num_free_lists--;
78 op = free_lists[num_free_lists];
79 assert(PyList_CheckExact(op));
80 PyObject_GC_Del(op);
81 }
82}
83
Guido van Rossumc0b618a1997-05-02 03:12:38 +000084PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000085PyList_New(Py_ssize_t size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000086{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000087 PyListObject *op;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +000088 size_t nbytes;
Tim Peters3986d4e2004-07-29 02:28:42 +000089
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000090 if (size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000091 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000092 return NULL;
93 }
Tim Peters7049d812004-01-18 20:31:02 +000094 nbytes = size * sizeof(PyObject *);
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000095 /* Check for overflow */
Raymond Hettingerfdfe6182004-05-05 06:28:16 +000096 if (nbytes / sizeof(PyObject *) != (size_t)size)
Guido van Rossumc0b618a1997-05-02 03:12:38 +000097 return PyErr_NoMemory();
Raymond Hettinger0468e412004-05-05 05:37:53 +000098 if (num_free_lists) {
99 num_free_lists--;
100 op = free_lists[num_free_lists];
101 _Py_NewReference((PyObject *)op);
102 } else {
103 op = PyObject_GC_New(PyListObject, &PyList_Type);
104 if (op == NULL)
105 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000106 }
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000107 if (size <= 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000108 op->ob_item = NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000109 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +0000110 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
Neal Norwitza00c0b92006-06-12 02:08:41 +0000111 if (op->ob_item == NULL) {
112 Py_DECREF(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000113 return PyErr_NoMemory();
Neal Norwitza00c0b92006-06-12 02:08:41 +0000114 }
Tim Peters3986d4e2004-07-29 02:28:42 +0000115 memset(op->ob_item, 0, nbytes);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000116 }
Christian Heimese93237d2007-12-19 02:37:44 +0000117 Py_SIZE(op) = size;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000118 op->allocated = size;
Neil Schemenauere83c00e2001-08-29 23:54:21 +0000119 _PyObject_GC_TRACK(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000120 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000121}
122
Martin v. Löwis18e16552006-02-15 17:27:45 +0000123Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000124PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000125{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000126 if (!PyList_Check(op)) {
127 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000128 return -1;
129 }
130 else
Christian Heimese93237d2007-12-19 02:37:44 +0000131 return Py_SIZE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000132}
133
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000134static PyObject *indexerr = NULL;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000135
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000136PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000137PyList_GetItem(PyObject *op, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000138{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000139 if (!PyList_Check(op)) {
140 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000141 return NULL;
142 }
Christian Heimese93237d2007-12-19 02:37:44 +0000143 if (i < 0 || i >= Py_SIZE(op)) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000144 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000145 indexerr = PyString_FromString(
146 "list index out of range");
147 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000148 return NULL;
149 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000150 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000151}
152
153int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000154PyList_SetItem(register PyObject *op, register Py_ssize_t i,
Fred Drakea2f55112000-07-09 15:16:51 +0000155 register PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000156{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000157 register PyObject *olditem;
158 register PyObject **p;
159 if (!PyList_Check(op)) {
160 Py_XDECREF(newitem);
161 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000162 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000163 }
Christian Heimese93237d2007-12-19 02:37:44 +0000164 if (i < 0 || i >= Py_SIZE(op)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000165 Py_XDECREF(newitem);
166 PyErr_SetString(PyExc_IndexError,
167 "list assignment index out of range");
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000168 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000169 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000170 p = ((PyListObject *)op) -> ob_item + i;
Guido van Rossum5fe60581995-03-09 12:12:50 +0000171 olditem = *p;
172 *p = newitem;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000173 Py_XDECREF(olditem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000174 return 0;
175}
176
177static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000178ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000179{
Christian Heimese93237d2007-12-19 02:37:44 +0000180 Py_ssize_t i, n = Py_SIZE(self);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000181 PyObject **items;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000182 if (v == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000183 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000184 return -1;
185 }
Martin v. Löwisb1ed7fa2006-04-13 07:52:27 +0000186 if (n == PY_SSIZE_T_MAX) {
Trent Micka5846642000-08-13 22:47:45 +0000187 PyErr_SetString(PyExc_OverflowError,
188 "cannot add more objects to list");
189 return -1;
190 }
Tim Petersb38e2b62004-07-29 02:29:26 +0000191
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000192 if (list_resize(self, n+1) == -1)
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000193 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000194
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000195 if (where < 0) {
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000196 where += n;
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000197 if (where < 0)
198 where = 0;
199 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000200 if (where > n)
201 where = n;
202 items = self->ob_item;
203 for (i = n; --i >= where; )
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000204 items[i+1] = items[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000205 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000206 items[where] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000207 return 0;
208}
209
210int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000211PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000212{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000213 if (!PyList_Check(op)) {
214 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000215 return -1;
216 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000217 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000218}
219
Raymond Hettinger40a03822004-04-12 13:05:09 +0000220static int
221app1(PyListObject *self, PyObject *v)
222{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000223 Py_ssize_t n = PyList_GET_SIZE(self);
Raymond Hettinger40a03822004-04-12 13:05:09 +0000224
225 assert (v != NULL);
Martin v. Löwisb1ed7fa2006-04-13 07:52:27 +0000226 if (n == PY_SSIZE_T_MAX) {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000227 PyErr_SetString(PyExc_OverflowError,
228 "cannot add more objects to list");
229 return -1;
230 }
231
232 if (list_resize(self, n+1) == -1)
233 return -1;
234
235 Py_INCREF(v);
236 PyList_SET_ITEM(self, n, v);
237 return 0;
238}
239
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000240int
Fred Drakea2f55112000-07-09 15:16:51 +0000241PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000242{
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000243 if (PyList_Check(op) && (newitem != NULL))
244 return app1((PyListObject *)op, newitem);
245 PyErr_BadInternalCall();
246 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000247}
248
249/* Methods */
250
251static void
Fred Drakea2f55112000-07-09 15:16:51 +0000252list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000253{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000254 Py_ssize_t i;
Guido van Rossumff413af2002-03-28 20:34:59 +0000255 PyObject_GC_UnTrack(op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000256 Py_TRASHCAN_SAFE_BEGIN(op)
Jack Jansen7874d1f1995-01-19 12:09:27 +0000257 if (op->ob_item != NULL) {
Guido van Rossumfa717011999-06-09 15:19:34 +0000258 /* Do it backwards, for Christian Tismer.
259 There's a simple test case where somehow this reduces
260 thrashing when a *very* large list is created and
261 immediately deleted. */
Christian Heimese93237d2007-12-19 02:37:44 +0000262 i = Py_SIZE(op);
Guido van Rossumfa717011999-06-09 15:19:34 +0000263 while (--i >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000264 Py_XDECREF(op->ob_item[i]);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000265 }
Guido van Rossumb18618d2000-05-03 23:44:39 +0000266 PyMem_FREE(op->ob_item);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000267 }
Raymond Hettinger0468e412004-05-05 05:37:53 +0000268 if (num_free_lists < MAXFREELISTS && PyList_CheckExact(op))
269 free_lists[num_free_lists++] = op;
Tim Petersb38e2b62004-07-29 02:29:26 +0000270 else
Christian Heimese93237d2007-12-19 02:37:44 +0000271 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000272 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000273}
274
Guido van Rossum90933611991-06-07 16:10:43 +0000275static int
Fred Drakea2f55112000-07-09 15:16:51 +0000276list_print(PyListObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000277{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000278 int rc;
279 Py_ssize_t i;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000280
Martin v. Löwis18e16552006-02-15 17:27:45 +0000281 rc = Py_ReprEnter((PyObject*)op);
282 if (rc != 0) {
283 if (rc < 0)
284 return rc;
Brett Cannon01531592007-09-17 03:28:34 +0000285 Py_BEGIN_ALLOW_THREADS
Guido van Rossumfb376de1998-04-10 22:47:27 +0000286 fprintf(fp, "[...]");
Brett Cannon01531592007-09-17 03:28:34 +0000287 Py_END_ALLOW_THREADS
Guido van Rossumfb376de1998-04-10 22:47:27 +0000288 return 0;
289 }
Brett Cannon01531592007-09-17 03:28:34 +0000290 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000291 fprintf(fp, "[");
Brett Cannon01531592007-09-17 03:28:34 +0000292 Py_END_ALLOW_THREADS
Christian Heimese93237d2007-12-19 02:37:44 +0000293 for (i = 0; i < Py_SIZE(op); i++) {
Brett Cannon01531592007-09-17 03:28:34 +0000294 if (i > 0) {
295 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000296 fprintf(fp, ", ");
Brett Cannon01531592007-09-17 03:28:34 +0000297 Py_END_ALLOW_THREADS
298 }
Guido van Rossumfb376de1998-04-10 22:47:27 +0000299 if (PyObject_Print(op->ob_item[i], fp, 0) != 0) {
300 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000301 return -1;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000302 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000303 }
Brett Cannon01531592007-09-17 03:28:34 +0000304 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000305 fprintf(fp, "]");
Brett Cannon01531592007-09-17 03:28:34 +0000306 Py_END_ALLOW_THREADS
Guido van Rossumfb376de1998-04-10 22:47:27 +0000307 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000308 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000309}
310
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000311static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000312list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000313{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000314 Py_ssize_t i;
Tim Petersa7259592001-06-16 05:11:17 +0000315 PyObject *s, *temp;
316 PyObject *pieces = NULL, *result = NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000317
318 i = Py_ReprEnter((PyObject*)v);
319 if (i != 0) {
Tim Petersa7259592001-06-16 05:11:17 +0000320 return i > 0 ? PyString_FromString("[...]") : NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000321 }
Tim Petersa7259592001-06-16 05:11:17 +0000322
Christian Heimese93237d2007-12-19 02:37:44 +0000323 if (Py_SIZE(v) == 0) {
Tim Petersa7259592001-06-16 05:11:17 +0000324 result = PyString_FromString("[]");
325 goto Done;
326 }
327
328 pieces = PyList_New(0);
329 if (pieces == NULL)
330 goto Done;
331
332 /* Do repr() on each element. Note that this may mutate the list,
333 so must refetch the list size on each iteration. */
Christian Heimese93237d2007-12-19 02:37:44 +0000334 for (i = 0; i < Py_SIZE(v); ++i) {
Tim Petersa7259592001-06-16 05:11:17 +0000335 int status;
Brett Cannona0c05512007-09-10 21:38:27 +0000336 if (Py_EnterRecursiveCall(" while getting the repr of a list"))
337 goto Done;
Tim Petersa7259592001-06-16 05:11:17 +0000338 s = PyObject_Repr(v->ob_item[i]);
Brett Cannona0c05512007-09-10 21:38:27 +0000339 Py_LeaveRecursiveCall();
Tim Petersa7259592001-06-16 05:11:17 +0000340 if (s == NULL)
341 goto Done;
342 status = PyList_Append(pieces, s);
343 Py_DECREF(s); /* append created a new ref */
344 if (status < 0)
345 goto Done;
346 }
347
348 /* Add "[]" decorations to the first and last items. */
349 assert(PyList_GET_SIZE(pieces) > 0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000350 s = PyString_FromString("[");
Tim Petersa7259592001-06-16 05:11:17 +0000351 if (s == NULL)
352 goto Done;
353 temp = PyList_GET_ITEM(pieces, 0);
354 PyString_ConcatAndDel(&s, temp);
355 PyList_SET_ITEM(pieces, 0, s);
356 if (s == NULL)
357 goto Done;
358
359 s = PyString_FromString("]");
360 if (s == NULL)
361 goto Done;
362 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
363 PyString_ConcatAndDel(&temp, s);
364 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
365 if (temp == NULL)
366 goto Done;
367
368 /* Paste them all together with ", " between. */
369 s = PyString_FromString(", ");
370 if (s == NULL)
371 goto Done;
372 result = _PyString_Join(s, pieces);
Tim Peters3b01a122002-07-19 02:35:45 +0000373 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +0000374
375Done:
376 Py_XDECREF(pieces);
Guido van Rossumfb376de1998-04-10 22:47:27 +0000377 Py_ReprLeave((PyObject *)v);
Tim Petersa7259592001-06-16 05:11:17 +0000378 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000379}
380
Martin v. Löwis18e16552006-02-15 17:27:45 +0000381static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000382list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000383{
Christian Heimese93237d2007-12-19 02:37:44 +0000384 return Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000385}
386
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000387static int
Fred Drakea2f55112000-07-09 15:16:51 +0000388list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000389{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000390 Py_ssize_t i;
391 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000392
Christian Heimese93237d2007-12-19 02:37:44 +0000393 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
Raymond Hettingeraae59992002-09-05 14:23:49 +0000394 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000395 Py_EQ);
Neal Norwitzbb9c5f52002-09-05 21:32:55 +0000396 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000397}
398
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000399static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000400list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000401{
Christian Heimese93237d2007-12-19 02:37:44 +0000402 if (i < 0 || i >= Py_SIZE(a)) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000403 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000404 indexerr = PyString_FromString(
405 "list index out of range");
406 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000407 return NULL;
408 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000409 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000410 return a->ob_item[i];
411}
412
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000413static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000414list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000415{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000416 PyListObject *np;
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000417 PyObject **src, **dest;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000418 Py_ssize_t i, len;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000419 if (ilow < 0)
420 ilow = 0;
Christian Heimese93237d2007-12-19 02:37:44 +0000421 else if (ilow > Py_SIZE(a))
422 ilow = Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000423 if (ihigh < ilow)
424 ihigh = ilow;
Christian Heimese93237d2007-12-19 02:37:44 +0000425 else if (ihigh > Py_SIZE(a))
426 ihigh = Py_SIZE(a);
Raymond Hettinger99842b62004-03-08 05:56:15 +0000427 len = ihigh - ilow;
428 np = (PyListObject *) PyList_New(len);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000429 if (np == NULL)
430 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000431
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000432 src = a->ob_item + ilow;
433 dest = np->ob_item;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000434 for (i = 0; i < len; i++) {
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000435 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000436 Py_INCREF(v);
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000437 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000438 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000439 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000440}
441
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000442PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000443PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000444{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000445 if (!PyList_Check(a)) {
446 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000447 return NULL;
448 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000449 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000450}
451
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000452static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000453list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000454{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000455 Py_ssize_t size;
456 Py_ssize_t i;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000457 PyObject **src, **dest;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000458 PyListObject *np;
459 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000460 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000461 "can only concatenate list (not \"%.200s\") to list",
462 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000463 return NULL;
464 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000465#define b ((PyListObject *)bb)
Christian Heimese93237d2007-12-19 02:37:44 +0000466 size = Py_SIZE(a) + Py_SIZE(b);
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000467 if (size < 0)
468 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000469 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000470 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000471 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000472 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000473 src = a->ob_item;
474 dest = np->ob_item;
Christian Heimese93237d2007-12-19 02:37:44 +0000475 for (i = 0; i < Py_SIZE(a); i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000476 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000477 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000478 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000479 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000480 src = b->ob_item;
Christian Heimese93237d2007-12-19 02:37:44 +0000481 dest = np->ob_item + Py_SIZE(a);
482 for (i = 0; i < Py_SIZE(b); i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000483 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000484 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000485 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000486 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000487 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000488#undef b
489}
490
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000491static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000492list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000493{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000494 Py_ssize_t i, j;
495 Py_ssize_t size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000496 PyListObject *np;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000497 PyObject **p, **items;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000498 PyObject *elem;
Guido van Rossumed98d481991-03-06 13:07:53 +0000499 if (n < 0)
500 n = 0;
Christian Heimese93237d2007-12-19 02:37:44 +0000501 size = Py_SIZE(a) * n;
502 if (n && size/n != Py_SIZE(a))
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000503 return PyErr_NoMemory();
Armin Rigoa1e42e12007-10-17 18:46:37 +0000504 if (size == 0)
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000505 return PyList_New(0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000506 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000507 if (np == NULL)
508 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000509
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000510 items = np->ob_item;
Christian Heimese93237d2007-12-19 02:37:44 +0000511 if (Py_SIZE(a) == 1) {
Raymond Hettinger6624e682003-05-21 05:58:46 +0000512 elem = a->ob_item[0];
513 for (i = 0; i < n; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000514 items[i] = elem;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000515 Py_INCREF(elem);
516 }
517 return (PyObject *) np;
518 }
Guido van Rossumed98d481991-03-06 13:07:53 +0000519 p = np->ob_item;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000520 items = a->ob_item;
Guido van Rossumed98d481991-03-06 13:07:53 +0000521 for (i = 0; i < n; i++) {
Christian Heimese93237d2007-12-19 02:37:44 +0000522 for (j = 0; j < Py_SIZE(a); j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000523 *p = items[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000524 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000525 p++;
526 }
527 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000528 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000529}
530
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000531static int
Armin Rigo93677f02004-07-29 12:40:23 +0000532list_clear(PyListObject *a)
533{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000534 Py_ssize_t i;
Armin Rigo93677f02004-07-29 12:40:23 +0000535 PyObject **item = a->ob_item;
536 if (item != NULL) {
537 /* Because XDECREF can recursively invoke operations on
538 this list, we make it empty first. */
Christian Heimese93237d2007-12-19 02:37:44 +0000539 i = Py_SIZE(a);
540 Py_SIZE(a) = 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000541 a->ob_item = NULL;
542 a->allocated = 0;
543 while (--i >= 0) {
544 Py_XDECREF(item[i]);
545 }
546 PyMem_FREE(item);
547 }
548 /* Never fails; the return value can be ignored.
549 Note that there is no guarantee that the list is actually empty
550 at this point, because XDECREF may have populated it again! */
551 return 0;
552}
553
Tim Peters8fc4a912004-07-31 21:53:19 +0000554/* a[ilow:ihigh] = v if v != NULL.
555 * del a[ilow:ihigh] if v == NULL.
556 *
557 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
558 * guaranteed the call cannot fail.
559 */
Armin Rigo93677f02004-07-29 12:40:23 +0000560static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000561list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000562{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000563 /* Because [X]DECREF can recursively invoke list operations on
564 this list, we must postpone all [X]DECREF activity until
565 after the list is back in its canonical shape. Therefore
566 we must allocate an additional array, 'recycle', into which
567 we temporarily copy the items that are deleted from the
568 list. :-( */
Tim Peters73572222004-07-31 02:54:42 +0000569 PyObject *recycle_on_stack[8];
570 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000571 PyObject **item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000572 PyObject **vitem = NULL;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000573 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000574 Py_ssize_t n; /* # of elements in replacement list */
575 Py_ssize_t norig; /* # of elements in list getting replaced */
576 Py_ssize_t d; /* Change in size */
577 Py_ssize_t k;
Tim Peters8d9eb102004-07-31 02:24:20 +0000578 size_t s;
579 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000580#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000581 if (v == NULL)
582 n = 0;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000583 else {
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000584 if (a == b) {
585 /* Special case "a[i:j] = a" -- copy b first */
Christian Heimese93237d2007-12-19 02:37:44 +0000586 v = list_slice(b, 0, Py_SIZE(b));
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000587 if (v == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000588 return result;
589 result = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000590 Py_DECREF(v);
Tim Peters8d9eb102004-07-31 02:24:20 +0000591 return result;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000592 }
Raymond Hettingerf889e102004-03-09 08:04:33 +0000593 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000594 if(v_as_SF == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000595 goto Error;
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000596 n = PySequence_Fast_GET_SIZE(v_as_SF);
Raymond Hettinger42bec932004-03-12 16:38:17 +0000597 vitem = PySequence_Fast_ITEMS(v_as_SF);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000598 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000599 if (ilow < 0)
600 ilow = 0;
Christian Heimese93237d2007-12-19 02:37:44 +0000601 else if (ilow > Py_SIZE(a))
602 ilow = Py_SIZE(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000603
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000604 if (ihigh < ilow)
605 ihigh = ilow;
Christian Heimese93237d2007-12-19 02:37:44 +0000606 else if (ihigh > Py_SIZE(a))
607 ihigh = Py_SIZE(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000608
Tim Peters8d9eb102004-07-31 02:24:20 +0000609 norig = ihigh - ilow;
610 assert(norig >= 0);
611 d = n - norig;
Christian Heimese93237d2007-12-19 02:37:44 +0000612 if (Py_SIZE(a) + d == 0) {
Armin Rigo93677f02004-07-29 12:40:23 +0000613 Py_XDECREF(v_as_SF);
614 return list_clear(a);
615 }
616 item = a->ob_item;
Tim Peters8d9eb102004-07-31 02:24:20 +0000617 /* recycle the items that we are about to remove */
618 s = norig * sizeof(PyObject *);
Tim Peters73572222004-07-31 02:54:42 +0000619 if (s > sizeof(recycle_on_stack)) {
Armin Rigo1dd04a02004-07-30 11:38:22 +0000620 recycle = (PyObject **)PyMem_MALLOC(s);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000621 if (recycle == NULL) {
622 PyErr_NoMemory();
Tim Peters8d9eb102004-07-31 02:24:20 +0000623 goto Error;
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000624 }
625 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000626 memcpy(recycle, &item[ilow], s);
Tim Peters8d9eb102004-07-31 02:24:20 +0000627
Armin Rigo1dd04a02004-07-30 11:38:22 +0000628 if (d < 0) { /* Delete -d items */
629 memmove(&item[ihigh+d], &item[ihigh],
Christian Heimese93237d2007-12-19 02:37:44 +0000630 (Py_SIZE(a) - ihigh)*sizeof(PyObject *));
631 list_resize(a, Py_SIZE(a) + d);
Armin Rigo1dd04a02004-07-30 11:38:22 +0000632 item = a->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000633 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000634 else if (d > 0) { /* Insert d items */
Christian Heimese93237d2007-12-19 02:37:44 +0000635 k = Py_SIZE(a);
Tim Peters73572222004-07-31 02:54:42 +0000636 if (list_resize(a, k+d) < 0)
Tim Peters8d9eb102004-07-31 02:24:20 +0000637 goto Error;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000638 item = a->ob_item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000639 memmove(&item[ihigh+d], &item[ihigh],
Tim Peters73572222004-07-31 02:54:42 +0000640 (k - ihigh)*sizeof(PyObject *));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000641 }
642 for (k = 0; k < n; k++, ilow++) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000643 PyObject *w = vitem[k];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000644 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000645 item[ilow] = w;
646 }
Tim Peters73572222004-07-31 02:54:42 +0000647 for (k = norig - 1; k >= 0; --k)
648 Py_XDECREF(recycle[k]);
Tim Peters8d9eb102004-07-31 02:24:20 +0000649 result = 0;
650 Error:
Tim Peters73572222004-07-31 02:54:42 +0000651 if (recycle != recycle_on_stack)
Armin Rigo1dd04a02004-07-30 11:38:22 +0000652 PyMem_FREE(recycle);
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000653 Py_XDECREF(v_as_SF);
Tim Peters8d9eb102004-07-31 02:24:20 +0000654 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000655#undef b
656}
657
Guido van Rossum234f9421993-06-17 12:35:49 +0000658int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000659PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000660{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000661 if (!PyList_Check(a)) {
662 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000663 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000664 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000665 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000666}
667
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000668static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000669list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000670{
671 PyObject **items;
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000672 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000673
674
675 size = PyList_GET_SIZE(self);
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000676 if (size == 0 || n == 1) {
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000677 Py_INCREF(self);
678 return (PyObject *)self;
679 }
680
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000681 if (n < 1) {
Armin Rigo93677f02004-07-29 12:40:23 +0000682 (void)list_clear(self);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000683 Py_INCREF(self);
684 return (PyObject *)self;
685 }
686
Thomas Woutersa97744c2008-01-25 21:09:34 +0000687 if (size > PY_SSIZE_T_MAX / n) {
Armin Rigoa1e42e12007-10-17 18:46:37 +0000688 return PyErr_NoMemory();
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000689 }
690
691 if (list_resize(self, size*n) == -1)
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000692 return NULL;
693
694 p = size;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000695 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000696 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
697 for (j = 0; j < size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000698 PyObject *o = items[j];
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000699 Py_INCREF(o);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000700 items[p++] = o;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000701 }
702 }
703 Py_INCREF(self);
704 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000705}
706
Guido van Rossum4a450d01991-04-03 19:05:18 +0000707static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000708list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000709{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000710 PyObject *old_value;
Christian Heimese93237d2007-12-19 02:37:44 +0000711 if (i < 0 || i >= Py_SIZE(a)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000712 PyErr_SetString(PyExc_IndexError,
713 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000714 return -1;
715 }
716 if (v == NULL)
717 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000718 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000719 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000720 a->ob_item[i] = v;
Tim Peters3b01a122002-07-19 02:35:45 +0000721 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000722 return 0;
723}
724
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000725static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000726listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000727{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000728 Py_ssize_t i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000729 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000730 if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000731 return NULL;
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000732 if (ins1(self, i, v) == 0)
733 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000734 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000735}
736
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000737static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000738listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000739{
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000740 if (app1(self, v) == 0)
741 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000742 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000743}
744
Barry Warsawdedf6d61998-10-09 16:37:25 +0000745static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000746listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000747{
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000748 PyObject *it; /* iter(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000749 Py_ssize_t m; /* size of self */
750 Py_ssize_t n; /* guess for size of b */
751 Py_ssize_t mn; /* m + n */
752 Py_ssize_t i;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000753 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000754
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000755 /* Special cases:
Tim Petersb38e2b62004-07-29 02:29:26 +0000756 1) lists and tuples which can use PySequence_Fast ops
757 2) extending self to self requires making a copy first
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000758 */
759 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
Armin Rigo70d172d2004-03-20 22:19:23 +0000760 PyObject **src, **dest;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000761 b = PySequence_Fast(b, "argument must be iterable");
762 if (!b)
763 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000764 n = PySequence_Fast_GET_SIZE(b);
765 if (n == 0) {
766 /* short circuit when b is empty */
767 Py_DECREF(b);
768 Py_RETURN_NONE;
769 }
Christian Heimese93237d2007-12-19 02:37:44 +0000770 m = Py_SIZE(self);
Armin Rigo70d172d2004-03-20 22:19:23 +0000771 if (list_resize(self, m + n) == -1) {
772 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000773 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000774 }
775 /* note that we may still have self == b here for the
776 * situation a.extend(a), but the following code works
777 * in that case too. Just make sure to resize self
778 * before calling PySequence_Fast_ITEMS.
779 */
780 /* populate the end of self with b's items */
781 src = PySequence_Fast_ITEMS(b);
782 dest = self->ob_item + m;
783 for (i = 0; i < n; i++) {
784 PyObject *o = src[i];
785 Py_INCREF(o);
786 dest[i] = o;
787 }
788 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000789 Py_RETURN_NONE;
790 }
791
792 it = PyObject_GetIter(b);
793 if (it == NULL)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000794 return NULL;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000795 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000796
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000797 /* Guess a result list size. */
Raymond Hettinger4e2f7142007-12-06 00:56:53 +0000798 n = _PyObject_LengthHint(b, 8);
Christian Heimese93237d2007-12-19 02:37:44 +0000799 m = Py_SIZE(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000800 mn = m + n;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000801 if (mn >= m) {
802 /* Make room. */
803 if (list_resize(self, mn) == -1)
804 goto error;
805 /* Make the list sane again. */
Christian Heimese93237d2007-12-19 02:37:44 +0000806 Py_SIZE(self) = m;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000807 }
808 /* Else m + n overflowed; on the chance that n lied, and there really
809 * is enough room, ignore it. If n was telling the truth, we'll
810 * eventually run out of memory during the loop.
811 */
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000812
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000813 /* Run iterator to exhaustion. */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000814 for (;;) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000815 PyObject *item = iternext(it);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000816 if (item == NULL) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000817 if (PyErr_Occurred()) {
818 if (PyErr_ExceptionMatches(PyExc_StopIteration))
819 PyErr_Clear();
820 else
821 goto error;
822 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000823 break;
824 }
Christian Heimese93237d2007-12-19 02:37:44 +0000825 if (Py_SIZE(self) < self->allocated) {
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000826 /* steals ref */
Christian Heimese93237d2007-12-19 02:37:44 +0000827 PyList_SET_ITEM(self, Py_SIZE(self), item);
828 ++Py_SIZE(self);
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000829 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000830 else {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000831 int status = app1(self, item);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000832 Py_DECREF(item); /* append creates a new ref */
833 if (status < 0)
834 goto error;
835 }
836 }
837
838 /* Cut back result list if initial guess was too large. */
Christian Heimese93237d2007-12-19 02:37:44 +0000839 if (Py_SIZE(self) < self->allocated)
840 list_resize(self, Py_SIZE(self)); /* shrinking can't fail */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000841
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000842 Py_DECREF(it);
843 Py_RETURN_NONE;
844
845 error:
846 Py_DECREF(it);
847 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000848}
849
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000850PyObject *
851_PyList_Extend(PyListObject *self, PyObject *b)
852{
853 return listextend(self, b);
854}
855
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000856static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000857list_inplace_concat(PyListObject *self, PyObject *other)
858{
859 PyObject *result;
860
861 result = listextend(self, other);
862 if (result == NULL)
863 return result;
864 Py_DECREF(result);
865 Py_INCREF(self);
866 return (PyObject *)self;
867}
868
869static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000870listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000871{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000872 Py_ssize_t i = -1;
Armin Rigo7ccbca92006-10-04 12:17:45 +0000873 PyObject *v;
Tim Peters8fc4a912004-07-31 21:53:19 +0000874 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000875
Armin Rigo7ccbca92006-10-04 12:17:45 +0000876 if (!PyArg_ParseTuple(args, "|n:pop", &i))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000877 return NULL;
Armin Rigo7ccbca92006-10-04 12:17:45 +0000878
Christian Heimese93237d2007-12-19 02:37:44 +0000879 if (Py_SIZE(self) == 0) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000880 /* Special-case most common failure cause */
881 PyErr_SetString(PyExc_IndexError, "pop from empty list");
882 return NULL;
883 }
884 if (i < 0)
Christian Heimese93237d2007-12-19 02:37:44 +0000885 i += Py_SIZE(self);
886 if (i < 0 || i >= Py_SIZE(self)) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000887 PyErr_SetString(PyExc_IndexError, "pop index out of range");
888 return NULL;
889 }
890 v = self->ob_item[i];
Christian Heimese93237d2007-12-19 02:37:44 +0000891 if (i == Py_SIZE(self) - 1) {
892 status = list_resize(self, Py_SIZE(self) - 1);
Tim Peters8fc4a912004-07-31 21:53:19 +0000893 assert(status >= 0);
894 return v; /* and v now owns the reference the list had */
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000895 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000896 Py_INCREF(v);
Tim Peters8fc4a912004-07-31 21:53:19 +0000897 status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
898 assert(status >= 0);
899 /* Use status, so that in a release build compilers don't
900 * complain about the unused name.
901 */
Brett Cannon651dd522004-08-08 21:21:18 +0000902 (void) status;
903
904 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000905}
906
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000907/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
908static void
909reverse_slice(PyObject **lo, PyObject **hi)
910{
911 assert(lo && hi);
912
913 --hi;
914 while (lo < hi) {
915 PyObject *t = *lo;
916 *lo = *hi;
917 *hi = t;
918 ++lo;
919 --hi;
920 }
921}
922
Tim Petersa64dc242002-08-01 02:13:36 +0000923/* Lots of code for an adaptive, stable, natural mergesort. There are many
924 * pieces to this algorithm; read listsort.txt for overviews and details.
925 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000926
Guido van Rossum3f236de1996-12-10 23:55:39 +0000927/* Comparison function. Takes care of calling a user-supplied
Tim Peters66860f62002-08-04 17:47:26 +0000928 * comparison function (any callable Python object), which must not be
929 * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool
930 * with Py_LT if you know it's NULL).
Tim Petersa64dc242002-08-01 02:13:36 +0000931 * Returns -1 on error, 1 if x < y, 0 if x >= y.
932 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000933static int
Tim Petersa8c974c2002-07-19 03:30:57 +0000934islt(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000935{
Tim Petersf2a04732002-07-11 21:46:16 +0000936 PyObject *res;
937 PyObject *args;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000938 Py_ssize_t i;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000939
Tim Peters66860f62002-08-04 17:47:26 +0000940 assert(compare != NULL);
Tim Petersa8c974c2002-07-19 03:30:57 +0000941 /* Call the user's comparison function and translate the 3-way
942 * result into true or false (or error).
943 */
Tim Petersf2a04732002-07-11 21:46:16 +0000944 args = PyTuple_New(2);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000945 if (args == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000946 return -1;
Tim Petersf2a04732002-07-11 21:46:16 +0000947 Py_INCREF(x);
948 Py_INCREF(y);
949 PyTuple_SET_ITEM(args, 0, x);
950 PyTuple_SET_ITEM(args, 1, y);
Tim Peters58cf3612002-07-15 05:16:13 +0000951 res = PyObject_Call(compare, args, NULL);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000952 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000953 if (res == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000954 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000955 if (!PyInt_Check(res)) {
Georg Brandl283a1352006-11-19 08:48:30 +0000956 PyErr_Format(PyExc_TypeError,
957 "comparison function must return int, not %.200s",
958 res->ob_type->tp_name);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000959 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +0000960 return -1;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000961 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000962 i = PyInt_AsLong(res);
963 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +0000964 return i < 0;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000965}
966
Tim Peters66860f62002-08-04 17:47:26 +0000967/* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
968 * islt. This avoids a layer of function call in the usual case, and
969 * sorting does many comparisons.
970 * Returns -1 on error, 1 if x < y, 0 if x >= y.
971 */
972#define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
973 PyObject_RichCompareBool(X, Y, Py_LT) : \
974 islt(X, Y, COMPARE))
975
976/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +0000977 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
978 started. It makes more sense in context <wink>. X and Y are PyObject*s.
979*/
Tim Peters66860f62002-08-04 17:47:26 +0000980#define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
Tim Petersa8c974c2002-07-19 03:30:57 +0000981 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000982
983/* binarysort is the best method for sorting small arrays: it does
984 few compares, but can do data movement quadratic in the number of
985 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000986 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +0000987 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000988 On entry, must have lo <= start <= hi, and that [lo, start) is already
989 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +0000990 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000991 Even in case of error, the output slice will be some permutation of
992 the input (nothing is lost or duplicated).
993*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000994static int
Fred Drakea2f55112000-07-09 15:16:51 +0000995binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
996 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000997{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000998 register Py_ssize_t k;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000999 register PyObject **l, **p, **r;
1000 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001001
Tim Petersa8c974c2002-07-19 03:30:57 +00001002 assert(lo <= start && start <= hi);
1003 /* assert [lo, start) is sorted */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001004 if (lo == start)
1005 ++start;
1006 for (; start < hi; ++start) {
1007 /* set l to where *start belongs */
1008 l = lo;
1009 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001010 pivot = *r;
Tim Peters0fe977c2002-07-19 06:12:32 +00001011 /* Invariants:
1012 * pivot >= all in [lo, l).
1013 * pivot < all in [r, start).
1014 * The second is vacuously true at the start.
1015 */
1016 assert(l < r);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001017 do {
1018 p = l + ((r - l) >> 1);
Tim Petersa8c974c2002-07-19 03:30:57 +00001019 IFLT(pivot, *p)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001020 r = p;
1021 else
Tim Peters0fe977c2002-07-19 06:12:32 +00001022 l = p+1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001023 } while (l < r);
Tim Peters0fe977c2002-07-19 06:12:32 +00001024 assert(l == r);
1025 /* The invariants still hold, so pivot >= all in [lo, l) and
1026 pivot < all in [l, start), so pivot belongs at l. Note
1027 that if there are elements equal to pivot, l points to the
1028 first slot after them -- that's why this sort is stable.
1029 Slide over to make room.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001030 Caution: using memmove is much slower under MSVC 5;
1031 we're not usually moving many slots. */
1032 for (p = start; p > l; --p)
1033 *p = *(p-1);
1034 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001035 }
Guido van Rossum3f236de1996-12-10 23:55:39 +00001036 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001037
1038 fail:
1039 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001040}
1041
Tim Petersa64dc242002-08-01 02:13:36 +00001042/*
1043Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1044is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001045
Tim Petersa64dc242002-08-01 02:13:36 +00001046 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001047
Tim Petersa64dc242002-08-01 02:13:36 +00001048or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001049
Tim Petersa64dc242002-08-01 02:13:36 +00001050 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001051
Tim Petersa64dc242002-08-01 02:13:36 +00001052Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1053For its intended use in a stable mergesort, the strictness of the defn of
1054"descending" is needed so that the caller can safely reverse a descending
1055sequence without violating stability (strict > ensures there are no equal
1056elements to get out of order).
1057
1058Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001059*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001060static Py_ssize_t
Tim Petersa64dc242002-08-01 02:13:36 +00001061count_run(PyObject **lo, PyObject **hi, PyObject *compare, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001062{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001063 Py_ssize_t k;
1064 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001065
Tim Petersa64dc242002-08-01 02:13:36 +00001066 assert(lo < hi);
1067 *descending = 0;
1068 ++lo;
1069 if (lo == hi)
1070 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001071
Tim Petersa64dc242002-08-01 02:13:36 +00001072 n = 2;
1073 IFLT(*lo, *(lo-1)) {
1074 *descending = 1;
1075 for (lo = lo+1; lo < hi; ++lo, ++n) {
1076 IFLT(*lo, *(lo-1))
1077 ;
1078 else
1079 break;
1080 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001081 }
Tim Petersa64dc242002-08-01 02:13:36 +00001082 else {
1083 for (lo = lo+1; lo < hi; ++lo, ++n) {
1084 IFLT(*lo, *(lo-1))
1085 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001086 }
1087 }
1088
Tim Petersa64dc242002-08-01 02:13:36 +00001089 return n;
1090fail:
1091 return -1;
1092}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001093
Tim Petersa64dc242002-08-01 02:13:36 +00001094/*
1095Locate the proper position of key in a sorted vector; if the vector contains
1096an element equal to key, return the position immediately to the left of
1097the leftmost equal element. [gallop_right() does the same except returns
1098the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001099
Tim Petersa64dc242002-08-01 02:13:36 +00001100"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001101
Tim Petersa64dc242002-08-01 02:13:36 +00001102"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1103hint is to the final result, the faster this runs.
1104
1105The return value is the int k in 0..n such that
1106
1107 a[k-1] < key <= a[k]
1108
1109pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1110key belongs at index k; or, IOW, the first k elements of a should precede
1111key, and the last n-k should follow key.
1112
1113Returns -1 on error. See listsort.txt for info on the method.
1114*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001115static Py_ssize_t
1116gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
Tim Petersa64dc242002-08-01 02:13:36 +00001117{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001118 Py_ssize_t ofs;
1119 Py_ssize_t lastofs;
1120 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001121
1122 assert(key && a && n > 0 && hint >= 0 && hint < n);
1123
1124 a += hint;
1125 lastofs = 0;
1126 ofs = 1;
1127 IFLT(*a, key) {
1128 /* a[hint] < key -- gallop right, until
1129 * a[hint + lastofs] < key <= a[hint + ofs]
1130 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001131 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001132 while (ofs < maxofs) {
1133 IFLT(a[ofs], key) {
1134 lastofs = ofs;
1135 ofs = (ofs << 1) + 1;
1136 if (ofs <= 0) /* int overflow */
1137 ofs = maxofs;
1138 }
1139 else /* key <= a[hint + ofs] */
1140 break;
1141 }
1142 if (ofs > maxofs)
1143 ofs = maxofs;
1144 /* Translate back to offsets relative to &a[0]. */
1145 lastofs += hint;
1146 ofs += hint;
1147 }
1148 else {
1149 /* key <= a[hint] -- gallop left, until
1150 * a[hint - ofs] < key <= a[hint - lastofs]
1151 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001152 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001153 while (ofs < maxofs) {
1154 IFLT(*(a-ofs), key)
1155 break;
1156 /* key <= a[hint - ofs] */
1157 lastofs = ofs;
1158 ofs = (ofs << 1) + 1;
1159 if (ofs <= 0) /* int overflow */
1160 ofs = maxofs;
1161 }
1162 if (ofs > maxofs)
1163 ofs = maxofs;
1164 /* Translate back to positive offsets relative to &a[0]. */
1165 k = lastofs;
1166 lastofs = hint - ofs;
1167 ofs = hint - k;
1168 }
1169 a -= hint;
1170
1171 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1172 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1173 * right of lastofs but no farther right than ofs. Do a binary
1174 * search, with invariant a[lastofs-1] < key <= a[ofs].
1175 */
1176 ++lastofs;
1177 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001178 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001179
1180 IFLT(a[m], key)
1181 lastofs = m+1; /* a[m] < key */
1182 else
1183 ofs = m; /* key <= a[m] */
1184 }
1185 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1186 return ofs;
1187
1188fail:
1189 return -1;
1190}
1191
1192/*
1193Exactly like gallop_left(), except that if key already exists in a[0:n],
1194finds the position immediately to the right of the rightmost equal value.
1195
1196The return value is the int k in 0..n such that
1197
1198 a[k-1] <= key < a[k]
1199
1200or -1 if error.
1201
1202The code duplication is massive, but this is enough different given that
1203we're sticking to "<" comparisons that it's much harder to follow if
1204written as one routine with yet another "left or right?" flag.
1205*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001206static Py_ssize_t
1207gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
Tim Petersa64dc242002-08-01 02:13:36 +00001208{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001209 Py_ssize_t ofs;
1210 Py_ssize_t lastofs;
1211 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001212
1213 assert(key && a && n > 0 && hint >= 0 && hint < n);
1214
1215 a += hint;
1216 lastofs = 0;
1217 ofs = 1;
1218 IFLT(key, *a) {
1219 /* key < a[hint] -- gallop left, until
1220 * a[hint - ofs] <= key < a[hint - lastofs]
1221 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001222 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001223 while (ofs < maxofs) {
1224 IFLT(key, *(a-ofs)) {
1225 lastofs = ofs;
1226 ofs = (ofs << 1) + 1;
1227 if (ofs <= 0) /* int overflow */
1228 ofs = maxofs;
1229 }
1230 else /* a[hint - ofs] <= key */
1231 break;
1232 }
1233 if (ofs > maxofs)
1234 ofs = maxofs;
1235 /* Translate back to positive offsets relative to &a[0]. */
1236 k = lastofs;
1237 lastofs = hint - ofs;
1238 ofs = hint - k;
1239 }
1240 else {
1241 /* a[hint] <= key -- gallop right, until
1242 * a[hint + lastofs] <= key < a[hint + ofs]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001243 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001244 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001245 while (ofs < maxofs) {
1246 IFLT(key, a[ofs])
1247 break;
1248 /* a[hint + ofs] <= key */
1249 lastofs = ofs;
1250 ofs = (ofs << 1) + 1;
1251 if (ofs <= 0) /* int overflow */
1252 ofs = maxofs;
1253 }
1254 if (ofs > maxofs)
1255 ofs = maxofs;
1256 /* Translate back to offsets relative to &a[0]. */
1257 lastofs += hint;
1258 ofs += hint;
1259 }
1260 a -= hint;
1261
1262 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1263 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1264 * right of lastofs but no farther right than ofs. Do a binary
1265 * search, with invariant a[lastofs-1] <= key < a[ofs].
1266 */
1267 ++lastofs;
1268 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001269 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001270
1271 IFLT(key, a[m])
1272 ofs = m; /* key < a[m] */
1273 else
1274 lastofs = m+1; /* a[m] <= key */
1275 }
1276 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1277 return ofs;
1278
1279fail:
1280 return -1;
1281}
1282
1283/* The maximum number of entries in a MergeState's pending-runs stack.
1284 * This is enough to sort arrays of size up to about
1285 * 32 * phi ** MAX_MERGE_PENDING
1286 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1287 * with 2**64 elements.
1288 */
1289#define MAX_MERGE_PENDING 85
1290
Tim Peterse05f65a2002-08-10 05:21:15 +00001291/* When we get into galloping mode, we stay there until both runs win less
1292 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001293 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001294#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001295
1296/* Avoid malloc for small temp arrays. */
1297#define MERGESTATE_TEMP_SIZE 256
1298
1299/* One MergeState exists on the stack per invocation of mergesort. It's just
1300 * a convenient way to pass state around among the helper functions.
1301 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001302struct s_slice {
1303 PyObject **base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001304 Py_ssize_t len;
Tim Peterse05f65a2002-08-10 05:21:15 +00001305};
1306
Tim Petersa64dc242002-08-01 02:13:36 +00001307typedef struct s_MergeState {
1308 /* The user-supplied comparison function. or NULL if none given. */
1309 PyObject *compare;
1310
Tim Peterse05f65a2002-08-10 05:21:15 +00001311 /* This controls when we get *into* galloping mode. It's initialized
1312 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1313 * random data, and lower for highly structured data.
1314 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001315 Py_ssize_t min_gallop;
Tim Peterse05f65a2002-08-10 05:21:15 +00001316
Tim Petersa64dc242002-08-01 02:13:36 +00001317 /* 'a' is temp storage to help with merges. It contains room for
1318 * alloced entries.
1319 */
1320 PyObject **a; /* may point to temparray below */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001321 Py_ssize_t alloced;
Tim Petersa64dc242002-08-01 02:13:36 +00001322
1323 /* A stack of n pending runs yet to be merged. Run #i starts at
1324 * address base[i] and extends for len[i] elements. It's always
1325 * true (so long as the indices are in bounds) that
1326 *
Tim Peterse05f65a2002-08-10 05:21:15 +00001327 * pending[i].base + pending[i].len == pending[i+1].base
Tim Petersa64dc242002-08-01 02:13:36 +00001328 *
1329 * so we could cut the storage for this, but it's a minor amount,
1330 * and keeping all the info explicit simplifies the code.
1331 */
1332 int n;
Tim Peterse05f65a2002-08-10 05:21:15 +00001333 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001334
1335 /* 'a' points to this when possible, rather than muck with malloc. */
1336 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1337} MergeState;
1338
1339/* Conceptually a MergeState's constructor. */
1340static void
1341merge_init(MergeState *ms, PyObject *compare)
1342{
1343 assert(ms != NULL);
1344 ms->compare = compare;
1345 ms->a = ms->temparray;
1346 ms->alloced = MERGESTATE_TEMP_SIZE;
1347 ms->n = 0;
Tim Peterse05f65a2002-08-10 05:21:15 +00001348 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001349}
1350
1351/* Free all the temp memory owned by the MergeState. This must be called
1352 * when you're done with a MergeState, and may be called before then if
1353 * you want to free the temp memory early.
1354 */
1355static void
1356merge_freemem(MergeState *ms)
1357{
1358 assert(ms != NULL);
1359 if (ms->a != ms->temparray)
1360 PyMem_Free(ms->a);
1361 ms->a = ms->temparray;
1362 ms->alloced = MERGESTATE_TEMP_SIZE;
1363}
1364
1365/* Ensure enough temp memory for 'need' array slots is available.
1366 * Returns 0 on success and -1 if the memory can't be gotten.
1367 */
1368static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001369merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001370{
1371 assert(ms != NULL);
1372 if (need <= ms->alloced)
1373 return 0;
1374 /* Don't realloc! That can cost cycles to copy the old data, but
1375 * we don't care what's in the block.
1376 */
1377 merge_freemem(ms);
1378 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1379 if (ms->a) {
1380 ms->alloced = need;
1381 return 0;
1382 }
1383 PyErr_NoMemory();
1384 merge_freemem(ms); /* reset to sane state */
1385 return -1;
1386}
1387#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1388 merge_getmem(MS, NEED))
1389
1390/* Merge the na elements starting at pa with the nb elements starting at pb
1391 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1392 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1393 * merge, and should have na <= nb. See listsort.txt for more info.
1394 * Return 0 if successful, -1 if error.
1395 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001396static Py_ssize_t
1397merge_lo(MergeState *ms, PyObject **pa, Py_ssize_t na,
1398 PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001399{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001400 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001401 PyObject *compare;
1402 PyObject **dest;
1403 int result = -1; /* guilty until proved innocent */
Neal Norwitz7fd96072006-08-19 04:28:55 +00001404 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001405
1406 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1407 if (MERGE_GETMEM(ms, na) < 0)
1408 return -1;
1409 memcpy(ms->a, pa, na * sizeof(PyObject*));
1410 dest = pa;
1411 pa = ms->a;
1412
1413 *dest++ = *pb++;
1414 --nb;
1415 if (nb == 0)
1416 goto Succeed;
1417 if (na == 1)
1418 goto CopyB;
1419
Neal Norwitz7fd96072006-08-19 04:28:55 +00001420 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001421 compare = ms->compare;
1422 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001423 Py_ssize_t acount = 0; /* # of times A won in a row */
1424 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001425
1426 /* Do the straightforward thing until (if ever) one run
1427 * appears to win consistently.
1428 */
1429 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001430 assert(na > 1 && nb > 0);
Tim Peters66860f62002-08-04 17:47:26 +00001431 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001432 if (k) {
1433 if (k < 0)
1434 goto Fail;
1435 *dest++ = *pb++;
1436 ++bcount;
1437 acount = 0;
1438 --nb;
1439 if (nb == 0)
1440 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001441 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001442 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001443 }
1444 else {
Tim Petersa64dc242002-08-01 02:13:36 +00001445 *dest++ = *pa++;
1446 ++acount;
1447 bcount = 0;
1448 --na;
1449 if (na == 1)
1450 goto CopyB;
Tim Peterse05f65a2002-08-10 05:21:15 +00001451 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001452 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001453 }
Tim Petersa64dc242002-08-01 02:13:36 +00001454 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001455
Tim Petersa64dc242002-08-01 02:13:36 +00001456 /* One run is winning so consistently that galloping may
1457 * be a huge win. So try that, and continue galloping until
1458 * (if ever) neither run appears to be winning consistently
1459 * anymore.
1460 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001461 ++min_gallop;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001462 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001463 assert(na > 1 && nb > 0);
1464 min_gallop -= min_gallop > 1;
1465 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001466 k = gallop_right(*pb, pa, na, 0, compare);
1467 acount = k;
1468 if (k) {
1469 if (k < 0)
1470 goto Fail;
1471 memcpy(dest, pa, k * sizeof(PyObject *));
1472 dest += k;
1473 pa += k;
1474 na -= k;
1475 if (na == 1)
1476 goto CopyB;
1477 /* na==0 is impossible now if the comparison
1478 * function is consistent, but we can't assume
1479 * that it is.
1480 */
1481 if (na == 0)
1482 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001483 }
Tim Petersa64dc242002-08-01 02:13:36 +00001484 *dest++ = *pb++;
1485 --nb;
1486 if (nb == 0)
1487 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001488
Tim Petersa64dc242002-08-01 02:13:36 +00001489 k = gallop_left(*pa, pb, nb, 0, compare);
1490 bcount = k;
1491 if (k) {
1492 if (k < 0)
1493 goto Fail;
1494 memmove(dest, pb, k * sizeof(PyObject *));
1495 dest += k;
1496 pb += k;
1497 nb -= k;
1498 if (nb == 0)
1499 goto Succeed;
1500 }
1501 *dest++ = *pa++;
1502 --na;
1503 if (na == 1)
1504 goto CopyB;
1505 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001506 ++min_gallop; /* penalize it for leaving galloping mode */
1507 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001508 }
1509Succeed:
1510 result = 0;
1511Fail:
1512 if (na)
1513 memcpy(dest, pa, na * sizeof(PyObject*));
1514 return result;
1515CopyB:
1516 assert(na == 1 && nb > 0);
1517 /* The last element of pa belongs at the end of the merge. */
1518 memmove(dest, pb, nb * sizeof(PyObject *));
1519 dest[nb] = *pa;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001520 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001521}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001522
Tim Petersa64dc242002-08-01 02:13:36 +00001523/* Merge the na elements starting at pa with the nb elements starting at pb
1524 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1525 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1526 * merge, and should have na >= nb. See listsort.txt for more info.
1527 * Return 0 if successful, -1 if error.
1528 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001529static Py_ssize_t
1530merge_hi(MergeState *ms, PyObject **pa, Py_ssize_t na, PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001531{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001532 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001533 PyObject *compare;
1534 PyObject **dest;
1535 int result = -1; /* guilty until proved innocent */
1536 PyObject **basea;
1537 PyObject **baseb;
Neal Norwitz7fd96072006-08-19 04:28:55 +00001538 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001539
1540 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1541 if (MERGE_GETMEM(ms, nb) < 0)
1542 return -1;
1543 dest = pb + nb - 1;
1544 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1545 basea = pa;
1546 baseb = ms->a;
1547 pb = ms->a + nb - 1;
1548 pa += na - 1;
1549
1550 *dest-- = *pa--;
1551 --na;
1552 if (na == 0)
1553 goto Succeed;
1554 if (nb == 1)
1555 goto CopyA;
1556
Neal Norwitz7fd96072006-08-19 04:28:55 +00001557 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001558 compare = ms->compare;
1559 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001560 Py_ssize_t acount = 0; /* # of times A won in a row */
1561 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001562
1563 /* Do the straightforward thing until (if ever) one run
1564 * appears to win consistently.
1565 */
1566 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001567 assert(na > 0 && nb > 1);
Tim Peters66860f62002-08-04 17:47:26 +00001568 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001569 if (k) {
1570 if (k < 0)
1571 goto Fail;
1572 *dest-- = *pa--;
1573 ++acount;
1574 bcount = 0;
1575 --na;
1576 if (na == 0)
1577 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001578 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001579 break;
1580 }
1581 else {
1582 *dest-- = *pb--;
1583 ++bcount;
1584 acount = 0;
1585 --nb;
1586 if (nb == 1)
1587 goto CopyA;
Tim Peterse05f65a2002-08-10 05:21:15 +00001588 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001589 break;
1590 }
1591 }
1592
1593 /* One run is winning so consistently that galloping may
1594 * be a huge win. So try that, and continue galloping until
1595 * (if ever) neither run appears to be winning consistently
1596 * anymore.
1597 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001598 ++min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001599 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001600 assert(na > 0 && nb > 1);
1601 min_gallop -= min_gallop > 1;
1602 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001603 k = gallop_right(*pb, basea, na, na-1, compare);
1604 if (k < 0)
1605 goto Fail;
1606 k = na - k;
1607 acount = k;
1608 if (k) {
1609 dest -= k;
1610 pa -= k;
1611 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1612 na -= k;
1613 if (na == 0)
1614 goto Succeed;
1615 }
1616 *dest-- = *pb--;
1617 --nb;
1618 if (nb == 1)
1619 goto CopyA;
1620
1621 k = gallop_left(*pa, baseb, nb, nb-1, compare);
1622 if (k < 0)
1623 goto Fail;
1624 k = nb - k;
1625 bcount = k;
1626 if (k) {
1627 dest -= k;
1628 pb -= k;
1629 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1630 nb -= k;
1631 if (nb == 1)
1632 goto CopyA;
1633 /* nb==0 is impossible now if the comparison
1634 * function is consistent, but we can't assume
1635 * that it is.
1636 */
1637 if (nb == 0)
1638 goto Succeed;
1639 }
1640 *dest-- = *pa--;
1641 --na;
1642 if (na == 0)
1643 goto Succeed;
1644 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001645 ++min_gallop; /* penalize it for leaving galloping mode */
1646 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001647 }
1648Succeed:
1649 result = 0;
1650Fail:
1651 if (nb)
1652 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1653 return result;
1654CopyA:
1655 assert(nb == 1 && na > 0);
1656 /* The first element of pb belongs at the front of the merge. */
1657 dest -= na;
1658 pa -= na;
1659 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1660 *dest = *pb;
1661 return 0;
1662}
1663
1664/* Merge the two runs at stack indices i and i+1.
1665 * Returns 0 on success, -1 on error.
1666 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001667static Py_ssize_t
1668merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001669{
1670 PyObject **pa, **pb;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001671 Py_ssize_t na, nb;
1672 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001673 PyObject *compare;
1674
1675 assert(ms != NULL);
1676 assert(ms->n >= 2);
1677 assert(i >= 0);
1678 assert(i == ms->n - 2 || i == ms->n - 3);
1679
Tim Peterse05f65a2002-08-10 05:21:15 +00001680 pa = ms->pending[i].base;
1681 na = ms->pending[i].len;
1682 pb = ms->pending[i+1].base;
1683 nb = ms->pending[i+1].len;
Tim Petersa64dc242002-08-01 02:13:36 +00001684 assert(na > 0 && nb > 0);
1685 assert(pa + na == pb);
1686
1687 /* Record the length of the combined runs; if i is the 3rd-last
1688 * run now, also slide over the last run (which isn't involved
1689 * in this merge). The current run i+1 goes away in any case.
1690 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001691 ms->pending[i].len = na + nb;
1692 if (i == ms->n - 3)
1693 ms->pending[i+1] = ms->pending[i+2];
Tim Petersa64dc242002-08-01 02:13:36 +00001694 --ms->n;
1695
1696 /* Where does b start in a? Elements in a before that can be
1697 * ignored (already in place).
1698 */
1699 compare = ms->compare;
1700 k = gallop_right(*pb, pa, na, 0, compare);
1701 if (k < 0)
1702 return -1;
1703 pa += k;
1704 na -= k;
1705 if (na == 0)
1706 return 0;
1707
1708 /* Where does a end in b? Elements in b after that can be
1709 * ignored (already in place).
1710 */
1711 nb = gallop_left(pa[na-1], pb, nb, nb-1, compare);
1712 if (nb <= 0)
1713 return nb;
1714
1715 /* Merge what remains of the runs, using a temp array with
1716 * min(na, nb) elements.
1717 */
1718 if (na <= nb)
1719 return merge_lo(ms, pa, na, pb, nb);
1720 else
1721 return merge_hi(ms, pa, na, pb, nb);
1722}
1723
1724/* Examine the stack of runs waiting to be merged, merging adjacent runs
1725 * until the stack invariants are re-established:
1726 *
1727 * 1. len[-3] > len[-2] + len[-1]
1728 * 2. len[-2] > len[-1]
1729 *
1730 * See listsort.txt for more info.
1731 *
1732 * Returns 0 on success, -1 on error.
1733 */
1734static int
1735merge_collapse(MergeState *ms)
1736{
Tim Peterse05f65a2002-08-10 05:21:15 +00001737 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001738
1739 assert(ms);
1740 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001741 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001742 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1743 if (p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001744 --n;
1745 if (merge_at(ms, n) < 0)
1746 return -1;
1747 }
Tim Peterse05f65a2002-08-10 05:21:15 +00001748 else if (p[n].len <= p[n+1].len) {
Tim Petersa64dc242002-08-01 02:13:36 +00001749 if (merge_at(ms, n) < 0)
1750 return -1;
1751 }
1752 else
1753 break;
1754 }
1755 return 0;
1756}
1757
1758/* Regardless of invariants, merge all runs on the stack until only one
1759 * remains. This is used at the end of the mergesort.
1760 *
1761 * Returns 0 on success, -1 on error.
1762 */
1763static int
1764merge_force_collapse(MergeState *ms)
1765{
Tim Peterse05f65a2002-08-10 05:21:15 +00001766 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001767
1768 assert(ms);
1769 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001770 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001771 if (n > 0 && p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001772 --n;
1773 if (merge_at(ms, n) < 0)
1774 return -1;
1775 }
1776 return 0;
1777}
1778
1779/* Compute a good value for the minimum run length; natural runs shorter
1780 * than this are boosted artificially via binary insertion.
1781 *
1782 * If n < 64, return n (it's too small to bother with fancy stuff).
1783 * Else if n is an exact power of 2, return 32.
1784 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1785 * strictly less than, an exact power of 2.
1786 *
1787 * See listsort.txt for more info.
1788 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001789static Py_ssize_t
1790merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001791{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001792 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001793
1794 assert(n >= 0);
1795 while (n >= 64) {
1796 r |= n & 1;
1797 n >>= 1;
1798 }
1799 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001800}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001801
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001802/* Special wrapper to support stable sorting using the decorate-sort-undecorate
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001803 pattern. Holds a key which is used for comparisons and the original record
Tim Petersb38e2b62004-07-29 02:29:26 +00001804 which is returned during the undecorate phase. By exposing only the key
1805 during comparisons, the underlying sort stability characteristics are left
1806 unchanged. Also, if a custom comparison function is used, it will only see
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001807 the key instead of a full record. */
1808
1809typedef struct {
1810 PyObject_HEAD
1811 PyObject *key;
1812 PyObject *value;
1813} sortwrapperobject;
1814
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001815PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
Anthony Baxter377be112006-04-11 06:54:30 +00001816static PyObject *
1817sortwrapper_richcompare(sortwrapperobject *, sortwrapperobject *, int);
1818static void
1819sortwrapper_dealloc(sortwrapperobject *);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001820
1821static PyTypeObject sortwrapper_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001822 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001823 "sortwrapper", /* tp_name */
1824 sizeof(sortwrapperobject), /* tp_basicsize */
1825 0, /* tp_itemsize */
1826 /* methods */
1827 (destructor)sortwrapper_dealloc, /* tp_dealloc */
1828 0, /* tp_print */
1829 0, /* tp_getattr */
1830 0, /* tp_setattr */
1831 0, /* tp_compare */
1832 0, /* tp_repr */
1833 0, /* tp_as_number */
1834 0, /* tp_as_sequence */
1835 0, /* tp_as_mapping */
1836 0, /* tp_hash */
1837 0, /* tp_call */
1838 0, /* tp_str */
1839 PyObject_GenericGetAttr, /* tp_getattro */
1840 0, /* tp_setattro */
1841 0, /* tp_as_buffer */
Tim Petersb38e2b62004-07-29 02:29:26 +00001842 Py_TPFLAGS_DEFAULT |
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001843 Py_TPFLAGS_HAVE_RICHCOMPARE, /* tp_flags */
1844 sortwrapper_doc, /* tp_doc */
1845 0, /* tp_traverse */
1846 0, /* tp_clear */
1847 (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
1848};
1849
Anthony Baxter377be112006-04-11 06:54:30 +00001850
1851static PyObject *
1852sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
1853{
1854 if (!PyObject_TypeCheck(b, &sortwrapper_type)) {
1855 PyErr_SetString(PyExc_TypeError,
1856 "expected a sortwrapperobject");
1857 return NULL;
1858 }
1859 return PyObject_RichCompare(a->key, b->key, op);
1860}
1861
1862static void
1863sortwrapper_dealloc(sortwrapperobject *so)
1864{
1865 Py_XDECREF(so->key);
1866 Py_XDECREF(so->value);
1867 PyObject_Del(so);
1868}
1869
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001870/* Returns a new reference to a sortwrapper.
1871 Consumes the references to the two underlying objects. */
1872
1873static PyObject *
1874build_sortwrapper(PyObject *key, PyObject *value)
1875{
1876 sortwrapperobject *so;
Tim Petersb38e2b62004-07-29 02:29:26 +00001877
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001878 so = PyObject_New(sortwrapperobject, &sortwrapper_type);
1879 if (so == NULL)
1880 return NULL;
1881 so->key = key;
1882 so->value = value;
1883 return (PyObject *)so;
1884}
1885
1886/* Returns a new reference to the value underlying the wrapper. */
1887static PyObject *
1888sortwrapper_getvalue(PyObject *so)
1889{
1890 PyObject *value;
1891
1892 if (!PyObject_TypeCheck(so, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001893 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001894 "expected a sortwrapperobject");
1895 return NULL;
1896 }
1897 value = ((sortwrapperobject *)so)->value;
1898 Py_INCREF(value);
1899 return value;
1900}
1901
1902/* Wrapper for user specified cmp functions in combination with a
1903 specified key function. Makes sure the cmp function is presented
1904 with the actual key instead of the sortwrapper */
1905
1906typedef struct {
1907 PyObject_HEAD
1908 PyObject *func;
1909} cmpwrapperobject;
1910
1911static void
1912cmpwrapper_dealloc(cmpwrapperobject *co)
1913{
1914 Py_XDECREF(co->func);
1915 PyObject_Del(co);
1916}
1917
1918static PyObject *
1919cmpwrapper_call(cmpwrapperobject *co, PyObject *args, PyObject *kwds)
1920{
1921 PyObject *x, *y, *xx, *yy;
1922
1923 if (!PyArg_UnpackTuple(args, "", 2, 2, &x, &y))
1924 return NULL;
1925 if (!PyObject_TypeCheck(x, &sortwrapper_type) ||
Raymond Hettingerae4a2992003-10-16 17:16:30 +00001926 !PyObject_TypeCheck(y, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001927 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001928 "expected a sortwrapperobject");
1929 return NULL;
1930 }
1931 xx = ((sortwrapperobject *)x)->key;
1932 yy = ((sortwrapperobject *)y)->key;
1933 return PyObject_CallFunctionObjArgs(co->func, xx, yy, NULL);
1934}
1935
1936PyDoc_STRVAR(cmpwrapper_doc, "cmp() wrapper for sort with custom keys.");
1937
1938static PyTypeObject cmpwrapper_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001939 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001940 "cmpwrapper", /* tp_name */
1941 sizeof(cmpwrapperobject), /* tp_basicsize */
1942 0, /* tp_itemsize */
1943 /* methods */
1944 (destructor)cmpwrapper_dealloc, /* tp_dealloc */
1945 0, /* tp_print */
1946 0, /* tp_getattr */
1947 0, /* tp_setattr */
1948 0, /* tp_compare */
1949 0, /* tp_repr */
1950 0, /* tp_as_number */
1951 0, /* tp_as_sequence */
1952 0, /* tp_as_mapping */
1953 0, /* tp_hash */
1954 (ternaryfunc)cmpwrapper_call, /* tp_call */
1955 0, /* tp_str */
1956 PyObject_GenericGetAttr, /* tp_getattro */
1957 0, /* tp_setattro */
1958 0, /* tp_as_buffer */
1959 Py_TPFLAGS_DEFAULT, /* tp_flags */
1960 cmpwrapper_doc, /* tp_doc */
1961};
1962
1963static PyObject *
1964build_cmpwrapper(PyObject *cmpfunc)
1965{
1966 cmpwrapperobject *co;
Tim Petersb38e2b62004-07-29 02:29:26 +00001967
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001968 co = PyObject_New(cmpwrapperobject, &cmpwrapper_type);
1969 if (co == NULL)
1970 return NULL;
1971 Py_INCREF(cmpfunc);
1972 co->func = cmpfunc;
1973 return (PyObject *)co;
1974}
1975
Tim Petersa64dc242002-08-01 02:13:36 +00001976/* An adaptive, stable, natural mergesort. See listsort.txt.
1977 * Returns Py_None on success, NULL on error. Even in case of error, the
1978 * list will be some permutation of its input state (nothing is lost or
1979 * duplicated).
1980 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001981static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001982listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001983{
Tim Petersa64dc242002-08-01 02:13:36 +00001984 MergeState ms;
1985 PyObject **lo, **hi;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001986 Py_ssize_t nremaining;
1987 Py_ssize_t minrun;
1988 Py_ssize_t saved_ob_size, saved_allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00001989 PyObject **saved_ob_item;
Armin Rigo93677f02004-07-29 12:40:23 +00001990 PyObject **final_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001991 PyObject *compare = NULL;
1992 PyObject *result = NULL; /* guilty until proved innocent */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001993 int reverse = 0;
1994 PyObject *keyfunc = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001995 Py_ssize_t i;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001996 PyObject *key, *value, *kvpair;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001997 static char *kwlist[] = {"cmp", "key", "reverse", 0};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001998
Tim Petersa64dc242002-08-01 02:13:36 +00001999 assert(self != NULL);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002000 assert (PyList_Check(self));
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002001 if (args != NULL) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002002 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:sort",
2003 kwlist, &compare, &keyfunc, &reverse))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002004 return NULL;
2005 }
Skip Montanaro4abd5f02003-01-02 20:51:08 +00002006 if (compare == Py_None)
2007 compare = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002008 if (keyfunc == Py_None)
2009 keyfunc = NULL;
2010 if (compare != NULL && keyfunc != NULL) {
2011 compare = build_cmpwrapper(compare);
2012 if (compare == NULL)
Hye-Shik Chang19cb1932003-12-10 07:31:08 +00002013 return NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002014 } else
2015 Py_XINCREF(compare);
2016
Tim Petersb9099c32002-11-12 22:08:10 +00002017 /* The list is temporarily made empty, so that mutations performed
2018 * by comparison functions can't affect the slice of memory we're
2019 * sorting (allowing mutations during sorting is a core-dump
2020 * factory, since ob_item may change).
2021 */
Christian Heimese93237d2007-12-19 02:37:44 +00002022 saved_ob_size = Py_SIZE(self);
Tim Petersb9099c32002-11-12 22:08:10 +00002023 saved_ob_item = self->ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002024 saved_allocated = self->allocated;
Christian Heimese93237d2007-12-19 02:37:44 +00002025 Py_SIZE(self) = 0;
Tim Peters51b4ade2004-07-29 04:07:15 +00002026 self->ob_item = NULL;
Armin Rigo93677f02004-07-29 12:40:23 +00002027 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00002028
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002029 if (keyfunc != NULL) {
2030 for (i=0 ; i < saved_ob_size ; i++) {
2031 value = saved_ob_item[i];
Tim Petersb38e2b62004-07-29 02:29:26 +00002032 key = PyObject_CallFunctionObjArgs(keyfunc, value,
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002033 NULL);
2034 if (key == NULL) {
2035 for (i=i-1 ; i>=0 ; i--) {
2036 kvpair = saved_ob_item[i];
2037 value = sortwrapper_getvalue(kvpair);
2038 saved_ob_item[i] = value;
2039 Py_DECREF(kvpair);
2040 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002041 goto dsu_fail;
2042 }
2043 kvpair = build_sortwrapper(key, value);
2044 if (kvpair == NULL)
2045 goto dsu_fail;
2046 saved_ob_item[i] = kvpair;
2047 }
2048 }
2049
2050 /* Reverse sort stability achieved by initially reversing the list,
2051 applying a stable forward sort, then reversing the final result. */
2052 if (reverse && saved_ob_size > 1)
2053 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2054
2055 merge_init(&ms, compare);
2056
Tim Petersb9099c32002-11-12 22:08:10 +00002057 nremaining = saved_ob_size;
Tim Petersa64dc242002-08-01 02:13:36 +00002058 if (nremaining < 2)
2059 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00002060
Tim Petersa64dc242002-08-01 02:13:36 +00002061 /* March over the array once, left to right, finding natural runs,
2062 * and extending short natural runs to minrun elements.
2063 */
Tim Petersb9099c32002-11-12 22:08:10 +00002064 lo = saved_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00002065 hi = lo + nremaining;
2066 minrun = merge_compute_minrun(nremaining);
2067 do {
2068 int descending;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002069 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00002070
Tim Petersa64dc242002-08-01 02:13:36 +00002071 /* Identify next run. */
2072 n = count_run(lo, hi, compare, &descending);
2073 if (n < 0)
2074 goto fail;
2075 if (descending)
2076 reverse_slice(lo, lo + n);
2077 /* If short, extend to min(minrun, nremaining). */
2078 if (n < minrun) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002079 const Py_ssize_t force = nremaining <= minrun ?
Tim Petersa64dc242002-08-01 02:13:36 +00002080 nremaining : minrun;
2081 if (binarysort(lo, lo + force, lo + n, compare) < 0)
2082 goto fail;
2083 n = force;
2084 }
2085 /* Push run onto pending-runs stack, and maybe merge. */
2086 assert(ms.n < MAX_MERGE_PENDING);
Tim Peterse05f65a2002-08-10 05:21:15 +00002087 ms.pending[ms.n].base = lo;
2088 ms.pending[ms.n].len = n;
Tim Petersa64dc242002-08-01 02:13:36 +00002089 ++ms.n;
2090 if (merge_collapse(&ms) < 0)
2091 goto fail;
2092 /* Advance to find next run. */
2093 lo += n;
2094 nremaining -= n;
2095 } while (nremaining);
2096 assert(lo == hi);
Tim Peters330f9e92002-07-19 07:05:44 +00002097
Tim Petersa64dc242002-08-01 02:13:36 +00002098 if (merge_force_collapse(&ms) < 0)
2099 goto fail;
2100 assert(ms.n == 1);
Tim Petersb9099c32002-11-12 22:08:10 +00002101 assert(ms.pending[0].base == saved_ob_item);
2102 assert(ms.pending[0].len == saved_ob_size);
Tim Petersa64dc242002-08-01 02:13:36 +00002103
2104succeed:
2105 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002106fail:
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002107 if (keyfunc != NULL) {
2108 for (i=0 ; i < saved_ob_size ; i++) {
2109 kvpair = saved_ob_item[i];
2110 value = sortwrapper_getvalue(kvpair);
2111 saved_ob_item[i] = value;
2112 Py_DECREF(kvpair);
2113 }
2114 }
2115
Armin Rigo93677f02004-07-29 12:40:23 +00002116 if (self->allocated != -1 && result != NULL) {
Tim Peters51b4ade2004-07-29 04:07:15 +00002117 /* The user mucked with the list during the sort,
2118 * and we don't already have another error to report.
2119 */
2120 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2121 result = NULL;
Tim Petersb9099c32002-11-12 22:08:10 +00002122 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002123
2124 if (reverse && saved_ob_size > 1)
2125 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2126
2127 merge_freemem(&ms);
2128
2129dsu_fail:
Armin Rigo93677f02004-07-29 12:40:23 +00002130 final_ob_item = self->ob_item;
Christian Heimese93237d2007-12-19 02:37:44 +00002131 i = Py_SIZE(self);
2132 Py_SIZE(self) = saved_ob_size;
Tim Petersb9099c32002-11-12 22:08:10 +00002133 self->ob_item = saved_ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002134 self->allocated = saved_allocated;
Armin Rigo93677f02004-07-29 12:40:23 +00002135 if (final_ob_item != NULL) {
2136 /* we cannot use list_clear() for this because it does not
2137 guarantee that the list is really empty when it returns */
2138 while (--i >= 0) {
2139 Py_XDECREF(final_ob_item[i]);
2140 }
2141 PyMem_FREE(final_ob_item);
2142 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002143 Py_XDECREF(compare);
Tim Petersa64dc242002-08-01 02:13:36 +00002144 Py_XINCREF(result);
2145 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002146}
Tim Peters330f9e92002-07-19 07:05:44 +00002147#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002148#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002149
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002150int
Fred Drakea2f55112000-07-09 15:16:51 +00002151PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002152{
2153 if (v == NULL || !PyList_Check(v)) {
2154 PyErr_BadInternalCall();
2155 return -1;
2156 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002157 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002158 if (v == NULL)
2159 return -1;
2160 Py_DECREF(v);
2161 return 0;
2162}
2163
Guido van Rossumb86c5492001-02-12 22:06:02 +00002164static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002165listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002166{
Christian Heimese93237d2007-12-19 02:37:44 +00002167 if (Py_SIZE(self) > 1)
2168 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002169 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002170}
2171
Guido van Rossum84c76f51990-10-30 13:32:20 +00002172int
Fred Drakea2f55112000-07-09 15:16:51 +00002173PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002174{
Tim Peters6063e262002-08-08 01:06:39 +00002175 PyListObject *self = (PyListObject *)v;
2176
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002177 if (v == NULL || !PyList_Check(v)) {
2178 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002179 return -1;
2180 }
Christian Heimese93237d2007-12-19 02:37:44 +00002181 if (Py_SIZE(self) > 1)
2182 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002183 return 0;
2184}
2185
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002186PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002187PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002188{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002189 PyObject *w;
Raymond Hettinger6c87af52007-12-15 00:07:25 +00002190 PyObject **p, **q;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002191 Py_ssize_t n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002192 if (v == NULL || !PyList_Check(v)) {
2193 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002194 return NULL;
2195 }
Christian Heimese93237d2007-12-19 02:37:44 +00002196 n = Py_SIZE(v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002197 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002198 if (w == NULL)
2199 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002200 p = ((PyTupleObject *)w)->ob_item;
Raymond Hettinger6c87af52007-12-15 00:07:25 +00002201 q = ((PyListObject *)v)->ob_item;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002202 while (--n >= 0) {
Raymond Hettinger6c87af52007-12-15 00:07:25 +00002203 Py_INCREF(*q);
2204 *p = *q;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002205 p++;
Raymond Hettinger6c87af52007-12-15 00:07:25 +00002206 q++;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002207 }
2208 return w;
2209}
2210
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002211static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002212listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002213{
Christian Heimese93237d2007-12-19 02:37:44 +00002214 Py_ssize_t i, start=0, stop=Py_SIZE(self);
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002215 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002216
Walter Dörwalde8049bef2003-06-17 19:27:39 +00002217 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2218 _PyEval_SliceIndex, &start,
2219 _PyEval_SliceIndex, &stop))
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002220 return NULL;
Guido van Rossum2743d872003-06-17 14:25:14 +00002221 if (start < 0) {
Christian Heimese93237d2007-12-19 02:37:44 +00002222 start += Py_SIZE(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002223 if (start < 0)
2224 start = 0;
2225 }
2226 if (stop < 0) {
Christian Heimese93237d2007-12-19 02:37:44 +00002227 stop += Py_SIZE(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002228 if (stop < 0)
2229 stop = 0;
2230 }
Christian Heimese93237d2007-12-19 02:37:44 +00002231 for (i = start; i < stop && i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002232 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2233 if (cmp > 0)
Martin v. Löwis18e16552006-02-15 17:27:45 +00002234 return PyInt_FromSsize_t(i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002235 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002236 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002237 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002238 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002239 return NULL;
2240}
2241
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002242static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002243listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002244{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002245 Py_ssize_t count = 0;
2246 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002247
Christian Heimese93237d2007-12-19 02:37:44 +00002248 for (i = 0; i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002249 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2250 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002251 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002252 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002253 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00002254 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002255 return PyInt_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002256}
2257
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002258static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002259listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002260{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002261 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002262
Christian Heimese93237d2007-12-19 02:37:44 +00002263 for (i = 0; i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002264 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2265 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002266 if (list_ass_slice(self, i, i+1,
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002267 (PyObject *)NULL) == 0)
2268 Py_RETURN_NONE;
2269 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002270 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002271 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002272 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002273 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002274 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002275 return NULL;
2276}
2277
Jeremy Hylton8caad492000-06-23 14:18:11 +00002278static int
2279list_traverse(PyListObject *o, visitproc visit, void *arg)
2280{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002281 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002282
Christian Heimese93237d2007-12-19 02:37:44 +00002283 for (i = Py_SIZE(o); --i >= 0; )
Thomas Woutersc6e55062006-04-15 21:47:09 +00002284 Py_VISIT(o->ob_item[i]);
Jeremy Hylton8caad492000-06-23 14:18:11 +00002285 return 0;
2286}
2287
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002288static PyObject *
2289list_richcompare(PyObject *v, PyObject *w, int op)
2290{
2291 PyListObject *vl, *wl;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002292 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002293
2294 if (!PyList_Check(v) || !PyList_Check(w)) {
2295 Py_INCREF(Py_NotImplemented);
2296 return Py_NotImplemented;
2297 }
2298
2299 vl = (PyListObject *)v;
2300 wl = (PyListObject *)w;
2301
Christian Heimese93237d2007-12-19 02:37:44 +00002302 if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002303 /* Shortcut: if the lengths differ, the lists differ */
2304 PyObject *res;
2305 if (op == Py_EQ)
2306 res = Py_False;
2307 else
2308 res = Py_True;
2309 Py_INCREF(res);
2310 return res;
2311 }
2312
2313 /* Search for the first index where items are different */
Christian Heimese93237d2007-12-19 02:37:44 +00002314 for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002315 int k = PyObject_RichCompareBool(vl->ob_item[i],
2316 wl->ob_item[i], Py_EQ);
2317 if (k < 0)
2318 return NULL;
2319 if (!k)
2320 break;
2321 }
2322
Christian Heimese93237d2007-12-19 02:37:44 +00002323 if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002324 /* No more items to compare -- compare sizes */
Christian Heimese93237d2007-12-19 02:37:44 +00002325 Py_ssize_t vs = Py_SIZE(vl);
2326 Py_ssize_t ws = Py_SIZE(wl);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002327 int cmp;
2328 PyObject *res;
2329 switch (op) {
2330 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00002331 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002332 case Py_EQ: cmp = vs == ws; break;
2333 case Py_NE: cmp = vs != ws; break;
2334 case Py_GT: cmp = vs > ws; break;
2335 case Py_GE: cmp = vs >= ws; break;
2336 default: return NULL; /* cannot happen */
2337 }
2338 if (cmp)
2339 res = Py_True;
2340 else
2341 res = Py_False;
2342 Py_INCREF(res);
2343 return res;
2344 }
2345
2346 /* We have an item that differs -- shortcuts for EQ/NE */
2347 if (op == Py_EQ) {
2348 Py_INCREF(Py_False);
2349 return Py_False;
2350 }
2351 if (op == Py_NE) {
2352 Py_INCREF(Py_True);
2353 return Py_True;
2354 }
2355
2356 /* Compare the final item again using the proper operator */
2357 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
2358}
2359
Tim Peters6d6c1a32001-08-02 04:15:00 +00002360static int
2361list_init(PyListObject *self, PyObject *args, PyObject *kw)
2362{
2363 PyObject *arg = NULL;
Martin v. Löwis15e62742006-02-27 16:46:16 +00002364 static char *kwlist[] = {"sequence", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002365
2366 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2367 return -1;
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002368
2369 /* Verify list invariants established by PyType_GenericAlloc() */
Christian Heimese93237d2007-12-19 02:37:44 +00002370 assert(0 <= Py_SIZE(self));
2371 assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
Armin Rigoa37bbf22004-07-30 11:20:18 +00002372 assert(self->ob_item != NULL ||
2373 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002374
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002375 /* Empty previous contents */
Armin Rigo93677f02004-07-29 12:40:23 +00002376 if (self->ob_item != NULL) {
2377 (void)list_clear(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002378 }
2379 if (arg != NULL) {
2380 PyObject *rv = listextend(self, arg);
2381 if (rv == NULL)
2382 return -1;
2383 Py_DECREF(rv);
2384 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002385 return 0;
2386}
2387
Raymond Hettinger1021c442003-11-07 15:38:09 +00002388static PyObject *list_iter(PyObject *seq);
2389static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2390
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002391PyDoc_STRVAR(getitem_doc,
2392"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002393PyDoc_STRVAR(reversed_doc,
2394"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002395PyDoc_STRVAR(append_doc,
2396"L.append(object) -- append object to end");
2397PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002398"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002399PyDoc_STRVAR(insert_doc,
2400"L.insert(index, object) -- insert object before index");
2401PyDoc_STRVAR(pop_doc,
2402"L.pop([index]) -> item -- remove and return item at index (default last)");
2403PyDoc_STRVAR(remove_doc,
2404"L.remove(value) -- remove first occurrence of value");
2405PyDoc_STRVAR(index_doc,
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002406"L.index(value, [start, [stop]]) -> integer -- return first index of value");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002407PyDoc_STRVAR(count_doc,
2408"L.count(value) -> integer -- return number of occurrences of value");
2409PyDoc_STRVAR(reverse_doc,
2410"L.reverse() -- reverse *IN PLACE*");
2411PyDoc_STRVAR(sort_doc,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002412"L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n\
2413cmp(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002414
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002415static PyObject *list_subscript(PyListObject*, PyObject*);
2416
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002417static PyMethodDef list_methods[] = {
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002418 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
Raymond Hettinger1021c442003-11-07 15:38:09 +00002419 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002420 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002421 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002422 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002423 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002424 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002425 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002426 {"count", (PyCFunction)listcount, METH_O, count_doc},
2427 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002428 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
Tim Petersa64dc242002-08-01 02:13:36 +00002429 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002430};
2431
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002432static PySequenceMethods list_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002433 (lenfunc)list_length, /* sq_length */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002434 (binaryfunc)list_concat, /* sq_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002435 (ssizeargfunc)list_repeat, /* sq_repeat */
2436 (ssizeargfunc)list_item, /* sq_item */
2437 (ssizessizeargfunc)list_slice, /* sq_slice */
2438 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
2439 (ssizessizeobjargproc)list_ass_slice, /* sq_ass_slice */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002440 (objobjproc)list_contains, /* sq_contains */
2441 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002442 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002443};
2444
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002445PyDoc_STRVAR(list_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002446"list() -> new list\n"
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002447"list(sequence) -> new list initialized from sequence's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002448
Guido van Rossum38fff8c2006-03-07 18:50:55 +00002449
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002450static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002451list_subscript(PyListObject* self, PyObject* item)
2452{
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00002453 if (PyIndex_Check(item)) {
2454 Py_ssize_t i;
2455 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002456 if (i == -1 && PyErr_Occurred())
2457 return NULL;
2458 if (i < 0)
2459 i += PyList_GET_SIZE(self);
2460 return list_item(self, i);
2461 }
2462 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002463 Py_ssize_t start, stop, step, slicelength, cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002464 PyObject* result;
2465 PyObject* it;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002466 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002467
Christian Heimese93237d2007-12-19 02:37:44 +00002468 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002469 &start, &stop, &step, &slicelength) < 0) {
2470 return NULL;
2471 }
2472
2473 if (slicelength <= 0) {
2474 return PyList_New(0);
2475 }
Thomas Wouters3ccec682007-08-28 15:28:19 +00002476 else if (step == 1) {
2477 return list_slice(self, start, stop);
2478 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002479 else {
2480 result = PyList_New(slicelength);
2481 if (!result) return NULL;
2482
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002483 src = self->ob_item;
2484 dest = ((PyListObject *)result)->ob_item;
Tim Peters3b01a122002-07-19 02:35:45 +00002485 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002486 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002487 it = src[cur];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002488 Py_INCREF(it);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002489 dest[i] = it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002490 }
Tim Peters3b01a122002-07-19 02:35:45 +00002491
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002492 return result;
2493 }
2494 }
2495 else {
Georg Brandl283a1352006-11-19 08:48:30 +00002496 PyErr_Format(PyExc_TypeError,
2497 "list indices must be integers, not %.200s",
2498 item->ob_type->tp_name);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002499 return NULL;
2500 }
2501}
2502
Tim Peters3b01a122002-07-19 02:35:45 +00002503static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002504list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2505{
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00002506 if (PyIndex_Check(item)) {
2507 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002508 if (i == -1 && PyErr_Occurred())
2509 return -1;
2510 if (i < 0)
2511 i += PyList_GET_SIZE(self);
2512 return list_ass_item(self, i, value);
2513 }
2514 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002515 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002516
Christian Heimese93237d2007-12-19 02:37:44 +00002517 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002518 &start, &stop, &step, &slicelength) < 0) {
2519 return -1;
2520 }
2521
Thomas Wouters3ccec682007-08-28 15:28:19 +00002522 if (step == 1)
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002523 return list_ass_slice(self, start, stop, value);
2524
Thomas Wouters3ccec682007-08-28 15:28:19 +00002525 /* Make sure s[5:2] = [..] inserts at the right place:
2526 before 5, not before 2. */
2527 if ((step < 0 && start < stop) ||
2528 (step > 0 && start > stop))
2529 stop = start;
2530
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002531 if (value == NULL) {
2532 /* delete slice */
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002533 PyObject **garbage;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002534 Py_ssize_t cur, i;
Tim Peters3b01a122002-07-19 02:35:45 +00002535
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002536 if (slicelength <= 0)
2537 return 0;
2538
2539 if (step < 0) {
2540 stop = start + 1;
2541 start = stop + step*(slicelength - 1) - 1;
2542 step = -step;
2543 }
2544
2545 garbage = (PyObject**)
2546 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Neal Norwitzb88cfad2006-08-12 03:16:54 +00002547 if (!garbage) {
2548 PyErr_NoMemory();
2549 return -1;
2550 }
Tim Peters3b01a122002-07-19 02:35:45 +00002551
Thomas Wouters3ccec682007-08-28 15:28:19 +00002552 /* drawing pictures might help understand these for
2553 loops. Basically, we memmove the parts of the
2554 list that are *not* part of the slice: step-1
2555 items for each item that is part of the slice,
2556 and then tail end of the list that was not
2557 covered by the slice */
Guido van Rossum75a20b12002-06-11 12:22:28 +00002558 for (cur = start, i = 0;
2559 cur < stop;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002560 cur += step, i++) {
Thomas Wouters3ccec682007-08-28 15:28:19 +00002561 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002562
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002563 garbage[i] = PyList_GET_ITEM(self, cur);
2564
Christian Heimese93237d2007-12-19 02:37:44 +00002565 if (cur + step >= Py_SIZE(self)) {
2566 lim = Py_SIZE(self) - cur - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002567 }
2568
Tim Petersb38e2b62004-07-29 02:29:26 +00002569 memmove(self->ob_item + cur - i,
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002570 self->ob_item + cur + 1,
2571 lim * sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002572 }
Thomas Wouters3ccec682007-08-28 15:28:19 +00002573 cur = start + slicelength*step;
Christian Heimese93237d2007-12-19 02:37:44 +00002574 if (cur < Py_SIZE(self)) {
Thomas Wouters3ccec682007-08-28 15:28:19 +00002575 memmove(self->ob_item + cur - slicelength,
2576 self->ob_item + cur,
Christian Heimese93237d2007-12-19 02:37:44 +00002577 (Py_SIZE(self) - cur) *
Thomas Wouters3ccec682007-08-28 15:28:19 +00002578 sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002579 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002580
Christian Heimese93237d2007-12-19 02:37:44 +00002581 Py_SIZE(self) -= slicelength;
2582 list_resize(self, Py_SIZE(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002583
2584 for (i = 0; i < slicelength; i++) {
2585 Py_DECREF(garbage[i]);
2586 }
2587 PyMem_FREE(garbage);
2588
2589 return 0;
2590 }
2591 else {
2592 /* assign slice */
Thomas Wouters3ccec682007-08-28 15:28:19 +00002593 PyObject *ins, *seq;
2594 PyObject **garbage, **seqitems, **selfitems;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002595 Py_ssize_t cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002596
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002597 /* protect against a[::-1] = a */
Tim Peters3b01a122002-07-19 02:35:45 +00002598 if (self == (PyListObject*)value) {
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002599 seq = list_slice((PyListObject*)value, 0,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002600 PyList_GET_SIZE(value));
Tim Peters3b01a122002-07-19 02:35:45 +00002601 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002602 else {
Tim Petersb38e2b62004-07-29 02:29:26 +00002603 seq = PySequence_Fast(value,
Thomas Wouters3ccec682007-08-28 15:28:19 +00002604 "must assign iterable "
2605 "to extended slice");
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002606 }
Neal Norwitzb88cfad2006-08-12 03:16:54 +00002607 if (!seq)
2608 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002609
2610 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2611 PyErr_Format(PyExc_ValueError,
Thomas Wouters3ccec682007-08-28 15:28:19 +00002612 "attempt to assign sequence of "
2613 "size %zd to extended slice of "
2614 "size %zd",
Martin v. Löwise0e89f72006-02-16 06:59:22 +00002615 PySequence_Fast_GET_SIZE(seq),
2616 slicelength);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002617 Py_DECREF(seq);
2618 return -1;
2619 }
2620
2621 if (!slicelength) {
2622 Py_DECREF(seq);
2623 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002624 }
2625
2626 garbage = (PyObject**)
2627 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Neal Norwitze7e4e2d2006-10-28 21:20:12 +00002628 if (!garbage) {
2629 Py_DECREF(seq);
2630 PyErr_NoMemory();
2631 return -1;
2632 }
Tim Peters3b01a122002-07-19 02:35:45 +00002633
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002634 selfitems = self->ob_item;
Raymond Hettinger42bec932004-03-12 16:38:17 +00002635 seqitems = PySequence_Fast_ITEMS(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002636 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002637 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002638 garbage[i] = selfitems[cur];
2639 ins = seqitems[i];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002640 Py_INCREF(ins);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002641 selfitems[cur] = ins;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002642 }
2643
2644 for (i = 0; i < slicelength; i++) {
2645 Py_DECREF(garbage[i]);
2646 }
Tim Peters3b01a122002-07-19 02:35:45 +00002647
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002648 PyMem_FREE(garbage);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002649 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002650
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002651 return 0;
2652 }
Tim Peters3b01a122002-07-19 02:35:45 +00002653 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002654 else {
Georg Brandl283a1352006-11-19 08:48:30 +00002655 PyErr_Format(PyExc_TypeError,
2656 "list indices must be integers, not %.200s",
2657 item->ob_type->tp_name);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002658 return -1;
2659 }
2660}
2661
2662static PyMappingMethods list_as_mapping = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002663 (lenfunc)list_length,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002664 (binaryfunc)list_subscript,
2665 (objobjargproc)list_ass_subscript
2666};
2667
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002668PyTypeObject PyList_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002669 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002670 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002671 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002672 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002673 (destructor)list_dealloc, /* tp_dealloc */
2674 (printfunc)list_print, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002675 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002676 0, /* tp_setattr */
2677 0, /* tp_compare */
2678 (reprfunc)list_repr, /* tp_repr */
2679 0, /* tp_as_number */
2680 &list_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002681 &list_as_mapping, /* tp_as_mapping */
Guido van Rossum64c06e32007-11-22 00:55:51 +00002682 0, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002683 0, /* tp_call */
2684 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002685 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002686 0, /* tp_setattro */
2687 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002688 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Neal Norwitzee3a1b52007-02-25 19:44:48 +00002689 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002690 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002691 (traverseproc)list_traverse, /* tp_traverse */
2692 (inquiry)list_clear, /* tp_clear */
2693 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002694 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002695 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002696 0, /* tp_iternext */
2697 list_methods, /* tp_methods */
2698 0, /* tp_members */
2699 0, /* tp_getset */
2700 0, /* tp_base */
2701 0, /* tp_dict */
2702 0, /* tp_descr_get */
2703 0, /* tp_descr_set */
2704 0, /* tp_dictoffset */
2705 (initproc)list_init, /* tp_init */
2706 PyType_GenericAlloc, /* tp_alloc */
2707 PyType_GenericNew, /* tp_new */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002708 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002709};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002710
2711
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002712/*********************** List Iterator **************************/
2713
2714typedef struct {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002715 PyObject_HEAD
2716 long it_index;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002717 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002718} listiterobject;
2719
Anthony Baxter377be112006-04-11 06:54:30 +00002720static PyObject *list_iter(PyObject *);
2721static void listiter_dealloc(listiterobject *);
2722static int listiter_traverse(listiterobject *, visitproc, void *);
2723static PyObject *listiter_next(listiterobject *);
2724static PyObject *listiter_len(listiterobject *);
2725
2726PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
2727
2728static PyMethodDef listiter_methods[] = {
2729 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
2730 {NULL, NULL} /* sentinel */
2731};
2732
2733PyTypeObject PyListIter_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002734 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Anthony Baxter377be112006-04-11 06:54:30 +00002735 "listiterator", /* tp_name */
2736 sizeof(listiterobject), /* tp_basicsize */
2737 0, /* tp_itemsize */
2738 /* methods */
2739 (destructor)listiter_dealloc, /* tp_dealloc */
2740 0, /* tp_print */
2741 0, /* tp_getattr */
2742 0, /* tp_setattr */
2743 0, /* tp_compare */
2744 0, /* tp_repr */
2745 0, /* tp_as_number */
2746 0, /* tp_as_sequence */
2747 0, /* tp_as_mapping */
2748 0, /* tp_hash */
2749 0, /* tp_call */
2750 0, /* tp_str */
2751 PyObject_GenericGetAttr, /* tp_getattro */
2752 0, /* tp_setattro */
2753 0, /* tp_as_buffer */
2754 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2755 0, /* tp_doc */
2756 (traverseproc)listiter_traverse, /* tp_traverse */
2757 0, /* tp_clear */
2758 0, /* tp_richcompare */
2759 0, /* tp_weaklistoffset */
2760 PyObject_SelfIter, /* tp_iter */
2761 (iternextfunc)listiter_next, /* tp_iternext */
2762 listiter_methods, /* tp_methods */
2763 0, /* tp_members */
2764};
2765
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002766
Guido van Rossum5086e492002-07-16 15:56:52 +00002767static PyObject *
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002768list_iter(PyObject *seq)
2769{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002770 listiterobject *it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002771
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002772 if (!PyList_Check(seq)) {
2773 PyErr_BadInternalCall();
2774 return NULL;
2775 }
2776 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2777 if (it == NULL)
2778 return NULL;
2779 it->it_index = 0;
2780 Py_INCREF(seq);
2781 it->it_seq = (PyListObject *)seq;
2782 _PyObject_GC_TRACK(it);
2783 return (PyObject *)it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002784}
2785
2786static void
2787listiter_dealloc(listiterobject *it)
2788{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002789 _PyObject_GC_UNTRACK(it);
Guido van Rossum86103ae2002-07-16 20:07:32 +00002790 Py_XDECREF(it->it_seq);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002791 PyObject_GC_Del(it);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002792}
2793
2794static int
2795listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2796{
Thomas Woutersc6e55062006-04-15 21:47:09 +00002797 Py_VISIT(it->it_seq);
2798 return 0;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002799}
2800
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002801static PyObject *
Tim Peters93b2cc42002-06-01 05:22:55 +00002802listiter_next(listiterobject *it)
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002803{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002804 PyListObject *seq;
2805 PyObject *item;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002806
Tim Peters93b2cc42002-06-01 05:22:55 +00002807 assert(it != NULL);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002808 seq = it->it_seq;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002809 if (seq == NULL)
2810 return NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002811 assert(PyList_Check(seq));
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002812
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002813 if (it->it_index < PyList_GET_SIZE(seq)) {
Tim Peters93b2cc42002-06-01 05:22:55 +00002814 item = PyList_GET_ITEM(seq, it->it_index);
2815 ++it->it_index;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002816 Py_INCREF(item);
2817 return item;
2818 }
Guido van Rossum86103ae2002-07-16 20:07:32 +00002819
2820 Py_DECREF(seq);
2821 it->it_seq = NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002822 return NULL;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002823}
2824
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002825static PyObject *
Raymond Hettinger435bf582004-03-18 22:43:10 +00002826listiter_len(listiterobject *it)
2827{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002828 Py_ssize_t len;
Raymond Hettinger40a03822004-04-12 13:05:09 +00002829 if (it->it_seq) {
2830 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2831 if (len >= 0)
Martin v. Löwis18e16552006-02-15 17:27:45 +00002832 return PyInt_FromSsize_t(len);
Raymond Hettinger40a03822004-04-12 13:05:09 +00002833 }
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002834 return PyInt_FromLong(0);
Raymond Hettinger435bf582004-03-18 22:43:10 +00002835}
Anthony Baxter377be112006-04-11 06:54:30 +00002836/*********************** List Reverse Iterator **************************/
Raymond Hettinger435bf582004-03-18 22:43:10 +00002837
Anthony Baxter377be112006-04-11 06:54:30 +00002838typedef struct {
2839 PyObject_HEAD
2840 Py_ssize_t it_index;
2841 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
2842} listreviterobject;
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002843
Anthony Baxter377be112006-04-11 06:54:30 +00002844static PyObject *list_reversed(PyListObject *, PyObject *);
2845static void listreviter_dealloc(listreviterobject *);
2846static int listreviter_traverse(listreviterobject *, visitproc, void *);
2847static PyObject *listreviter_next(listreviterobject *);
2848static Py_ssize_t listreviter_len(listreviterobject *);
2849
2850static PySequenceMethods listreviter_as_sequence = {
2851 (lenfunc)listreviter_len, /* sq_length */
2852 0, /* sq_concat */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002853};
2854
Anthony Baxter377be112006-04-11 06:54:30 +00002855PyTypeObject PyListRevIter_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002856 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Anthony Baxter377be112006-04-11 06:54:30 +00002857 "listreverseiterator", /* tp_name */
2858 sizeof(listreviterobject), /* tp_basicsize */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002859 0, /* tp_itemsize */
2860 /* methods */
Anthony Baxter377be112006-04-11 06:54:30 +00002861 (destructor)listreviter_dealloc, /* tp_dealloc */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002862 0, /* tp_print */
2863 0, /* tp_getattr */
2864 0, /* tp_setattr */
2865 0, /* tp_compare */
2866 0, /* tp_repr */
2867 0, /* tp_as_number */
Anthony Baxter377be112006-04-11 06:54:30 +00002868 &listreviter_as_sequence, /* tp_as_sequence */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002869 0, /* tp_as_mapping */
2870 0, /* tp_hash */
2871 0, /* tp_call */
2872 0, /* tp_str */
2873 PyObject_GenericGetAttr, /* tp_getattro */
2874 0, /* tp_setattro */
2875 0, /* tp_as_buffer */
2876 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2877 0, /* tp_doc */
Anthony Baxter377be112006-04-11 06:54:30 +00002878 (traverseproc)listreviter_traverse, /* tp_traverse */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002879 0, /* tp_clear */
2880 0, /* tp_richcompare */
2881 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00002882 PyObject_SelfIter, /* tp_iter */
Anthony Baxter377be112006-04-11 06:54:30 +00002883 (iternextfunc)listreviter_next, /* tp_iternext */
2884 0,
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002885};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002886
Raymond Hettinger1021c442003-11-07 15:38:09 +00002887static PyObject *
2888list_reversed(PyListObject *seq, PyObject *unused)
2889{
2890 listreviterobject *it;
2891
2892 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2893 if (it == NULL)
2894 return NULL;
2895 assert(PyList_Check(seq));
2896 it->it_index = PyList_GET_SIZE(seq) - 1;
2897 Py_INCREF(seq);
2898 it->it_seq = seq;
2899 PyObject_GC_Track(it);
2900 return (PyObject *)it;
2901}
2902
2903static void
2904listreviter_dealloc(listreviterobject *it)
2905{
2906 PyObject_GC_UnTrack(it);
2907 Py_XDECREF(it->it_seq);
2908 PyObject_GC_Del(it);
2909}
2910
2911static int
2912listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2913{
Thomas Woutersc6e55062006-04-15 21:47:09 +00002914 Py_VISIT(it->it_seq);
2915 return 0;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002916}
2917
2918static PyObject *
2919listreviter_next(listreviterobject *it)
2920{
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002921 PyObject *item;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002922 Py_ssize_t index = it->it_index;
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002923 PyListObject *seq = it->it_seq;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002924
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002925 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2926 item = PyList_GET_ITEM(seq, index);
Raymond Hettinger1021c442003-11-07 15:38:09 +00002927 it->it_index--;
2928 Py_INCREF(item);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002929 return item;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002930 }
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002931 it->it_index = -1;
2932 if (seq != NULL) {
2933 it->it_seq = NULL;
2934 Py_DECREF(seq);
2935 }
2936 return NULL;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002937}
2938
Martin v. Löwis18e16552006-02-15 17:27:45 +00002939static Py_ssize_t
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002940listreviter_len(listreviterobject *it)
2941{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002942 Py_ssize_t len = it->it_index + 1;
Raymond Hettinger40a03822004-04-12 13:05:09 +00002943 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
2944 return 0;
2945 return len;
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002946}