blob: 7e2483e7fd6a044a7ee748bd93c37ed698632780 [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öwis9f2e3462007-07-21 17:22:18 +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öwis9f2e3462007-07-21 17:22:18 +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);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000111 if (op->ob_item == NULL) {
112 Py_DECREF(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000113 return PyErr_NoMemory();
Thomas Wouters0e3f5912006-08-11 14:57:12 +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öwis9f2e3462007-07-21 17:22:18 +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öwis9f2e3462007-07-21 17:22:18 +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öwis9f2e3462007-07-21 17:22:18 +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öwis9f2e3462007-07-21 17:22:18 +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öwis9f2e3462007-07-21 17:22:18 +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 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +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);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +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öwis9f2e3462007-07-21 17:22:18 +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öwis9f2e3462007-07-21 17:22:18 +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 Rossumc0b618a1997-05-02 03:12:38 +0000275static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000276list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000277{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000278 Py_ssize_t i;
Tim Petersa7259592001-06-16 05:11:17 +0000279 PyObject *s, *temp;
280 PyObject *pieces = NULL, *result = NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000281
282 i = Py_ReprEnter((PyObject*)v);
283 if (i != 0) {
Walter Dörwald1ab83302007-05-18 17:15:44 +0000284 return i > 0 ? PyUnicode_FromString("[...]") : NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000285 }
Tim Petersa7259592001-06-16 05:11:17 +0000286
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000287 if (Py_Size(v) == 0) {
Walter Dörwald1ab83302007-05-18 17:15:44 +0000288 result = PyUnicode_FromString("[]");
Tim Petersa7259592001-06-16 05:11:17 +0000289 goto Done;
290 }
291
292 pieces = PyList_New(0);
293 if (pieces == NULL)
294 goto Done;
295
296 /* Do repr() on each element. Note that this may mutate the list,
297 so must refetch the list size on each iteration. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000298 for (i = 0; i < Py_Size(v); ++i) {
Tim Petersa7259592001-06-16 05:11:17 +0000299 int status;
300 s = PyObject_Repr(v->ob_item[i]);
301 if (s == NULL)
302 goto Done;
303 status = PyList_Append(pieces, s);
304 Py_DECREF(s); /* append created a new ref */
305 if (status < 0)
306 goto Done;
307 }
308
309 /* Add "[]" decorations to the first and last items. */
310 assert(PyList_GET_SIZE(pieces) > 0);
Walter Dörwald1ab83302007-05-18 17:15:44 +0000311 s = PyUnicode_FromString("[");
Tim Petersa7259592001-06-16 05:11:17 +0000312 if (s == NULL)
313 goto Done;
314 temp = PyList_GET_ITEM(pieces, 0);
Walter Dörwald1ab83302007-05-18 17:15:44 +0000315 PyUnicode_AppendAndDel(&s, temp);
Tim Petersa7259592001-06-16 05:11:17 +0000316 PyList_SET_ITEM(pieces, 0, s);
317 if (s == NULL)
318 goto Done;
319
Walter Dörwald1ab83302007-05-18 17:15:44 +0000320 s = PyUnicode_FromString("]");
Tim Petersa7259592001-06-16 05:11:17 +0000321 if (s == NULL)
322 goto Done;
323 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
Walter Dörwald1ab83302007-05-18 17:15:44 +0000324 PyUnicode_AppendAndDel(&temp, s);
Tim Petersa7259592001-06-16 05:11:17 +0000325 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
326 if (temp == NULL)
327 goto Done;
328
329 /* Paste them all together with ", " between. */
Walter Dörwald1ab83302007-05-18 17:15:44 +0000330 s = PyUnicode_FromString(", ");
Tim Petersa7259592001-06-16 05:11:17 +0000331 if (s == NULL)
332 goto Done;
Walter Dörwald1ab83302007-05-18 17:15:44 +0000333 result = PyUnicode_Join(s, pieces);
Tim Peters3b01a122002-07-19 02:35:45 +0000334 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +0000335
336Done:
337 Py_XDECREF(pieces);
Guido van Rossumfb376de1998-04-10 22:47:27 +0000338 Py_ReprLeave((PyObject *)v);
Tim Petersa7259592001-06-16 05:11:17 +0000339 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000340}
341
Martin v. Löwis18e16552006-02-15 17:27:45 +0000342static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000343list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000344{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000345 return Py_Size(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000346}
347
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000348static int
Fred Drakea2f55112000-07-09 15:16:51 +0000349list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000350{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000351 Py_ssize_t i;
352 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000353
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000354 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_Size(a); ++i)
Raymond Hettingeraae59992002-09-05 14:23:49 +0000355 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000356 Py_EQ);
Neal Norwitzbb9c5f52002-09-05 21:32:55 +0000357 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000358}
359
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000360static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000361list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000362{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000363 if (i < 0 || i >= Py_Size(a)) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000364 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000365 indexerr = PyString_FromString(
366 "list index out of range");
367 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000368 return NULL;
369 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000370 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000371 return a->ob_item[i];
372}
373
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000374static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000375list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000376{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000377 PyListObject *np;
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000378 PyObject **src, **dest;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000379 Py_ssize_t i, len;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000380 if (ilow < 0)
381 ilow = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000382 else if (ilow > Py_Size(a))
383 ilow = Py_Size(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000384 if (ihigh < ilow)
385 ihigh = ilow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000386 else if (ihigh > Py_Size(a))
387 ihigh = Py_Size(a);
Raymond Hettinger99842b62004-03-08 05:56:15 +0000388 len = ihigh - ilow;
389 np = (PyListObject *) PyList_New(len);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000390 if (np == NULL)
391 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000392
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000393 src = a->ob_item + ilow;
394 dest = np->ob_item;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000395 for (i = 0; i < len; i++) {
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000396 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000397 Py_INCREF(v);
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000398 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000399 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000400 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000401}
402
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000403PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000404PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000405{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000406 if (!PyList_Check(a)) {
407 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000408 return NULL;
409 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000410 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000411}
412
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000413static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000414list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000415{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000416 Py_ssize_t size;
417 Py_ssize_t i;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000418 PyObject **src, **dest;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000419 PyListObject *np;
420 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000421 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000422 "can only concatenate list (not \"%.200s\") to list",
423 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000424 return NULL;
425 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000426#define b ((PyListObject *)bb)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000427 size = Py_Size(a) + Py_Size(b);
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000428 if (size < 0)
429 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000430 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000431 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000432 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000433 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000434 src = a->ob_item;
435 dest = np->ob_item;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000436 for (i = 0; i < Py_Size(a); i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000437 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000438 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000439 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000440 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000441 src = b->ob_item;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000442 dest = np->ob_item + Py_Size(a);
443 for (i = 0; i < Py_Size(b); i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000444 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000445 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000446 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000447 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000448 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000449#undef b
450}
451
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000452static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000453list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000454{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000455 Py_ssize_t i, j;
456 Py_ssize_t size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000457 PyListObject *np;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000458 PyObject **p, **items;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000459 PyObject *elem;
Guido van Rossumed98d481991-03-06 13:07:53 +0000460 if (n < 0)
461 n = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000462 size = Py_Size(a) * n;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000463 if (size == 0)
464 return PyList_New(0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000465 if (n && size/n != Py_Size(a))
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000466 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000467 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000468 if (np == NULL)
469 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000470
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000471 items = np->ob_item;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000472 if (Py_Size(a) == 1) {
Raymond Hettinger6624e682003-05-21 05:58:46 +0000473 elem = a->ob_item[0];
474 for (i = 0; i < n; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000475 items[i] = elem;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000476 Py_INCREF(elem);
477 }
478 return (PyObject *) np;
479 }
Guido van Rossumed98d481991-03-06 13:07:53 +0000480 p = np->ob_item;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000481 items = a->ob_item;
Guido van Rossumed98d481991-03-06 13:07:53 +0000482 for (i = 0; i < n; i++) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000483 for (j = 0; j < Py_Size(a); j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000484 *p = items[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000485 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000486 p++;
487 }
488 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000489 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000490}
491
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000492static int
Armin Rigo93677f02004-07-29 12:40:23 +0000493list_clear(PyListObject *a)
494{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000495 Py_ssize_t i;
Armin Rigo93677f02004-07-29 12:40:23 +0000496 PyObject **item = a->ob_item;
497 if (item != NULL) {
498 /* Because XDECREF can recursively invoke operations on
499 this list, we make it empty first. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000500 i = Py_Size(a);
501 Py_Size(a) = 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000502 a->ob_item = NULL;
503 a->allocated = 0;
504 while (--i >= 0) {
505 Py_XDECREF(item[i]);
506 }
507 PyMem_FREE(item);
508 }
509 /* Never fails; the return value can be ignored.
510 Note that there is no guarantee that the list is actually empty
511 at this point, because XDECREF may have populated it again! */
512 return 0;
513}
514
Tim Peters8fc4a912004-07-31 21:53:19 +0000515/* a[ilow:ihigh] = v if v != NULL.
516 * del a[ilow:ihigh] if v == NULL.
517 *
518 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
519 * guaranteed the call cannot fail.
520 */
Armin Rigo93677f02004-07-29 12:40:23 +0000521static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000522list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000523{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000524 /* Because [X]DECREF can recursively invoke list operations on
525 this list, we must postpone all [X]DECREF activity until
526 after the list is back in its canonical shape. Therefore
527 we must allocate an additional array, 'recycle', into which
528 we temporarily copy the items that are deleted from the
529 list. :-( */
Tim Peters73572222004-07-31 02:54:42 +0000530 PyObject *recycle_on_stack[8];
531 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000532 PyObject **item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000533 PyObject **vitem = NULL;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000534 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000535 Py_ssize_t n; /* # of elements in replacement list */
536 Py_ssize_t norig; /* # of elements in list getting replaced */
537 Py_ssize_t d; /* Change in size */
538 Py_ssize_t k;
Tim Peters8d9eb102004-07-31 02:24:20 +0000539 size_t s;
540 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000541#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000542 if (v == NULL)
543 n = 0;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000544 else {
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000545 if (a == b) {
546 /* Special case "a[i:j] = a" -- copy b first */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000547 v = list_slice(b, 0, Py_Size(b));
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000548 if (v == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000549 return result;
550 result = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000551 Py_DECREF(v);
Tim Peters8d9eb102004-07-31 02:24:20 +0000552 return result;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000553 }
Raymond Hettingerf889e102004-03-09 08:04:33 +0000554 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000555 if(v_as_SF == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000556 goto Error;
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000557 n = PySequence_Fast_GET_SIZE(v_as_SF);
Raymond Hettinger42bec932004-03-12 16:38:17 +0000558 vitem = PySequence_Fast_ITEMS(v_as_SF);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000559 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000560 if (ilow < 0)
561 ilow = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000562 else if (ilow > Py_Size(a))
563 ilow = Py_Size(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000564
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000565 if (ihigh < ilow)
566 ihigh = ilow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000567 else if (ihigh > Py_Size(a))
568 ihigh = Py_Size(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000569
Tim Peters8d9eb102004-07-31 02:24:20 +0000570 norig = ihigh - ilow;
571 assert(norig >= 0);
572 d = n - norig;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000573 if (Py_Size(a) + d == 0) {
Armin Rigo93677f02004-07-29 12:40:23 +0000574 Py_XDECREF(v_as_SF);
575 return list_clear(a);
576 }
577 item = a->ob_item;
Tim Peters8d9eb102004-07-31 02:24:20 +0000578 /* recycle the items that we are about to remove */
579 s = norig * sizeof(PyObject *);
Tim Peters73572222004-07-31 02:54:42 +0000580 if (s > sizeof(recycle_on_stack)) {
Armin Rigo1dd04a02004-07-30 11:38:22 +0000581 recycle = (PyObject **)PyMem_MALLOC(s);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000582 if (recycle == NULL) {
583 PyErr_NoMemory();
Tim Peters8d9eb102004-07-31 02:24:20 +0000584 goto Error;
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000585 }
586 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000587 memcpy(recycle, &item[ilow], s);
Tim Peters8d9eb102004-07-31 02:24:20 +0000588
Armin Rigo1dd04a02004-07-30 11:38:22 +0000589 if (d < 0) { /* Delete -d items */
590 memmove(&item[ihigh+d], &item[ihigh],
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000591 (Py_Size(a) - ihigh)*sizeof(PyObject *));
592 list_resize(a, Py_Size(a) + d);
Armin Rigo1dd04a02004-07-30 11:38:22 +0000593 item = a->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000594 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000595 else if (d > 0) { /* Insert d items */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000596 k = Py_Size(a);
Tim Peters73572222004-07-31 02:54:42 +0000597 if (list_resize(a, k+d) < 0)
Tim Peters8d9eb102004-07-31 02:24:20 +0000598 goto Error;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000599 item = a->ob_item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000600 memmove(&item[ihigh+d], &item[ihigh],
Tim Peters73572222004-07-31 02:54:42 +0000601 (k - ihigh)*sizeof(PyObject *));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000602 }
603 for (k = 0; k < n; k++, ilow++) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000604 PyObject *w = vitem[k];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000605 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000606 item[ilow] = w;
607 }
Tim Peters73572222004-07-31 02:54:42 +0000608 for (k = norig - 1; k >= 0; --k)
609 Py_XDECREF(recycle[k]);
Tim Peters8d9eb102004-07-31 02:24:20 +0000610 result = 0;
611 Error:
Tim Peters73572222004-07-31 02:54:42 +0000612 if (recycle != recycle_on_stack)
Armin Rigo1dd04a02004-07-30 11:38:22 +0000613 PyMem_FREE(recycle);
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000614 Py_XDECREF(v_as_SF);
Tim Peters8d9eb102004-07-31 02:24:20 +0000615 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000616#undef b
617}
618
Guido van Rossum234f9421993-06-17 12:35:49 +0000619int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000620PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000621{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000622 if (!PyList_Check(a)) {
623 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000624 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000625 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000626 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000627}
628
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000629static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000630list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000631{
632 PyObject **items;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000633 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000634
635
636 size = PyList_GET_SIZE(self);
637 if (size == 0) {
638 Py_INCREF(self);
639 return (PyObject *)self;
640 }
641
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000642 if (n < 1) {
Armin Rigo93677f02004-07-29 12:40:23 +0000643 (void)list_clear(self);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000644 Py_INCREF(self);
645 return (PyObject *)self;
646 }
647
Tim Petersb38e2b62004-07-29 02:29:26 +0000648 if (list_resize(self, size*n) == -1)
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000649 return NULL;
650
651 p = size;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000652 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000653 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
654 for (j = 0; j < size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000655 PyObject *o = items[j];
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000656 Py_INCREF(o);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000657 items[p++] = o;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000658 }
659 }
660 Py_INCREF(self);
661 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000662}
663
Guido van Rossum4a450d01991-04-03 19:05:18 +0000664static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000665list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000666{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000667 PyObject *old_value;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000668 if (i < 0 || i >= Py_Size(a)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000669 PyErr_SetString(PyExc_IndexError,
670 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000671 return -1;
672 }
673 if (v == NULL)
674 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000675 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000676 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000677 a->ob_item[i] = v;
Tim Peters3b01a122002-07-19 02:35:45 +0000678 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000679 return 0;
680}
681
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000682static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000683listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000684{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000685 Py_ssize_t i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000686 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000687 if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000688 return NULL;
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000689 if (ins1(self, i, v) == 0)
690 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000691 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000692}
693
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000694static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000695listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000696{
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000697 if (app1(self, v) == 0)
698 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000699 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000700}
701
Barry Warsawdedf6d61998-10-09 16:37:25 +0000702static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000703listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000704{
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000705 PyObject *it; /* iter(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000706 Py_ssize_t m; /* size of self */
707 Py_ssize_t n; /* guess for size of b */
708 Py_ssize_t mn; /* m + n */
709 Py_ssize_t i;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000710 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000711
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000712 /* Special cases:
Tim Petersb38e2b62004-07-29 02:29:26 +0000713 1) lists and tuples which can use PySequence_Fast ops
714 2) extending self to self requires making a copy first
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000715 */
716 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
Armin Rigo70d172d2004-03-20 22:19:23 +0000717 PyObject **src, **dest;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000718 b = PySequence_Fast(b, "argument must be iterable");
719 if (!b)
720 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000721 n = PySequence_Fast_GET_SIZE(b);
722 if (n == 0) {
723 /* short circuit when b is empty */
724 Py_DECREF(b);
725 Py_RETURN_NONE;
726 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000727 m = Py_Size(self);
Armin Rigo70d172d2004-03-20 22:19:23 +0000728 if (list_resize(self, m + n) == -1) {
729 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000730 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000731 }
732 /* note that we may still have self == b here for the
733 * situation a.extend(a), but the following code works
734 * in that case too. Just make sure to resize self
735 * before calling PySequence_Fast_ITEMS.
736 */
737 /* populate the end of self with b's items */
738 src = PySequence_Fast_ITEMS(b);
739 dest = self->ob_item + m;
740 for (i = 0; i < n; i++) {
741 PyObject *o = src[i];
742 Py_INCREF(o);
743 dest[i] = o;
744 }
745 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000746 Py_RETURN_NONE;
747 }
748
749 it = PyObject_GetIter(b);
750 if (it == NULL)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000751 return NULL;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000752 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000753
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000754 /* Guess a result list size. */
Armin Rigof5b3e362006-02-11 21:32:43 +0000755 n = _PyObject_LengthHint(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000756 if (n < 0) {
Raymond Hettingera710b332005-08-21 11:03:59 +0000757 if (!PyErr_ExceptionMatches(PyExc_TypeError) &&
758 !PyErr_ExceptionMatches(PyExc_AttributeError)) {
759 Py_DECREF(it);
760 return NULL;
761 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000762 PyErr_Clear();
763 n = 8; /* arbitrary */
764 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000765 m = Py_Size(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000766 mn = m + n;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000767 if (mn >= m) {
768 /* Make room. */
769 if (list_resize(self, mn) == -1)
770 goto error;
771 /* Make the list sane again. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000772 Py_Size(self) = m;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000773 }
774 /* Else m + n overflowed; on the chance that n lied, and there really
775 * is enough room, ignore it. If n was telling the truth, we'll
776 * eventually run out of memory during the loop.
777 */
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000778
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000779 /* Run iterator to exhaustion. */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000780 for (;;) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000781 PyObject *item = iternext(it);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000782 if (item == NULL) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000783 if (PyErr_Occurred()) {
784 if (PyErr_ExceptionMatches(PyExc_StopIteration))
785 PyErr_Clear();
786 else
787 goto error;
788 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000789 break;
790 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000791 if (Py_Size(self) < self->allocated) {
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000792 /* steals ref */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000793 PyList_SET_ITEM(self, Py_Size(self), item);
794 ++Py_Size(self);
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000795 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000796 else {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000797 int status = app1(self, item);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000798 Py_DECREF(item); /* append creates a new ref */
799 if (status < 0)
800 goto error;
801 }
802 }
803
804 /* Cut back result list if initial guess was too large. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000805 if (Py_Size(self) < self->allocated)
806 list_resize(self, Py_Size(self)); /* shrinking can't fail */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000807
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000808 Py_DECREF(it);
809 Py_RETURN_NONE;
810
811 error:
812 Py_DECREF(it);
813 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000814}
815
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000816PyObject *
817_PyList_Extend(PyListObject *self, PyObject *b)
818{
819 return listextend(self, b);
820}
821
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000822static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000823list_inplace_concat(PyListObject *self, PyObject *other)
824{
825 PyObject *result;
826
827 result = listextend(self, other);
828 if (result == NULL)
829 return result;
830 Py_DECREF(result);
831 Py_INCREF(self);
832 return (PyObject *)self;
833}
834
835static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000836listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000837{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000838 Py_ssize_t i = -1;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000839 PyObject *v;
Tim Peters8fc4a912004-07-31 21:53:19 +0000840 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000841
Thomas Wouters89f507f2006-12-13 04:49:30 +0000842 if (!PyArg_ParseTuple(args, "|n:pop", &i))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000843 return NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000844
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000845 if (Py_Size(self) == 0) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000846 /* Special-case most common failure cause */
847 PyErr_SetString(PyExc_IndexError, "pop from empty list");
848 return NULL;
849 }
850 if (i < 0)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000851 i += Py_Size(self);
852 if (i < 0 || i >= Py_Size(self)) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000853 PyErr_SetString(PyExc_IndexError, "pop index out of range");
854 return NULL;
855 }
856 v = self->ob_item[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000857 if (i == Py_Size(self) - 1) {
858 status = list_resize(self, Py_Size(self) - 1);
Tim Peters8fc4a912004-07-31 21:53:19 +0000859 assert(status >= 0);
860 return v; /* and v now owns the reference the list had */
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000861 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000862 Py_INCREF(v);
Tim Peters8fc4a912004-07-31 21:53:19 +0000863 status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
864 assert(status >= 0);
865 /* Use status, so that in a release build compilers don't
866 * complain about the unused name.
867 */
Brett Cannon651dd522004-08-08 21:21:18 +0000868 (void) status;
869
870 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000871}
872
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000873/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
874static void
875reverse_slice(PyObject **lo, PyObject **hi)
876{
877 assert(lo && hi);
878
879 --hi;
880 while (lo < hi) {
881 PyObject *t = *lo;
882 *lo = *hi;
883 *hi = t;
884 ++lo;
885 --hi;
886 }
887}
888
Tim Petersa64dc242002-08-01 02:13:36 +0000889/* Lots of code for an adaptive, stable, natural mergesort. There are many
890 * pieces to this algorithm; read listsort.txt for overviews and details.
891 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000892
Guido van Rossum3f236de1996-12-10 23:55:39 +0000893/* Comparison function. Takes care of calling a user-supplied
Tim Peters66860f62002-08-04 17:47:26 +0000894 * comparison function (any callable Python object), which must not be
895 * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool
896 * with Py_LT if you know it's NULL).
Tim Petersa64dc242002-08-01 02:13:36 +0000897 * Returns -1 on error, 1 if x < y, 0 if x >= y.
898 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000899static int
Tim Petersa8c974c2002-07-19 03:30:57 +0000900islt(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000901{
Tim Petersf2a04732002-07-11 21:46:16 +0000902 PyObject *res;
903 PyObject *args;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000904 Py_ssize_t i;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000905
Tim Peters66860f62002-08-04 17:47:26 +0000906 assert(compare != NULL);
Tim Petersa8c974c2002-07-19 03:30:57 +0000907 /* Call the user's comparison function and translate the 3-way
908 * result into true or false (or error).
909 */
Tim Petersf2a04732002-07-11 21:46:16 +0000910 args = PyTuple_New(2);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000911 if (args == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000912 return -1;
Tim Petersf2a04732002-07-11 21:46:16 +0000913 Py_INCREF(x);
914 Py_INCREF(y);
915 PyTuple_SET_ITEM(args, 0, x);
916 PyTuple_SET_ITEM(args, 1, y);
Tim Peters58cf3612002-07-15 05:16:13 +0000917 res = PyObject_Call(compare, args, NULL);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000918 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000919 if (res == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000920 return -1;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000921 if (!PyInt_CheckExact(res)) {
Thomas Wouters89f507f2006-12-13 04:49:30 +0000922 PyErr_Format(PyExc_TypeError,
923 "comparison function must return int, not %.200s",
924 res->ob_type->tp_name);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000925 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +0000926 return -1;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000927 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000928 i = PyInt_AsLong(res);
929 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +0000930 return i < 0;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000931}
932
Tim Peters66860f62002-08-04 17:47:26 +0000933/* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
934 * islt. This avoids a layer of function call in the usual case, and
935 * sorting does many comparisons.
936 * Returns -1 on error, 1 if x < y, 0 if x >= y.
937 */
938#define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
939 PyObject_RichCompareBool(X, Y, Py_LT) : \
940 islt(X, Y, COMPARE))
941
942/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +0000943 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
944 started. It makes more sense in context <wink>. X and Y are PyObject*s.
945*/
Tim Peters66860f62002-08-04 17:47:26 +0000946#define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
Tim Petersa8c974c2002-07-19 03:30:57 +0000947 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000948
949/* binarysort is the best method for sorting small arrays: it does
950 few compares, but can do data movement quadratic in the number of
951 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000952 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +0000953 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000954 On entry, must have lo <= start <= hi, and that [lo, start) is already
955 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +0000956 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000957 Even in case of error, the output slice will be some permutation of
958 the input (nothing is lost or duplicated).
959*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000960static int
Fred Drakea2f55112000-07-09 15:16:51 +0000961binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
962 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000963{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000964 register Py_ssize_t k;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000965 register PyObject **l, **p, **r;
966 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000967
Tim Petersa8c974c2002-07-19 03:30:57 +0000968 assert(lo <= start && start <= hi);
969 /* assert [lo, start) is sorted */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000970 if (lo == start)
971 ++start;
972 for (; start < hi; ++start) {
973 /* set l to where *start belongs */
974 l = lo;
975 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000976 pivot = *r;
Tim Peters0fe977c2002-07-19 06:12:32 +0000977 /* Invariants:
978 * pivot >= all in [lo, l).
979 * pivot < all in [r, start).
980 * The second is vacuously true at the start.
981 */
982 assert(l < r);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000983 do {
984 p = l + ((r - l) >> 1);
Tim Petersa8c974c2002-07-19 03:30:57 +0000985 IFLT(pivot, *p)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000986 r = p;
987 else
Tim Peters0fe977c2002-07-19 06:12:32 +0000988 l = p+1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000989 } while (l < r);
Tim Peters0fe977c2002-07-19 06:12:32 +0000990 assert(l == r);
991 /* The invariants still hold, so pivot >= all in [lo, l) and
992 pivot < all in [l, start), so pivot belongs at l. Note
993 that if there are elements equal to pivot, l points to the
994 first slot after them -- that's why this sort is stable.
995 Slide over to make room.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000996 Caution: using memmove is much slower under MSVC 5;
997 we're not usually moving many slots. */
998 for (p = start; p > l; --p)
999 *p = *(p-1);
1000 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001001 }
Guido van Rossum3f236de1996-12-10 23:55:39 +00001002 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001003
1004 fail:
1005 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001006}
1007
Tim Petersa64dc242002-08-01 02:13:36 +00001008/*
1009Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1010is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001011
Tim Petersa64dc242002-08-01 02:13:36 +00001012 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001013
Tim Petersa64dc242002-08-01 02:13:36 +00001014or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001015
Tim Petersa64dc242002-08-01 02:13:36 +00001016 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001017
Tim Petersa64dc242002-08-01 02:13:36 +00001018Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1019For its intended use in a stable mergesort, the strictness of the defn of
1020"descending" is needed so that the caller can safely reverse a descending
1021sequence without violating stability (strict > ensures there are no equal
1022elements to get out of order).
1023
1024Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001025*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001026static Py_ssize_t
Tim Petersa64dc242002-08-01 02:13:36 +00001027count_run(PyObject **lo, PyObject **hi, PyObject *compare, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001028{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001029 Py_ssize_t k;
1030 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001031
Tim Petersa64dc242002-08-01 02:13:36 +00001032 assert(lo < hi);
1033 *descending = 0;
1034 ++lo;
1035 if (lo == hi)
1036 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001037
Tim Petersa64dc242002-08-01 02:13:36 +00001038 n = 2;
1039 IFLT(*lo, *(lo-1)) {
1040 *descending = 1;
1041 for (lo = lo+1; lo < hi; ++lo, ++n) {
1042 IFLT(*lo, *(lo-1))
1043 ;
1044 else
1045 break;
1046 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001047 }
Tim Petersa64dc242002-08-01 02:13:36 +00001048 else {
1049 for (lo = lo+1; lo < hi; ++lo, ++n) {
1050 IFLT(*lo, *(lo-1))
1051 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001052 }
1053 }
1054
Tim Petersa64dc242002-08-01 02:13:36 +00001055 return n;
1056fail:
1057 return -1;
1058}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001059
Tim Petersa64dc242002-08-01 02:13:36 +00001060/*
1061Locate the proper position of key in a sorted vector; if the vector contains
1062an element equal to key, return the position immediately to the left of
1063the leftmost equal element. [gallop_right() does the same except returns
1064the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001065
Tim Petersa64dc242002-08-01 02:13:36 +00001066"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001067
Tim Petersa64dc242002-08-01 02:13:36 +00001068"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1069hint is to the final result, the faster this runs.
1070
1071The return value is the int k in 0..n such that
1072
1073 a[k-1] < key <= a[k]
1074
1075pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1076key belongs at index k; or, IOW, the first k elements of a should precede
1077key, and the last n-k should follow key.
1078
1079Returns -1 on error. See listsort.txt for info on the method.
1080*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001081static Py_ssize_t
1082gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
Tim Petersa64dc242002-08-01 02:13:36 +00001083{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001084 Py_ssize_t ofs;
1085 Py_ssize_t lastofs;
1086 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001087
1088 assert(key && a && n > 0 && hint >= 0 && hint < n);
1089
1090 a += hint;
1091 lastofs = 0;
1092 ofs = 1;
1093 IFLT(*a, key) {
1094 /* a[hint] < key -- gallop right, until
1095 * a[hint + lastofs] < key <= a[hint + ofs]
1096 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001097 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001098 while (ofs < maxofs) {
1099 IFLT(a[ofs], key) {
1100 lastofs = ofs;
1101 ofs = (ofs << 1) + 1;
1102 if (ofs <= 0) /* int overflow */
1103 ofs = maxofs;
1104 }
1105 else /* key <= a[hint + ofs] */
1106 break;
1107 }
1108 if (ofs > maxofs)
1109 ofs = maxofs;
1110 /* Translate back to offsets relative to &a[0]. */
1111 lastofs += hint;
1112 ofs += hint;
1113 }
1114 else {
1115 /* key <= a[hint] -- gallop left, until
1116 * a[hint - ofs] < key <= a[hint - lastofs]
1117 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001118 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001119 while (ofs < maxofs) {
1120 IFLT(*(a-ofs), key)
1121 break;
1122 /* key <= a[hint - ofs] */
1123 lastofs = ofs;
1124 ofs = (ofs << 1) + 1;
1125 if (ofs <= 0) /* int overflow */
1126 ofs = maxofs;
1127 }
1128 if (ofs > maxofs)
1129 ofs = maxofs;
1130 /* Translate back to positive offsets relative to &a[0]. */
1131 k = lastofs;
1132 lastofs = hint - ofs;
1133 ofs = hint - k;
1134 }
1135 a -= hint;
1136
1137 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1138 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1139 * right of lastofs but no farther right than ofs. Do a binary
1140 * search, with invariant a[lastofs-1] < key <= a[ofs].
1141 */
1142 ++lastofs;
1143 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001144 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001145
1146 IFLT(a[m], key)
1147 lastofs = m+1; /* a[m] < key */
1148 else
1149 ofs = m; /* key <= a[m] */
1150 }
1151 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1152 return ofs;
1153
1154fail:
1155 return -1;
1156}
1157
1158/*
1159Exactly like gallop_left(), except that if key already exists in a[0:n],
1160finds the position immediately to the right of the rightmost equal value.
1161
1162The return value is the int k in 0..n such that
1163
1164 a[k-1] <= key < a[k]
1165
1166or -1 if error.
1167
1168The code duplication is massive, but this is enough different given that
1169we're sticking to "<" comparisons that it's much harder to follow if
1170written as one routine with yet another "left or right?" flag.
1171*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001172static Py_ssize_t
1173gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
Tim Petersa64dc242002-08-01 02:13:36 +00001174{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001175 Py_ssize_t ofs;
1176 Py_ssize_t lastofs;
1177 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001178
1179 assert(key && a && n > 0 && hint >= 0 && hint < n);
1180
1181 a += hint;
1182 lastofs = 0;
1183 ofs = 1;
1184 IFLT(key, *a) {
1185 /* key < a[hint] -- gallop left, until
1186 * a[hint - ofs] <= key < a[hint - lastofs]
1187 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001188 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001189 while (ofs < maxofs) {
1190 IFLT(key, *(a-ofs)) {
1191 lastofs = ofs;
1192 ofs = (ofs << 1) + 1;
1193 if (ofs <= 0) /* int overflow */
1194 ofs = maxofs;
1195 }
1196 else /* a[hint - ofs] <= key */
1197 break;
1198 }
1199 if (ofs > maxofs)
1200 ofs = maxofs;
1201 /* Translate back to positive offsets relative to &a[0]. */
1202 k = lastofs;
1203 lastofs = hint - ofs;
1204 ofs = hint - k;
1205 }
1206 else {
1207 /* a[hint] <= key -- gallop right, until
1208 * a[hint + lastofs] <= key < a[hint + ofs]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001209 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001210 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001211 while (ofs < maxofs) {
1212 IFLT(key, a[ofs])
1213 break;
1214 /* a[hint + ofs] <= key */
1215 lastofs = ofs;
1216 ofs = (ofs << 1) + 1;
1217 if (ofs <= 0) /* int overflow */
1218 ofs = maxofs;
1219 }
1220 if (ofs > maxofs)
1221 ofs = maxofs;
1222 /* Translate back to offsets relative to &a[0]. */
1223 lastofs += hint;
1224 ofs += hint;
1225 }
1226 a -= hint;
1227
1228 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1229 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1230 * right of lastofs but no farther right than ofs. Do a binary
1231 * search, with invariant a[lastofs-1] <= key < a[ofs].
1232 */
1233 ++lastofs;
1234 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001235 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001236
1237 IFLT(key, a[m])
1238 ofs = m; /* key < a[m] */
1239 else
1240 lastofs = m+1; /* a[m] <= key */
1241 }
1242 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1243 return ofs;
1244
1245fail:
1246 return -1;
1247}
1248
1249/* The maximum number of entries in a MergeState's pending-runs stack.
1250 * This is enough to sort arrays of size up to about
1251 * 32 * phi ** MAX_MERGE_PENDING
1252 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1253 * with 2**64 elements.
1254 */
1255#define MAX_MERGE_PENDING 85
1256
Tim Peterse05f65a2002-08-10 05:21:15 +00001257/* When we get into galloping mode, we stay there until both runs win less
1258 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001259 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001260#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001261
1262/* Avoid malloc for small temp arrays. */
1263#define MERGESTATE_TEMP_SIZE 256
1264
1265/* One MergeState exists on the stack per invocation of mergesort. It's just
1266 * a convenient way to pass state around among the helper functions.
1267 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001268struct s_slice {
1269 PyObject **base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001270 Py_ssize_t len;
Tim Peterse05f65a2002-08-10 05:21:15 +00001271};
1272
Tim Petersa64dc242002-08-01 02:13:36 +00001273typedef struct s_MergeState {
1274 /* The user-supplied comparison function. or NULL if none given. */
1275 PyObject *compare;
1276
Tim Peterse05f65a2002-08-10 05:21:15 +00001277 /* This controls when we get *into* galloping mode. It's initialized
1278 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1279 * random data, and lower for highly structured data.
1280 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001281 Py_ssize_t min_gallop;
Tim Peterse05f65a2002-08-10 05:21:15 +00001282
Tim Petersa64dc242002-08-01 02:13:36 +00001283 /* 'a' is temp storage to help with merges. It contains room for
1284 * alloced entries.
1285 */
1286 PyObject **a; /* may point to temparray below */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001287 Py_ssize_t alloced;
Tim Petersa64dc242002-08-01 02:13:36 +00001288
1289 /* A stack of n pending runs yet to be merged. Run #i starts at
1290 * address base[i] and extends for len[i] elements. It's always
1291 * true (so long as the indices are in bounds) that
1292 *
Tim Peterse05f65a2002-08-10 05:21:15 +00001293 * pending[i].base + pending[i].len == pending[i+1].base
Tim Petersa64dc242002-08-01 02:13:36 +00001294 *
1295 * so we could cut the storage for this, but it's a minor amount,
1296 * and keeping all the info explicit simplifies the code.
1297 */
1298 int n;
Tim Peterse05f65a2002-08-10 05:21:15 +00001299 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001300
1301 /* 'a' points to this when possible, rather than muck with malloc. */
1302 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1303} MergeState;
1304
1305/* Conceptually a MergeState's constructor. */
1306static void
1307merge_init(MergeState *ms, PyObject *compare)
1308{
1309 assert(ms != NULL);
1310 ms->compare = compare;
1311 ms->a = ms->temparray;
1312 ms->alloced = MERGESTATE_TEMP_SIZE;
1313 ms->n = 0;
Tim Peterse05f65a2002-08-10 05:21:15 +00001314 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001315}
1316
1317/* Free all the temp memory owned by the MergeState. This must be called
1318 * when you're done with a MergeState, and may be called before then if
1319 * you want to free the temp memory early.
1320 */
1321static void
1322merge_freemem(MergeState *ms)
1323{
1324 assert(ms != NULL);
1325 if (ms->a != ms->temparray)
1326 PyMem_Free(ms->a);
1327 ms->a = ms->temparray;
1328 ms->alloced = MERGESTATE_TEMP_SIZE;
1329}
1330
1331/* Ensure enough temp memory for 'need' array slots is available.
1332 * Returns 0 on success and -1 if the memory can't be gotten.
1333 */
1334static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001335merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001336{
1337 assert(ms != NULL);
1338 if (need <= ms->alloced)
1339 return 0;
1340 /* Don't realloc! That can cost cycles to copy the old data, but
1341 * we don't care what's in the block.
1342 */
1343 merge_freemem(ms);
1344 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1345 if (ms->a) {
1346 ms->alloced = need;
1347 return 0;
1348 }
1349 PyErr_NoMemory();
1350 merge_freemem(ms); /* reset to sane state */
1351 return -1;
1352}
1353#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1354 merge_getmem(MS, NEED))
1355
1356/* Merge the na elements starting at pa with the nb elements starting at pb
1357 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1358 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1359 * merge, and should have na <= nb. See listsort.txt for more info.
1360 * Return 0 if successful, -1 if error.
1361 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001362static Py_ssize_t
1363merge_lo(MergeState *ms, PyObject **pa, Py_ssize_t na,
1364 PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001365{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001366 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001367 PyObject *compare;
1368 PyObject **dest;
1369 int result = -1; /* guilty until proved innocent */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001370 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001371
1372 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1373 if (MERGE_GETMEM(ms, na) < 0)
1374 return -1;
1375 memcpy(ms->a, pa, na * sizeof(PyObject*));
1376 dest = pa;
1377 pa = ms->a;
1378
1379 *dest++ = *pb++;
1380 --nb;
1381 if (nb == 0)
1382 goto Succeed;
1383 if (na == 1)
1384 goto CopyB;
1385
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001386 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001387 compare = ms->compare;
1388 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001389 Py_ssize_t acount = 0; /* # of times A won in a row */
1390 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001391
1392 /* Do the straightforward thing until (if ever) one run
1393 * appears to win consistently.
1394 */
1395 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001396 assert(na > 1 && nb > 0);
Tim Peters66860f62002-08-04 17:47:26 +00001397 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001398 if (k) {
1399 if (k < 0)
1400 goto Fail;
1401 *dest++ = *pb++;
1402 ++bcount;
1403 acount = 0;
1404 --nb;
1405 if (nb == 0)
1406 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001407 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001408 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001409 }
1410 else {
Tim Petersa64dc242002-08-01 02:13:36 +00001411 *dest++ = *pa++;
1412 ++acount;
1413 bcount = 0;
1414 --na;
1415 if (na == 1)
1416 goto CopyB;
Tim Peterse05f65a2002-08-10 05:21:15 +00001417 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001418 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001419 }
Tim Petersa64dc242002-08-01 02:13:36 +00001420 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001421
Tim Petersa64dc242002-08-01 02:13:36 +00001422 /* One run is winning so consistently that galloping may
1423 * be a huge win. So try that, and continue galloping until
1424 * (if ever) neither run appears to be winning consistently
1425 * anymore.
1426 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001427 ++min_gallop;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001428 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001429 assert(na > 1 && nb > 0);
1430 min_gallop -= min_gallop > 1;
1431 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001432 k = gallop_right(*pb, pa, na, 0, compare);
1433 acount = k;
1434 if (k) {
1435 if (k < 0)
1436 goto Fail;
1437 memcpy(dest, pa, k * sizeof(PyObject *));
1438 dest += k;
1439 pa += k;
1440 na -= k;
1441 if (na == 1)
1442 goto CopyB;
1443 /* na==0 is impossible now if the comparison
1444 * function is consistent, but we can't assume
1445 * that it is.
1446 */
1447 if (na == 0)
1448 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001449 }
Tim Petersa64dc242002-08-01 02:13:36 +00001450 *dest++ = *pb++;
1451 --nb;
1452 if (nb == 0)
1453 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001454
Tim Petersa64dc242002-08-01 02:13:36 +00001455 k = gallop_left(*pa, pb, nb, 0, compare);
1456 bcount = k;
1457 if (k) {
1458 if (k < 0)
1459 goto Fail;
1460 memmove(dest, pb, k * sizeof(PyObject *));
1461 dest += k;
1462 pb += k;
1463 nb -= k;
1464 if (nb == 0)
1465 goto Succeed;
1466 }
1467 *dest++ = *pa++;
1468 --na;
1469 if (na == 1)
1470 goto CopyB;
1471 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001472 ++min_gallop; /* penalize it for leaving galloping mode */
1473 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001474 }
1475Succeed:
1476 result = 0;
1477Fail:
1478 if (na)
1479 memcpy(dest, pa, na * sizeof(PyObject*));
1480 return result;
1481CopyB:
1482 assert(na == 1 && nb > 0);
1483 /* The last element of pa belongs at the end of the merge. */
1484 memmove(dest, pb, nb * sizeof(PyObject *));
1485 dest[nb] = *pa;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001486 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001487}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001488
Tim Petersa64dc242002-08-01 02:13:36 +00001489/* Merge the na elements starting at pa with the nb elements starting at pb
1490 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1491 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1492 * merge, and should have na >= nb. See listsort.txt for more info.
1493 * Return 0 if successful, -1 if error.
1494 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001495static Py_ssize_t
1496merge_hi(MergeState *ms, PyObject **pa, Py_ssize_t na, PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001497{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001498 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001499 PyObject *compare;
1500 PyObject **dest;
1501 int result = -1; /* guilty until proved innocent */
1502 PyObject **basea;
1503 PyObject **baseb;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001504 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001505
1506 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1507 if (MERGE_GETMEM(ms, nb) < 0)
1508 return -1;
1509 dest = pb + nb - 1;
1510 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1511 basea = pa;
1512 baseb = ms->a;
1513 pb = ms->a + nb - 1;
1514 pa += na - 1;
1515
1516 *dest-- = *pa--;
1517 --na;
1518 if (na == 0)
1519 goto Succeed;
1520 if (nb == 1)
1521 goto CopyA;
1522
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001523 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001524 compare = ms->compare;
1525 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001526 Py_ssize_t acount = 0; /* # of times A won in a row */
1527 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001528
1529 /* Do the straightforward thing until (if ever) one run
1530 * appears to win consistently.
1531 */
1532 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001533 assert(na > 0 && nb > 1);
Tim Peters66860f62002-08-04 17:47:26 +00001534 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001535 if (k) {
1536 if (k < 0)
1537 goto Fail;
1538 *dest-- = *pa--;
1539 ++acount;
1540 bcount = 0;
1541 --na;
1542 if (na == 0)
1543 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001544 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001545 break;
1546 }
1547 else {
1548 *dest-- = *pb--;
1549 ++bcount;
1550 acount = 0;
1551 --nb;
1552 if (nb == 1)
1553 goto CopyA;
Tim Peterse05f65a2002-08-10 05:21:15 +00001554 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001555 break;
1556 }
1557 }
1558
1559 /* One run is winning so consistently that galloping may
1560 * be a huge win. So try that, and continue galloping until
1561 * (if ever) neither run appears to be winning consistently
1562 * anymore.
1563 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001564 ++min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001565 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001566 assert(na > 0 && nb > 1);
1567 min_gallop -= min_gallop > 1;
1568 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001569 k = gallop_right(*pb, basea, na, na-1, compare);
1570 if (k < 0)
1571 goto Fail;
1572 k = na - k;
1573 acount = k;
1574 if (k) {
1575 dest -= k;
1576 pa -= k;
1577 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1578 na -= k;
1579 if (na == 0)
1580 goto Succeed;
1581 }
1582 *dest-- = *pb--;
1583 --nb;
1584 if (nb == 1)
1585 goto CopyA;
1586
1587 k = gallop_left(*pa, baseb, nb, nb-1, compare);
1588 if (k < 0)
1589 goto Fail;
1590 k = nb - k;
1591 bcount = k;
1592 if (k) {
1593 dest -= k;
1594 pb -= k;
1595 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1596 nb -= k;
1597 if (nb == 1)
1598 goto CopyA;
1599 /* nb==0 is impossible now if the comparison
1600 * function is consistent, but we can't assume
1601 * that it is.
1602 */
1603 if (nb == 0)
1604 goto Succeed;
1605 }
1606 *dest-- = *pa--;
1607 --na;
1608 if (na == 0)
1609 goto Succeed;
1610 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001611 ++min_gallop; /* penalize it for leaving galloping mode */
1612 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001613 }
1614Succeed:
1615 result = 0;
1616Fail:
1617 if (nb)
1618 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1619 return result;
1620CopyA:
1621 assert(nb == 1 && na > 0);
1622 /* The first element of pb belongs at the front of the merge. */
1623 dest -= na;
1624 pa -= na;
1625 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1626 *dest = *pb;
1627 return 0;
1628}
1629
1630/* Merge the two runs at stack indices i and i+1.
1631 * Returns 0 on success, -1 on error.
1632 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001633static Py_ssize_t
1634merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001635{
1636 PyObject **pa, **pb;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001637 Py_ssize_t na, nb;
1638 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001639 PyObject *compare;
1640
1641 assert(ms != NULL);
1642 assert(ms->n >= 2);
1643 assert(i >= 0);
1644 assert(i == ms->n - 2 || i == ms->n - 3);
1645
Tim Peterse05f65a2002-08-10 05:21:15 +00001646 pa = ms->pending[i].base;
1647 na = ms->pending[i].len;
1648 pb = ms->pending[i+1].base;
1649 nb = ms->pending[i+1].len;
Tim Petersa64dc242002-08-01 02:13:36 +00001650 assert(na > 0 && nb > 0);
1651 assert(pa + na == pb);
1652
1653 /* Record the length of the combined runs; if i is the 3rd-last
1654 * run now, also slide over the last run (which isn't involved
1655 * in this merge). The current run i+1 goes away in any case.
1656 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001657 ms->pending[i].len = na + nb;
1658 if (i == ms->n - 3)
1659 ms->pending[i+1] = ms->pending[i+2];
Tim Petersa64dc242002-08-01 02:13:36 +00001660 --ms->n;
1661
1662 /* Where does b start in a? Elements in a before that can be
1663 * ignored (already in place).
1664 */
1665 compare = ms->compare;
1666 k = gallop_right(*pb, pa, na, 0, compare);
1667 if (k < 0)
1668 return -1;
1669 pa += k;
1670 na -= k;
1671 if (na == 0)
1672 return 0;
1673
1674 /* Where does a end in b? Elements in b after that can be
1675 * ignored (already in place).
1676 */
1677 nb = gallop_left(pa[na-1], pb, nb, nb-1, compare);
1678 if (nb <= 0)
1679 return nb;
1680
1681 /* Merge what remains of the runs, using a temp array with
1682 * min(na, nb) elements.
1683 */
1684 if (na <= nb)
1685 return merge_lo(ms, pa, na, pb, nb);
1686 else
1687 return merge_hi(ms, pa, na, pb, nb);
1688}
1689
1690/* Examine the stack of runs waiting to be merged, merging adjacent runs
1691 * until the stack invariants are re-established:
1692 *
1693 * 1. len[-3] > len[-2] + len[-1]
1694 * 2. len[-2] > len[-1]
1695 *
1696 * See listsort.txt for more info.
1697 *
1698 * Returns 0 on success, -1 on error.
1699 */
1700static int
1701merge_collapse(MergeState *ms)
1702{
Tim Peterse05f65a2002-08-10 05:21:15 +00001703 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001704
1705 assert(ms);
1706 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001707 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001708 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1709 if (p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001710 --n;
1711 if (merge_at(ms, n) < 0)
1712 return -1;
1713 }
Tim Peterse05f65a2002-08-10 05:21:15 +00001714 else if (p[n].len <= p[n+1].len) {
Tim Petersa64dc242002-08-01 02:13:36 +00001715 if (merge_at(ms, n) < 0)
1716 return -1;
1717 }
1718 else
1719 break;
1720 }
1721 return 0;
1722}
1723
1724/* Regardless of invariants, merge all runs on the stack until only one
1725 * remains. This is used at the end of the mergesort.
1726 *
1727 * Returns 0 on success, -1 on error.
1728 */
1729static int
1730merge_force_collapse(MergeState *ms)
1731{
Tim Peterse05f65a2002-08-10 05:21:15 +00001732 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001733
1734 assert(ms);
1735 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001736 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001737 if (n > 0 && p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001738 --n;
1739 if (merge_at(ms, n) < 0)
1740 return -1;
1741 }
1742 return 0;
1743}
1744
1745/* Compute a good value for the minimum run length; natural runs shorter
1746 * than this are boosted artificially via binary insertion.
1747 *
1748 * If n < 64, return n (it's too small to bother with fancy stuff).
1749 * Else if n is an exact power of 2, return 32.
1750 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1751 * strictly less than, an exact power of 2.
1752 *
1753 * See listsort.txt for more info.
1754 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001755static Py_ssize_t
1756merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001757{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001758 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001759
1760 assert(n >= 0);
1761 while (n >= 64) {
1762 r |= n & 1;
1763 n >>= 1;
1764 }
1765 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001766}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001767
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001768/* Special wrapper to support stable sorting using the decorate-sort-undecorate
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001769 pattern. Holds a key which is used for comparisons and the original record
Tim Petersb38e2b62004-07-29 02:29:26 +00001770 which is returned during the undecorate phase. By exposing only the key
1771 during comparisons, the underlying sort stability characteristics are left
1772 unchanged. Also, if a custom comparison function is used, it will only see
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001773 the key instead of a full record. */
1774
1775typedef struct {
1776 PyObject_HEAD
1777 PyObject *key;
1778 PyObject *value;
1779} sortwrapperobject;
1780
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001781PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001782static PyObject *
1783sortwrapper_richcompare(sortwrapperobject *, sortwrapperobject *, int);
1784static void
1785sortwrapper_dealloc(sortwrapperobject *);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001786
1787static PyTypeObject sortwrapper_type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001788 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001789 "sortwrapper", /* tp_name */
1790 sizeof(sortwrapperobject), /* tp_basicsize */
1791 0, /* tp_itemsize */
1792 /* methods */
1793 (destructor)sortwrapper_dealloc, /* tp_dealloc */
1794 0, /* tp_print */
1795 0, /* tp_getattr */
1796 0, /* tp_setattr */
1797 0, /* tp_compare */
1798 0, /* tp_repr */
1799 0, /* tp_as_number */
1800 0, /* tp_as_sequence */
1801 0, /* tp_as_mapping */
1802 0, /* tp_hash */
1803 0, /* tp_call */
1804 0, /* tp_str */
1805 PyObject_GenericGetAttr, /* tp_getattro */
1806 0, /* tp_setattro */
1807 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001808 Py_TPFLAGS_DEFAULT, /* tp_flags */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001809 sortwrapper_doc, /* tp_doc */
1810 0, /* tp_traverse */
1811 0, /* tp_clear */
1812 (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
1813};
1814
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001815
1816static PyObject *
1817sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
1818{
1819 if (!PyObject_TypeCheck(b, &sortwrapper_type)) {
1820 PyErr_SetString(PyExc_TypeError,
1821 "expected a sortwrapperobject");
1822 return NULL;
1823 }
1824 return PyObject_RichCompare(a->key, b->key, op);
1825}
1826
1827static void
1828sortwrapper_dealloc(sortwrapperobject *so)
1829{
1830 Py_XDECREF(so->key);
1831 Py_XDECREF(so->value);
1832 PyObject_Del(so);
1833}
1834
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001835/* Returns a new reference to a sortwrapper.
1836 Consumes the references to the two underlying objects. */
1837
1838static PyObject *
1839build_sortwrapper(PyObject *key, PyObject *value)
1840{
1841 sortwrapperobject *so;
Tim Petersb38e2b62004-07-29 02:29:26 +00001842
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001843 so = PyObject_New(sortwrapperobject, &sortwrapper_type);
1844 if (so == NULL)
1845 return NULL;
1846 so->key = key;
1847 so->value = value;
1848 return (PyObject *)so;
1849}
1850
1851/* Returns a new reference to the value underlying the wrapper. */
1852static PyObject *
1853sortwrapper_getvalue(PyObject *so)
1854{
1855 PyObject *value;
1856
1857 if (!PyObject_TypeCheck(so, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001858 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001859 "expected a sortwrapperobject");
1860 return NULL;
1861 }
1862 value = ((sortwrapperobject *)so)->value;
1863 Py_INCREF(value);
1864 return value;
1865}
1866
1867/* Wrapper for user specified cmp functions in combination with a
1868 specified key function. Makes sure the cmp function is presented
1869 with the actual key instead of the sortwrapper */
1870
1871typedef struct {
1872 PyObject_HEAD
1873 PyObject *func;
1874} cmpwrapperobject;
1875
1876static void
1877cmpwrapper_dealloc(cmpwrapperobject *co)
1878{
1879 Py_XDECREF(co->func);
1880 PyObject_Del(co);
1881}
1882
1883static PyObject *
1884cmpwrapper_call(cmpwrapperobject *co, PyObject *args, PyObject *kwds)
1885{
1886 PyObject *x, *y, *xx, *yy;
1887
1888 if (!PyArg_UnpackTuple(args, "", 2, 2, &x, &y))
1889 return NULL;
1890 if (!PyObject_TypeCheck(x, &sortwrapper_type) ||
Raymond Hettingerae4a2992003-10-16 17:16:30 +00001891 !PyObject_TypeCheck(y, &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 xx = ((sortwrapperobject *)x)->key;
1897 yy = ((sortwrapperobject *)y)->key;
1898 return PyObject_CallFunctionObjArgs(co->func, xx, yy, NULL);
1899}
1900
1901PyDoc_STRVAR(cmpwrapper_doc, "cmp() wrapper for sort with custom keys.");
1902
1903static PyTypeObject cmpwrapper_type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001904 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001905 "cmpwrapper", /* tp_name */
1906 sizeof(cmpwrapperobject), /* tp_basicsize */
1907 0, /* tp_itemsize */
1908 /* methods */
1909 (destructor)cmpwrapper_dealloc, /* tp_dealloc */
1910 0, /* tp_print */
1911 0, /* tp_getattr */
1912 0, /* tp_setattr */
1913 0, /* tp_compare */
1914 0, /* tp_repr */
1915 0, /* tp_as_number */
1916 0, /* tp_as_sequence */
1917 0, /* tp_as_mapping */
1918 0, /* tp_hash */
1919 (ternaryfunc)cmpwrapper_call, /* tp_call */
1920 0, /* tp_str */
1921 PyObject_GenericGetAttr, /* tp_getattro */
1922 0, /* tp_setattro */
1923 0, /* tp_as_buffer */
1924 Py_TPFLAGS_DEFAULT, /* tp_flags */
1925 cmpwrapper_doc, /* tp_doc */
1926};
1927
1928static PyObject *
1929build_cmpwrapper(PyObject *cmpfunc)
1930{
1931 cmpwrapperobject *co;
Tim Petersb38e2b62004-07-29 02:29:26 +00001932
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001933 co = PyObject_New(cmpwrapperobject, &cmpwrapper_type);
1934 if (co == NULL)
1935 return NULL;
1936 Py_INCREF(cmpfunc);
1937 co->func = cmpfunc;
1938 return (PyObject *)co;
1939}
1940
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001941static int
1942is_default_cmp(PyObject *cmpfunc)
1943{
1944 PyCFunctionObject *f;
1945 if (cmpfunc == NULL || cmpfunc == Py_None)
1946 return 1;
1947 if (!PyCFunction_Check(cmpfunc))
1948 return 0;
Guido van Rossumf1624cd2006-08-24 23:43:52 +00001949 f = (PyCFunctionObject *)cmpfunc;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001950 if (f->m_self != NULL)
1951 return 0;
1952 if (!PyString_Check(f->m_module))
1953 return 0;
1954 if (strcmp(PyString_AS_STRING(f->m_module), "__builtin__") != 0)
1955 return 0;
1956 if (strcmp(f->m_ml->ml_name, "cmp") != 0)
1957 return 0;
1958 return 1;
1959}
1960
Tim Petersa64dc242002-08-01 02:13:36 +00001961/* An adaptive, stable, natural mergesort. See listsort.txt.
1962 * Returns Py_None on success, NULL on error. Even in case of error, the
1963 * list will be some permutation of its input state (nothing is lost or
1964 * duplicated).
1965 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001966static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001967listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001968{
Tim Petersa64dc242002-08-01 02:13:36 +00001969 MergeState ms;
1970 PyObject **lo, **hi;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001971 Py_ssize_t nremaining;
1972 Py_ssize_t minrun;
1973 Py_ssize_t saved_ob_size, saved_allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00001974 PyObject **saved_ob_item;
Armin Rigo93677f02004-07-29 12:40:23 +00001975 PyObject **final_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001976 PyObject *compare = NULL;
1977 PyObject *result = NULL; /* guilty until proved innocent */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001978 int reverse = 0;
1979 PyObject *keyfunc = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001980 Py_ssize_t i;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001981 PyObject *key, *value, *kvpair;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001982 static char *kwlist[] = {"cmp", "key", "reverse", 0};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001983
Tim Petersa64dc242002-08-01 02:13:36 +00001984 assert(self != NULL);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001985 assert (PyList_Check(self));
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001986 if (args != NULL) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001987 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:sort",
1988 kwlist, &compare, &keyfunc, &reverse))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001989 return NULL;
1990 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001991 if (is_default_cmp(compare))
Skip Montanaro4abd5f02003-01-02 20:51:08 +00001992 compare = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001993 if (keyfunc == Py_None)
1994 keyfunc = NULL;
1995 if (compare != NULL && keyfunc != NULL) {
1996 compare = build_cmpwrapper(compare);
1997 if (compare == NULL)
Hye-Shik Chang19cb1932003-12-10 07:31:08 +00001998 return NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001999 } else
2000 Py_XINCREF(compare);
2001
Tim Petersb9099c32002-11-12 22:08:10 +00002002 /* The list is temporarily made empty, so that mutations performed
2003 * by comparison functions can't affect the slice of memory we're
2004 * sorting (allowing mutations during sorting is a core-dump
2005 * factory, since ob_item may change).
2006 */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002007 saved_ob_size = Py_Size(self);
Tim Petersb9099c32002-11-12 22:08:10 +00002008 saved_ob_item = self->ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002009 saved_allocated = self->allocated;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002010 Py_Size(self) = 0;
Tim Peters51b4ade2004-07-29 04:07:15 +00002011 self->ob_item = NULL;
Armin Rigo93677f02004-07-29 12:40:23 +00002012 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00002013
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002014 if (keyfunc != NULL) {
2015 for (i=0 ; i < saved_ob_size ; i++) {
2016 value = saved_ob_item[i];
Tim Petersb38e2b62004-07-29 02:29:26 +00002017 key = PyObject_CallFunctionObjArgs(keyfunc, value,
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002018 NULL);
2019 if (key == NULL) {
2020 for (i=i-1 ; i>=0 ; i--) {
2021 kvpair = saved_ob_item[i];
2022 value = sortwrapper_getvalue(kvpair);
2023 saved_ob_item[i] = value;
2024 Py_DECREF(kvpair);
2025 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002026 goto dsu_fail;
2027 }
2028 kvpair = build_sortwrapper(key, value);
2029 if (kvpair == NULL)
2030 goto dsu_fail;
2031 saved_ob_item[i] = kvpair;
2032 }
2033 }
2034
2035 /* Reverse sort stability achieved by initially reversing the list,
2036 applying a stable forward sort, then reversing the final result. */
2037 if (reverse && saved_ob_size > 1)
2038 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2039
2040 merge_init(&ms, compare);
2041
Tim Petersb9099c32002-11-12 22:08:10 +00002042 nremaining = saved_ob_size;
Tim Petersa64dc242002-08-01 02:13:36 +00002043 if (nremaining < 2)
2044 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00002045
Tim Petersa64dc242002-08-01 02:13:36 +00002046 /* March over the array once, left to right, finding natural runs,
2047 * and extending short natural runs to minrun elements.
2048 */
Tim Petersb9099c32002-11-12 22:08:10 +00002049 lo = saved_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00002050 hi = lo + nremaining;
2051 minrun = merge_compute_minrun(nremaining);
2052 do {
2053 int descending;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002054 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00002055
Tim Petersa64dc242002-08-01 02:13:36 +00002056 /* Identify next run. */
2057 n = count_run(lo, hi, compare, &descending);
2058 if (n < 0)
2059 goto fail;
2060 if (descending)
2061 reverse_slice(lo, lo + n);
2062 /* If short, extend to min(minrun, nremaining). */
2063 if (n < minrun) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002064 const Py_ssize_t force = nremaining <= minrun ?
Tim Petersa64dc242002-08-01 02:13:36 +00002065 nremaining : minrun;
2066 if (binarysort(lo, lo + force, lo + n, compare) < 0)
2067 goto fail;
2068 n = force;
2069 }
2070 /* Push run onto pending-runs stack, and maybe merge. */
2071 assert(ms.n < MAX_MERGE_PENDING);
Tim Peterse05f65a2002-08-10 05:21:15 +00002072 ms.pending[ms.n].base = lo;
2073 ms.pending[ms.n].len = n;
Tim Petersa64dc242002-08-01 02:13:36 +00002074 ++ms.n;
2075 if (merge_collapse(&ms) < 0)
2076 goto fail;
2077 /* Advance to find next run. */
2078 lo += n;
2079 nremaining -= n;
2080 } while (nremaining);
2081 assert(lo == hi);
Tim Peters330f9e92002-07-19 07:05:44 +00002082
Tim Petersa64dc242002-08-01 02:13:36 +00002083 if (merge_force_collapse(&ms) < 0)
2084 goto fail;
2085 assert(ms.n == 1);
Tim Petersb9099c32002-11-12 22:08:10 +00002086 assert(ms.pending[0].base == saved_ob_item);
2087 assert(ms.pending[0].len == saved_ob_size);
Tim Petersa64dc242002-08-01 02:13:36 +00002088
2089succeed:
2090 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002091fail:
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002092 if (keyfunc != NULL) {
2093 for (i=0 ; i < saved_ob_size ; i++) {
2094 kvpair = saved_ob_item[i];
2095 value = sortwrapper_getvalue(kvpair);
2096 saved_ob_item[i] = value;
2097 Py_DECREF(kvpair);
2098 }
2099 }
2100
Armin Rigo93677f02004-07-29 12:40:23 +00002101 if (self->allocated != -1 && result != NULL) {
Tim Peters51b4ade2004-07-29 04:07:15 +00002102 /* The user mucked with the list during the sort,
2103 * and we don't already have another error to report.
2104 */
2105 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2106 result = NULL;
Tim Petersb9099c32002-11-12 22:08:10 +00002107 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002108
2109 if (reverse && saved_ob_size > 1)
2110 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2111
2112 merge_freemem(&ms);
2113
2114dsu_fail:
Armin Rigo93677f02004-07-29 12:40:23 +00002115 final_ob_item = self->ob_item;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002116 i = Py_Size(self);
2117 Py_Size(self) = saved_ob_size;
Tim Petersb9099c32002-11-12 22:08:10 +00002118 self->ob_item = saved_ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002119 self->allocated = saved_allocated;
Armin Rigo93677f02004-07-29 12:40:23 +00002120 if (final_ob_item != NULL) {
2121 /* we cannot use list_clear() for this because it does not
2122 guarantee that the list is really empty when it returns */
2123 while (--i >= 0) {
2124 Py_XDECREF(final_ob_item[i]);
2125 }
2126 PyMem_FREE(final_ob_item);
2127 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002128 Py_XDECREF(compare);
Tim Petersa64dc242002-08-01 02:13:36 +00002129 Py_XINCREF(result);
2130 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002131}
Tim Peters330f9e92002-07-19 07:05:44 +00002132#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002133#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002134
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002135int
Fred Drakea2f55112000-07-09 15:16:51 +00002136PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002137{
2138 if (v == NULL || !PyList_Check(v)) {
2139 PyErr_BadInternalCall();
2140 return -1;
2141 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002142 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002143 if (v == NULL)
2144 return -1;
2145 Py_DECREF(v);
2146 return 0;
2147}
2148
Guido van Rossumb86c5492001-02-12 22:06:02 +00002149static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002150listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002151{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002152 if (Py_Size(self) > 1)
2153 reverse_slice(self->ob_item, self->ob_item + Py_Size(self));
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002154 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002155}
2156
Guido van Rossum84c76f51990-10-30 13:32:20 +00002157int
Fred Drakea2f55112000-07-09 15:16:51 +00002158PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002159{
Tim Peters6063e262002-08-08 01:06:39 +00002160 PyListObject *self = (PyListObject *)v;
2161
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002162 if (v == NULL || !PyList_Check(v)) {
2163 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002164 return -1;
2165 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002166 if (Py_Size(self) > 1)
2167 reverse_slice(self->ob_item, self->ob_item + Py_Size(self));
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002168 return 0;
2169}
2170
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002171PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002172PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002173{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002174 PyObject *w;
2175 PyObject **p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002176 Py_ssize_t n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002177 if (v == NULL || !PyList_Check(v)) {
2178 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002179 return NULL;
2180 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002181 n = Py_Size(v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002182 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002183 if (w == NULL)
2184 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002185 p = ((PyTupleObject *)w)->ob_item;
Thomas Wouters334fb892000-07-25 12:56:38 +00002186 memcpy((void *)p,
2187 (void *)((PyListObject *)v)->ob_item,
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002188 n*sizeof(PyObject *));
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002189 while (--n >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002190 Py_INCREF(*p);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002191 p++;
2192 }
2193 return w;
2194}
2195
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002196static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002197listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002198{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002199 Py_ssize_t i, start=0, stop=Py_Size(self);
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002200 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002201
Walter Dörwalde8049bef2003-06-17 19:27:39 +00002202 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2203 _PyEval_SliceIndex, &start,
2204 _PyEval_SliceIndex, &stop))
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002205 return NULL;
Guido van Rossum2743d872003-06-17 14:25:14 +00002206 if (start < 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002207 start += Py_Size(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002208 if (start < 0)
2209 start = 0;
2210 }
2211 if (stop < 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002212 stop += Py_Size(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002213 if (stop < 0)
2214 stop = 0;
2215 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002216 for (i = start; i < stop && i < Py_Size(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002217 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2218 if (cmp > 0)
Martin v. Löwis18e16552006-02-15 17:27:45 +00002219 return PyInt_FromSsize_t(i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002220 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002221 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002222 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002223 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002224 return NULL;
2225}
2226
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002227static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002228listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002229{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002230 Py_ssize_t count = 0;
2231 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002232
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002233 for (i = 0; i < Py_Size(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002234 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2235 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002236 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002237 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002238 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00002239 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002240 return PyInt_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002241}
2242
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002243static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002244listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002245{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002246 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002247
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002248 for (i = 0; i < Py_Size(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002249 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2250 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002251 if (list_ass_slice(self, i, i+1,
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002252 (PyObject *)NULL) == 0)
2253 Py_RETURN_NONE;
2254 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002255 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002256 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002257 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002258 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002259 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002260 return NULL;
2261}
2262
Jeremy Hylton8caad492000-06-23 14:18:11 +00002263static int
2264list_traverse(PyListObject *o, visitproc visit, void *arg)
2265{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002266 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002267
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002268 for (i = Py_Size(o); --i >= 0; )
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002269 Py_VISIT(o->ob_item[i]);
Jeremy Hylton8caad492000-06-23 14:18:11 +00002270 return 0;
2271}
2272
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002273static PyObject *
2274list_richcompare(PyObject *v, PyObject *w, int op)
2275{
2276 PyListObject *vl, *wl;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002277 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002278
2279 if (!PyList_Check(v) || !PyList_Check(w)) {
2280 Py_INCREF(Py_NotImplemented);
2281 return Py_NotImplemented;
2282 }
2283
2284 vl = (PyListObject *)v;
2285 wl = (PyListObject *)w;
2286
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002287 if (Py_Size(vl) != Py_Size(wl) && (op == Py_EQ || op == Py_NE)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002288 /* Shortcut: if the lengths differ, the lists differ */
2289 PyObject *res;
2290 if (op == Py_EQ)
2291 res = Py_False;
2292 else
2293 res = Py_True;
2294 Py_INCREF(res);
2295 return res;
2296 }
2297
2298 /* Search for the first index where items are different */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002299 for (i = 0; i < Py_Size(vl) && i < Py_Size(wl); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002300 int k = PyObject_RichCompareBool(vl->ob_item[i],
2301 wl->ob_item[i], Py_EQ);
2302 if (k < 0)
2303 return NULL;
2304 if (!k)
2305 break;
2306 }
2307
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002308 if (i >= Py_Size(vl) || i >= Py_Size(wl)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002309 /* No more items to compare -- compare sizes */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002310 Py_ssize_t vs = Py_Size(vl);
2311 Py_ssize_t ws = Py_Size(wl);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002312 int cmp;
2313 PyObject *res;
2314 switch (op) {
2315 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00002316 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002317 case Py_EQ: cmp = vs == ws; break;
2318 case Py_NE: cmp = vs != ws; break;
2319 case Py_GT: cmp = vs > ws; break;
2320 case Py_GE: cmp = vs >= ws; break;
2321 default: return NULL; /* cannot happen */
2322 }
2323 if (cmp)
2324 res = Py_True;
2325 else
2326 res = Py_False;
2327 Py_INCREF(res);
2328 return res;
2329 }
2330
2331 /* We have an item that differs -- shortcuts for EQ/NE */
2332 if (op == Py_EQ) {
2333 Py_INCREF(Py_False);
2334 return Py_False;
2335 }
2336 if (op == Py_NE) {
2337 Py_INCREF(Py_True);
2338 return Py_True;
2339 }
2340
2341 /* Compare the final item again using the proper operator */
2342 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
2343}
2344
Tim Peters6d6c1a32001-08-02 04:15:00 +00002345static int
2346list_init(PyListObject *self, PyObject *args, PyObject *kw)
2347{
2348 PyObject *arg = NULL;
Martin v. Löwis15e62742006-02-27 16:46:16 +00002349 static char *kwlist[] = {"sequence", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002350
2351 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2352 return -1;
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002353
2354 /* Verify list invariants established by PyType_GenericAlloc() */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002355 assert(0 <= Py_Size(self));
2356 assert(Py_Size(self) <= self->allocated || self->allocated == -1);
Armin Rigoa37bbf22004-07-30 11:20:18 +00002357 assert(self->ob_item != NULL ||
2358 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002359
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002360 /* Empty previous contents */
Armin Rigo93677f02004-07-29 12:40:23 +00002361 if (self->ob_item != NULL) {
2362 (void)list_clear(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002363 }
2364 if (arg != NULL) {
2365 PyObject *rv = listextend(self, arg);
2366 if (rv == NULL)
2367 return -1;
2368 Py_DECREF(rv);
2369 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002370 return 0;
2371}
2372
Raymond Hettinger1021c442003-11-07 15:38:09 +00002373static PyObject *list_iter(PyObject *seq);
2374static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2375
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002376PyDoc_STRVAR(getitem_doc,
2377"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002378PyDoc_STRVAR(reversed_doc,
2379"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002380PyDoc_STRVAR(append_doc,
2381"L.append(object) -- append object to end");
2382PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002383"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002384PyDoc_STRVAR(insert_doc,
2385"L.insert(index, object) -- insert object before index");
2386PyDoc_STRVAR(pop_doc,
2387"L.pop([index]) -> item -- remove and return item at index (default last)");
2388PyDoc_STRVAR(remove_doc,
2389"L.remove(value) -- remove first occurrence of value");
2390PyDoc_STRVAR(index_doc,
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002391"L.index(value, [start, [stop]]) -> integer -- return first index of value");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002392PyDoc_STRVAR(count_doc,
2393"L.count(value) -> integer -- return number of occurrences of value");
2394PyDoc_STRVAR(reverse_doc,
2395"L.reverse() -- reverse *IN PLACE*");
2396PyDoc_STRVAR(sort_doc,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002397"L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n\
2398cmp(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002399
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002400static PyObject *list_subscript(PyListObject*, PyObject*);
2401
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002402static PyMethodDef list_methods[] = {
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002403 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
Raymond Hettinger1021c442003-11-07 15:38:09 +00002404 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002405 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002406 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002407 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002408 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002409 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002410 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002411 {"count", (PyCFunction)listcount, METH_O, count_doc},
2412 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002413 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
Tim Petersa64dc242002-08-01 02:13:36 +00002414 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002415};
2416
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002417static PySequenceMethods list_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002418 (lenfunc)list_length, /* sq_length */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002419 (binaryfunc)list_concat, /* sq_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002420 (ssizeargfunc)list_repeat, /* sq_repeat */
2421 (ssizeargfunc)list_item, /* sq_item */
2422 (ssizessizeargfunc)list_slice, /* sq_slice */
2423 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
2424 (ssizessizeobjargproc)list_ass_slice, /* sq_ass_slice */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002425 (objobjproc)list_contains, /* sq_contains */
2426 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002427 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002428};
2429
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002430PyDoc_STRVAR(list_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002431"list() -> new list\n"
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002432"list(sequence) -> new list initialized from sequence's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002433
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002434static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002435list_subscript(PyListObject* self, PyObject* item)
2436{
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002437 if (PyIndex_Check(item)) {
2438 Py_ssize_t i;
2439 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002440 if (i == -1 && PyErr_Occurred())
2441 return NULL;
2442 if (i < 0)
2443 i += PyList_GET_SIZE(self);
2444 return list_item(self, i);
2445 }
2446 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002447 Py_ssize_t start, stop, step, slicelength, cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002448 PyObject* result;
2449 PyObject* it;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002450 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002451
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002452 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_Size(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002453 &start, &stop, &step, &slicelength) < 0) {
2454 return NULL;
2455 }
2456
2457 if (slicelength <= 0) {
2458 return PyList_New(0);
2459 }
2460 else {
2461 result = PyList_New(slicelength);
2462 if (!result) return NULL;
2463
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002464 src = self->ob_item;
2465 dest = ((PyListObject *)result)->ob_item;
Tim Peters3b01a122002-07-19 02:35:45 +00002466 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002467 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002468 it = src[cur];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002469 Py_INCREF(it);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002470 dest[i] = it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002471 }
Tim Peters3b01a122002-07-19 02:35:45 +00002472
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002473 return result;
2474 }
2475 }
2476 else {
Thomas Wouters89f507f2006-12-13 04:49:30 +00002477 PyErr_Format(PyExc_TypeError,
2478 "list indices must be integers, not %.200s",
2479 item->ob_type->tp_name);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002480 return NULL;
2481 }
2482}
2483
Tim Peters3b01a122002-07-19 02:35:45 +00002484static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002485list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2486{
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002487 if (PyIndex_Check(item)) {
2488 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002489 if (i == -1 && PyErr_Occurred())
2490 return -1;
2491 if (i < 0)
2492 i += PyList_GET_SIZE(self);
2493 return list_ass_item(self, i, value);
2494 }
2495 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002496 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002497
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002498 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_Size(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002499 &start, &stop, &step, &slicelength) < 0) {
2500 return -1;
2501 }
2502
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002503 /* treat L[slice(a,b)] = v _exactly_ like L[a:b] = v */
2504 if (step == 1 && ((PySliceObject*)item)->step == Py_None)
2505 return list_ass_slice(self, start, stop, value);
2506
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002507 if (value == NULL) {
2508 /* delete slice */
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002509 PyObject **garbage;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002510 Py_ssize_t cur, i;
Tim Peters3b01a122002-07-19 02:35:45 +00002511
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002512 if (slicelength <= 0)
2513 return 0;
2514
2515 if (step < 0) {
2516 stop = start + 1;
2517 start = stop + step*(slicelength - 1) - 1;
2518 step = -step;
2519 }
2520
2521 garbage = (PyObject**)
2522 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002523 if (!garbage) {
2524 PyErr_NoMemory();
2525 return -1;
2526 }
Tim Peters3b01a122002-07-19 02:35:45 +00002527
2528 /* drawing pictures might help
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002529 understand these for loops */
Guido van Rossum75a20b12002-06-11 12:22:28 +00002530 for (cur = start, i = 0;
2531 cur < stop;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002532 cur += step, i++) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002533 Py_ssize_t lim = step;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002534
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002535 garbage[i] = PyList_GET_ITEM(self, cur);
2536
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002537 if (cur + step >= Py_Size(self)) {
2538 lim = Py_Size(self) - cur - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002539 }
2540
Tim Petersb38e2b62004-07-29 02:29:26 +00002541 memmove(self->ob_item + cur - i,
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002542 self->ob_item + cur + 1,
2543 lim * sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002544 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002545
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002546 for (cur = start + slicelength*step + 1;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002547 cur < Py_Size(self); cur++) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002548 PyList_SET_ITEM(self, cur - slicelength,
2549 PyList_GET_ITEM(self, cur));
2550 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002551
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002552 Py_Size(self) -= slicelength;
2553 list_resize(self, Py_Size(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002554
2555 for (i = 0; i < slicelength; i++) {
2556 Py_DECREF(garbage[i]);
2557 }
2558 PyMem_FREE(garbage);
2559
2560 return 0;
2561 }
2562 else {
2563 /* assign slice */
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002564 PyObject **garbage, *ins, *seq, **seqitems, **selfitems;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002565 Py_ssize_t cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002566
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002567 /* protect against a[::-1] = a */
Tim Peters3b01a122002-07-19 02:35:45 +00002568 if (self == (PyListObject*)value) {
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002569 seq = list_slice((PyListObject*)value, 0,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002570 PyList_GET_SIZE(value));
Tim Peters3b01a122002-07-19 02:35:45 +00002571 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002572 else {
Tim Petersb38e2b62004-07-29 02:29:26 +00002573 seq = PySequence_Fast(value,
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002574 "must assign iterable to extended slice");
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002575 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002576 if (!seq)
2577 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002578
2579 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2580 PyErr_Format(PyExc_ValueError,
Martin v. Löwis2c95cc62006-02-16 06:54:25 +00002581 "attempt to assign sequence of size %zd to extended slice of size %zd",
Martin v. Löwise0e89f72006-02-16 06:59:22 +00002582 PySequence_Fast_GET_SIZE(seq),
2583 slicelength);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002584 Py_DECREF(seq);
2585 return -1;
2586 }
2587
2588 if (!slicelength) {
2589 Py_DECREF(seq);
2590 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002591 }
2592
2593 garbage = (PyObject**)
2594 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Thomas Wouters89f507f2006-12-13 04:49:30 +00002595 if (!garbage) {
2596 Py_DECREF(seq);
2597 PyErr_NoMemory();
2598 return -1;
2599 }
Tim Peters3b01a122002-07-19 02:35:45 +00002600
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002601 selfitems = self->ob_item;
Raymond Hettinger42bec932004-03-12 16:38:17 +00002602 seqitems = PySequence_Fast_ITEMS(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002603 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002604 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002605 garbage[i] = selfitems[cur];
2606 ins = seqitems[i];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002607 Py_INCREF(ins);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002608 selfitems[cur] = ins;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002609 }
2610
2611 for (i = 0; i < slicelength; i++) {
2612 Py_DECREF(garbage[i]);
2613 }
Tim Peters3b01a122002-07-19 02:35:45 +00002614
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002615 PyMem_FREE(garbage);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002616 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002617
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002618 return 0;
2619 }
Tim Peters3b01a122002-07-19 02:35:45 +00002620 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002621 else {
Thomas Wouters89f507f2006-12-13 04:49:30 +00002622 PyErr_Format(PyExc_TypeError,
2623 "list indices must be integers, not %.200s",
2624 item->ob_type->tp_name);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002625 return -1;
2626 }
2627}
2628
2629static PyMappingMethods list_as_mapping = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002630 (lenfunc)list_length,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002631 (binaryfunc)list_subscript,
2632 (objobjargproc)list_ass_subscript
2633};
2634
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002635PyTypeObject PyList_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002636 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002637 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002638 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002639 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002640 (destructor)list_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00002641 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002642 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002643 0, /* tp_setattr */
2644 0, /* tp_compare */
2645 (reprfunc)list_repr, /* tp_repr */
2646 0, /* tp_as_number */
2647 &list_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002648 &list_as_mapping, /* tp_as_mapping */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00002649 0, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002650 0, /* tp_call */
2651 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002652 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002653 0, /* tp_setattro */
2654 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002655 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Thomas Wouters27d517b2007-02-25 20:39:11 +00002656 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002657 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002658 (traverseproc)list_traverse, /* tp_traverse */
2659 (inquiry)list_clear, /* tp_clear */
2660 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002661 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002662 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002663 0, /* tp_iternext */
2664 list_methods, /* tp_methods */
2665 0, /* tp_members */
2666 0, /* tp_getset */
2667 0, /* tp_base */
2668 0, /* tp_dict */
2669 0, /* tp_descr_get */
2670 0, /* tp_descr_set */
2671 0, /* tp_dictoffset */
2672 (initproc)list_init, /* tp_init */
2673 PyType_GenericAlloc, /* tp_alloc */
2674 PyType_GenericNew, /* tp_new */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002675 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002676};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002677
2678
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002679/*********************** List Iterator **************************/
2680
2681typedef struct {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002682 PyObject_HEAD
2683 long it_index;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002684 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002685} listiterobject;
2686
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002687static PyObject *list_iter(PyObject *);
2688static void listiter_dealloc(listiterobject *);
2689static int listiter_traverse(listiterobject *, visitproc, void *);
2690static PyObject *listiter_next(listiterobject *);
2691static PyObject *listiter_len(listiterobject *);
Raymond Hettinger435bf582004-03-18 22:43:10 +00002692
Armin Rigof5b3e362006-02-11 21:32:43 +00002693PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002694
2695static PyMethodDef listiter_methods[] = {
Armin Rigof5b3e362006-02-11 21:32:43 +00002696 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002697 {NULL, NULL} /* sentinel */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002698};
2699
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002700PyTypeObject PyListIter_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002701 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002702 "listiterator", /* tp_name */
2703 sizeof(listiterobject), /* tp_basicsize */
2704 0, /* tp_itemsize */
2705 /* methods */
2706 (destructor)listiter_dealloc, /* tp_dealloc */
2707 0, /* tp_print */
2708 0, /* tp_getattr */
2709 0, /* tp_setattr */
2710 0, /* tp_compare */
2711 0, /* tp_repr */
2712 0, /* tp_as_number */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002713 0, /* tp_as_sequence */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002714 0, /* tp_as_mapping */
2715 0, /* tp_hash */
2716 0, /* tp_call */
2717 0, /* tp_str */
2718 PyObject_GenericGetAttr, /* tp_getattro */
2719 0, /* tp_setattro */
2720 0, /* tp_as_buffer */
2721 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2722 0, /* tp_doc */
2723 (traverseproc)listiter_traverse, /* tp_traverse */
2724 0, /* tp_clear */
2725 0, /* tp_richcompare */
2726 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00002727 PyObject_SelfIter, /* tp_iter */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002728 (iternextfunc)listiter_next, /* tp_iternext */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002729 listiter_methods, /* tp_methods */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002730 0, /* tp_members */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002731};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002732
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002733
2734static PyObject *
2735list_iter(PyObject *seq)
2736{
2737 listiterobject *it;
2738
2739 if (!PyList_Check(seq)) {
2740 PyErr_BadInternalCall();
2741 return NULL;
2742 }
2743 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2744 if (it == NULL)
2745 return NULL;
2746 it->it_index = 0;
2747 Py_INCREF(seq);
2748 it->it_seq = (PyListObject *)seq;
2749 _PyObject_GC_TRACK(it);
2750 return (PyObject *)it;
2751}
2752
2753static void
2754listiter_dealloc(listiterobject *it)
2755{
2756 _PyObject_GC_UNTRACK(it);
2757 Py_XDECREF(it->it_seq);
2758 PyObject_GC_Del(it);
2759}
2760
2761static int
2762listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2763{
2764 Py_VISIT(it->it_seq);
2765 return 0;
2766}
2767
2768static PyObject *
2769listiter_next(listiterobject *it)
2770{
2771 PyListObject *seq;
2772 PyObject *item;
2773
2774 assert(it != NULL);
2775 seq = it->it_seq;
2776 if (seq == NULL)
2777 return NULL;
2778 assert(PyList_Check(seq));
2779
2780 if (it->it_index < PyList_GET_SIZE(seq)) {
2781 item = PyList_GET_ITEM(seq, it->it_index);
2782 ++it->it_index;
2783 Py_INCREF(item);
2784 return item;
2785 }
2786
2787 Py_DECREF(seq);
2788 it->it_seq = NULL;
2789 return NULL;
2790}
2791
2792static PyObject *
2793listiter_len(listiterobject *it)
2794{
2795 Py_ssize_t len;
2796 if (it->it_seq) {
2797 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2798 if (len >= 0)
2799 return PyInt_FromSsize_t(len);
2800 }
2801 return PyInt_FromLong(0);
2802}
Raymond Hettinger1021c442003-11-07 15:38:09 +00002803/*********************** List Reverse Iterator **************************/
2804
2805typedef struct {
2806 PyObject_HEAD
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002807 Py_ssize_t it_index;
Raymond Hettinger001f2282003-11-08 11:58:44 +00002808 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002809} listreviterobject;
2810
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002811static PyObject *list_reversed(PyListObject *, PyObject *);
2812static void listreviter_dealloc(listreviterobject *);
2813static int listreviter_traverse(listreviterobject *, visitproc, void *);
2814static PyObject *listreviter_next(listreviterobject *);
2815static Py_ssize_t listreviter_len(listreviterobject *);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002816
2817static PySequenceMethods listreviter_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002818 (lenfunc)listreviter_len, /* sq_length */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002819 0, /* sq_concat */
2820};
2821
Raymond Hettinger1021c442003-11-07 15:38:09 +00002822PyTypeObject PyListRevIter_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002823 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Raymond Hettinger1021c442003-11-07 15:38:09 +00002824 "listreverseiterator", /* tp_name */
2825 sizeof(listreviterobject), /* tp_basicsize */
2826 0, /* tp_itemsize */
2827 /* methods */
2828 (destructor)listreviter_dealloc, /* tp_dealloc */
2829 0, /* tp_print */
2830 0, /* tp_getattr */
2831 0, /* tp_setattr */
2832 0, /* tp_compare */
2833 0, /* tp_repr */
2834 0, /* tp_as_number */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002835 &listreviter_as_sequence, /* tp_as_sequence */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002836 0, /* tp_as_mapping */
2837 0, /* tp_hash */
2838 0, /* tp_call */
2839 0, /* tp_str */
2840 PyObject_GenericGetAttr, /* tp_getattro */
2841 0, /* tp_setattro */
2842 0, /* tp_as_buffer */
2843 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2844 0, /* tp_doc */
2845 (traverseproc)listreviter_traverse, /* tp_traverse */
2846 0, /* tp_clear */
2847 0, /* tp_richcompare */
2848 0, /* tp_weaklistoffset */
2849 PyObject_SelfIter, /* tp_iter */
2850 (iternextfunc)listreviter_next, /* tp_iternext */
2851 0,
2852};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002853
2854static PyObject *
2855list_reversed(PyListObject *seq, PyObject *unused)
2856{
2857 listreviterobject *it;
2858
2859 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2860 if (it == NULL)
2861 return NULL;
2862 assert(PyList_Check(seq));
2863 it->it_index = PyList_GET_SIZE(seq) - 1;
2864 Py_INCREF(seq);
2865 it->it_seq = seq;
2866 PyObject_GC_Track(it);
2867 return (PyObject *)it;
2868}
2869
2870static void
2871listreviter_dealloc(listreviterobject *it)
2872{
2873 PyObject_GC_UnTrack(it);
2874 Py_XDECREF(it->it_seq);
2875 PyObject_GC_Del(it);
2876}
2877
2878static int
2879listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2880{
2881 Py_VISIT(it->it_seq);
2882 return 0;
2883}
2884
2885static PyObject *
2886listreviter_next(listreviterobject *it)
2887{
2888 PyObject *item;
2889 Py_ssize_t index = it->it_index;
2890 PyListObject *seq = it->it_seq;
2891
2892 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2893 item = PyList_GET_ITEM(seq, index);
2894 it->it_index--;
2895 Py_INCREF(item);
2896 return item;
2897 }
2898 it->it_index = -1;
2899 if (seq != NULL) {
2900 it->it_seq = NULL;
2901 Py_DECREF(seq);
2902 }
2903 return NULL;
2904}
2905
2906static Py_ssize_t
2907listreviter_len(listreviterobject *it)
2908{
2909 Py_ssize_t len = it->it_index + 1;
2910 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
2911 return 0;
2912 return len;
2913}
2914