blob: ca767da9dcc5f011605085bb83a08b6ae64cc965 [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);
Martin v. Löwis68192102007-07-21 06:55:02 +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;
Martin v. Löwis68192102007-07-21 06:55:02 +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 }
Martin v. Löwis68192102007-07-21 06:55:02 +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
Martin v. Löwis68192102007-07-21 06:55:02 +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 }
Martin v. Löwis68192102007-07-21 06:55:02 +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 }
Martin v. Löwis68192102007-07-21 06:55:02 +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{
Martin v. Löwis68192102007-07-21 06:55:02 +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. */
Martin v. Löwis68192102007-07-21 06:55:02 +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
Martin v. Löwis68192102007-07-21 06:55:02 +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
Martin v. Löwis68192102007-07-21 06:55:02 +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
Martin v. Löwis68192102007-07-21 06:55:02 +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. */
Martin v. Löwis68192102007-07-21 06:55:02 +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{
Martin v. Löwis68192102007-07-21 06:55:02 +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
Martin v. Löwis68192102007-07-21 06:55:02 +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{
Martin v. Löwis68192102007-07-21 06:55:02 +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;
Martin v. Löwis68192102007-07-21 06:55:02 +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;
Martin v. Löwis68192102007-07-21 06:55:02 +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)
Martin v. Löwis68192102007-07-21 06:55:02 +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;
Martin v. Löwis68192102007-07-21 06:55:02 +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;
Martin v. Löwis68192102007-07-21 06:55:02 +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;
Martin v. Löwis68192102007-07-21 06:55:02 +0000501 size = Py_Size(a) * n;
Martin v. Löwis68192102007-07-21 06:55:02 +0000502 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)
505 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;
Martin v. Löwis68192102007-07-21 06:55:02 +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++) {
Martin v. Löwis68192102007-07-21 06:55:02 +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. */
Martin v. Löwis68192102007-07-21 06:55:02 +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 */
Martin v. Löwis68192102007-07-21 06:55:02 +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;
Martin v. Löwis68192102007-07-21 06:55:02 +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;
Martin v. Löwis68192102007-07-21 06:55:02 +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;
Martin v. Löwis68192102007-07-21 06:55:02 +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],
Martin v. Löwis68192102007-07-21 06:55:02 +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 */
Martin v. Löwis68192102007-07-21 06:55:02 +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;
Armin Rigoa1e42e12007-10-17 18:46:37 +0000672 Py_ssize_t size, i, j, p, newsize;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000673
674
675 size = PyList_GET_SIZE(self);
676 if (size == 0) {
677 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
Armin Rigoa1e42e12007-10-17 18:46:37 +0000687 newsize = size * n;
688 if (newsize/n != size)
689 return PyErr_NoMemory();
690 if (list_resize(self, newsize) == -1)
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000691 return NULL;
692
693 p = size;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000694 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000695 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
696 for (j = 0; j < size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000697 PyObject *o = items[j];
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000698 Py_INCREF(o);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000699 items[p++] = o;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000700 }
701 }
702 Py_INCREF(self);
703 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000704}
705
Guido van Rossum4a450d01991-04-03 19:05:18 +0000706static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000707list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000708{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000709 PyObject *old_value;
Martin v. Löwis68192102007-07-21 06:55:02 +0000710 if (i < 0 || i >= Py_Size(a)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000711 PyErr_SetString(PyExc_IndexError,
712 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000713 return -1;
714 }
715 if (v == NULL)
716 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000717 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000718 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000719 a->ob_item[i] = v;
Tim Peters3b01a122002-07-19 02:35:45 +0000720 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000721 return 0;
722}
723
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000724static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000725listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000726{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000727 Py_ssize_t i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000728 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000729 if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000730 return NULL;
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000731 if (ins1(self, i, v) == 0)
732 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000733 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000734}
735
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000736static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000737listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000738{
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000739 if (app1(self, v) == 0)
740 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000741 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000742}
743
Barry Warsawdedf6d61998-10-09 16:37:25 +0000744static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000745listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000746{
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000747 PyObject *it; /* iter(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000748 Py_ssize_t m; /* size of self */
749 Py_ssize_t n; /* guess for size of b */
750 Py_ssize_t mn; /* m + n */
751 Py_ssize_t i;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000752 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000753
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000754 /* Special cases:
Tim Petersb38e2b62004-07-29 02:29:26 +0000755 1) lists and tuples which can use PySequence_Fast ops
756 2) extending self to self requires making a copy first
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000757 */
758 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
Armin Rigo70d172d2004-03-20 22:19:23 +0000759 PyObject **src, **dest;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000760 b = PySequence_Fast(b, "argument must be iterable");
761 if (!b)
762 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000763 n = PySequence_Fast_GET_SIZE(b);
764 if (n == 0) {
765 /* short circuit when b is empty */
766 Py_DECREF(b);
767 Py_RETURN_NONE;
768 }
Martin v. Löwis68192102007-07-21 06:55:02 +0000769 m = Py_Size(self);
Armin Rigo70d172d2004-03-20 22:19:23 +0000770 if (list_resize(self, m + n) == -1) {
771 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000772 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000773 }
774 /* note that we may still have self == b here for the
775 * situation a.extend(a), but the following code works
776 * in that case too. Just make sure to resize self
777 * before calling PySequence_Fast_ITEMS.
778 */
779 /* populate the end of self with b's items */
780 src = PySequence_Fast_ITEMS(b);
781 dest = self->ob_item + m;
782 for (i = 0; i < n; i++) {
783 PyObject *o = src[i];
784 Py_INCREF(o);
785 dest[i] = o;
786 }
787 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000788 Py_RETURN_NONE;
789 }
790
791 it = PyObject_GetIter(b);
792 if (it == NULL)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000793 return NULL;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000794 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000795
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000796 /* Guess a result list size. */
Raymond Hettinger4e2f7142007-12-06 00:56:53 +0000797 n = _PyObject_LengthHint(b, 8);
Martin v. Löwis68192102007-07-21 06:55:02 +0000798 m = Py_Size(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000799 mn = m + n;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000800 if (mn >= m) {
801 /* Make room. */
802 if (list_resize(self, mn) == -1)
803 goto error;
804 /* Make the list sane again. */
Martin v. Löwis68192102007-07-21 06:55:02 +0000805 Py_Size(self) = m;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000806 }
807 /* Else m + n overflowed; on the chance that n lied, and there really
808 * is enough room, ignore it. If n was telling the truth, we'll
809 * eventually run out of memory during the loop.
810 */
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000811
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000812 /* Run iterator to exhaustion. */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000813 for (;;) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000814 PyObject *item = iternext(it);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000815 if (item == NULL) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000816 if (PyErr_Occurred()) {
817 if (PyErr_ExceptionMatches(PyExc_StopIteration))
818 PyErr_Clear();
819 else
820 goto error;
821 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000822 break;
823 }
Martin v. Löwis68192102007-07-21 06:55:02 +0000824 if (Py_Size(self) < self->allocated) {
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000825 /* steals ref */
Martin v. Löwis68192102007-07-21 06:55:02 +0000826 PyList_SET_ITEM(self, Py_Size(self), item);
827 ++Py_Size(self);
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000828 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000829 else {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000830 int status = app1(self, item);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000831 Py_DECREF(item); /* append creates a new ref */
832 if (status < 0)
833 goto error;
834 }
835 }
836
837 /* Cut back result list if initial guess was too large. */
Martin v. Löwis68192102007-07-21 06:55:02 +0000838 if (Py_Size(self) < self->allocated)
839 list_resize(self, Py_Size(self)); /* shrinking can't fail */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000840
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000841 Py_DECREF(it);
842 Py_RETURN_NONE;
843
844 error:
845 Py_DECREF(it);
846 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000847}
848
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000849PyObject *
850_PyList_Extend(PyListObject *self, PyObject *b)
851{
852 return listextend(self, b);
853}
854
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000855static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000856list_inplace_concat(PyListObject *self, PyObject *other)
857{
858 PyObject *result;
859
860 result = listextend(self, other);
861 if (result == NULL)
862 return result;
863 Py_DECREF(result);
864 Py_INCREF(self);
865 return (PyObject *)self;
866}
867
868static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000869listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000870{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000871 Py_ssize_t i = -1;
Armin Rigo7ccbca92006-10-04 12:17:45 +0000872 PyObject *v;
Tim Peters8fc4a912004-07-31 21:53:19 +0000873 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000874
Armin Rigo7ccbca92006-10-04 12:17:45 +0000875 if (!PyArg_ParseTuple(args, "|n:pop", &i))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000876 return NULL;
Armin Rigo7ccbca92006-10-04 12:17:45 +0000877
Martin v. Löwis68192102007-07-21 06:55:02 +0000878 if (Py_Size(self) == 0) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000879 /* Special-case most common failure cause */
880 PyErr_SetString(PyExc_IndexError, "pop from empty list");
881 return NULL;
882 }
883 if (i < 0)
Martin v. Löwis68192102007-07-21 06:55:02 +0000884 i += Py_Size(self);
885 if (i < 0 || i >= Py_Size(self)) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000886 PyErr_SetString(PyExc_IndexError, "pop index out of range");
887 return NULL;
888 }
889 v = self->ob_item[i];
Martin v. Löwis68192102007-07-21 06:55:02 +0000890 if (i == Py_Size(self) - 1) {
891 status = list_resize(self, Py_Size(self) - 1);
Tim Peters8fc4a912004-07-31 21:53:19 +0000892 assert(status >= 0);
893 return v; /* and v now owns the reference the list had */
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000894 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000895 Py_INCREF(v);
Tim Peters8fc4a912004-07-31 21:53:19 +0000896 status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
897 assert(status >= 0);
898 /* Use status, so that in a release build compilers don't
899 * complain about the unused name.
900 */
Brett Cannon651dd522004-08-08 21:21:18 +0000901 (void) status;
902
903 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000904}
905
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000906/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
907static void
908reverse_slice(PyObject **lo, PyObject **hi)
909{
910 assert(lo && hi);
911
912 --hi;
913 while (lo < hi) {
914 PyObject *t = *lo;
915 *lo = *hi;
916 *hi = t;
917 ++lo;
918 --hi;
919 }
920}
921
Tim Petersa64dc242002-08-01 02:13:36 +0000922/* Lots of code for an adaptive, stable, natural mergesort. There are many
923 * pieces to this algorithm; read listsort.txt for overviews and details.
924 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000925
Guido van Rossum3f236de1996-12-10 23:55:39 +0000926/* Comparison function. Takes care of calling a user-supplied
Tim Peters66860f62002-08-04 17:47:26 +0000927 * comparison function (any callable Python object), which must not be
928 * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool
929 * with Py_LT if you know it's NULL).
Tim Petersa64dc242002-08-01 02:13:36 +0000930 * Returns -1 on error, 1 if x < y, 0 if x >= y.
931 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000932static int
Tim Petersa8c974c2002-07-19 03:30:57 +0000933islt(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000934{
Tim Petersf2a04732002-07-11 21:46:16 +0000935 PyObject *res;
936 PyObject *args;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000937 Py_ssize_t i;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000938
Tim Peters66860f62002-08-04 17:47:26 +0000939 assert(compare != NULL);
Tim Petersa8c974c2002-07-19 03:30:57 +0000940 /* Call the user's comparison function and translate the 3-way
941 * result into true or false (or error).
942 */
Tim Petersf2a04732002-07-11 21:46:16 +0000943 args = PyTuple_New(2);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000944 if (args == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000945 return -1;
Tim Petersf2a04732002-07-11 21:46:16 +0000946 Py_INCREF(x);
947 Py_INCREF(y);
948 PyTuple_SET_ITEM(args, 0, x);
949 PyTuple_SET_ITEM(args, 1, y);
Tim Peters58cf3612002-07-15 05:16:13 +0000950 res = PyObject_Call(compare, args, NULL);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000951 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000952 if (res == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000953 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000954 if (!PyInt_Check(res)) {
Georg Brandl283a1352006-11-19 08:48:30 +0000955 PyErr_Format(PyExc_TypeError,
956 "comparison function must return int, not %.200s",
957 res->ob_type->tp_name);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000958 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +0000959 return -1;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000960 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000961 i = PyInt_AsLong(res);
962 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +0000963 return i < 0;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000964}
965
Tim Peters66860f62002-08-04 17:47:26 +0000966/* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
967 * islt. This avoids a layer of function call in the usual case, and
968 * sorting does many comparisons.
969 * Returns -1 on error, 1 if x < y, 0 if x >= y.
970 */
971#define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
972 PyObject_RichCompareBool(X, Y, Py_LT) : \
973 islt(X, Y, COMPARE))
974
975/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +0000976 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
977 started. It makes more sense in context <wink>. X and Y are PyObject*s.
978*/
Tim Peters66860f62002-08-04 17:47:26 +0000979#define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
Tim Petersa8c974c2002-07-19 03:30:57 +0000980 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000981
982/* binarysort is the best method for sorting small arrays: it does
983 few compares, but can do data movement quadratic in the number of
984 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000985 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +0000986 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000987 On entry, must have lo <= start <= hi, and that [lo, start) is already
988 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +0000989 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000990 Even in case of error, the output slice will be some permutation of
991 the input (nothing is lost or duplicated).
992*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000993static int
Fred Drakea2f55112000-07-09 15:16:51 +0000994binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
995 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000996{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000997 register Py_ssize_t k;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000998 register PyObject **l, **p, **r;
999 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001000
Tim Petersa8c974c2002-07-19 03:30:57 +00001001 assert(lo <= start && start <= hi);
1002 /* assert [lo, start) is sorted */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001003 if (lo == start)
1004 ++start;
1005 for (; start < hi; ++start) {
1006 /* set l to where *start belongs */
1007 l = lo;
1008 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001009 pivot = *r;
Tim Peters0fe977c2002-07-19 06:12:32 +00001010 /* Invariants:
1011 * pivot >= all in [lo, l).
1012 * pivot < all in [r, start).
1013 * The second is vacuously true at the start.
1014 */
1015 assert(l < r);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001016 do {
1017 p = l + ((r - l) >> 1);
Tim Petersa8c974c2002-07-19 03:30:57 +00001018 IFLT(pivot, *p)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001019 r = p;
1020 else
Tim Peters0fe977c2002-07-19 06:12:32 +00001021 l = p+1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001022 } while (l < r);
Tim Peters0fe977c2002-07-19 06:12:32 +00001023 assert(l == r);
1024 /* The invariants still hold, so pivot >= all in [lo, l) and
1025 pivot < all in [l, start), so pivot belongs at l. Note
1026 that if there are elements equal to pivot, l points to the
1027 first slot after them -- that's why this sort is stable.
1028 Slide over to make room.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001029 Caution: using memmove is much slower under MSVC 5;
1030 we're not usually moving many slots. */
1031 for (p = start; p > l; --p)
1032 *p = *(p-1);
1033 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001034 }
Guido van Rossum3f236de1996-12-10 23:55:39 +00001035 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001036
1037 fail:
1038 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001039}
1040
Tim Petersa64dc242002-08-01 02:13:36 +00001041/*
1042Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1043is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001044
Tim Petersa64dc242002-08-01 02:13:36 +00001045 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001046
Tim Petersa64dc242002-08-01 02:13:36 +00001047or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001048
Tim Petersa64dc242002-08-01 02:13:36 +00001049 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001050
Tim Petersa64dc242002-08-01 02:13:36 +00001051Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1052For its intended use in a stable mergesort, the strictness of the defn of
1053"descending" is needed so that the caller can safely reverse a descending
1054sequence without violating stability (strict > ensures there are no equal
1055elements to get out of order).
1056
1057Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001058*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001059static Py_ssize_t
Tim Petersa64dc242002-08-01 02:13:36 +00001060count_run(PyObject **lo, PyObject **hi, PyObject *compare, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001061{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001062 Py_ssize_t k;
1063 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001064
Tim Petersa64dc242002-08-01 02:13:36 +00001065 assert(lo < hi);
1066 *descending = 0;
1067 ++lo;
1068 if (lo == hi)
1069 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001070
Tim Petersa64dc242002-08-01 02:13:36 +00001071 n = 2;
1072 IFLT(*lo, *(lo-1)) {
1073 *descending = 1;
1074 for (lo = lo+1; lo < hi; ++lo, ++n) {
1075 IFLT(*lo, *(lo-1))
1076 ;
1077 else
1078 break;
1079 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001080 }
Tim Petersa64dc242002-08-01 02:13:36 +00001081 else {
1082 for (lo = lo+1; lo < hi; ++lo, ++n) {
1083 IFLT(*lo, *(lo-1))
1084 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001085 }
1086 }
1087
Tim Petersa64dc242002-08-01 02:13:36 +00001088 return n;
1089fail:
1090 return -1;
1091}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001092
Tim Petersa64dc242002-08-01 02:13:36 +00001093/*
1094Locate the proper position of key in a sorted vector; if the vector contains
1095an element equal to key, return the position immediately to the left of
1096the leftmost equal element. [gallop_right() does the same except returns
1097the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001098
Tim Petersa64dc242002-08-01 02:13:36 +00001099"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001100
Tim Petersa64dc242002-08-01 02:13:36 +00001101"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1102hint is to the final result, the faster this runs.
1103
1104The return value is the int k in 0..n such that
1105
1106 a[k-1] < key <= a[k]
1107
1108pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1109key belongs at index k; or, IOW, the first k elements of a should precede
1110key, and the last n-k should follow key.
1111
1112Returns -1 on error. See listsort.txt for info on the method.
1113*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001114static Py_ssize_t
1115gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
Tim Petersa64dc242002-08-01 02:13:36 +00001116{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001117 Py_ssize_t ofs;
1118 Py_ssize_t lastofs;
1119 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001120
1121 assert(key && a && n > 0 && hint >= 0 && hint < n);
1122
1123 a += hint;
1124 lastofs = 0;
1125 ofs = 1;
1126 IFLT(*a, key) {
1127 /* a[hint] < key -- gallop right, until
1128 * a[hint + lastofs] < key <= a[hint + ofs]
1129 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001130 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001131 while (ofs < maxofs) {
1132 IFLT(a[ofs], key) {
1133 lastofs = ofs;
1134 ofs = (ofs << 1) + 1;
1135 if (ofs <= 0) /* int overflow */
1136 ofs = maxofs;
1137 }
1138 else /* key <= a[hint + ofs] */
1139 break;
1140 }
1141 if (ofs > maxofs)
1142 ofs = maxofs;
1143 /* Translate back to offsets relative to &a[0]. */
1144 lastofs += hint;
1145 ofs += hint;
1146 }
1147 else {
1148 /* key <= a[hint] -- gallop left, until
1149 * a[hint - ofs] < key <= a[hint - lastofs]
1150 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001151 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001152 while (ofs < maxofs) {
1153 IFLT(*(a-ofs), key)
1154 break;
1155 /* key <= a[hint - ofs] */
1156 lastofs = ofs;
1157 ofs = (ofs << 1) + 1;
1158 if (ofs <= 0) /* int overflow */
1159 ofs = maxofs;
1160 }
1161 if (ofs > maxofs)
1162 ofs = maxofs;
1163 /* Translate back to positive offsets relative to &a[0]. */
1164 k = lastofs;
1165 lastofs = hint - ofs;
1166 ofs = hint - k;
1167 }
1168 a -= hint;
1169
1170 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1171 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1172 * right of lastofs but no farther right than ofs. Do a binary
1173 * search, with invariant a[lastofs-1] < key <= a[ofs].
1174 */
1175 ++lastofs;
1176 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001177 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001178
1179 IFLT(a[m], key)
1180 lastofs = m+1; /* a[m] < key */
1181 else
1182 ofs = m; /* key <= a[m] */
1183 }
1184 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1185 return ofs;
1186
1187fail:
1188 return -1;
1189}
1190
1191/*
1192Exactly like gallop_left(), except that if key already exists in a[0:n],
1193finds the position immediately to the right of the rightmost equal value.
1194
1195The return value is the int k in 0..n such that
1196
1197 a[k-1] <= key < a[k]
1198
1199or -1 if error.
1200
1201The code duplication is massive, but this is enough different given that
1202we're sticking to "<" comparisons that it's much harder to follow if
1203written as one routine with yet another "left or right?" flag.
1204*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001205static Py_ssize_t
1206gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
Tim Petersa64dc242002-08-01 02:13:36 +00001207{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001208 Py_ssize_t ofs;
1209 Py_ssize_t lastofs;
1210 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001211
1212 assert(key && a && n > 0 && hint >= 0 && hint < n);
1213
1214 a += hint;
1215 lastofs = 0;
1216 ofs = 1;
1217 IFLT(key, *a) {
1218 /* key < a[hint] -- gallop left, until
1219 * a[hint - ofs] <= key < a[hint - lastofs]
1220 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001221 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001222 while (ofs < maxofs) {
1223 IFLT(key, *(a-ofs)) {
1224 lastofs = ofs;
1225 ofs = (ofs << 1) + 1;
1226 if (ofs <= 0) /* int overflow */
1227 ofs = maxofs;
1228 }
1229 else /* a[hint - ofs] <= key */
1230 break;
1231 }
1232 if (ofs > maxofs)
1233 ofs = maxofs;
1234 /* Translate back to positive offsets relative to &a[0]. */
1235 k = lastofs;
1236 lastofs = hint - ofs;
1237 ofs = hint - k;
1238 }
1239 else {
1240 /* a[hint] <= key -- gallop right, until
1241 * a[hint + lastofs] <= key < a[hint + ofs]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001242 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001243 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001244 while (ofs < maxofs) {
1245 IFLT(key, a[ofs])
1246 break;
1247 /* a[hint + ofs] <= key */
1248 lastofs = ofs;
1249 ofs = (ofs << 1) + 1;
1250 if (ofs <= 0) /* int overflow */
1251 ofs = maxofs;
1252 }
1253 if (ofs > maxofs)
1254 ofs = maxofs;
1255 /* Translate back to offsets relative to &a[0]. */
1256 lastofs += hint;
1257 ofs += hint;
1258 }
1259 a -= hint;
1260
1261 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1262 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1263 * right of lastofs but no farther right than ofs. Do a binary
1264 * search, with invariant a[lastofs-1] <= key < a[ofs].
1265 */
1266 ++lastofs;
1267 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001268 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001269
1270 IFLT(key, a[m])
1271 ofs = m; /* key < a[m] */
1272 else
1273 lastofs = m+1; /* a[m] <= key */
1274 }
1275 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1276 return ofs;
1277
1278fail:
1279 return -1;
1280}
1281
1282/* The maximum number of entries in a MergeState's pending-runs stack.
1283 * This is enough to sort arrays of size up to about
1284 * 32 * phi ** MAX_MERGE_PENDING
1285 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1286 * with 2**64 elements.
1287 */
1288#define MAX_MERGE_PENDING 85
1289
Tim Peterse05f65a2002-08-10 05:21:15 +00001290/* When we get into galloping mode, we stay there until both runs win less
1291 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001292 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001293#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001294
1295/* Avoid malloc for small temp arrays. */
1296#define MERGESTATE_TEMP_SIZE 256
1297
1298/* One MergeState exists on the stack per invocation of mergesort. It's just
1299 * a convenient way to pass state around among the helper functions.
1300 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001301struct s_slice {
1302 PyObject **base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001303 Py_ssize_t len;
Tim Peterse05f65a2002-08-10 05:21:15 +00001304};
1305
Tim Petersa64dc242002-08-01 02:13:36 +00001306typedef struct s_MergeState {
1307 /* The user-supplied comparison function. or NULL if none given. */
1308 PyObject *compare;
1309
Tim Peterse05f65a2002-08-10 05:21:15 +00001310 /* This controls when we get *into* galloping mode. It's initialized
1311 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1312 * random data, and lower for highly structured data.
1313 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001314 Py_ssize_t min_gallop;
Tim Peterse05f65a2002-08-10 05:21:15 +00001315
Tim Petersa64dc242002-08-01 02:13:36 +00001316 /* 'a' is temp storage to help with merges. It contains room for
1317 * alloced entries.
1318 */
1319 PyObject **a; /* may point to temparray below */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001320 Py_ssize_t alloced;
Tim Petersa64dc242002-08-01 02:13:36 +00001321
1322 /* A stack of n pending runs yet to be merged. Run #i starts at
1323 * address base[i] and extends for len[i] elements. It's always
1324 * true (so long as the indices are in bounds) that
1325 *
Tim Peterse05f65a2002-08-10 05:21:15 +00001326 * pending[i].base + pending[i].len == pending[i+1].base
Tim Petersa64dc242002-08-01 02:13:36 +00001327 *
1328 * so we could cut the storage for this, but it's a minor amount,
1329 * and keeping all the info explicit simplifies the code.
1330 */
1331 int n;
Tim Peterse05f65a2002-08-10 05:21:15 +00001332 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001333
1334 /* 'a' points to this when possible, rather than muck with malloc. */
1335 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1336} MergeState;
1337
1338/* Conceptually a MergeState's constructor. */
1339static void
1340merge_init(MergeState *ms, PyObject *compare)
1341{
1342 assert(ms != NULL);
1343 ms->compare = compare;
1344 ms->a = ms->temparray;
1345 ms->alloced = MERGESTATE_TEMP_SIZE;
1346 ms->n = 0;
Tim Peterse05f65a2002-08-10 05:21:15 +00001347 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001348}
1349
1350/* Free all the temp memory owned by the MergeState. This must be called
1351 * when you're done with a MergeState, and may be called before then if
1352 * you want to free the temp memory early.
1353 */
1354static void
1355merge_freemem(MergeState *ms)
1356{
1357 assert(ms != NULL);
1358 if (ms->a != ms->temparray)
1359 PyMem_Free(ms->a);
1360 ms->a = ms->temparray;
1361 ms->alloced = MERGESTATE_TEMP_SIZE;
1362}
1363
1364/* Ensure enough temp memory for 'need' array slots is available.
1365 * Returns 0 on success and -1 if the memory can't be gotten.
1366 */
1367static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001368merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001369{
1370 assert(ms != NULL);
1371 if (need <= ms->alloced)
1372 return 0;
1373 /* Don't realloc! That can cost cycles to copy the old data, but
1374 * we don't care what's in the block.
1375 */
1376 merge_freemem(ms);
1377 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1378 if (ms->a) {
1379 ms->alloced = need;
1380 return 0;
1381 }
1382 PyErr_NoMemory();
1383 merge_freemem(ms); /* reset to sane state */
1384 return -1;
1385}
1386#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1387 merge_getmem(MS, NEED))
1388
1389/* Merge the na elements starting at pa with the nb elements starting at pb
1390 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1391 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1392 * merge, and should have na <= nb. See listsort.txt for more info.
1393 * Return 0 if successful, -1 if error.
1394 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001395static Py_ssize_t
1396merge_lo(MergeState *ms, PyObject **pa, Py_ssize_t na,
1397 PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001398{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001399 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001400 PyObject *compare;
1401 PyObject **dest;
1402 int result = -1; /* guilty until proved innocent */
Neal Norwitz7fd96072006-08-19 04:28:55 +00001403 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001404
1405 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1406 if (MERGE_GETMEM(ms, na) < 0)
1407 return -1;
1408 memcpy(ms->a, pa, na * sizeof(PyObject*));
1409 dest = pa;
1410 pa = ms->a;
1411
1412 *dest++ = *pb++;
1413 --nb;
1414 if (nb == 0)
1415 goto Succeed;
1416 if (na == 1)
1417 goto CopyB;
1418
Neal Norwitz7fd96072006-08-19 04:28:55 +00001419 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001420 compare = ms->compare;
1421 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001422 Py_ssize_t acount = 0; /* # of times A won in a row */
1423 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001424
1425 /* Do the straightforward thing until (if ever) one run
1426 * appears to win consistently.
1427 */
1428 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001429 assert(na > 1 && nb > 0);
Tim Peters66860f62002-08-04 17:47:26 +00001430 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001431 if (k) {
1432 if (k < 0)
1433 goto Fail;
1434 *dest++ = *pb++;
1435 ++bcount;
1436 acount = 0;
1437 --nb;
1438 if (nb == 0)
1439 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001440 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001441 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001442 }
1443 else {
Tim Petersa64dc242002-08-01 02:13:36 +00001444 *dest++ = *pa++;
1445 ++acount;
1446 bcount = 0;
1447 --na;
1448 if (na == 1)
1449 goto CopyB;
Tim Peterse05f65a2002-08-10 05:21:15 +00001450 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001451 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001452 }
Tim Petersa64dc242002-08-01 02:13:36 +00001453 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001454
Tim Petersa64dc242002-08-01 02:13:36 +00001455 /* One run is winning so consistently that galloping may
1456 * be a huge win. So try that, and continue galloping until
1457 * (if ever) neither run appears to be winning consistently
1458 * anymore.
1459 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001460 ++min_gallop;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001461 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001462 assert(na > 1 && nb > 0);
1463 min_gallop -= min_gallop > 1;
1464 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001465 k = gallop_right(*pb, pa, na, 0, compare);
1466 acount = k;
1467 if (k) {
1468 if (k < 0)
1469 goto Fail;
1470 memcpy(dest, pa, k * sizeof(PyObject *));
1471 dest += k;
1472 pa += k;
1473 na -= k;
1474 if (na == 1)
1475 goto CopyB;
1476 /* na==0 is impossible now if the comparison
1477 * function is consistent, but we can't assume
1478 * that it is.
1479 */
1480 if (na == 0)
1481 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001482 }
Tim Petersa64dc242002-08-01 02:13:36 +00001483 *dest++ = *pb++;
1484 --nb;
1485 if (nb == 0)
1486 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001487
Tim Petersa64dc242002-08-01 02:13:36 +00001488 k = gallop_left(*pa, pb, nb, 0, compare);
1489 bcount = k;
1490 if (k) {
1491 if (k < 0)
1492 goto Fail;
1493 memmove(dest, pb, k * sizeof(PyObject *));
1494 dest += k;
1495 pb += k;
1496 nb -= k;
1497 if (nb == 0)
1498 goto Succeed;
1499 }
1500 *dest++ = *pa++;
1501 --na;
1502 if (na == 1)
1503 goto CopyB;
1504 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001505 ++min_gallop; /* penalize it for leaving galloping mode */
1506 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001507 }
1508Succeed:
1509 result = 0;
1510Fail:
1511 if (na)
1512 memcpy(dest, pa, na * sizeof(PyObject*));
1513 return result;
1514CopyB:
1515 assert(na == 1 && nb > 0);
1516 /* The last element of pa belongs at the end of the merge. */
1517 memmove(dest, pb, nb * sizeof(PyObject *));
1518 dest[nb] = *pa;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001519 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001520}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001521
Tim Petersa64dc242002-08-01 02:13:36 +00001522/* Merge the na elements starting at pa with the nb elements starting at pb
1523 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1524 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1525 * merge, and should have na >= nb. See listsort.txt for more info.
1526 * Return 0 if successful, -1 if error.
1527 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001528static Py_ssize_t
1529merge_hi(MergeState *ms, PyObject **pa, Py_ssize_t na, PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001530{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001531 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001532 PyObject *compare;
1533 PyObject **dest;
1534 int result = -1; /* guilty until proved innocent */
1535 PyObject **basea;
1536 PyObject **baseb;
Neal Norwitz7fd96072006-08-19 04:28:55 +00001537 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001538
1539 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1540 if (MERGE_GETMEM(ms, nb) < 0)
1541 return -1;
1542 dest = pb + nb - 1;
1543 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1544 basea = pa;
1545 baseb = ms->a;
1546 pb = ms->a + nb - 1;
1547 pa += na - 1;
1548
1549 *dest-- = *pa--;
1550 --na;
1551 if (na == 0)
1552 goto Succeed;
1553 if (nb == 1)
1554 goto CopyA;
1555
Neal Norwitz7fd96072006-08-19 04:28:55 +00001556 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001557 compare = ms->compare;
1558 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001559 Py_ssize_t acount = 0; /* # of times A won in a row */
1560 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001561
1562 /* Do the straightforward thing until (if ever) one run
1563 * appears to win consistently.
1564 */
1565 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001566 assert(na > 0 && nb > 1);
Tim Peters66860f62002-08-04 17:47:26 +00001567 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001568 if (k) {
1569 if (k < 0)
1570 goto Fail;
1571 *dest-- = *pa--;
1572 ++acount;
1573 bcount = 0;
1574 --na;
1575 if (na == 0)
1576 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001577 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001578 break;
1579 }
1580 else {
1581 *dest-- = *pb--;
1582 ++bcount;
1583 acount = 0;
1584 --nb;
1585 if (nb == 1)
1586 goto CopyA;
Tim Peterse05f65a2002-08-10 05:21:15 +00001587 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001588 break;
1589 }
1590 }
1591
1592 /* One run is winning so consistently that galloping may
1593 * be a huge win. So try that, and continue galloping until
1594 * (if ever) neither run appears to be winning consistently
1595 * anymore.
1596 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001597 ++min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001598 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001599 assert(na > 0 && nb > 1);
1600 min_gallop -= min_gallop > 1;
1601 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001602 k = gallop_right(*pb, basea, na, na-1, compare);
1603 if (k < 0)
1604 goto Fail;
1605 k = na - k;
1606 acount = k;
1607 if (k) {
1608 dest -= k;
1609 pa -= k;
1610 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1611 na -= k;
1612 if (na == 0)
1613 goto Succeed;
1614 }
1615 *dest-- = *pb--;
1616 --nb;
1617 if (nb == 1)
1618 goto CopyA;
1619
1620 k = gallop_left(*pa, baseb, nb, nb-1, compare);
1621 if (k < 0)
1622 goto Fail;
1623 k = nb - k;
1624 bcount = k;
1625 if (k) {
1626 dest -= k;
1627 pb -= k;
1628 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1629 nb -= k;
1630 if (nb == 1)
1631 goto CopyA;
1632 /* nb==0 is impossible now if the comparison
1633 * function is consistent, but we can't assume
1634 * that it is.
1635 */
1636 if (nb == 0)
1637 goto Succeed;
1638 }
1639 *dest-- = *pa--;
1640 --na;
1641 if (na == 0)
1642 goto Succeed;
1643 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001644 ++min_gallop; /* penalize it for leaving galloping mode */
1645 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001646 }
1647Succeed:
1648 result = 0;
1649Fail:
1650 if (nb)
1651 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1652 return result;
1653CopyA:
1654 assert(nb == 1 && na > 0);
1655 /* The first element of pb belongs at the front of the merge. */
1656 dest -= na;
1657 pa -= na;
1658 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1659 *dest = *pb;
1660 return 0;
1661}
1662
1663/* Merge the two runs at stack indices i and i+1.
1664 * Returns 0 on success, -1 on error.
1665 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001666static Py_ssize_t
1667merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001668{
1669 PyObject **pa, **pb;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001670 Py_ssize_t na, nb;
1671 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001672 PyObject *compare;
1673
1674 assert(ms != NULL);
1675 assert(ms->n >= 2);
1676 assert(i >= 0);
1677 assert(i == ms->n - 2 || i == ms->n - 3);
1678
Tim Peterse05f65a2002-08-10 05:21:15 +00001679 pa = ms->pending[i].base;
1680 na = ms->pending[i].len;
1681 pb = ms->pending[i+1].base;
1682 nb = ms->pending[i+1].len;
Tim Petersa64dc242002-08-01 02:13:36 +00001683 assert(na > 0 && nb > 0);
1684 assert(pa + na == pb);
1685
1686 /* Record the length of the combined runs; if i is the 3rd-last
1687 * run now, also slide over the last run (which isn't involved
1688 * in this merge). The current run i+1 goes away in any case.
1689 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001690 ms->pending[i].len = na + nb;
1691 if (i == ms->n - 3)
1692 ms->pending[i+1] = ms->pending[i+2];
Tim Petersa64dc242002-08-01 02:13:36 +00001693 --ms->n;
1694
1695 /* Where does b start in a? Elements in a before that can be
1696 * ignored (already in place).
1697 */
1698 compare = ms->compare;
1699 k = gallop_right(*pb, pa, na, 0, compare);
1700 if (k < 0)
1701 return -1;
1702 pa += k;
1703 na -= k;
1704 if (na == 0)
1705 return 0;
1706
1707 /* Where does a end in b? Elements in b after that can be
1708 * ignored (already in place).
1709 */
1710 nb = gallop_left(pa[na-1], pb, nb, nb-1, compare);
1711 if (nb <= 0)
1712 return nb;
1713
1714 /* Merge what remains of the runs, using a temp array with
1715 * min(na, nb) elements.
1716 */
1717 if (na <= nb)
1718 return merge_lo(ms, pa, na, pb, nb);
1719 else
1720 return merge_hi(ms, pa, na, pb, nb);
1721}
1722
1723/* Examine the stack of runs waiting to be merged, merging adjacent runs
1724 * until the stack invariants are re-established:
1725 *
1726 * 1. len[-3] > len[-2] + len[-1]
1727 * 2. len[-2] > len[-1]
1728 *
1729 * See listsort.txt for more info.
1730 *
1731 * Returns 0 on success, -1 on error.
1732 */
1733static int
1734merge_collapse(MergeState *ms)
1735{
Tim Peterse05f65a2002-08-10 05:21:15 +00001736 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001737
1738 assert(ms);
1739 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001740 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001741 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1742 if (p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001743 --n;
1744 if (merge_at(ms, n) < 0)
1745 return -1;
1746 }
Tim Peterse05f65a2002-08-10 05:21:15 +00001747 else if (p[n].len <= p[n+1].len) {
Tim Petersa64dc242002-08-01 02:13:36 +00001748 if (merge_at(ms, n) < 0)
1749 return -1;
1750 }
1751 else
1752 break;
1753 }
1754 return 0;
1755}
1756
1757/* Regardless of invariants, merge all runs on the stack until only one
1758 * remains. This is used at the end of the mergesort.
1759 *
1760 * Returns 0 on success, -1 on error.
1761 */
1762static int
1763merge_force_collapse(MergeState *ms)
1764{
Tim Peterse05f65a2002-08-10 05:21:15 +00001765 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001766
1767 assert(ms);
1768 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001769 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001770 if (n > 0 && p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001771 --n;
1772 if (merge_at(ms, n) < 0)
1773 return -1;
1774 }
1775 return 0;
1776}
1777
1778/* Compute a good value for the minimum run length; natural runs shorter
1779 * than this are boosted artificially via binary insertion.
1780 *
1781 * If n < 64, return n (it's too small to bother with fancy stuff).
1782 * Else if n is an exact power of 2, return 32.
1783 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1784 * strictly less than, an exact power of 2.
1785 *
1786 * See listsort.txt for more info.
1787 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001788static Py_ssize_t
1789merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001790{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001791 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001792
1793 assert(n >= 0);
1794 while (n >= 64) {
1795 r |= n & 1;
1796 n >>= 1;
1797 }
1798 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001799}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001800
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001801/* Special wrapper to support stable sorting using the decorate-sort-undecorate
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001802 pattern. Holds a key which is used for comparisons and the original record
Tim Petersb38e2b62004-07-29 02:29:26 +00001803 which is returned during the undecorate phase. By exposing only the key
1804 during comparisons, the underlying sort stability characteristics are left
1805 unchanged. Also, if a custom comparison function is used, it will only see
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001806 the key instead of a full record. */
1807
1808typedef struct {
1809 PyObject_HEAD
1810 PyObject *key;
1811 PyObject *value;
1812} sortwrapperobject;
1813
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001814PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
Anthony Baxter377be112006-04-11 06:54:30 +00001815static PyObject *
1816sortwrapper_richcompare(sortwrapperobject *, sortwrapperobject *, int);
1817static void
1818sortwrapper_dealloc(sortwrapperobject *);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001819
1820static PyTypeObject sortwrapper_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001821 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001822 "sortwrapper", /* tp_name */
1823 sizeof(sortwrapperobject), /* tp_basicsize */
1824 0, /* tp_itemsize */
1825 /* methods */
1826 (destructor)sortwrapper_dealloc, /* tp_dealloc */
1827 0, /* tp_print */
1828 0, /* tp_getattr */
1829 0, /* tp_setattr */
1830 0, /* tp_compare */
1831 0, /* tp_repr */
1832 0, /* tp_as_number */
1833 0, /* tp_as_sequence */
1834 0, /* tp_as_mapping */
1835 0, /* tp_hash */
1836 0, /* tp_call */
1837 0, /* tp_str */
1838 PyObject_GenericGetAttr, /* tp_getattro */
1839 0, /* tp_setattro */
1840 0, /* tp_as_buffer */
Tim Petersb38e2b62004-07-29 02:29:26 +00001841 Py_TPFLAGS_DEFAULT |
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001842 Py_TPFLAGS_HAVE_RICHCOMPARE, /* tp_flags */
1843 sortwrapper_doc, /* tp_doc */
1844 0, /* tp_traverse */
1845 0, /* tp_clear */
1846 (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
1847};
1848
Anthony Baxter377be112006-04-11 06:54:30 +00001849
1850static PyObject *
1851sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
1852{
1853 if (!PyObject_TypeCheck(b, &sortwrapper_type)) {
1854 PyErr_SetString(PyExc_TypeError,
1855 "expected a sortwrapperobject");
1856 return NULL;
1857 }
1858 return PyObject_RichCompare(a->key, b->key, op);
1859}
1860
1861static void
1862sortwrapper_dealloc(sortwrapperobject *so)
1863{
1864 Py_XDECREF(so->key);
1865 Py_XDECREF(so->value);
1866 PyObject_Del(so);
1867}
1868
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001869/* Returns a new reference to a sortwrapper.
1870 Consumes the references to the two underlying objects. */
1871
1872static PyObject *
1873build_sortwrapper(PyObject *key, PyObject *value)
1874{
1875 sortwrapperobject *so;
Tim Petersb38e2b62004-07-29 02:29:26 +00001876
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001877 so = PyObject_New(sortwrapperobject, &sortwrapper_type);
1878 if (so == NULL)
1879 return NULL;
1880 so->key = key;
1881 so->value = value;
1882 return (PyObject *)so;
1883}
1884
1885/* Returns a new reference to the value underlying the wrapper. */
1886static PyObject *
1887sortwrapper_getvalue(PyObject *so)
1888{
1889 PyObject *value;
1890
1891 if (!PyObject_TypeCheck(so, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001892 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001893 "expected a sortwrapperobject");
1894 return NULL;
1895 }
1896 value = ((sortwrapperobject *)so)->value;
1897 Py_INCREF(value);
1898 return value;
1899}
1900
1901/* Wrapper for user specified cmp functions in combination with a
1902 specified key function. Makes sure the cmp function is presented
1903 with the actual key instead of the sortwrapper */
1904
1905typedef struct {
1906 PyObject_HEAD
1907 PyObject *func;
1908} cmpwrapperobject;
1909
1910static void
1911cmpwrapper_dealloc(cmpwrapperobject *co)
1912{
1913 Py_XDECREF(co->func);
1914 PyObject_Del(co);
1915}
1916
1917static PyObject *
1918cmpwrapper_call(cmpwrapperobject *co, PyObject *args, PyObject *kwds)
1919{
1920 PyObject *x, *y, *xx, *yy;
1921
1922 if (!PyArg_UnpackTuple(args, "", 2, 2, &x, &y))
1923 return NULL;
1924 if (!PyObject_TypeCheck(x, &sortwrapper_type) ||
Raymond Hettingerae4a2992003-10-16 17:16:30 +00001925 !PyObject_TypeCheck(y, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001926 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001927 "expected a sortwrapperobject");
1928 return NULL;
1929 }
1930 xx = ((sortwrapperobject *)x)->key;
1931 yy = ((sortwrapperobject *)y)->key;
1932 return PyObject_CallFunctionObjArgs(co->func, xx, yy, NULL);
1933}
1934
1935PyDoc_STRVAR(cmpwrapper_doc, "cmp() wrapper for sort with custom keys.");
1936
1937static PyTypeObject cmpwrapper_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001938 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001939 "cmpwrapper", /* tp_name */
1940 sizeof(cmpwrapperobject), /* tp_basicsize */
1941 0, /* tp_itemsize */
1942 /* methods */
1943 (destructor)cmpwrapper_dealloc, /* tp_dealloc */
1944 0, /* tp_print */
1945 0, /* tp_getattr */
1946 0, /* tp_setattr */
1947 0, /* tp_compare */
1948 0, /* tp_repr */
1949 0, /* tp_as_number */
1950 0, /* tp_as_sequence */
1951 0, /* tp_as_mapping */
1952 0, /* tp_hash */
1953 (ternaryfunc)cmpwrapper_call, /* tp_call */
1954 0, /* tp_str */
1955 PyObject_GenericGetAttr, /* tp_getattro */
1956 0, /* tp_setattro */
1957 0, /* tp_as_buffer */
1958 Py_TPFLAGS_DEFAULT, /* tp_flags */
1959 cmpwrapper_doc, /* tp_doc */
1960};
1961
1962static PyObject *
1963build_cmpwrapper(PyObject *cmpfunc)
1964{
1965 cmpwrapperobject *co;
Tim Petersb38e2b62004-07-29 02:29:26 +00001966
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001967 co = PyObject_New(cmpwrapperobject, &cmpwrapper_type);
1968 if (co == NULL)
1969 return NULL;
1970 Py_INCREF(cmpfunc);
1971 co->func = cmpfunc;
1972 return (PyObject *)co;
1973}
1974
Tim Petersa64dc242002-08-01 02:13:36 +00001975/* An adaptive, stable, natural mergesort. See listsort.txt.
1976 * Returns Py_None on success, NULL on error. Even in case of error, the
1977 * list will be some permutation of its input state (nothing is lost or
1978 * duplicated).
1979 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001980static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001981listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001982{
Tim Petersa64dc242002-08-01 02:13:36 +00001983 MergeState ms;
1984 PyObject **lo, **hi;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001985 Py_ssize_t nremaining;
1986 Py_ssize_t minrun;
1987 Py_ssize_t saved_ob_size, saved_allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00001988 PyObject **saved_ob_item;
Armin Rigo93677f02004-07-29 12:40:23 +00001989 PyObject **final_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001990 PyObject *compare = NULL;
1991 PyObject *result = NULL; /* guilty until proved innocent */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001992 int reverse = 0;
1993 PyObject *keyfunc = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001994 Py_ssize_t i;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001995 PyObject *key, *value, *kvpair;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001996 static char *kwlist[] = {"cmp", "key", "reverse", 0};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001997
Tim Petersa64dc242002-08-01 02:13:36 +00001998 assert(self != NULL);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001999 assert (PyList_Check(self));
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002000 if (args != NULL) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002001 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:sort",
2002 kwlist, &compare, &keyfunc, &reverse))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002003 return NULL;
2004 }
Skip Montanaro4abd5f02003-01-02 20:51:08 +00002005 if (compare == Py_None)
2006 compare = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002007 if (keyfunc == Py_None)
2008 keyfunc = NULL;
2009 if (compare != NULL && keyfunc != NULL) {
2010 compare = build_cmpwrapper(compare);
2011 if (compare == NULL)
Hye-Shik Chang19cb1932003-12-10 07:31:08 +00002012 return NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002013 } else
2014 Py_XINCREF(compare);
2015
Tim Petersb9099c32002-11-12 22:08:10 +00002016 /* The list is temporarily made empty, so that mutations performed
2017 * by comparison functions can't affect the slice of memory we're
2018 * sorting (allowing mutations during sorting is a core-dump
2019 * factory, since ob_item may change).
2020 */
Martin v. Löwis68192102007-07-21 06:55:02 +00002021 saved_ob_size = Py_Size(self);
Tim Petersb9099c32002-11-12 22:08:10 +00002022 saved_ob_item = self->ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002023 saved_allocated = self->allocated;
Martin v. Löwis68192102007-07-21 06:55:02 +00002024 Py_Size(self) = 0;
Tim Peters51b4ade2004-07-29 04:07:15 +00002025 self->ob_item = NULL;
Armin Rigo93677f02004-07-29 12:40:23 +00002026 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00002027
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002028 if (keyfunc != NULL) {
2029 for (i=0 ; i < saved_ob_size ; i++) {
2030 value = saved_ob_item[i];
Tim Petersb38e2b62004-07-29 02:29:26 +00002031 key = PyObject_CallFunctionObjArgs(keyfunc, value,
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002032 NULL);
2033 if (key == NULL) {
2034 for (i=i-1 ; i>=0 ; i--) {
2035 kvpair = saved_ob_item[i];
2036 value = sortwrapper_getvalue(kvpair);
2037 saved_ob_item[i] = value;
2038 Py_DECREF(kvpair);
2039 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002040 goto dsu_fail;
2041 }
2042 kvpair = build_sortwrapper(key, value);
2043 if (kvpair == NULL)
2044 goto dsu_fail;
2045 saved_ob_item[i] = kvpair;
2046 }
2047 }
2048
2049 /* Reverse sort stability achieved by initially reversing the list,
2050 applying a stable forward sort, then reversing the final result. */
2051 if (reverse && saved_ob_size > 1)
2052 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2053
2054 merge_init(&ms, compare);
2055
Tim Petersb9099c32002-11-12 22:08:10 +00002056 nremaining = saved_ob_size;
Tim Petersa64dc242002-08-01 02:13:36 +00002057 if (nremaining < 2)
2058 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00002059
Tim Petersa64dc242002-08-01 02:13:36 +00002060 /* March over the array once, left to right, finding natural runs,
2061 * and extending short natural runs to minrun elements.
2062 */
Tim Petersb9099c32002-11-12 22:08:10 +00002063 lo = saved_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00002064 hi = lo + nremaining;
2065 minrun = merge_compute_minrun(nremaining);
2066 do {
2067 int descending;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002068 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00002069
Tim Petersa64dc242002-08-01 02:13:36 +00002070 /* Identify next run. */
2071 n = count_run(lo, hi, compare, &descending);
2072 if (n < 0)
2073 goto fail;
2074 if (descending)
2075 reverse_slice(lo, lo + n);
2076 /* If short, extend to min(minrun, nremaining). */
2077 if (n < minrun) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002078 const Py_ssize_t force = nremaining <= minrun ?
Tim Petersa64dc242002-08-01 02:13:36 +00002079 nremaining : minrun;
2080 if (binarysort(lo, lo + force, lo + n, compare) < 0)
2081 goto fail;
2082 n = force;
2083 }
2084 /* Push run onto pending-runs stack, and maybe merge. */
2085 assert(ms.n < MAX_MERGE_PENDING);
Tim Peterse05f65a2002-08-10 05:21:15 +00002086 ms.pending[ms.n].base = lo;
2087 ms.pending[ms.n].len = n;
Tim Petersa64dc242002-08-01 02:13:36 +00002088 ++ms.n;
2089 if (merge_collapse(&ms) < 0)
2090 goto fail;
2091 /* Advance to find next run. */
2092 lo += n;
2093 nremaining -= n;
2094 } while (nremaining);
2095 assert(lo == hi);
Tim Peters330f9e92002-07-19 07:05:44 +00002096
Tim Petersa64dc242002-08-01 02:13:36 +00002097 if (merge_force_collapse(&ms) < 0)
2098 goto fail;
2099 assert(ms.n == 1);
Tim Petersb9099c32002-11-12 22:08:10 +00002100 assert(ms.pending[0].base == saved_ob_item);
2101 assert(ms.pending[0].len == saved_ob_size);
Tim Petersa64dc242002-08-01 02:13:36 +00002102
2103succeed:
2104 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002105fail:
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002106 if (keyfunc != NULL) {
2107 for (i=0 ; i < saved_ob_size ; i++) {
2108 kvpair = saved_ob_item[i];
2109 value = sortwrapper_getvalue(kvpair);
2110 saved_ob_item[i] = value;
2111 Py_DECREF(kvpair);
2112 }
2113 }
2114
Armin Rigo93677f02004-07-29 12:40:23 +00002115 if (self->allocated != -1 && result != NULL) {
Tim Peters51b4ade2004-07-29 04:07:15 +00002116 /* The user mucked with the list during the sort,
2117 * and we don't already have another error to report.
2118 */
2119 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2120 result = NULL;
Tim Petersb9099c32002-11-12 22:08:10 +00002121 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002122
2123 if (reverse && saved_ob_size > 1)
2124 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2125
2126 merge_freemem(&ms);
2127
2128dsu_fail:
Armin Rigo93677f02004-07-29 12:40:23 +00002129 final_ob_item = self->ob_item;
Martin v. Löwis68192102007-07-21 06:55:02 +00002130 i = Py_Size(self);
2131 Py_Size(self) = saved_ob_size;
Tim Petersb9099c32002-11-12 22:08:10 +00002132 self->ob_item = saved_ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002133 self->allocated = saved_allocated;
Armin Rigo93677f02004-07-29 12:40:23 +00002134 if (final_ob_item != NULL) {
2135 /* we cannot use list_clear() for this because it does not
2136 guarantee that the list is really empty when it returns */
2137 while (--i >= 0) {
2138 Py_XDECREF(final_ob_item[i]);
2139 }
2140 PyMem_FREE(final_ob_item);
2141 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002142 Py_XDECREF(compare);
Tim Petersa64dc242002-08-01 02:13:36 +00002143 Py_XINCREF(result);
2144 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002145}
Tim Peters330f9e92002-07-19 07:05:44 +00002146#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002147#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002148
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002149int
Fred Drakea2f55112000-07-09 15:16:51 +00002150PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002151{
2152 if (v == NULL || !PyList_Check(v)) {
2153 PyErr_BadInternalCall();
2154 return -1;
2155 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002156 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002157 if (v == NULL)
2158 return -1;
2159 Py_DECREF(v);
2160 return 0;
2161}
2162
Guido van Rossumb86c5492001-02-12 22:06:02 +00002163static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002164listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002165{
Martin v. Löwis68192102007-07-21 06:55:02 +00002166 if (Py_Size(self) > 1)
2167 reverse_slice(self->ob_item, self->ob_item + Py_Size(self));
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002168 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002169}
2170
Guido van Rossum84c76f51990-10-30 13:32:20 +00002171int
Fred Drakea2f55112000-07-09 15:16:51 +00002172PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002173{
Tim Peters6063e262002-08-08 01:06:39 +00002174 PyListObject *self = (PyListObject *)v;
2175
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002176 if (v == NULL || !PyList_Check(v)) {
2177 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002178 return -1;
2179 }
Martin v. Löwis68192102007-07-21 06:55:02 +00002180 if (Py_Size(self) > 1)
2181 reverse_slice(self->ob_item, self->ob_item + Py_Size(self));
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002182 return 0;
2183}
2184
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002185PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002186PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002187{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002188 PyObject *w;
2189 PyObject **p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002190 Py_ssize_t n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002191 if (v == NULL || !PyList_Check(v)) {
2192 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002193 return NULL;
2194 }
Martin v. Löwis68192102007-07-21 06:55:02 +00002195 n = Py_Size(v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002196 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002197 if (w == NULL)
2198 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002199 p = ((PyTupleObject *)w)->ob_item;
Thomas Wouters334fb892000-07-25 12:56:38 +00002200 memcpy((void *)p,
2201 (void *)((PyListObject *)v)->ob_item,
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002202 n*sizeof(PyObject *));
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002203 while (--n >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002204 Py_INCREF(*p);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002205 p++;
2206 }
2207 return w;
2208}
2209
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002210static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002211listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002212{
Martin v. Löwis68192102007-07-21 06:55:02 +00002213 Py_ssize_t i, start=0, stop=Py_Size(self);
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002214 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002215
Walter Dörwalde8049bef2003-06-17 19:27:39 +00002216 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2217 _PyEval_SliceIndex, &start,
2218 _PyEval_SliceIndex, &stop))
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002219 return NULL;
Guido van Rossum2743d872003-06-17 14:25:14 +00002220 if (start < 0) {
Martin v. Löwis68192102007-07-21 06:55:02 +00002221 start += Py_Size(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002222 if (start < 0)
2223 start = 0;
2224 }
2225 if (stop < 0) {
Martin v. Löwis68192102007-07-21 06:55:02 +00002226 stop += Py_Size(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002227 if (stop < 0)
2228 stop = 0;
2229 }
Martin v. Löwis68192102007-07-21 06:55:02 +00002230 for (i = start; i < stop && i < Py_Size(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002231 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2232 if (cmp > 0)
Martin v. Löwis18e16552006-02-15 17:27:45 +00002233 return PyInt_FromSsize_t(i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002234 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002235 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002236 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002237 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002238 return NULL;
2239}
2240
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002241static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002242listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002243{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002244 Py_ssize_t count = 0;
2245 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002246
Martin v. Löwis68192102007-07-21 06:55:02 +00002247 for (i = 0; i < Py_Size(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002248 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2249 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002250 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002251 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002252 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00002253 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002254 return PyInt_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002255}
2256
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002257static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002258listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002259{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002260 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002261
Martin v. Löwis68192102007-07-21 06:55:02 +00002262 for (i = 0; i < Py_Size(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002263 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2264 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002265 if (list_ass_slice(self, i, i+1,
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002266 (PyObject *)NULL) == 0)
2267 Py_RETURN_NONE;
2268 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002269 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002270 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002271 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002272 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002273 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002274 return NULL;
2275}
2276
Jeremy Hylton8caad492000-06-23 14:18:11 +00002277static int
2278list_traverse(PyListObject *o, visitproc visit, void *arg)
2279{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002280 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002281
Martin v. Löwis68192102007-07-21 06:55:02 +00002282 for (i = Py_Size(o); --i >= 0; )
Thomas Woutersc6e55062006-04-15 21:47:09 +00002283 Py_VISIT(o->ob_item[i]);
Jeremy Hylton8caad492000-06-23 14:18:11 +00002284 return 0;
2285}
2286
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002287static PyObject *
2288list_richcompare(PyObject *v, PyObject *w, int op)
2289{
2290 PyListObject *vl, *wl;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002291 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002292
2293 if (!PyList_Check(v) || !PyList_Check(w)) {
2294 Py_INCREF(Py_NotImplemented);
2295 return Py_NotImplemented;
2296 }
2297
2298 vl = (PyListObject *)v;
2299 wl = (PyListObject *)w;
2300
Martin v. Löwis68192102007-07-21 06:55:02 +00002301 if (Py_Size(vl) != Py_Size(wl) && (op == Py_EQ || op == Py_NE)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002302 /* Shortcut: if the lengths differ, the lists differ */
2303 PyObject *res;
2304 if (op == Py_EQ)
2305 res = Py_False;
2306 else
2307 res = Py_True;
2308 Py_INCREF(res);
2309 return res;
2310 }
2311
2312 /* Search for the first index where items are different */
Martin v. Löwis68192102007-07-21 06:55:02 +00002313 for (i = 0; i < Py_Size(vl) && i < Py_Size(wl); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002314 int k = PyObject_RichCompareBool(vl->ob_item[i],
2315 wl->ob_item[i], Py_EQ);
2316 if (k < 0)
2317 return NULL;
2318 if (!k)
2319 break;
2320 }
2321
Martin v. Löwis68192102007-07-21 06:55:02 +00002322 if (i >= Py_Size(vl) || i >= Py_Size(wl)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002323 /* No more items to compare -- compare sizes */
Martin v. Löwis68192102007-07-21 06:55:02 +00002324 Py_ssize_t vs = Py_Size(vl);
2325 Py_ssize_t ws = Py_Size(wl);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002326 int cmp;
2327 PyObject *res;
2328 switch (op) {
2329 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00002330 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002331 case Py_EQ: cmp = vs == ws; break;
2332 case Py_NE: cmp = vs != ws; break;
2333 case Py_GT: cmp = vs > ws; break;
2334 case Py_GE: cmp = vs >= ws; break;
2335 default: return NULL; /* cannot happen */
2336 }
2337 if (cmp)
2338 res = Py_True;
2339 else
2340 res = Py_False;
2341 Py_INCREF(res);
2342 return res;
2343 }
2344
2345 /* We have an item that differs -- shortcuts for EQ/NE */
2346 if (op == Py_EQ) {
2347 Py_INCREF(Py_False);
2348 return Py_False;
2349 }
2350 if (op == Py_NE) {
2351 Py_INCREF(Py_True);
2352 return Py_True;
2353 }
2354
2355 /* Compare the final item again using the proper operator */
2356 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
2357}
2358
Tim Peters6d6c1a32001-08-02 04:15:00 +00002359static int
2360list_init(PyListObject *self, PyObject *args, PyObject *kw)
2361{
2362 PyObject *arg = NULL;
Martin v. Löwis15e62742006-02-27 16:46:16 +00002363 static char *kwlist[] = {"sequence", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002364
2365 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2366 return -1;
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002367
2368 /* Verify list invariants established by PyType_GenericAlloc() */
Martin v. Löwis68192102007-07-21 06:55:02 +00002369 assert(0 <= Py_Size(self));
2370 assert(Py_Size(self) <= self->allocated || self->allocated == -1);
Armin Rigoa37bbf22004-07-30 11:20:18 +00002371 assert(self->ob_item != NULL ||
2372 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002373
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002374 /* Empty previous contents */
Armin Rigo93677f02004-07-29 12:40:23 +00002375 if (self->ob_item != NULL) {
2376 (void)list_clear(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002377 }
2378 if (arg != NULL) {
2379 PyObject *rv = listextend(self, arg);
2380 if (rv == NULL)
2381 return -1;
2382 Py_DECREF(rv);
2383 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002384 return 0;
2385}
2386
Raymond Hettinger1021c442003-11-07 15:38:09 +00002387static PyObject *list_iter(PyObject *seq);
2388static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2389
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002390PyDoc_STRVAR(getitem_doc,
2391"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002392PyDoc_STRVAR(reversed_doc,
2393"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002394PyDoc_STRVAR(append_doc,
2395"L.append(object) -- append object to end");
2396PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002397"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002398PyDoc_STRVAR(insert_doc,
2399"L.insert(index, object) -- insert object before index");
2400PyDoc_STRVAR(pop_doc,
2401"L.pop([index]) -> item -- remove and return item at index (default last)");
2402PyDoc_STRVAR(remove_doc,
2403"L.remove(value) -- remove first occurrence of value");
2404PyDoc_STRVAR(index_doc,
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002405"L.index(value, [start, [stop]]) -> integer -- return first index of value");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002406PyDoc_STRVAR(count_doc,
2407"L.count(value) -> integer -- return number of occurrences of value");
2408PyDoc_STRVAR(reverse_doc,
2409"L.reverse() -- reverse *IN PLACE*");
2410PyDoc_STRVAR(sort_doc,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002411"L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n\
2412cmp(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002413
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002414static PyObject *list_subscript(PyListObject*, PyObject*);
2415
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002416static PyMethodDef list_methods[] = {
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002417 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
Raymond Hettinger1021c442003-11-07 15:38:09 +00002418 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002419 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002420 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002421 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002422 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002423 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002424 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002425 {"count", (PyCFunction)listcount, METH_O, count_doc},
2426 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002427 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
Tim Petersa64dc242002-08-01 02:13:36 +00002428 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002429};
2430
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002431static PySequenceMethods list_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002432 (lenfunc)list_length, /* sq_length */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002433 (binaryfunc)list_concat, /* sq_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002434 (ssizeargfunc)list_repeat, /* sq_repeat */
2435 (ssizeargfunc)list_item, /* sq_item */
2436 (ssizessizeargfunc)list_slice, /* sq_slice */
2437 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
2438 (ssizessizeobjargproc)list_ass_slice, /* sq_ass_slice */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002439 (objobjproc)list_contains, /* sq_contains */
2440 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002441 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002442};
2443
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002444PyDoc_STRVAR(list_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002445"list() -> new list\n"
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002446"list(sequence) -> new list initialized from sequence's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002447
Guido van Rossum38fff8c2006-03-07 18:50:55 +00002448
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002449static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002450list_subscript(PyListObject* self, PyObject* item)
2451{
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00002452 if (PyIndex_Check(item)) {
2453 Py_ssize_t i;
2454 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002455 if (i == -1 && PyErr_Occurred())
2456 return NULL;
2457 if (i < 0)
2458 i += PyList_GET_SIZE(self);
2459 return list_item(self, i);
2460 }
2461 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002462 Py_ssize_t start, stop, step, slicelength, cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002463 PyObject* result;
2464 PyObject* it;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002465 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002466
Martin v. Löwis68192102007-07-21 06:55:02 +00002467 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_Size(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002468 &start, &stop, &step, &slicelength) < 0) {
2469 return NULL;
2470 }
2471
2472 if (slicelength <= 0) {
2473 return PyList_New(0);
2474 }
Thomas Wouters3ccec682007-08-28 15:28:19 +00002475 else if (step == 1) {
2476 return list_slice(self, start, stop);
2477 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002478 else {
2479 result = PyList_New(slicelength);
2480 if (!result) return NULL;
2481
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002482 src = self->ob_item;
2483 dest = ((PyListObject *)result)->ob_item;
Tim Peters3b01a122002-07-19 02:35:45 +00002484 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002485 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002486 it = src[cur];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002487 Py_INCREF(it);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002488 dest[i] = it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002489 }
Tim Peters3b01a122002-07-19 02:35:45 +00002490
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002491 return result;
2492 }
2493 }
2494 else {
Georg Brandl283a1352006-11-19 08:48:30 +00002495 PyErr_Format(PyExc_TypeError,
2496 "list indices must be integers, not %.200s",
2497 item->ob_type->tp_name);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002498 return NULL;
2499 }
2500}
2501
Tim Peters3b01a122002-07-19 02:35:45 +00002502static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002503list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2504{
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00002505 if (PyIndex_Check(item)) {
2506 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002507 if (i == -1 && PyErr_Occurred())
2508 return -1;
2509 if (i < 0)
2510 i += PyList_GET_SIZE(self);
2511 return list_ass_item(self, i, value);
2512 }
2513 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002514 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002515
Martin v. Löwis68192102007-07-21 06:55:02 +00002516 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_Size(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002517 &start, &stop, &step, &slicelength) < 0) {
2518 return -1;
2519 }
2520
Thomas Wouters3ccec682007-08-28 15:28:19 +00002521 if (step == 1)
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002522 return list_ass_slice(self, start, stop, value);
2523
Thomas Wouters3ccec682007-08-28 15:28:19 +00002524 /* Make sure s[5:2] = [..] inserts at the right place:
2525 before 5, not before 2. */
2526 if ((step < 0 && start < stop) ||
2527 (step > 0 && start > stop))
2528 stop = start;
2529
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002530 if (value == NULL) {
2531 /* delete slice */
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002532 PyObject **garbage;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002533 Py_ssize_t cur, i;
Tim Peters3b01a122002-07-19 02:35:45 +00002534
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002535 if (slicelength <= 0)
2536 return 0;
2537
2538 if (step < 0) {
2539 stop = start + 1;
2540 start = stop + step*(slicelength - 1) - 1;
2541 step = -step;
2542 }
2543
2544 garbage = (PyObject**)
2545 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Neal Norwitzb88cfad2006-08-12 03:16:54 +00002546 if (!garbage) {
2547 PyErr_NoMemory();
2548 return -1;
2549 }
Tim Peters3b01a122002-07-19 02:35:45 +00002550
Thomas Wouters3ccec682007-08-28 15:28:19 +00002551 /* drawing pictures might help understand these for
2552 loops. Basically, we memmove the parts of the
2553 list that are *not* part of the slice: step-1
2554 items for each item that is part of the slice,
2555 and then tail end of the list that was not
2556 covered by the slice */
Guido van Rossum75a20b12002-06-11 12:22:28 +00002557 for (cur = start, i = 0;
2558 cur < stop;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002559 cur += step, i++) {
Thomas Wouters3ccec682007-08-28 15:28:19 +00002560 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002561
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002562 garbage[i] = PyList_GET_ITEM(self, cur);
2563
Martin v. Löwis68192102007-07-21 06:55:02 +00002564 if (cur + step >= Py_Size(self)) {
2565 lim = Py_Size(self) - cur - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002566 }
2567
Tim Petersb38e2b62004-07-29 02:29:26 +00002568 memmove(self->ob_item + cur - i,
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002569 self->ob_item + cur + 1,
2570 lim * sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002571 }
Thomas Wouters3ccec682007-08-28 15:28:19 +00002572 cur = start + slicelength*step;
2573 if (cur < Py_Size(self)) {
2574 memmove(self->ob_item + cur - slicelength,
2575 self->ob_item + cur,
2576 (Py_Size(self) - cur) *
2577 sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002578 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002579
Martin v. Löwis68192102007-07-21 06:55:02 +00002580 Py_Size(self) -= slicelength;
2581 list_resize(self, Py_Size(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002582
2583 for (i = 0; i < slicelength; i++) {
2584 Py_DECREF(garbage[i]);
2585 }
2586 PyMem_FREE(garbage);
2587
2588 return 0;
2589 }
2590 else {
2591 /* assign slice */
Thomas Wouters3ccec682007-08-28 15:28:19 +00002592 PyObject *ins, *seq;
2593 PyObject **garbage, **seqitems, **selfitems;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002594 Py_ssize_t cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002595
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002596 /* protect against a[::-1] = a */
Tim Peters3b01a122002-07-19 02:35:45 +00002597 if (self == (PyListObject*)value) {
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002598 seq = list_slice((PyListObject*)value, 0,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002599 PyList_GET_SIZE(value));
Tim Peters3b01a122002-07-19 02:35:45 +00002600 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002601 else {
Tim Petersb38e2b62004-07-29 02:29:26 +00002602 seq = PySequence_Fast(value,
Thomas Wouters3ccec682007-08-28 15:28:19 +00002603 "must assign iterable "
2604 "to extended slice");
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002605 }
Neal Norwitzb88cfad2006-08-12 03:16:54 +00002606 if (!seq)
2607 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002608
2609 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2610 PyErr_Format(PyExc_ValueError,
Thomas Wouters3ccec682007-08-28 15:28:19 +00002611 "attempt to assign sequence of "
2612 "size %zd to extended slice of "
2613 "size %zd",
Martin v. Löwise0e89f72006-02-16 06:59:22 +00002614 PySequence_Fast_GET_SIZE(seq),
2615 slicelength);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002616 Py_DECREF(seq);
2617 return -1;
2618 }
2619
2620 if (!slicelength) {
2621 Py_DECREF(seq);
2622 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002623 }
2624
2625 garbage = (PyObject**)
2626 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Neal Norwitze7e4e2d2006-10-28 21:20:12 +00002627 if (!garbage) {
2628 Py_DECREF(seq);
2629 PyErr_NoMemory();
2630 return -1;
2631 }
Tim Peters3b01a122002-07-19 02:35:45 +00002632
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002633 selfitems = self->ob_item;
Raymond Hettinger42bec932004-03-12 16:38:17 +00002634 seqitems = PySequence_Fast_ITEMS(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002635 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002636 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002637 garbage[i] = selfitems[cur];
2638 ins = seqitems[i];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002639 Py_INCREF(ins);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002640 selfitems[cur] = ins;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002641 }
2642
2643 for (i = 0; i < slicelength; i++) {
2644 Py_DECREF(garbage[i]);
2645 }
Tim Peters3b01a122002-07-19 02:35:45 +00002646
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002647 PyMem_FREE(garbage);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002648 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002649
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002650 return 0;
2651 }
Tim Peters3b01a122002-07-19 02:35:45 +00002652 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002653 else {
Georg Brandl283a1352006-11-19 08:48:30 +00002654 PyErr_Format(PyExc_TypeError,
2655 "list indices must be integers, not %.200s",
2656 item->ob_type->tp_name);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002657 return -1;
2658 }
2659}
2660
2661static PyMappingMethods list_as_mapping = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002662 (lenfunc)list_length,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002663 (binaryfunc)list_subscript,
2664 (objobjargproc)list_ass_subscript
2665};
2666
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002667PyTypeObject PyList_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002668 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002669 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002670 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002671 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002672 (destructor)list_dealloc, /* tp_dealloc */
2673 (printfunc)list_print, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002674 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002675 0, /* tp_setattr */
2676 0, /* tp_compare */
2677 (reprfunc)list_repr, /* tp_repr */
2678 0, /* tp_as_number */
2679 &list_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002680 &list_as_mapping, /* tp_as_mapping */
Guido van Rossum64c06e32007-11-22 00:55:51 +00002681 0, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002682 0, /* tp_call */
2683 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002684 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002685 0, /* tp_setattro */
2686 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002687 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Neal Norwitzee3a1b52007-02-25 19:44:48 +00002688 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002689 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002690 (traverseproc)list_traverse, /* tp_traverse */
2691 (inquiry)list_clear, /* tp_clear */
2692 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002693 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002694 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002695 0, /* tp_iternext */
2696 list_methods, /* tp_methods */
2697 0, /* tp_members */
2698 0, /* tp_getset */
2699 0, /* tp_base */
2700 0, /* tp_dict */
2701 0, /* tp_descr_get */
2702 0, /* tp_descr_set */
2703 0, /* tp_dictoffset */
2704 (initproc)list_init, /* tp_init */
2705 PyType_GenericAlloc, /* tp_alloc */
2706 PyType_GenericNew, /* tp_new */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002707 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002708};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002709
2710
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002711/*********************** List Iterator **************************/
2712
2713typedef struct {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002714 PyObject_HEAD
2715 long it_index;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002716 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002717} listiterobject;
2718
Anthony Baxter377be112006-04-11 06:54:30 +00002719static PyObject *list_iter(PyObject *);
2720static void listiter_dealloc(listiterobject *);
2721static int listiter_traverse(listiterobject *, visitproc, void *);
2722static PyObject *listiter_next(listiterobject *);
2723static PyObject *listiter_len(listiterobject *);
2724
2725PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
2726
2727static PyMethodDef listiter_methods[] = {
2728 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
2729 {NULL, NULL} /* sentinel */
2730};
2731
2732PyTypeObject PyListIter_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002733 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Anthony Baxter377be112006-04-11 06:54:30 +00002734 "listiterator", /* tp_name */
2735 sizeof(listiterobject), /* tp_basicsize */
2736 0, /* tp_itemsize */
2737 /* methods */
2738 (destructor)listiter_dealloc, /* tp_dealloc */
2739 0, /* tp_print */
2740 0, /* tp_getattr */
2741 0, /* tp_setattr */
2742 0, /* tp_compare */
2743 0, /* tp_repr */
2744 0, /* tp_as_number */
2745 0, /* tp_as_sequence */
2746 0, /* tp_as_mapping */
2747 0, /* tp_hash */
2748 0, /* tp_call */
2749 0, /* tp_str */
2750 PyObject_GenericGetAttr, /* tp_getattro */
2751 0, /* tp_setattro */
2752 0, /* tp_as_buffer */
2753 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2754 0, /* tp_doc */
2755 (traverseproc)listiter_traverse, /* tp_traverse */
2756 0, /* tp_clear */
2757 0, /* tp_richcompare */
2758 0, /* tp_weaklistoffset */
2759 PyObject_SelfIter, /* tp_iter */
2760 (iternextfunc)listiter_next, /* tp_iternext */
2761 listiter_methods, /* tp_methods */
2762 0, /* tp_members */
2763};
2764
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002765
Guido van Rossum5086e492002-07-16 15:56:52 +00002766static PyObject *
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002767list_iter(PyObject *seq)
2768{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002769 listiterobject *it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002770
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002771 if (!PyList_Check(seq)) {
2772 PyErr_BadInternalCall();
2773 return NULL;
2774 }
2775 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2776 if (it == NULL)
2777 return NULL;
2778 it->it_index = 0;
2779 Py_INCREF(seq);
2780 it->it_seq = (PyListObject *)seq;
2781 _PyObject_GC_TRACK(it);
2782 return (PyObject *)it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002783}
2784
2785static void
2786listiter_dealloc(listiterobject *it)
2787{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002788 _PyObject_GC_UNTRACK(it);
Guido van Rossum86103ae2002-07-16 20:07:32 +00002789 Py_XDECREF(it->it_seq);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002790 PyObject_GC_Del(it);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002791}
2792
2793static int
2794listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2795{
Thomas Woutersc6e55062006-04-15 21:47:09 +00002796 Py_VISIT(it->it_seq);
2797 return 0;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002798}
2799
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002800static PyObject *
Tim Peters93b2cc42002-06-01 05:22:55 +00002801listiter_next(listiterobject *it)
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002802{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002803 PyListObject *seq;
2804 PyObject *item;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002805
Tim Peters93b2cc42002-06-01 05:22:55 +00002806 assert(it != NULL);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002807 seq = it->it_seq;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002808 if (seq == NULL)
2809 return NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002810 assert(PyList_Check(seq));
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002811
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002812 if (it->it_index < PyList_GET_SIZE(seq)) {
Tim Peters93b2cc42002-06-01 05:22:55 +00002813 item = PyList_GET_ITEM(seq, it->it_index);
2814 ++it->it_index;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002815 Py_INCREF(item);
2816 return item;
2817 }
Guido van Rossum86103ae2002-07-16 20:07:32 +00002818
2819 Py_DECREF(seq);
2820 it->it_seq = NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002821 return NULL;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002822}
2823
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002824static PyObject *
Raymond Hettinger435bf582004-03-18 22:43:10 +00002825listiter_len(listiterobject *it)
2826{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002827 Py_ssize_t len;
Raymond Hettinger40a03822004-04-12 13:05:09 +00002828 if (it->it_seq) {
2829 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2830 if (len >= 0)
Martin v. Löwis18e16552006-02-15 17:27:45 +00002831 return PyInt_FromSsize_t(len);
Raymond Hettinger40a03822004-04-12 13:05:09 +00002832 }
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002833 return PyInt_FromLong(0);
Raymond Hettinger435bf582004-03-18 22:43:10 +00002834}
Anthony Baxter377be112006-04-11 06:54:30 +00002835/*********************** List Reverse Iterator **************************/
Raymond Hettinger435bf582004-03-18 22:43:10 +00002836
Anthony Baxter377be112006-04-11 06:54:30 +00002837typedef struct {
2838 PyObject_HEAD
2839 Py_ssize_t it_index;
2840 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
2841} listreviterobject;
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002842
Anthony Baxter377be112006-04-11 06:54:30 +00002843static PyObject *list_reversed(PyListObject *, PyObject *);
2844static void listreviter_dealloc(listreviterobject *);
2845static int listreviter_traverse(listreviterobject *, visitproc, void *);
2846static PyObject *listreviter_next(listreviterobject *);
2847static Py_ssize_t listreviter_len(listreviterobject *);
2848
2849static PySequenceMethods listreviter_as_sequence = {
2850 (lenfunc)listreviter_len, /* sq_length */
2851 0, /* sq_concat */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002852};
2853
Anthony Baxter377be112006-04-11 06:54:30 +00002854PyTypeObject PyListRevIter_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002855 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Anthony Baxter377be112006-04-11 06:54:30 +00002856 "listreverseiterator", /* tp_name */
2857 sizeof(listreviterobject), /* tp_basicsize */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002858 0, /* tp_itemsize */
2859 /* methods */
Anthony Baxter377be112006-04-11 06:54:30 +00002860 (destructor)listreviter_dealloc, /* tp_dealloc */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002861 0, /* tp_print */
2862 0, /* tp_getattr */
2863 0, /* tp_setattr */
2864 0, /* tp_compare */
2865 0, /* tp_repr */
2866 0, /* tp_as_number */
Anthony Baxter377be112006-04-11 06:54:30 +00002867 &listreviter_as_sequence, /* tp_as_sequence */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002868 0, /* tp_as_mapping */
2869 0, /* tp_hash */
2870 0, /* tp_call */
2871 0, /* tp_str */
2872 PyObject_GenericGetAttr, /* tp_getattro */
2873 0, /* tp_setattro */
2874 0, /* tp_as_buffer */
2875 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2876 0, /* tp_doc */
Anthony Baxter377be112006-04-11 06:54:30 +00002877 (traverseproc)listreviter_traverse, /* tp_traverse */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002878 0, /* tp_clear */
2879 0, /* tp_richcompare */
2880 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00002881 PyObject_SelfIter, /* tp_iter */
Anthony Baxter377be112006-04-11 06:54:30 +00002882 (iternextfunc)listreviter_next, /* tp_iternext */
2883 0,
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002884};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002885
Raymond Hettinger1021c442003-11-07 15:38:09 +00002886static PyObject *
2887list_reversed(PyListObject *seq, PyObject *unused)
2888{
2889 listreviterobject *it;
2890
2891 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2892 if (it == NULL)
2893 return NULL;
2894 assert(PyList_Check(seq));
2895 it->it_index = PyList_GET_SIZE(seq) - 1;
2896 Py_INCREF(seq);
2897 it->it_seq = seq;
2898 PyObject_GC_Track(it);
2899 return (PyObject *)it;
2900}
2901
2902static void
2903listreviter_dealloc(listreviterobject *it)
2904{
2905 PyObject_GC_UnTrack(it);
2906 Py_XDECREF(it->it_seq);
2907 PyObject_GC_Del(it);
2908}
2909
2910static int
2911listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2912{
Thomas Woutersc6e55062006-04-15 21:47:09 +00002913 Py_VISIT(it->it_seq);
2914 return 0;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002915}
2916
2917static PyObject *
2918listreviter_next(listreviterobject *it)
2919{
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002920 PyObject *item;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002921 Py_ssize_t index = it->it_index;
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002922 PyListObject *seq = it->it_seq;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002923
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002924 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2925 item = PyList_GET_ITEM(seq, index);
Raymond Hettinger1021c442003-11-07 15:38:09 +00002926 it->it_index--;
2927 Py_INCREF(item);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002928 return item;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002929 }
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002930 it->it_index = -1;
2931 if (seq != NULL) {
2932 it->it_seq = NULL;
2933 Py_DECREF(seq);
2934 }
2935 return NULL;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002936}
2937
Martin v. Löwis18e16552006-02-15 17:27:45 +00002938static Py_ssize_t
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002939listreviter_len(listreviterobject *it)
2940{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002941 Py_ssize_t len = it->it_index + 1;
Raymond Hettinger40a03822004-04-12 13:05:09 +00002942 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
2943 return 0;
2944 return len;
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002945}