blob: 7a2cdeaf31f006aa265e96636ada0a252168967b [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
Guido van Rossuma46d51d1995-01-26 22:59:43 +000011static int
Raymond Hettingerd4ff7412004-03-15 09:01:31 +000012list_resize(PyListObject *self, int newsize)
Guido van Rossuma46d51d1995-01-26 22:59:43 +000013{
Raymond Hettinger4bb95402004-02-13 11:36:39 +000014 PyObject **items;
15 size_t _new_size;
Tim Peters65b8b842001-05-26 05:28:40 +000016
Raymond Hettinger4bb95402004-02-13 11:36:39 +000017 /* Bypass realloc() when a previous overallocation is large enough
18 to accommodate the newsize. If the newsize is 16 smaller than the
19 current size, then proceed with the realloc() to shrink the list.
20 */
21
22 if (self->allocated >= newsize &&
23 self->ob_size < newsize + 16 &&
24 self->ob_item != NULL) {
25 self->ob_size = newsize;
26 return 0;
27 }
28
29 /* This over-allocates proportional to the list size, making room
Tim Peters65b8b842001-05-26 05:28:40 +000030 * for additional growth. The over-allocation is mild, but is
31 * enough to give linear-time amortized behavior over a long
32 * sequence of appends() in the presence of a poorly-performing
Raymond Hettingerab517d22004-02-14 18:34:46 +000033 * system realloc().
34 * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
Tim Peters65b8b842001-05-26 05:28:40 +000035 */
Raymond Hettingerd4ff7412004-03-15 09:01:31 +000036 _new_size = (newsize >> 3) + (self->ob_size < 8 ? 3 : 6) + newsize;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000037 items = self->ob_item;
38 if (_new_size <= ((~(size_t)0) / sizeof(PyObject *)))
39 PyMem_RESIZE(items, PyObject *, _new_size);
40 else
41 items = NULL;
42 if (items == NULL) {
43 PyErr_NoMemory();
44 return -1;
45 }
46 self->ob_item = items;
47 self->ob_size = newsize;
48 self->allocated = _new_size;
49 return 0;
50}
Guido van Rossuma46d51d1995-01-26 22:59:43 +000051
Guido van Rossumc0b618a1997-05-02 03:12:38 +000052PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +000053PyList_New(int size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000054{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000055 PyListObject *op;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +000056 size_t nbytes;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000057 if (size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000058 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000059 return NULL;
60 }
Tim Peters7049d812004-01-18 20:31:02 +000061 nbytes = size * sizeof(PyObject *);
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000062 /* Check for overflow */
Tim Peters7049d812004-01-18 20:31:02 +000063 if (nbytes / sizeof(PyObject *) != (size_t)size) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000064 return PyErr_NoMemory();
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000065 }
Neil Schemenauere83c00e2001-08-29 23:54:21 +000066 op = PyObject_GC_New(PyListObject, &PyList_Type);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000067 if (op == NULL) {
Neil Schemenauere83c00e2001-08-29 23:54:21 +000068 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000069 }
70 if (size <= 0) {
71 op->ob_item = NULL;
72 }
73 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +000074 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000075 if (op->ob_item == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000076 return PyErr_NoMemory();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000077 }
Tim Peters7049d812004-01-18 20:31:02 +000078 memset(op->ob_item, 0, sizeof(*op->ob_item) * size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000079 }
Neil Schemenauere83c00e2001-08-29 23:54:21 +000080 op->ob_size = size;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000081 op->allocated = size;
Neil Schemenauere83c00e2001-08-29 23:54:21 +000082 _PyObject_GC_TRACK(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +000083 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000084}
85
86int
Fred Drakea2f55112000-07-09 15:16:51 +000087PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000088{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000089 if (!PyList_Check(op)) {
90 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000091 return -1;
92 }
93 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000094 return ((PyListObject *)op) -> ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000095}
96
Guido van Rossumc0b618a1997-05-02 03:12:38 +000097static PyObject *indexerr;
Guido van Rossum929f1b81996-08-09 20:51:27 +000098
Guido van Rossumc0b618a1997-05-02 03:12:38 +000099PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000100PyList_GetItem(PyObject *op, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000101{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000102 if (!PyList_Check(op)) {
103 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000104 return NULL;
105 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000106 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000107 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000108 indexerr = PyString_FromString(
109 "list index out of range");
110 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000111 return NULL;
112 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000113 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000114}
115
116int
Fred Drakea2f55112000-07-09 15:16:51 +0000117PyList_SetItem(register PyObject *op, register int i,
118 register PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000119{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000120 register PyObject *olditem;
121 register PyObject **p;
122 if (!PyList_Check(op)) {
123 Py_XDECREF(newitem);
124 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000125 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000126 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000127 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
128 Py_XDECREF(newitem);
129 PyErr_SetString(PyExc_IndexError,
130 "list assignment index out of range");
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000131 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000132 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000133 p = ((PyListObject *)op) -> ob_item + i;
Guido van Rossum5fe60581995-03-09 12:12:50 +0000134 olditem = *p;
135 *p = newitem;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000136 Py_XDECREF(olditem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000137 return 0;
138}
139
140static int
Fred Drakea2f55112000-07-09 15:16:51 +0000141ins1(PyListObject *self, int where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000142{
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000143 int i, n = self->ob_size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000144 PyObject **items;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000145 if (v == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000146 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000147 return -1;
148 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000149 if (n == INT_MAX) {
Trent Micka5846642000-08-13 22:47:45 +0000150 PyErr_SetString(PyExc_OverflowError,
151 "cannot add more objects to list");
152 return -1;
153 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000154
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000155 if (list_resize(self, n+1) == -1)
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000156 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000157
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000158 if (where < 0) {
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000159 where += n;
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000160 if (where < 0)
161 where = 0;
162 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000163 if (where > n)
164 where = n;
165 items = self->ob_item;
166 for (i = n; --i >= where; )
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000167 items[i+1] = items[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000168 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000169 items[where] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000170 return 0;
171}
172
173int
Fred Drakea2f55112000-07-09 15:16:51 +0000174PyList_Insert(PyObject *op, int where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000175{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000176 if (!PyList_Check(op)) {
177 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000178 return -1;
179 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000180 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000181}
182
Raymond Hettinger40a03822004-04-12 13:05:09 +0000183static int
184app1(PyListObject *self, PyObject *v)
185{
186 int n = PyList_GET_SIZE(self);
187
188 assert (v != NULL);
189 if (n == INT_MAX) {
190 PyErr_SetString(PyExc_OverflowError,
191 "cannot add more objects to list");
192 return -1;
193 }
194
195 if (list_resize(self, n+1) == -1)
196 return -1;
197
198 Py_INCREF(v);
199 PyList_SET_ITEM(self, n, v);
200 return 0;
201}
202
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000203int
Fred Drakea2f55112000-07-09 15:16:51 +0000204PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000205{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000206 if (!PyList_Check(op)) {
207 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000208 return -1;
209 }
Raymond Hettinger40a03822004-04-12 13:05:09 +0000210 if (newitem == NULL) {
211 PyErr_BadInternalCall();
212 return -1;
213 }
214 return app1((PyListObject *)op, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000215}
216
217/* Methods */
218
219static void
Fred Drakea2f55112000-07-09 15:16:51 +0000220list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000221{
222 int i;
Guido van Rossumff413af2002-03-28 20:34:59 +0000223 PyObject_GC_UnTrack(op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000224 Py_TRASHCAN_SAFE_BEGIN(op)
Jack Jansen7874d1f1995-01-19 12:09:27 +0000225 if (op->ob_item != NULL) {
Guido van Rossumfa717011999-06-09 15:19:34 +0000226 /* Do it backwards, for Christian Tismer.
227 There's a simple test case where somehow this reduces
228 thrashing when a *very* large list is created and
229 immediately deleted. */
230 i = op->ob_size;
231 while (--i >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000232 Py_XDECREF(op->ob_item[i]);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000233 }
Guido van Rossumb18618d2000-05-03 23:44:39 +0000234 PyMem_FREE(op->ob_item);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000235 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000236 op->ob_type->tp_free((PyObject *)op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000237 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000238}
239
Guido van Rossum90933611991-06-07 16:10:43 +0000240static int
Fred Drakea2f55112000-07-09 15:16:51 +0000241list_print(PyListObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000242{
243 int i;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000244
245 i = Py_ReprEnter((PyObject*)op);
246 if (i != 0) {
247 if (i < 0)
248 return i;
249 fprintf(fp, "[...]");
250 return 0;
251 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000252 fprintf(fp, "[");
Guido van Rossum90933611991-06-07 16:10:43 +0000253 for (i = 0; i < op->ob_size; i++) {
254 if (i > 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000255 fprintf(fp, ", ");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000256 if (PyObject_Print(op->ob_item[i], fp, 0) != 0) {
257 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000258 return -1;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000259 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000260 }
261 fprintf(fp, "]");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000262 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000263 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000264}
265
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000266static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000267list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000268{
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000269 int i;
Tim Petersa7259592001-06-16 05:11:17 +0000270 PyObject *s, *temp;
271 PyObject *pieces = NULL, *result = NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000272
273 i = Py_ReprEnter((PyObject*)v);
274 if (i != 0) {
Tim Petersa7259592001-06-16 05:11:17 +0000275 return i > 0 ? PyString_FromString("[...]") : NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000276 }
Tim Petersa7259592001-06-16 05:11:17 +0000277
278 if (v->ob_size == 0) {
279 result = PyString_FromString("[]");
280 goto Done;
281 }
282
283 pieces = PyList_New(0);
284 if (pieces == NULL)
285 goto Done;
286
287 /* Do repr() on each element. Note that this may mutate the list,
288 so must refetch the list size on each iteration. */
289 for (i = 0; i < v->ob_size; ++i) {
290 int status;
291 s = PyObject_Repr(v->ob_item[i]);
292 if (s == NULL)
293 goto Done;
294 status = PyList_Append(pieces, s);
295 Py_DECREF(s); /* append created a new ref */
296 if (status < 0)
297 goto Done;
298 }
299
300 /* Add "[]" decorations to the first and last items. */
301 assert(PyList_GET_SIZE(pieces) > 0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000302 s = PyString_FromString("[");
Tim Petersa7259592001-06-16 05:11:17 +0000303 if (s == NULL)
304 goto Done;
305 temp = PyList_GET_ITEM(pieces, 0);
306 PyString_ConcatAndDel(&s, temp);
307 PyList_SET_ITEM(pieces, 0, s);
308 if (s == NULL)
309 goto Done;
310
311 s = PyString_FromString("]");
312 if (s == NULL)
313 goto Done;
314 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
315 PyString_ConcatAndDel(&temp, s);
316 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
317 if (temp == NULL)
318 goto Done;
319
320 /* Paste them all together with ", " between. */
321 s = PyString_FromString(", ");
322 if (s == NULL)
323 goto Done;
324 result = _PyString_Join(s, pieces);
Tim Peters3b01a122002-07-19 02:35:45 +0000325 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +0000326
327Done:
328 Py_XDECREF(pieces);
Guido van Rossumfb376de1998-04-10 22:47:27 +0000329 Py_ReprLeave((PyObject *)v);
Tim Petersa7259592001-06-16 05:11:17 +0000330 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000331}
332
333static int
Fred Drakea2f55112000-07-09 15:16:51 +0000334list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000335{
336 return a->ob_size;
337}
338
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000339static int
Fred Drakea2f55112000-07-09 15:16:51 +0000340list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000341{
Raymond Hettingeraae59992002-09-05 14:23:49 +0000342 int i, cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000343
Raymond Hettingeraae59992002-09-05 14:23:49 +0000344 for (i = 0, cmp = 0 ; cmp == 0 && i < a->ob_size; ++i)
345 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000346 Py_EQ);
Neal Norwitzbb9c5f52002-09-05 21:32:55 +0000347 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000348}
349
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000350static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000351list_item(PyListObject *a, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000352{
353 if (i < 0 || i >= a->ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000354 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000355 indexerr = PyString_FromString(
356 "list index out of range");
357 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000358 return NULL;
359 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000360 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000361 return a->ob_item[i];
362}
363
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000364static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000365list_slice(PyListObject *a, int ilow, int ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000366{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000367 PyListObject *np;
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000368 PyObject **src, **dest;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000369 int i, len;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000370 if (ilow < 0)
371 ilow = 0;
372 else if (ilow > a->ob_size)
373 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000374 if (ihigh < ilow)
375 ihigh = ilow;
376 else if (ihigh > a->ob_size)
377 ihigh = a->ob_size;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000378 len = ihigh - ilow;
379 np = (PyListObject *) PyList_New(len);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000380 if (np == NULL)
381 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000382
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000383 src = a->ob_item + ilow;
384 dest = np->ob_item;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000385 for (i = 0; i < len; i++) {
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000386 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000387 Py_INCREF(v);
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000388 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000389 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000390 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000391}
392
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000393PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000394PyList_GetSlice(PyObject *a, int ilow, int ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000395{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000396 if (!PyList_Check(a)) {
397 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000398 return NULL;
399 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000400 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000401}
402
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000403static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000404list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000405{
406 int size;
407 int i;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000408 PyObject **src, **dest;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000409 PyListObject *np;
410 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000411 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000412 "can only concatenate list (not \"%.200s\") to list",
413 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000414 return NULL;
415 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000416#define b ((PyListObject *)bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000417 size = a->ob_size + b->ob_size;
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000418 if (size < 0)
419 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000420 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000421 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000422 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000423 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000424 src = a->ob_item;
425 dest = np->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000426 for (i = 0; i < a->ob_size; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000427 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000428 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000429 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000430 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000431 src = b->ob_item;
432 dest = np->ob_item + a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000433 for (i = 0; i < b->ob_size; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000434 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000435 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000436 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000437 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000438 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000439#undef b
440}
441
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000442static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000443list_repeat(PyListObject *a, int n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000444{
445 int i, j;
446 int size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000447 PyListObject *np;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000448 PyObject **p, **items;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000449 PyObject *elem;
Guido van Rossumed98d481991-03-06 13:07:53 +0000450 if (n < 0)
451 n = 0;
452 size = a->ob_size * n;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000453 if (size == 0)
454 return PyList_New(0);
Guido van Rossumbfa5a142002-10-11 23:39:35 +0000455 if (n && size/n != a->ob_size)
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000456 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000457 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000458 if (np == NULL)
459 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000460
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000461 items = np->ob_item;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000462 if (a->ob_size == 1) {
463 elem = a->ob_item[0];
464 for (i = 0; i < n; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000465 items[i] = elem;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000466 Py_INCREF(elem);
467 }
468 return (PyObject *) np;
469 }
Guido van Rossumed98d481991-03-06 13:07:53 +0000470 p = np->ob_item;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000471 items = a->ob_item;
Guido van Rossumed98d481991-03-06 13:07:53 +0000472 for (i = 0; i < n; i++) {
473 for (j = 0; j < a->ob_size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000474 *p = items[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000475 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000476 p++;
477 }
478 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000479 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000480}
481
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000482static int
Fred Drakea2f55112000-07-09 15:16:51 +0000483list_ass_slice(PyListObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000484{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000485 /* Because [X]DECREF can recursively invoke list operations on
486 this list, we must postpone all [X]DECREF activity until
487 after the list is back in its canonical shape. Therefore
488 we must allocate an additional array, 'recycle', into which
489 we temporarily copy the items that are deleted from the
490 list. :-( */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000491 PyObject **recycle, **p;
492 PyObject **item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000493 PyObject **vitem = NULL;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000494 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000495 int n; /* Size of replacement list */
496 int d; /* Change in size */
497 int k; /* Loop index */
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000498 int s;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000499#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000500 if (v == NULL)
501 n = 0;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000502 else {
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000503 if (a == b) {
504 /* Special case "a[i:j] = a" -- copy b first */
505 int ret;
Michael W. Hudsonda0a0672003-08-15 12:06:41 +0000506 v = list_slice(b, 0, b->ob_size);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000507 if (v == NULL)
508 return -1;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000509 ret = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000510 Py_DECREF(v);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000511 return ret;
512 }
Raymond Hettingerf889e102004-03-09 08:04:33 +0000513 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000514 if(v_as_SF == NULL)
515 return -1;
516 n = PySequence_Fast_GET_SIZE(v_as_SF);
Raymond Hettinger42bec932004-03-12 16:38:17 +0000517 vitem = PySequence_Fast_ITEMS(v_as_SF);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000518 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000519 if (ilow < 0)
520 ilow = 0;
521 else if (ilow > a->ob_size)
522 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000523 if (ihigh < ilow)
524 ihigh = ilow;
525 else if (ihigh > a->ob_size)
526 ihigh = a->ob_size;
527 item = a->ob_item;
528 d = n - (ihigh-ilow);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000529 if (ihigh > ilow) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000530 p = recycle = PyMem_NEW(PyObject *, (ihigh-ilow));
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000531 if (recycle == NULL) {
532 PyErr_NoMemory();
533 return -1;
534 }
535 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000536 else
537 p = recycle = NULL;
538 if (d <= 0) { /* Delete -d items; recycle ihigh-ilow items */
Raymond Hettinger66d31f82004-03-10 11:44:04 +0000539 memcpy(p, &item[ilow], (ihigh - ilow)*sizeof(PyObject *));
Raymond Hettingerf889e102004-03-09 08:04:33 +0000540 p += ihigh - ilow;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000541 if (d < 0) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000542 memmove(&item[ihigh+d], &item[ihigh],
543 (a->ob_size - ihigh)*sizeof(PyObject *));
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000544 list_resize(a, a->ob_size + d);
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000545 item = a->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000546 }
547 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000548 else { /* Insert d items; recycle ihigh-ilow items */
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000549 s = a->ob_size;
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000550 if (list_resize(a, s+d) == -1) {
Guido van Rossumb18618d2000-05-03 23:44:39 +0000551 if (recycle != NULL)
552 PyMem_DEL(recycle);
Raymond Hettinger2731ae42004-02-14 03:07:21 +0000553 return -1;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000554 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000555 item = a->ob_item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000556 memmove(&item[ihigh+d], &item[ihigh],
557 (s - ihigh)*sizeof(PyObject *));
Raymond Hettinger66d31f82004-03-10 11:44:04 +0000558 memcpy(p, &item[ilow], (ihigh - ilow)*sizeof(PyObject *));
Raymond Hettingerf889e102004-03-09 08:04:33 +0000559 p += ihigh - ilow;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000560 }
561 for (k = 0; k < n; k++, ilow++) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000562 PyObject *w = vitem[k];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000563 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000564 item[ilow] = w;
565 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000566 if (recycle) {
567 while (--p >= recycle)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000568 Py_XDECREF(*p);
569 PyMem_DEL(recycle);
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000570 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000571 if (a->ob_size == 0 && a->ob_item != NULL) {
572 PyMem_FREE(a->ob_item);
573 a->ob_item = NULL;
574 }
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000575 Py_XDECREF(v_as_SF);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000576 return 0;
577#undef b
578}
579
Guido van Rossum234f9421993-06-17 12:35:49 +0000580int
Fred Drakea2f55112000-07-09 15:16:51 +0000581PyList_SetSlice(PyObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000582{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000583 if (!PyList_Check(a)) {
584 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000585 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000586 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000587 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000588}
589
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000590static PyObject *
591list_inplace_repeat(PyListObject *self, int n)
592{
593 PyObject **items;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000594 int size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000595
596
597 size = PyList_GET_SIZE(self);
598 if (size == 0) {
599 Py_INCREF(self);
600 return (PyObject *)self;
601 }
602
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000603 if (n < 1) {
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000604 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000605 self->ob_item = NULL;
606 self->ob_size = 0;
607 for (i = 0; i < size; i++)
608 Py_XDECREF(items[i]);
609 PyMem_DEL(items);
610 Py_INCREF(self);
611 return (PyObject *)self;
612 }
613
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000614 if (list_resize(self, size*n) == -1)
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000615 return NULL;
616
617 p = size;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000618 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000619 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
620 for (j = 0; j < size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000621 PyObject *o = items[j];
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000622 Py_INCREF(o);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000623 items[p++] = o;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000624 }
625 }
626 Py_INCREF(self);
627 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000628}
629
Guido van Rossum4a450d01991-04-03 19:05:18 +0000630static int
Fred Drakea2f55112000-07-09 15:16:51 +0000631list_ass_item(PyListObject *a, int i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000632{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000633 PyObject *old_value;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000634 if (i < 0 || i >= a->ob_size) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000635 PyErr_SetString(PyExc_IndexError,
636 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000637 return -1;
638 }
639 if (v == NULL)
640 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000641 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000642 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000643 a->ob_item[i] = v;
Tim Peters3b01a122002-07-19 02:35:45 +0000644 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000645 return 0;
646}
647
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000648static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000649listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000650{
651 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000652 PyObject *v;
Guido van Rossumc00a9382000-02-24 21:48:29 +0000653 if (!PyArg_ParseTuple(args, "iO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000654 return NULL;
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000655 if (ins1(self, i, v) == 0)
656 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000657 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000658}
659
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000660static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000661listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000662{
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000663 if (app1(self, v) == 0)
664 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000665 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000666}
667
Barry Warsawdedf6d61998-10-09 16:37:25 +0000668static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000669listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000670{
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000671 PyObject *it; /* iter(v) */
672 int m; /* size of self */
673 int n; /* guess for size of b */
674 int mn; /* m + n */
675 int i;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000676 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000677
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000678 /* Special cases:
679 1) lists and tuples which can use PySequence_Fast ops
680 2) extending self to self requires making a copy first
681 */
682 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
Armin Rigo70d172d2004-03-20 22:19:23 +0000683 PyObject **src, **dest;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000684 b = PySequence_Fast(b, "argument must be iterable");
685 if (!b)
686 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000687 n = PySequence_Fast_GET_SIZE(b);
688 if (n == 0) {
689 /* short circuit when b is empty */
690 Py_DECREF(b);
691 Py_RETURN_NONE;
692 }
693 m = self->ob_size;
694 if (list_resize(self, m + n) == -1) {
695 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000696 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000697 }
698 /* note that we may still have self == b here for the
699 * situation a.extend(a), but the following code works
700 * in that case too. Just make sure to resize self
701 * before calling PySequence_Fast_ITEMS.
702 */
703 /* populate the end of self with b's items */
704 src = PySequence_Fast_ITEMS(b);
705 dest = self->ob_item + m;
706 for (i = 0; i < n; i++) {
707 PyObject *o = src[i];
708 Py_INCREF(o);
709 dest[i] = o;
710 }
711 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000712 Py_RETURN_NONE;
713 }
714
715 it = PyObject_GetIter(b);
716 if (it == NULL)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000717 return NULL;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000718 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000719
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000720 /* Guess a result list size. */
721 n = PyObject_Size(b);
722 if (n < 0) {
723 PyErr_Clear();
724 n = 8; /* arbitrary */
725 }
726 m = self->ob_size;
727 mn = m + n;
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000728 if (list_resize(self, mn) == -1)
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000729 goto error;
730 memset(&(self->ob_item[m]), 0, sizeof(*self->ob_item) * n);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000731
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000732 /* Run iterator to exhaustion. */
733 for (i = m; ; i++) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000734 PyObject *item = iternext(it);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000735 if (item == NULL) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000736 if (PyErr_Occurred()) {
737 if (PyErr_ExceptionMatches(PyExc_StopIteration))
738 PyErr_Clear();
739 else
740 goto error;
741 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000742 break;
743 }
744 if (i < mn)
745 PyList_SET_ITEM(self, i, item); /* steals ref */
746 else {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000747 int status = app1(self, item);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000748 Py_DECREF(item); /* append creates a new ref */
749 if (status < 0)
750 goto error;
751 }
752 }
753
754 /* Cut back result list if initial guess was too large. */
755 if (i < mn && self != NULL) {
756 if (list_ass_slice(self, i, mn, (PyObject *)NULL) != 0)
757 goto error;
758 }
759 Py_DECREF(it);
760 Py_RETURN_NONE;
761
762 error:
763 Py_DECREF(it);
764 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000765}
766
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000767PyObject *
768_PyList_Extend(PyListObject *self, PyObject *b)
769{
770 return listextend(self, b);
771}
772
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000773static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000774list_inplace_concat(PyListObject *self, PyObject *other)
775{
776 PyObject *result;
777
778 result = listextend(self, other);
779 if (result == NULL)
780 return result;
781 Py_DECREF(result);
782 Py_INCREF(self);
783 return (PyObject *)self;
784}
785
786static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000787listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000788{
789 int i = -1;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000790 PyObject *v, *arg = NULL;
791
792 if (!PyArg_UnpackTuple(args, "pop", 0, 1, &arg))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000793 return NULL;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000794 if (arg != NULL) {
795 if (PyInt_Check(arg))
796 i = (int)(PyInt_AS_LONG((PyIntObject*) arg));
Raymond Hettingerfa6c6f82004-02-19 06:12:06 +0000797 else if (!PyArg_ParseTuple(args, "|i:pop", &i))
798 return NULL;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000799 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000800 if (self->ob_size == 0) {
801 /* Special-case most common failure cause */
802 PyErr_SetString(PyExc_IndexError, "pop from empty list");
803 return NULL;
804 }
805 if (i < 0)
806 i += self->ob_size;
807 if (i < 0 || i >= self->ob_size) {
808 PyErr_SetString(PyExc_IndexError, "pop index out of range");
809 return NULL;
810 }
811 v = self->ob_item[i];
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000812 if (i == self->ob_size - 1) {
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000813 if (list_resize(self, self->ob_size - 1) == -1)
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000814 return NULL;
815 return v;
816 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000817 Py_INCREF(v);
818 if (list_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) {
819 Py_DECREF(v);
820 return NULL;
821 }
822 return v;
823}
824
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000825/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
826static void
827reverse_slice(PyObject **lo, PyObject **hi)
828{
829 assert(lo && hi);
830
831 --hi;
832 while (lo < hi) {
833 PyObject *t = *lo;
834 *lo = *hi;
835 *hi = t;
836 ++lo;
837 --hi;
838 }
839}
840
Tim Petersa64dc242002-08-01 02:13:36 +0000841/* Lots of code for an adaptive, stable, natural mergesort. There are many
842 * pieces to this algorithm; read listsort.txt for overviews and details.
843 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000844
Guido van Rossum3f236de1996-12-10 23:55:39 +0000845/* Comparison function. Takes care of calling a user-supplied
Tim Peters66860f62002-08-04 17:47:26 +0000846 * comparison function (any callable Python object), which must not be
847 * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool
848 * with Py_LT if you know it's NULL).
Tim Petersa64dc242002-08-01 02:13:36 +0000849 * Returns -1 on error, 1 if x < y, 0 if x >= y.
850 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000851static int
Tim Petersa8c974c2002-07-19 03:30:57 +0000852islt(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000853{
Tim Petersf2a04732002-07-11 21:46:16 +0000854 PyObject *res;
855 PyObject *args;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000856 int i;
857
Tim Peters66860f62002-08-04 17:47:26 +0000858 assert(compare != NULL);
Tim Petersa8c974c2002-07-19 03:30:57 +0000859 /* Call the user's comparison function and translate the 3-way
860 * result into true or false (or error).
861 */
Tim Petersf2a04732002-07-11 21:46:16 +0000862 args = PyTuple_New(2);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000863 if (args == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000864 return -1;
Tim Petersf2a04732002-07-11 21:46:16 +0000865 Py_INCREF(x);
866 Py_INCREF(y);
867 PyTuple_SET_ITEM(args, 0, x);
868 PyTuple_SET_ITEM(args, 1, y);
Tim Peters58cf3612002-07-15 05:16:13 +0000869 res = PyObject_Call(compare, args, NULL);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000870 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000871 if (res == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000872 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000873 if (!PyInt_Check(res)) {
874 Py_DECREF(res);
875 PyErr_SetString(PyExc_TypeError,
Guido van Rossum9bcd1d71999-04-19 17:44:39 +0000876 "comparison function must return int");
Tim Petersa8c974c2002-07-19 03:30:57 +0000877 return -1;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000878 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000879 i = PyInt_AsLong(res);
880 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +0000881 return i < 0;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000882}
883
Tim Peters66860f62002-08-04 17:47:26 +0000884/* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
885 * islt. This avoids a layer of function call in the usual case, and
886 * sorting does many comparisons.
887 * Returns -1 on error, 1 if x < y, 0 if x >= y.
888 */
889#define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
890 PyObject_RichCompareBool(X, Y, Py_LT) : \
891 islt(X, Y, COMPARE))
892
893/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +0000894 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
895 started. It makes more sense in context <wink>. X and Y are PyObject*s.
896*/
Tim Peters66860f62002-08-04 17:47:26 +0000897#define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
Tim Petersa8c974c2002-07-19 03:30:57 +0000898 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000899
900/* binarysort is the best method for sorting small arrays: it does
901 few compares, but can do data movement quadratic in the number of
902 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000903 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +0000904 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000905 On entry, must have lo <= start <= hi, and that [lo, start) is already
906 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +0000907 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000908 Even in case of error, the output slice will be some permutation of
909 the input (nothing is lost or duplicated).
910*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000911static int
Fred Drakea2f55112000-07-09 15:16:51 +0000912binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
913 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000914{
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000915 register int k;
916 register PyObject **l, **p, **r;
917 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000918
Tim Petersa8c974c2002-07-19 03:30:57 +0000919 assert(lo <= start && start <= hi);
920 /* assert [lo, start) is sorted */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000921 if (lo == start)
922 ++start;
923 for (; start < hi; ++start) {
924 /* set l to where *start belongs */
925 l = lo;
926 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000927 pivot = *r;
Tim Peters0fe977c2002-07-19 06:12:32 +0000928 /* Invariants:
929 * pivot >= all in [lo, l).
930 * pivot < all in [r, start).
931 * The second is vacuously true at the start.
932 */
933 assert(l < r);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000934 do {
935 p = l + ((r - l) >> 1);
Tim Petersa8c974c2002-07-19 03:30:57 +0000936 IFLT(pivot, *p)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000937 r = p;
938 else
Tim Peters0fe977c2002-07-19 06:12:32 +0000939 l = p+1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000940 } while (l < r);
Tim Peters0fe977c2002-07-19 06:12:32 +0000941 assert(l == r);
942 /* The invariants still hold, so pivot >= all in [lo, l) and
943 pivot < all in [l, start), so pivot belongs at l. Note
944 that if there are elements equal to pivot, l points to the
945 first slot after them -- that's why this sort is stable.
946 Slide over to make room.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000947 Caution: using memmove is much slower under MSVC 5;
948 we're not usually moving many slots. */
949 for (p = start; p > l; --p)
950 *p = *(p-1);
951 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000952 }
Guido van Rossum3f236de1996-12-10 23:55:39 +0000953 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000954
955 fail:
956 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000957}
958
Tim Petersa64dc242002-08-01 02:13:36 +0000959/*
960Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
961is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000962
Tim Petersa64dc242002-08-01 02:13:36 +0000963 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000964
Tim Petersa64dc242002-08-01 02:13:36 +0000965or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000966
Tim Petersa64dc242002-08-01 02:13:36 +0000967 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +0000968
Tim Petersa64dc242002-08-01 02:13:36 +0000969Boolean *descending is set to 0 in the former case, or to 1 in the latter.
970For its intended use in a stable mergesort, the strictness of the defn of
971"descending" is needed so that the caller can safely reverse a descending
972sequence without violating stability (strict > ensures there are no equal
973elements to get out of order).
974
975Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000976*/
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000977static int
Tim Petersa64dc242002-08-01 02:13:36 +0000978count_run(PyObject **lo, PyObject **hi, PyObject *compare, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000979{
Tim Petersa64dc242002-08-01 02:13:36 +0000980 int k;
981 int n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000982
Tim Petersa64dc242002-08-01 02:13:36 +0000983 assert(lo < hi);
984 *descending = 0;
985 ++lo;
986 if (lo == hi)
987 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000988
Tim Petersa64dc242002-08-01 02:13:36 +0000989 n = 2;
990 IFLT(*lo, *(lo-1)) {
991 *descending = 1;
992 for (lo = lo+1; lo < hi; ++lo, ++n) {
993 IFLT(*lo, *(lo-1))
994 ;
995 else
996 break;
997 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000998 }
Tim Petersa64dc242002-08-01 02:13:36 +0000999 else {
1000 for (lo = lo+1; lo < hi; ++lo, ++n) {
1001 IFLT(*lo, *(lo-1))
1002 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001003 }
1004 }
1005
Tim Petersa64dc242002-08-01 02:13:36 +00001006 return n;
1007fail:
1008 return -1;
1009}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001010
Tim Petersa64dc242002-08-01 02:13:36 +00001011/*
1012Locate the proper position of key in a sorted vector; if the vector contains
1013an element equal to key, return the position immediately to the left of
1014the leftmost equal element. [gallop_right() does the same except returns
1015the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001016
Tim Petersa64dc242002-08-01 02:13:36 +00001017"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001018
Tim Petersa64dc242002-08-01 02:13:36 +00001019"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1020hint is to the final result, the faster this runs.
1021
1022The return value is the int k in 0..n such that
1023
1024 a[k-1] < key <= a[k]
1025
1026pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1027key belongs at index k; or, IOW, the first k elements of a should precede
1028key, and the last n-k should follow key.
1029
1030Returns -1 on error. See listsort.txt for info on the method.
1031*/
1032static int
1033gallop_left(PyObject *key, PyObject **a, int n, int hint, PyObject *compare)
1034{
1035 int ofs;
1036 int lastofs;
1037 int k;
1038
1039 assert(key && a && n > 0 && hint >= 0 && hint < n);
1040
1041 a += hint;
1042 lastofs = 0;
1043 ofs = 1;
1044 IFLT(*a, key) {
1045 /* a[hint] < key -- gallop right, until
1046 * a[hint + lastofs] < key <= a[hint + ofs]
1047 */
1048 const int maxofs = n - hint; /* &a[n-1] is highest */
1049 while (ofs < maxofs) {
1050 IFLT(a[ofs], key) {
1051 lastofs = ofs;
1052 ofs = (ofs << 1) + 1;
1053 if (ofs <= 0) /* int overflow */
1054 ofs = maxofs;
1055 }
1056 else /* key <= a[hint + ofs] */
1057 break;
1058 }
1059 if (ofs > maxofs)
1060 ofs = maxofs;
1061 /* Translate back to offsets relative to &a[0]. */
1062 lastofs += hint;
1063 ofs += hint;
1064 }
1065 else {
1066 /* key <= a[hint] -- gallop left, until
1067 * a[hint - ofs] < key <= a[hint - lastofs]
1068 */
1069 const int maxofs = hint + 1; /* &a[0] is lowest */
1070 while (ofs < maxofs) {
1071 IFLT(*(a-ofs), key)
1072 break;
1073 /* key <= a[hint - ofs] */
1074 lastofs = ofs;
1075 ofs = (ofs << 1) + 1;
1076 if (ofs <= 0) /* int overflow */
1077 ofs = maxofs;
1078 }
1079 if (ofs > maxofs)
1080 ofs = maxofs;
1081 /* Translate back to positive offsets relative to &a[0]. */
1082 k = lastofs;
1083 lastofs = hint - ofs;
1084 ofs = hint - k;
1085 }
1086 a -= hint;
1087
1088 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1089 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1090 * right of lastofs but no farther right than ofs. Do a binary
1091 * search, with invariant a[lastofs-1] < key <= a[ofs].
1092 */
1093 ++lastofs;
1094 while (lastofs < ofs) {
1095 int m = lastofs + ((ofs - lastofs) >> 1);
1096
1097 IFLT(a[m], key)
1098 lastofs = m+1; /* a[m] < key */
1099 else
1100 ofs = m; /* key <= a[m] */
1101 }
1102 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1103 return ofs;
1104
1105fail:
1106 return -1;
1107}
1108
1109/*
1110Exactly like gallop_left(), except that if key already exists in a[0:n],
1111finds the position immediately to the right of the rightmost equal value.
1112
1113The return value is the int k in 0..n such that
1114
1115 a[k-1] <= key < a[k]
1116
1117or -1 if error.
1118
1119The code duplication is massive, but this is enough different given that
1120we're sticking to "<" comparisons that it's much harder to follow if
1121written as one routine with yet another "left or right?" flag.
1122*/
1123static int
1124gallop_right(PyObject *key, PyObject **a, int n, int hint, PyObject *compare)
1125{
1126 int ofs;
1127 int lastofs;
1128 int k;
1129
1130 assert(key && a && n > 0 && hint >= 0 && hint < n);
1131
1132 a += hint;
1133 lastofs = 0;
1134 ofs = 1;
1135 IFLT(key, *a) {
1136 /* key < a[hint] -- gallop left, until
1137 * a[hint - ofs] <= key < a[hint - lastofs]
1138 */
1139 const int maxofs = hint + 1; /* &a[0] is lowest */
1140 while (ofs < maxofs) {
1141 IFLT(key, *(a-ofs)) {
1142 lastofs = ofs;
1143 ofs = (ofs << 1) + 1;
1144 if (ofs <= 0) /* int overflow */
1145 ofs = maxofs;
1146 }
1147 else /* a[hint - ofs] <= key */
1148 break;
1149 }
1150 if (ofs > maxofs)
1151 ofs = maxofs;
1152 /* Translate back to positive offsets relative to &a[0]. */
1153 k = lastofs;
1154 lastofs = hint - ofs;
1155 ofs = hint - k;
1156 }
1157 else {
1158 /* a[hint] <= key -- gallop right, until
1159 * a[hint + lastofs] <= key < a[hint + ofs]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001160 */
Tim Petersa64dc242002-08-01 02:13:36 +00001161 const int maxofs = n - hint; /* &a[n-1] is highest */
1162 while (ofs < maxofs) {
1163 IFLT(key, a[ofs])
1164 break;
1165 /* a[hint + ofs] <= key */
1166 lastofs = ofs;
1167 ofs = (ofs << 1) + 1;
1168 if (ofs <= 0) /* int overflow */
1169 ofs = maxofs;
1170 }
1171 if (ofs > maxofs)
1172 ofs = maxofs;
1173 /* Translate back to offsets relative to &a[0]. */
1174 lastofs += hint;
1175 ofs += hint;
1176 }
1177 a -= hint;
1178
1179 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1180 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1181 * right of lastofs but no farther right than ofs. Do a binary
1182 * search, with invariant a[lastofs-1] <= key < a[ofs].
1183 */
1184 ++lastofs;
1185 while (lastofs < ofs) {
1186 int m = lastofs + ((ofs - lastofs) >> 1);
1187
1188 IFLT(key, a[m])
1189 ofs = m; /* key < a[m] */
1190 else
1191 lastofs = m+1; /* a[m] <= key */
1192 }
1193 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1194 return ofs;
1195
1196fail:
1197 return -1;
1198}
1199
1200/* The maximum number of entries in a MergeState's pending-runs stack.
1201 * This is enough to sort arrays of size up to about
1202 * 32 * phi ** MAX_MERGE_PENDING
1203 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1204 * with 2**64 elements.
1205 */
1206#define MAX_MERGE_PENDING 85
1207
Tim Peterse05f65a2002-08-10 05:21:15 +00001208/* When we get into galloping mode, we stay there until both runs win less
1209 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001210 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001211#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001212
1213/* Avoid malloc for small temp arrays. */
1214#define MERGESTATE_TEMP_SIZE 256
1215
1216/* One MergeState exists on the stack per invocation of mergesort. It's just
1217 * a convenient way to pass state around among the helper functions.
1218 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001219struct s_slice {
1220 PyObject **base;
1221 int len;
1222};
1223
Tim Petersa64dc242002-08-01 02:13:36 +00001224typedef struct s_MergeState {
1225 /* The user-supplied comparison function. or NULL if none given. */
1226 PyObject *compare;
1227
Tim Peterse05f65a2002-08-10 05:21:15 +00001228 /* This controls when we get *into* galloping mode. It's initialized
1229 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1230 * random data, and lower for highly structured data.
1231 */
1232 int min_gallop;
1233
Tim Petersa64dc242002-08-01 02:13:36 +00001234 /* 'a' is temp storage to help with merges. It contains room for
1235 * alloced entries.
1236 */
1237 PyObject **a; /* may point to temparray below */
1238 int alloced;
1239
1240 /* A stack of n pending runs yet to be merged. Run #i starts at
1241 * address base[i] and extends for len[i] elements. It's always
1242 * true (so long as the indices are in bounds) that
1243 *
Tim Peterse05f65a2002-08-10 05:21:15 +00001244 * pending[i].base + pending[i].len == pending[i+1].base
Tim Petersa64dc242002-08-01 02:13:36 +00001245 *
1246 * so we could cut the storage for this, but it's a minor amount,
1247 * and keeping all the info explicit simplifies the code.
1248 */
1249 int n;
Tim Peterse05f65a2002-08-10 05:21:15 +00001250 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001251
1252 /* 'a' points to this when possible, rather than muck with malloc. */
1253 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1254} MergeState;
1255
1256/* Conceptually a MergeState's constructor. */
1257static void
1258merge_init(MergeState *ms, PyObject *compare)
1259{
1260 assert(ms != NULL);
1261 ms->compare = compare;
1262 ms->a = ms->temparray;
1263 ms->alloced = MERGESTATE_TEMP_SIZE;
1264 ms->n = 0;
Tim Peterse05f65a2002-08-10 05:21:15 +00001265 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001266}
1267
1268/* Free all the temp memory owned by the MergeState. This must be called
1269 * when you're done with a MergeState, and may be called before then if
1270 * you want to free the temp memory early.
1271 */
1272static void
1273merge_freemem(MergeState *ms)
1274{
1275 assert(ms != NULL);
1276 if (ms->a != ms->temparray)
1277 PyMem_Free(ms->a);
1278 ms->a = ms->temparray;
1279 ms->alloced = MERGESTATE_TEMP_SIZE;
1280}
1281
1282/* Ensure enough temp memory for 'need' array slots is available.
1283 * Returns 0 on success and -1 if the memory can't be gotten.
1284 */
1285static int
1286merge_getmem(MergeState *ms, int need)
1287{
1288 assert(ms != NULL);
1289 if (need <= ms->alloced)
1290 return 0;
1291 /* Don't realloc! That can cost cycles to copy the old data, but
1292 * we don't care what's in the block.
1293 */
1294 merge_freemem(ms);
1295 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1296 if (ms->a) {
1297 ms->alloced = need;
1298 return 0;
1299 }
1300 PyErr_NoMemory();
1301 merge_freemem(ms); /* reset to sane state */
1302 return -1;
1303}
1304#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1305 merge_getmem(MS, NEED))
1306
1307/* Merge the na elements starting at pa with the nb elements starting at pb
1308 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1309 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1310 * merge, and should have na <= nb. See listsort.txt for more info.
1311 * Return 0 if successful, -1 if error.
1312 */
1313static int
1314merge_lo(MergeState *ms, PyObject **pa, int na, PyObject **pb, int nb)
1315{
1316 int k;
1317 PyObject *compare;
1318 PyObject **dest;
1319 int result = -1; /* guilty until proved innocent */
Tim Peterse05f65a2002-08-10 05:21:15 +00001320 int min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001321
1322 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1323 if (MERGE_GETMEM(ms, na) < 0)
1324 return -1;
1325 memcpy(ms->a, pa, na * sizeof(PyObject*));
1326 dest = pa;
1327 pa = ms->a;
1328
1329 *dest++ = *pb++;
1330 --nb;
1331 if (nb == 0)
1332 goto Succeed;
1333 if (na == 1)
1334 goto CopyB;
1335
1336 compare = ms->compare;
1337 for (;;) {
1338 int acount = 0; /* # of times A won in a row */
1339 int bcount = 0; /* # of times B won in a row */
1340
1341 /* Do the straightforward thing until (if ever) one run
1342 * appears to win consistently.
1343 */
1344 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001345 assert(na > 1 && nb > 0);
Tim Peters66860f62002-08-04 17:47:26 +00001346 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001347 if (k) {
1348 if (k < 0)
1349 goto Fail;
1350 *dest++ = *pb++;
1351 ++bcount;
1352 acount = 0;
1353 --nb;
1354 if (nb == 0)
1355 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001356 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001357 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001358 }
1359 else {
Tim Petersa64dc242002-08-01 02:13:36 +00001360 *dest++ = *pa++;
1361 ++acount;
1362 bcount = 0;
1363 --na;
1364 if (na == 1)
1365 goto CopyB;
Tim Peterse05f65a2002-08-10 05:21:15 +00001366 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001367 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001368 }
Tim Petersa64dc242002-08-01 02:13:36 +00001369 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001370
Tim Petersa64dc242002-08-01 02:13:36 +00001371 /* One run is winning so consistently that galloping may
1372 * be a huge win. So try that, and continue galloping until
1373 * (if ever) neither run appears to be winning consistently
1374 * anymore.
1375 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001376 ++min_gallop;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001377 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001378 assert(na > 1 && nb > 0);
1379 min_gallop -= min_gallop > 1;
1380 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001381 k = gallop_right(*pb, pa, na, 0, compare);
1382 acount = k;
1383 if (k) {
1384 if (k < 0)
1385 goto Fail;
1386 memcpy(dest, pa, k * sizeof(PyObject *));
1387 dest += k;
1388 pa += k;
1389 na -= k;
1390 if (na == 1)
1391 goto CopyB;
1392 /* na==0 is impossible now if the comparison
1393 * function is consistent, but we can't assume
1394 * that it is.
1395 */
1396 if (na == 0)
1397 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001398 }
Tim Petersa64dc242002-08-01 02:13:36 +00001399 *dest++ = *pb++;
1400 --nb;
1401 if (nb == 0)
1402 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001403
Tim Petersa64dc242002-08-01 02:13:36 +00001404 k = gallop_left(*pa, pb, nb, 0, compare);
1405 bcount = k;
1406 if (k) {
1407 if (k < 0)
1408 goto Fail;
1409 memmove(dest, pb, k * sizeof(PyObject *));
1410 dest += k;
1411 pb += k;
1412 nb -= k;
1413 if (nb == 0)
1414 goto Succeed;
1415 }
1416 *dest++ = *pa++;
1417 --na;
1418 if (na == 1)
1419 goto CopyB;
1420 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001421 ++min_gallop; /* penalize it for leaving galloping mode */
1422 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001423 }
1424Succeed:
1425 result = 0;
1426Fail:
1427 if (na)
1428 memcpy(dest, pa, na * sizeof(PyObject*));
1429 return result;
1430CopyB:
1431 assert(na == 1 && nb > 0);
1432 /* The last element of pa belongs at the end of the merge. */
1433 memmove(dest, pb, nb * sizeof(PyObject *));
1434 dest[nb] = *pa;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001435 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001436}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001437
Tim Petersa64dc242002-08-01 02:13:36 +00001438/* Merge the na elements starting at pa with the nb elements starting at pb
1439 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1440 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1441 * merge, and should have na >= nb. See listsort.txt for more info.
1442 * Return 0 if successful, -1 if error.
1443 */
1444static int
1445merge_hi(MergeState *ms, PyObject **pa, int na, PyObject **pb, int nb)
1446{
1447 int k;
1448 PyObject *compare;
1449 PyObject **dest;
1450 int result = -1; /* guilty until proved innocent */
1451 PyObject **basea;
1452 PyObject **baseb;
Tim Peterse05f65a2002-08-10 05:21:15 +00001453 int min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001454
1455 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1456 if (MERGE_GETMEM(ms, nb) < 0)
1457 return -1;
1458 dest = pb + nb - 1;
1459 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1460 basea = pa;
1461 baseb = ms->a;
1462 pb = ms->a + nb - 1;
1463 pa += na - 1;
1464
1465 *dest-- = *pa--;
1466 --na;
1467 if (na == 0)
1468 goto Succeed;
1469 if (nb == 1)
1470 goto CopyA;
1471
1472 compare = ms->compare;
1473 for (;;) {
1474 int acount = 0; /* # of times A won in a row */
1475 int bcount = 0; /* # of times B won in a row */
1476
1477 /* Do the straightforward thing until (if ever) one run
1478 * appears to win consistently.
1479 */
1480 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001481 assert(na > 0 && nb > 1);
Tim Peters66860f62002-08-04 17:47:26 +00001482 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001483 if (k) {
1484 if (k < 0)
1485 goto Fail;
1486 *dest-- = *pa--;
1487 ++acount;
1488 bcount = 0;
1489 --na;
1490 if (na == 0)
1491 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001492 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001493 break;
1494 }
1495 else {
1496 *dest-- = *pb--;
1497 ++bcount;
1498 acount = 0;
1499 --nb;
1500 if (nb == 1)
1501 goto CopyA;
Tim Peterse05f65a2002-08-10 05:21:15 +00001502 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001503 break;
1504 }
1505 }
1506
1507 /* One run is winning so consistently that galloping may
1508 * be a huge win. So try that, and continue galloping until
1509 * (if ever) neither run appears to be winning consistently
1510 * anymore.
1511 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001512 ++min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001513 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001514 assert(na > 0 && nb > 1);
1515 min_gallop -= min_gallop > 1;
1516 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001517 k = gallop_right(*pb, basea, na, na-1, compare);
1518 if (k < 0)
1519 goto Fail;
1520 k = na - k;
1521 acount = k;
1522 if (k) {
1523 dest -= k;
1524 pa -= k;
1525 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1526 na -= k;
1527 if (na == 0)
1528 goto Succeed;
1529 }
1530 *dest-- = *pb--;
1531 --nb;
1532 if (nb == 1)
1533 goto CopyA;
1534
1535 k = gallop_left(*pa, baseb, nb, nb-1, compare);
1536 if (k < 0)
1537 goto Fail;
1538 k = nb - k;
1539 bcount = k;
1540 if (k) {
1541 dest -= k;
1542 pb -= k;
1543 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1544 nb -= k;
1545 if (nb == 1)
1546 goto CopyA;
1547 /* nb==0 is impossible now if the comparison
1548 * function is consistent, but we can't assume
1549 * that it is.
1550 */
1551 if (nb == 0)
1552 goto Succeed;
1553 }
1554 *dest-- = *pa--;
1555 --na;
1556 if (na == 0)
1557 goto Succeed;
1558 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001559 ++min_gallop; /* penalize it for leaving galloping mode */
1560 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001561 }
1562Succeed:
1563 result = 0;
1564Fail:
1565 if (nb)
1566 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1567 return result;
1568CopyA:
1569 assert(nb == 1 && na > 0);
1570 /* The first element of pb belongs at the front of the merge. */
1571 dest -= na;
1572 pa -= na;
1573 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1574 *dest = *pb;
1575 return 0;
1576}
1577
1578/* Merge the two runs at stack indices i and i+1.
1579 * Returns 0 on success, -1 on error.
1580 */
1581static int
1582merge_at(MergeState *ms, int i)
1583{
1584 PyObject **pa, **pb;
1585 int na, nb;
1586 int k;
1587 PyObject *compare;
1588
1589 assert(ms != NULL);
1590 assert(ms->n >= 2);
1591 assert(i >= 0);
1592 assert(i == ms->n - 2 || i == ms->n - 3);
1593
Tim Peterse05f65a2002-08-10 05:21:15 +00001594 pa = ms->pending[i].base;
1595 na = ms->pending[i].len;
1596 pb = ms->pending[i+1].base;
1597 nb = ms->pending[i+1].len;
Tim Petersa64dc242002-08-01 02:13:36 +00001598 assert(na > 0 && nb > 0);
1599 assert(pa + na == pb);
1600
1601 /* Record the length of the combined runs; if i is the 3rd-last
1602 * run now, also slide over the last run (which isn't involved
1603 * in this merge). The current run i+1 goes away in any case.
1604 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001605 ms->pending[i].len = na + nb;
1606 if (i == ms->n - 3)
1607 ms->pending[i+1] = ms->pending[i+2];
Tim Petersa64dc242002-08-01 02:13:36 +00001608 --ms->n;
1609
1610 /* Where does b start in a? Elements in a before that can be
1611 * ignored (already in place).
1612 */
1613 compare = ms->compare;
1614 k = gallop_right(*pb, pa, na, 0, compare);
1615 if (k < 0)
1616 return -1;
1617 pa += k;
1618 na -= k;
1619 if (na == 0)
1620 return 0;
1621
1622 /* Where does a end in b? Elements in b after that can be
1623 * ignored (already in place).
1624 */
1625 nb = gallop_left(pa[na-1], pb, nb, nb-1, compare);
1626 if (nb <= 0)
1627 return nb;
1628
1629 /* Merge what remains of the runs, using a temp array with
1630 * min(na, nb) elements.
1631 */
1632 if (na <= nb)
1633 return merge_lo(ms, pa, na, pb, nb);
1634 else
1635 return merge_hi(ms, pa, na, pb, nb);
1636}
1637
1638/* Examine the stack of runs waiting to be merged, merging adjacent runs
1639 * until the stack invariants are re-established:
1640 *
1641 * 1. len[-3] > len[-2] + len[-1]
1642 * 2. len[-2] > len[-1]
1643 *
1644 * See listsort.txt for more info.
1645 *
1646 * Returns 0 on success, -1 on error.
1647 */
1648static int
1649merge_collapse(MergeState *ms)
1650{
Tim Peterse05f65a2002-08-10 05:21:15 +00001651 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001652
1653 assert(ms);
1654 while (ms->n > 1) {
1655 int n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001656 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1657 if (p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001658 --n;
1659 if (merge_at(ms, n) < 0)
1660 return -1;
1661 }
Tim Peterse05f65a2002-08-10 05:21:15 +00001662 else if (p[n].len <= p[n+1].len) {
Tim Petersa64dc242002-08-01 02:13:36 +00001663 if (merge_at(ms, n) < 0)
1664 return -1;
1665 }
1666 else
1667 break;
1668 }
1669 return 0;
1670}
1671
1672/* Regardless of invariants, merge all runs on the stack until only one
1673 * remains. This is used at the end of the mergesort.
1674 *
1675 * Returns 0 on success, -1 on error.
1676 */
1677static int
1678merge_force_collapse(MergeState *ms)
1679{
Tim Peterse05f65a2002-08-10 05:21:15 +00001680 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001681
1682 assert(ms);
1683 while (ms->n > 1) {
1684 int n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001685 if (n > 0 && p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001686 --n;
1687 if (merge_at(ms, n) < 0)
1688 return -1;
1689 }
1690 return 0;
1691}
1692
1693/* Compute a good value for the minimum run length; natural runs shorter
1694 * than this are boosted artificially via binary insertion.
1695 *
1696 * If n < 64, return n (it's too small to bother with fancy stuff).
1697 * Else if n is an exact power of 2, return 32.
1698 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1699 * strictly less than, an exact power of 2.
1700 *
1701 * See listsort.txt for more info.
1702 */
1703static int
1704merge_compute_minrun(int n)
1705{
1706 int r = 0; /* becomes 1 if any 1 bits are shifted off */
1707
1708 assert(n >= 0);
1709 while (n >= 64) {
1710 r |= n & 1;
1711 n >>= 1;
1712 }
1713 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001714}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001715
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001716/* Special wrapper to support stable sorting using the decorate-sort-undecorate
1717 pattern. Holds a key which is used for comparisions and the original record
1718 which is returned during the undecorate phase. By exposing only the key
1719 during comparisons, the underlying sort stability characteristics are left
1720 unchanged. Also, if a custom comparison function is used, it will only see
1721 the key instead of a full record. */
1722
1723typedef struct {
1724 PyObject_HEAD
1725 PyObject *key;
1726 PyObject *value;
1727} sortwrapperobject;
1728
1729static PyTypeObject sortwrapper_type;
1730
1731static PyObject *
1732sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
1733{
1734 if (!PyObject_TypeCheck(b, &sortwrapper_type)) {
1735 PyErr_SetString(PyExc_TypeError,
1736 "expected a sortwrapperobject");
1737 return NULL;
1738 }
1739 return PyObject_RichCompare(a->key, b->key, op);
1740}
1741
1742static void
1743sortwrapper_dealloc(sortwrapperobject *so)
1744{
1745 Py_XDECREF(so->key);
1746 Py_XDECREF(so->value);
1747 PyObject_Del(so);
1748}
1749
1750PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
1751
1752static PyTypeObject sortwrapper_type = {
1753 PyObject_HEAD_INIT(&PyType_Type)
1754 0, /* ob_size */
1755 "sortwrapper", /* tp_name */
1756 sizeof(sortwrapperobject), /* tp_basicsize */
1757 0, /* tp_itemsize */
1758 /* methods */
1759 (destructor)sortwrapper_dealloc, /* tp_dealloc */
1760 0, /* tp_print */
1761 0, /* tp_getattr */
1762 0, /* tp_setattr */
1763 0, /* tp_compare */
1764 0, /* tp_repr */
1765 0, /* tp_as_number */
1766 0, /* tp_as_sequence */
1767 0, /* tp_as_mapping */
1768 0, /* tp_hash */
1769 0, /* tp_call */
1770 0, /* tp_str */
1771 PyObject_GenericGetAttr, /* tp_getattro */
1772 0, /* tp_setattro */
1773 0, /* tp_as_buffer */
1774 Py_TPFLAGS_DEFAULT |
1775 Py_TPFLAGS_HAVE_RICHCOMPARE, /* tp_flags */
1776 sortwrapper_doc, /* tp_doc */
1777 0, /* tp_traverse */
1778 0, /* tp_clear */
1779 (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
1780};
1781
1782/* Returns a new reference to a sortwrapper.
1783 Consumes the references to the two underlying objects. */
1784
1785static PyObject *
1786build_sortwrapper(PyObject *key, PyObject *value)
1787{
1788 sortwrapperobject *so;
1789
1790 so = PyObject_New(sortwrapperobject, &sortwrapper_type);
1791 if (so == NULL)
1792 return NULL;
1793 so->key = key;
1794 so->value = value;
1795 return (PyObject *)so;
1796}
1797
1798/* Returns a new reference to the value underlying the wrapper. */
1799static PyObject *
1800sortwrapper_getvalue(PyObject *so)
1801{
1802 PyObject *value;
1803
1804 if (!PyObject_TypeCheck(so, &sortwrapper_type)) {
1805 PyErr_SetString(PyExc_TypeError,
1806 "expected a sortwrapperobject");
1807 return NULL;
1808 }
1809 value = ((sortwrapperobject *)so)->value;
1810 Py_INCREF(value);
1811 return value;
1812}
1813
1814/* Wrapper for user specified cmp functions in combination with a
1815 specified key function. Makes sure the cmp function is presented
1816 with the actual key instead of the sortwrapper */
1817
1818typedef struct {
1819 PyObject_HEAD
1820 PyObject *func;
1821} cmpwrapperobject;
1822
1823static void
1824cmpwrapper_dealloc(cmpwrapperobject *co)
1825{
1826 Py_XDECREF(co->func);
1827 PyObject_Del(co);
1828}
1829
1830static PyObject *
1831cmpwrapper_call(cmpwrapperobject *co, PyObject *args, PyObject *kwds)
1832{
1833 PyObject *x, *y, *xx, *yy;
1834
1835 if (!PyArg_UnpackTuple(args, "", 2, 2, &x, &y))
1836 return NULL;
1837 if (!PyObject_TypeCheck(x, &sortwrapper_type) ||
Raymond Hettingerae4a2992003-10-16 17:16:30 +00001838 !PyObject_TypeCheck(y, &sortwrapper_type)) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001839 PyErr_SetString(PyExc_TypeError,
1840 "expected a sortwrapperobject");
1841 return NULL;
1842 }
1843 xx = ((sortwrapperobject *)x)->key;
1844 yy = ((sortwrapperobject *)y)->key;
1845 return PyObject_CallFunctionObjArgs(co->func, xx, yy, NULL);
1846}
1847
1848PyDoc_STRVAR(cmpwrapper_doc, "cmp() wrapper for sort with custom keys.");
1849
1850static PyTypeObject cmpwrapper_type = {
1851 PyObject_HEAD_INIT(&PyType_Type)
1852 0, /* ob_size */
1853 "cmpwrapper", /* tp_name */
1854 sizeof(cmpwrapperobject), /* tp_basicsize */
1855 0, /* tp_itemsize */
1856 /* methods */
1857 (destructor)cmpwrapper_dealloc, /* tp_dealloc */
1858 0, /* tp_print */
1859 0, /* tp_getattr */
1860 0, /* tp_setattr */
1861 0, /* tp_compare */
1862 0, /* tp_repr */
1863 0, /* tp_as_number */
1864 0, /* tp_as_sequence */
1865 0, /* tp_as_mapping */
1866 0, /* tp_hash */
1867 (ternaryfunc)cmpwrapper_call, /* tp_call */
1868 0, /* tp_str */
1869 PyObject_GenericGetAttr, /* tp_getattro */
1870 0, /* tp_setattro */
1871 0, /* tp_as_buffer */
1872 Py_TPFLAGS_DEFAULT, /* tp_flags */
1873 cmpwrapper_doc, /* tp_doc */
1874};
1875
1876static PyObject *
1877build_cmpwrapper(PyObject *cmpfunc)
1878{
1879 cmpwrapperobject *co;
1880
1881 co = PyObject_New(cmpwrapperobject, &cmpwrapper_type);
1882 if (co == NULL)
1883 return NULL;
1884 Py_INCREF(cmpfunc);
1885 co->func = cmpfunc;
1886 return (PyObject *)co;
1887}
1888
Tim Petersa64dc242002-08-01 02:13:36 +00001889/* An adaptive, stable, natural mergesort. See listsort.txt.
1890 * Returns Py_None on success, NULL on error. Even in case of error, the
1891 * list will be some permutation of its input state (nothing is lost or
1892 * duplicated).
1893 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001894static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001895listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001896{
Tim Petersa64dc242002-08-01 02:13:36 +00001897 MergeState ms;
1898 PyObject **lo, **hi;
1899 int nremaining;
1900 int minrun;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001901 int saved_ob_size, saved_allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00001902 PyObject **saved_ob_item;
1903 PyObject **empty_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001904 PyObject *compare = NULL;
1905 PyObject *result = NULL; /* guilty until proved innocent */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001906 int reverse = 0;
1907 PyObject *keyfunc = NULL;
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001908 int i;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001909 PyObject *key, *value, *kvpair;
1910 static char *kwlist[] = {"cmp", "key", "reverse", 0};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001911
Tim Petersa64dc242002-08-01 02:13:36 +00001912 assert(self != NULL);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001913 assert (PyList_Check(self));
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001914 if (args != NULL) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001915 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:sort",
1916 kwlist, &compare, &keyfunc, &reverse))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001917 return NULL;
1918 }
Skip Montanaro4abd5f02003-01-02 20:51:08 +00001919 if (compare == Py_None)
1920 compare = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001921 if (keyfunc == Py_None)
1922 keyfunc = NULL;
1923 if (compare != NULL && keyfunc != NULL) {
1924 compare = build_cmpwrapper(compare);
1925 if (compare == NULL)
Hye-Shik Chang19cb1932003-12-10 07:31:08 +00001926 return NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001927 } else
1928 Py_XINCREF(compare);
1929
Tim Petersb9099c32002-11-12 22:08:10 +00001930 /* The list is temporarily made empty, so that mutations performed
1931 * by comparison functions can't affect the slice of memory we're
1932 * sorting (allowing mutations during sorting is a core-dump
1933 * factory, since ob_item may change).
1934 */
1935 saved_ob_size = self->ob_size;
1936 saved_ob_item = self->ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001937 saved_allocated = self->allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00001938 self->ob_size = 0;
Tim Peters7049d812004-01-18 20:31:02 +00001939 self->ob_item = empty_ob_item = PyMem_NEW(PyObject *, 0);
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001940 self->allocated = 0;
Tim Peters330f9e92002-07-19 07:05:44 +00001941
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001942 if (keyfunc != NULL) {
1943 for (i=0 ; i < saved_ob_size ; i++) {
1944 value = saved_ob_item[i];
1945 key = PyObject_CallFunctionObjArgs(keyfunc, value,
1946 NULL);
1947 if (key == NULL) {
1948 for (i=i-1 ; i>=0 ; i--) {
1949 kvpair = saved_ob_item[i];
1950 value = sortwrapper_getvalue(kvpair);
1951 saved_ob_item[i] = value;
1952 Py_DECREF(kvpair);
1953 }
1954 if (self->ob_item != empty_ob_item
1955 || self->ob_size) {
1956 /* If the list changed *as well* we
1957 have two errors. We let the first
1958 one "win", but we shouldn't let
1959 what's in the list currently
1960 leak. */
1961 (void)list_ass_slice(
1962 self, 0, self->ob_size,
1963 (PyObject *)NULL);
1964 }
1965
1966 goto dsu_fail;
1967 }
1968 kvpair = build_sortwrapper(key, value);
1969 if (kvpair == NULL)
1970 goto dsu_fail;
1971 saved_ob_item[i] = kvpair;
1972 }
1973 }
1974
1975 /* Reverse sort stability achieved by initially reversing the list,
1976 applying a stable forward sort, then reversing the final result. */
1977 if (reverse && saved_ob_size > 1)
1978 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
1979
1980 merge_init(&ms, compare);
1981
Tim Petersb9099c32002-11-12 22:08:10 +00001982 nremaining = saved_ob_size;
Tim Petersa64dc242002-08-01 02:13:36 +00001983 if (nremaining < 2)
1984 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00001985
Tim Petersa64dc242002-08-01 02:13:36 +00001986 /* March over the array once, left to right, finding natural runs,
1987 * and extending short natural runs to minrun elements.
1988 */
Tim Petersb9099c32002-11-12 22:08:10 +00001989 lo = saved_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001990 hi = lo + nremaining;
1991 minrun = merge_compute_minrun(nremaining);
1992 do {
1993 int descending;
1994 int n;
Tim Peters330f9e92002-07-19 07:05:44 +00001995
Tim Petersa64dc242002-08-01 02:13:36 +00001996 /* Identify next run. */
1997 n = count_run(lo, hi, compare, &descending);
1998 if (n < 0)
1999 goto fail;
2000 if (descending)
2001 reverse_slice(lo, lo + n);
2002 /* If short, extend to min(minrun, nremaining). */
2003 if (n < minrun) {
2004 const int force = nremaining <= minrun ?
2005 nremaining : minrun;
2006 if (binarysort(lo, lo + force, lo + n, compare) < 0)
2007 goto fail;
2008 n = force;
2009 }
2010 /* Push run onto pending-runs stack, and maybe merge. */
2011 assert(ms.n < MAX_MERGE_PENDING);
Tim Peterse05f65a2002-08-10 05:21:15 +00002012 ms.pending[ms.n].base = lo;
2013 ms.pending[ms.n].len = n;
Tim Petersa64dc242002-08-01 02:13:36 +00002014 ++ms.n;
2015 if (merge_collapse(&ms) < 0)
2016 goto fail;
2017 /* Advance to find next run. */
2018 lo += n;
2019 nremaining -= n;
2020 } while (nremaining);
2021 assert(lo == hi);
Tim Peters330f9e92002-07-19 07:05:44 +00002022
Tim Petersa64dc242002-08-01 02:13:36 +00002023 if (merge_force_collapse(&ms) < 0)
2024 goto fail;
2025 assert(ms.n == 1);
Tim Petersb9099c32002-11-12 22:08:10 +00002026 assert(ms.pending[0].base == saved_ob_item);
2027 assert(ms.pending[0].len == saved_ob_size);
Tim Petersa64dc242002-08-01 02:13:36 +00002028
2029succeed:
2030 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002031fail:
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002032 if (keyfunc != NULL) {
2033 for (i=0 ; i < saved_ob_size ; i++) {
2034 kvpair = saved_ob_item[i];
2035 value = sortwrapper_getvalue(kvpair);
2036 saved_ob_item[i] = value;
2037 Py_DECREF(kvpair);
2038 }
2039 }
2040
Tim Petersb9099c32002-11-12 22:08:10 +00002041 if (self->ob_item != empty_ob_item || self->ob_size) {
2042 /* The user mucked with the list during the sort. */
2043 (void)list_ass_slice(self, 0, self->ob_size, (PyObject *)NULL);
2044 if (result != NULL) {
2045 PyErr_SetString(PyExc_ValueError,
2046 "list modified during sort");
2047 result = NULL;
2048 }
2049 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002050
2051 if (reverse && saved_ob_size > 1)
2052 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2053
2054 merge_freemem(&ms);
2055
2056dsu_fail:
Tim Petersb9099c32002-11-12 22:08:10 +00002057 if (self->ob_item == empty_ob_item)
2058 PyMem_FREE(empty_ob_item);
2059 self->ob_size = saved_ob_size;
2060 self->ob_item = saved_ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002061 self->allocated = saved_allocated;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002062 Py_XDECREF(compare);
Tim Petersa64dc242002-08-01 02:13:36 +00002063 Py_XINCREF(result);
2064 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002065}
Tim Peters330f9e92002-07-19 07:05:44 +00002066#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002067#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002068
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002069int
Fred Drakea2f55112000-07-09 15:16:51 +00002070PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002071{
2072 if (v == NULL || !PyList_Check(v)) {
2073 PyErr_BadInternalCall();
2074 return -1;
2075 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002076 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002077 if (v == NULL)
2078 return -1;
2079 Py_DECREF(v);
2080 return 0;
2081}
2082
Guido van Rossumb86c5492001-02-12 22:06:02 +00002083static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002084listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002085{
Tim Peters326b4482002-07-19 04:04:16 +00002086 if (self->ob_size > 1)
2087 reverse_slice(self->ob_item, self->ob_item + self->ob_size);
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002088 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002089}
2090
Guido van Rossum84c76f51990-10-30 13:32:20 +00002091int
Fred Drakea2f55112000-07-09 15:16:51 +00002092PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002093{
Tim Peters6063e262002-08-08 01:06:39 +00002094 PyListObject *self = (PyListObject *)v;
2095
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002096 if (v == NULL || !PyList_Check(v)) {
2097 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002098 return -1;
2099 }
Tim Peters6063e262002-08-08 01:06:39 +00002100 if (self->ob_size > 1)
2101 reverse_slice(self->ob_item, self->ob_item + self->ob_size);
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002102 return 0;
2103}
2104
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002105PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002106PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002107{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002108 PyObject *w;
2109 PyObject **p;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002110 int n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002111 if (v == NULL || !PyList_Check(v)) {
2112 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002113 return NULL;
2114 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002115 n = ((PyListObject *)v)->ob_size;
2116 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002117 if (w == NULL)
2118 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002119 p = ((PyTupleObject *)w)->ob_item;
Thomas Wouters334fb892000-07-25 12:56:38 +00002120 memcpy((void *)p,
2121 (void *)((PyListObject *)v)->ob_item,
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002122 n*sizeof(PyObject *));
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002123 while (--n >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002124 Py_INCREF(*p);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002125 p++;
2126 }
2127 return w;
2128}
2129
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002130static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002131listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002132{
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002133 int i, start=0, stop=self->ob_size;
2134 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002135
Walter Dörwalde8049bef2003-06-17 19:27:39 +00002136 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2137 _PyEval_SliceIndex, &start,
2138 _PyEval_SliceIndex, &stop))
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002139 return NULL;
Guido van Rossum2743d872003-06-17 14:25:14 +00002140 if (start < 0) {
2141 start += self->ob_size;
2142 if (start < 0)
2143 start = 0;
2144 }
2145 if (stop < 0) {
2146 stop += self->ob_size;
2147 if (stop < 0)
2148 stop = 0;
2149 }
2150 else if (stop > self->ob_size)
2151 stop = self->ob_size;
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002152 for (i = start; i < stop; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002153 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2154 if (cmp > 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002155 return PyInt_FromLong((long)i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002156 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002157 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002158 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002159 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002160 return NULL;
2161}
2162
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002163static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002164listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002165{
2166 int count = 0;
2167 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002168
Guido van Rossume6f7d181991-10-20 20:20:40 +00002169 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002170 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2171 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002172 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002173 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002174 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00002175 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002176 return PyInt_FromLong((long)count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002177}
2178
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002179static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002180listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002181{
2182 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002183
Guido van Rossumed98d481991-03-06 13:07:53 +00002184 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002185 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2186 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002187 if (list_ass_slice(self, i, i+1,
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002188 (PyObject *)NULL) == 0)
2189 Py_RETURN_NONE;
2190 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002191 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002192 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002193 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002194 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002195 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002196 return NULL;
2197}
2198
Jeremy Hylton8caad492000-06-23 14:18:11 +00002199static int
2200list_traverse(PyListObject *o, visitproc visit, void *arg)
2201{
2202 int i, err;
2203 PyObject *x;
2204
2205 for (i = o->ob_size; --i >= 0; ) {
2206 x = o->ob_item[i];
2207 if (x != NULL) {
2208 err = visit(x, arg);
2209 if (err)
2210 return err;
2211 }
2212 }
2213 return 0;
2214}
2215
2216static int
2217list_clear(PyListObject *lp)
2218{
2219 (void) PyList_SetSlice((PyObject *)lp, 0, lp->ob_size, 0);
2220 return 0;
2221}
2222
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002223static PyObject *
2224list_richcompare(PyObject *v, PyObject *w, int op)
2225{
2226 PyListObject *vl, *wl;
2227 int i;
2228
2229 if (!PyList_Check(v) || !PyList_Check(w)) {
2230 Py_INCREF(Py_NotImplemented);
2231 return Py_NotImplemented;
2232 }
2233
2234 vl = (PyListObject *)v;
2235 wl = (PyListObject *)w;
2236
2237 if (vl->ob_size != wl->ob_size && (op == Py_EQ || op == Py_NE)) {
2238 /* Shortcut: if the lengths differ, the lists differ */
2239 PyObject *res;
2240 if (op == Py_EQ)
2241 res = Py_False;
2242 else
2243 res = Py_True;
2244 Py_INCREF(res);
2245 return res;
2246 }
2247
2248 /* Search for the first index where items are different */
2249 for (i = 0; i < vl->ob_size && i < wl->ob_size; i++) {
2250 int k = PyObject_RichCompareBool(vl->ob_item[i],
2251 wl->ob_item[i], Py_EQ);
2252 if (k < 0)
2253 return NULL;
2254 if (!k)
2255 break;
2256 }
2257
2258 if (i >= vl->ob_size || i >= wl->ob_size) {
2259 /* No more items to compare -- compare sizes */
2260 int vs = vl->ob_size;
2261 int ws = wl->ob_size;
2262 int cmp;
2263 PyObject *res;
2264 switch (op) {
2265 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00002266 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002267 case Py_EQ: cmp = vs == ws; break;
2268 case Py_NE: cmp = vs != ws; break;
2269 case Py_GT: cmp = vs > ws; break;
2270 case Py_GE: cmp = vs >= ws; break;
2271 default: return NULL; /* cannot happen */
2272 }
2273 if (cmp)
2274 res = Py_True;
2275 else
2276 res = Py_False;
2277 Py_INCREF(res);
2278 return res;
2279 }
2280
2281 /* We have an item that differs -- shortcuts for EQ/NE */
2282 if (op == Py_EQ) {
2283 Py_INCREF(Py_False);
2284 return Py_False;
2285 }
2286 if (op == Py_NE) {
2287 Py_INCREF(Py_True);
2288 return Py_True;
2289 }
2290
2291 /* Compare the final item again using the proper operator */
2292 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
2293}
2294
Tim Peters6d6c1a32001-08-02 04:15:00 +00002295static int
2296list_init(PyListObject *self, PyObject *args, PyObject *kw)
2297{
2298 PyObject *arg = NULL;
2299 static char *kwlist[] = {"sequence", 0};
2300
2301 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2302 return -1;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002303 /* Empty previous contents */
2304 if (self->ob_size != 0) {
2305 if (list_ass_slice(self, 0, self->ob_size, (PyObject *)NULL) != 0)
2306 return -1;
2307 }
2308 if (arg != NULL) {
2309 PyObject *rv = listextend(self, arg);
2310 if (rv == NULL)
2311 return -1;
2312 Py_DECREF(rv);
2313 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002314 return 0;
2315}
2316
Guido van Rossumdbb53d92001-12-03 16:32:18 +00002317static long
2318list_nohash(PyObject *self)
2319{
2320 PyErr_SetString(PyExc_TypeError, "list objects are unhashable");
2321 return -1;
2322}
2323
Raymond Hettinger1021c442003-11-07 15:38:09 +00002324static PyObject *list_iter(PyObject *seq);
2325static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2326
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002327PyDoc_STRVAR(getitem_doc,
2328"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002329PyDoc_STRVAR(reversed_doc,
2330"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002331PyDoc_STRVAR(append_doc,
2332"L.append(object) -- append object to end");
2333PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002334"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002335PyDoc_STRVAR(insert_doc,
2336"L.insert(index, object) -- insert object before index");
2337PyDoc_STRVAR(pop_doc,
2338"L.pop([index]) -> item -- remove and return item at index (default last)");
2339PyDoc_STRVAR(remove_doc,
2340"L.remove(value) -- remove first occurrence of value");
2341PyDoc_STRVAR(index_doc,
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002342"L.index(value, [start, [stop]]) -> integer -- return first index of value");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002343PyDoc_STRVAR(count_doc,
2344"L.count(value) -> integer -- return number of occurrences of value");
2345PyDoc_STRVAR(reverse_doc,
2346"L.reverse() -- reverse *IN PLACE*");
2347PyDoc_STRVAR(sort_doc,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002348"L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n\
2349cmp(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002350
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002351static PyObject *list_subscript(PyListObject*, PyObject*);
2352
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002353static PyMethodDef list_methods[] = {
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002354 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
Raymond Hettinger1021c442003-11-07 15:38:09 +00002355 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002356 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002357 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002358 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002359 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002360 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002361 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002362 {"count", (PyCFunction)listcount, METH_O, count_doc},
2363 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002364 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
Tim Petersa64dc242002-08-01 02:13:36 +00002365 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002366};
2367
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002368static PySequenceMethods list_as_sequence = {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002369 (inquiry)list_length, /* sq_length */
2370 (binaryfunc)list_concat, /* sq_concat */
2371 (intargfunc)list_repeat, /* sq_repeat */
2372 (intargfunc)list_item, /* sq_item */
2373 (intintargfunc)list_slice, /* sq_slice */
2374 (intobjargproc)list_ass_item, /* sq_ass_item */
2375 (intintobjargproc)list_ass_slice, /* sq_ass_slice */
2376 (objobjproc)list_contains, /* sq_contains */
2377 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2378 (intargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002379};
2380
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002381PyDoc_STRVAR(list_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002382"list() -> new list\n"
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002383"list(sequence) -> new list initialized from sequence's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002384
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002385static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002386list_subscript(PyListObject* self, PyObject* item)
2387{
2388 if (PyInt_Check(item)) {
2389 long i = PyInt_AS_LONG(item);
2390 if (i < 0)
2391 i += PyList_GET_SIZE(self);
2392 return list_item(self, i);
2393 }
2394 else if (PyLong_Check(item)) {
2395 long i = PyLong_AsLong(item);
2396 if (i == -1 && PyErr_Occurred())
2397 return NULL;
2398 if (i < 0)
2399 i += PyList_GET_SIZE(self);
2400 return list_item(self, i);
2401 }
2402 else if (PySlice_Check(item)) {
2403 int start, stop, step, slicelength, cur, i;
2404 PyObject* result;
2405 PyObject* it;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002406 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002407
2408 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
2409 &start, &stop, &step, &slicelength) < 0) {
2410 return NULL;
2411 }
2412
2413 if (slicelength <= 0) {
2414 return PyList_New(0);
2415 }
2416 else {
2417 result = PyList_New(slicelength);
2418 if (!result) return NULL;
2419
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002420 src = self->ob_item;
2421 dest = ((PyListObject *)result)->ob_item;
Tim Peters3b01a122002-07-19 02:35:45 +00002422 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002423 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002424 it = src[cur];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002425 Py_INCREF(it);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002426 dest[i] = it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002427 }
Tim Peters3b01a122002-07-19 02:35:45 +00002428
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002429 return result;
2430 }
2431 }
2432 else {
2433 PyErr_SetString(PyExc_TypeError,
2434 "list indices must be integers");
2435 return NULL;
2436 }
2437}
2438
Tim Peters3b01a122002-07-19 02:35:45 +00002439static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002440list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2441{
2442 if (PyInt_Check(item)) {
2443 long i = PyInt_AS_LONG(item);
2444 if (i < 0)
2445 i += PyList_GET_SIZE(self);
2446 return list_ass_item(self, i, value);
2447 }
2448 else if (PyLong_Check(item)) {
2449 long i = PyLong_AsLong(item);
2450 if (i == -1 && PyErr_Occurred())
2451 return -1;
2452 if (i < 0)
2453 i += PyList_GET_SIZE(self);
2454 return list_ass_item(self, i, value);
2455 }
2456 else if (PySlice_Check(item)) {
2457 int start, stop, step, slicelength;
2458
2459 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
2460 &start, &stop, &step, &slicelength) < 0) {
2461 return -1;
2462 }
2463
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002464 /* treat L[slice(a,b)] = v _exactly_ like L[a:b] = v */
2465 if (step == 1 && ((PySliceObject*)item)->step == Py_None)
2466 return list_ass_slice(self, start, stop, value);
2467
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002468 if (value == NULL) {
2469 /* delete slice */
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002470 PyObject **garbage;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002471 int cur, i;
Tim Peters3b01a122002-07-19 02:35:45 +00002472
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002473 if (slicelength <= 0)
2474 return 0;
2475
2476 if (step < 0) {
2477 stop = start + 1;
2478 start = stop + step*(slicelength - 1) - 1;
2479 step = -step;
2480 }
2481
2482 garbage = (PyObject**)
2483 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Tim Peters3b01a122002-07-19 02:35:45 +00002484
2485 /* drawing pictures might help
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002486 understand these for loops */
Guido van Rossum75a20b12002-06-11 12:22:28 +00002487 for (cur = start, i = 0;
2488 cur < stop;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002489 cur += step, i++) {
2490 int lim = step;
2491
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002492 garbage[i] = PyList_GET_ITEM(self, cur);
2493
Michael W. Hudson56796f62002-07-29 14:35:04 +00002494 if (cur + step >= self->ob_size) {
2495 lim = self->ob_size - cur - 1;
2496 }
2497
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002498 memmove(self->ob_item + cur - i,
2499 self->ob_item + cur + 1,
2500 lim * sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002501 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002502
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002503 for (cur = start + slicelength*step + 1;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002504 cur < self->ob_size; cur++) {
2505 PyList_SET_ITEM(self, cur - slicelength,
2506 PyList_GET_ITEM(self, cur));
2507 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002508
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002509 self->ob_size -= slicelength;
Raymond Hettingerd4ff7412004-03-15 09:01:31 +00002510 list_resize(self, self->ob_size);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002511
2512 for (i = 0; i < slicelength; i++) {
2513 Py_DECREF(garbage[i]);
2514 }
2515 PyMem_FREE(garbage);
2516
2517 return 0;
2518 }
2519 else {
2520 /* assign slice */
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002521 PyObject **garbage, *ins, *seq, **seqitems, **selfitems;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002522 int cur, i;
2523
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002524 /* protect against a[::-1] = a */
Tim Peters3b01a122002-07-19 02:35:45 +00002525 if (self == (PyListObject*)value) {
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002526 seq = list_slice((PyListObject*)value, 0,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002527 PyList_GET_SIZE(value));
Tim Peters3b01a122002-07-19 02:35:45 +00002528 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002529 else {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002530 seq = PySequence_Fast(value,
2531 "must assign iterable to extended slice");
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002532 if (!seq)
2533 return -1;
2534 }
2535
2536 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2537 PyErr_Format(PyExc_ValueError,
2538 "attempt to assign sequence of size %d to extended slice of size %d",
2539 PySequence_Fast_GET_SIZE(seq),
2540 slicelength);
2541 Py_DECREF(seq);
2542 return -1;
2543 }
2544
2545 if (!slicelength) {
2546 Py_DECREF(seq);
2547 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002548 }
2549
2550 garbage = (PyObject**)
2551 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Tim Peters3b01a122002-07-19 02:35:45 +00002552
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002553 selfitems = self->ob_item;
Raymond Hettinger42bec932004-03-12 16:38:17 +00002554 seqitems = PySequence_Fast_ITEMS(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002555 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002556 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002557 garbage[i] = selfitems[cur];
2558 ins = seqitems[i];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002559 Py_INCREF(ins);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002560 selfitems[cur] = ins;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002561 }
2562
2563 for (i = 0; i < slicelength; i++) {
2564 Py_DECREF(garbage[i]);
2565 }
Tim Peters3b01a122002-07-19 02:35:45 +00002566
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002567 PyMem_FREE(garbage);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002568 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002569
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002570 return 0;
2571 }
Tim Peters3b01a122002-07-19 02:35:45 +00002572 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002573 else {
Tim Peters3b01a122002-07-19 02:35:45 +00002574 PyErr_SetString(PyExc_TypeError,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002575 "list indices must be integers");
2576 return -1;
2577 }
2578}
2579
2580static PyMappingMethods list_as_mapping = {
2581 (inquiry)list_length,
2582 (binaryfunc)list_subscript,
2583 (objobjargproc)list_ass_subscript
2584};
2585
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002586PyTypeObject PyList_Type = {
2587 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002588 0,
2589 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002590 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002591 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002592 (destructor)list_dealloc, /* tp_dealloc */
2593 (printfunc)list_print, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002594 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002595 0, /* tp_setattr */
2596 0, /* tp_compare */
2597 (reprfunc)list_repr, /* tp_repr */
2598 0, /* tp_as_number */
2599 &list_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002600 &list_as_mapping, /* tp_as_mapping */
Guido van Rossumdbb53d92001-12-03 16:32:18 +00002601 list_nohash, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002602 0, /* tp_call */
2603 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002604 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002605 0, /* tp_setattro */
2606 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002607 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Tim Peters6d6c1a32001-08-02 04:15:00 +00002608 Py_TPFLAGS_BASETYPE, /* tp_flags */
2609 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002610 (traverseproc)list_traverse, /* tp_traverse */
2611 (inquiry)list_clear, /* tp_clear */
2612 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002613 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002614 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002615 0, /* tp_iternext */
2616 list_methods, /* tp_methods */
2617 0, /* tp_members */
2618 0, /* tp_getset */
2619 0, /* tp_base */
2620 0, /* tp_dict */
2621 0, /* tp_descr_get */
2622 0, /* tp_descr_set */
2623 0, /* tp_dictoffset */
2624 (initproc)list_init, /* tp_init */
2625 PyType_GenericAlloc, /* tp_alloc */
2626 PyType_GenericNew, /* tp_new */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002627 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002628};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002629
2630
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002631/*********************** List Iterator **************************/
2632
2633typedef struct {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002634 PyObject_HEAD
2635 long it_index;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002636 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002637} listiterobject;
2638
2639PyTypeObject PyListIter_Type;
2640
Guido van Rossum5086e492002-07-16 15:56:52 +00002641static PyObject *
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002642list_iter(PyObject *seq)
2643{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002644 listiterobject *it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002645
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002646 if (!PyList_Check(seq)) {
2647 PyErr_BadInternalCall();
2648 return NULL;
2649 }
2650 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2651 if (it == NULL)
2652 return NULL;
2653 it->it_index = 0;
2654 Py_INCREF(seq);
2655 it->it_seq = (PyListObject *)seq;
2656 _PyObject_GC_TRACK(it);
2657 return (PyObject *)it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002658}
2659
2660static void
2661listiter_dealloc(listiterobject *it)
2662{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002663 _PyObject_GC_UNTRACK(it);
Guido van Rossum86103ae2002-07-16 20:07:32 +00002664 Py_XDECREF(it->it_seq);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002665 PyObject_GC_Del(it);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002666}
2667
2668static int
2669listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2670{
Guido van Rossum86103ae2002-07-16 20:07:32 +00002671 if (it->it_seq == NULL)
2672 return 0;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002673 return visit((PyObject *)it->it_seq, arg);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002674}
2675
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002676static PyObject *
Tim Peters93b2cc42002-06-01 05:22:55 +00002677listiter_next(listiterobject *it)
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002678{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002679 PyListObject *seq;
2680 PyObject *item;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002681
Tim Peters93b2cc42002-06-01 05:22:55 +00002682 assert(it != NULL);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002683 seq = it->it_seq;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002684 if (seq == NULL)
2685 return NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002686 assert(PyList_Check(seq));
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002687
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002688 if (it->it_index < PyList_GET_SIZE(seq)) {
Tim Peters93b2cc42002-06-01 05:22:55 +00002689 item = PyList_GET_ITEM(seq, it->it_index);
2690 ++it->it_index;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002691 Py_INCREF(item);
2692 return item;
2693 }
Guido van Rossum86103ae2002-07-16 20:07:32 +00002694
2695 Py_DECREF(seq);
2696 it->it_seq = NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002697 return NULL;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002698}
2699
Raymond Hettinger435bf582004-03-18 22:43:10 +00002700static int
2701listiter_len(listiterobject *it)
2702{
Raymond Hettinger40a03822004-04-12 13:05:09 +00002703 int len;
2704 if (it->it_seq) {
2705 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2706 if (len >= 0)
2707 return len;
2708 }
Raymond Hettinger435bf582004-03-18 22:43:10 +00002709 return 0;
2710}
2711
2712static PySequenceMethods listiter_as_sequence = {
2713 (inquiry)listiter_len, /* sq_length */
2714 0, /* sq_concat */
2715};
2716
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002717PyTypeObject PyListIter_Type = {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002718 PyObject_HEAD_INIT(&PyType_Type)
2719 0, /* ob_size */
2720 "listiterator", /* tp_name */
2721 sizeof(listiterobject), /* tp_basicsize */
2722 0, /* tp_itemsize */
2723 /* methods */
2724 (destructor)listiter_dealloc, /* tp_dealloc */
2725 0, /* tp_print */
2726 0, /* tp_getattr */
2727 0, /* tp_setattr */
2728 0, /* tp_compare */
2729 0, /* tp_repr */
2730 0, /* tp_as_number */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002731 &listiter_as_sequence, /* tp_as_sequence */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002732 0, /* tp_as_mapping */
2733 0, /* tp_hash */
2734 0, /* tp_call */
2735 0, /* tp_str */
2736 PyObject_GenericGetAttr, /* tp_getattro */
2737 0, /* tp_setattro */
2738 0, /* tp_as_buffer */
2739 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2740 0, /* tp_doc */
2741 (traverseproc)listiter_traverse, /* tp_traverse */
2742 0, /* tp_clear */
2743 0, /* tp_richcompare */
2744 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00002745 PyObject_SelfIter, /* tp_iter */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002746 (iternextfunc)listiter_next, /* tp_iternext */
Guido van Rossum86103ae2002-07-16 20:07:32 +00002747 0, /* tp_methods */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002748 0, /* tp_members */
2749 0, /* tp_getset */
2750 0, /* tp_base */
2751 0, /* tp_dict */
2752 0, /* tp_descr_get */
2753 0, /* tp_descr_set */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002754};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002755
2756/*********************** List Reverse Iterator **************************/
2757
2758typedef struct {
2759 PyObject_HEAD
2760 long it_index;
Raymond Hettinger001f2282003-11-08 11:58:44 +00002761 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002762} listreviterobject;
2763
2764PyTypeObject PyListRevIter_Type;
2765
2766static PyObject *
2767list_reversed(PyListObject *seq, PyObject *unused)
2768{
2769 listreviterobject *it;
2770
2771 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2772 if (it == NULL)
2773 return NULL;
2774 assert(PyList_Check(seq));
2775 it->it_index = PyList_GET_SIZE(seq) - 1;
2776 Py_INCREF(seq);
2777 it->it_seq = seq;
2778 PyObject_GC_Track(it);
2779 return (PyObject *)it;
2780}
2781
2782static void
2783listreviter_dealloc(listreviterobject *it)
2784{
2785 PyObject_GC_UnTrack(it);
2786 Py_XDECREF(it->it_seq);
2787 PyObject_GC_Del(it);
2788}
2789
2790static int
2791listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2792{
2793 if (it->it_seq == NULL)
2794 return 0;
2795 return visit((PyObject *)it->it_seq, arg);
2796}
2797
2798static PyObject *
2799listreviter_next(listreviterobject *it)
2800{
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002801 PyObject *item;
2802 long index = it->it_index;
2803 PyListObject *seq = it->it_seq;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002804
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002805 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2806 item = PyList_GET_ITEM(seq, index);
Raymond Hettinger1021c442003-11-07 15:38:09 +00002807 it->it_index--;
2808 Py_INCREF(item);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002809 return item;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002810 }
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002811 it->it_index = -1;
2812 if (seq != NULL) {
2813 it->it_seq = NULL;
2814 Py_DECREF(seq);
2815 }
2816 return NULL;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002817}
2818
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002819static int
2820listreviter_len(listreviterobject *it)
2821{
Raymond Hettinger40a03822004-04-12 13:05:09 +00002822 int len = it->it_index + 1;
2823 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
2824 return 0;
2825 return len;
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002826}
2827
2828static PySequenceMethods listreviter_as_sequence = {
2829 (inquiry)listreviter_len, /* sq_length */
2830 0, /* sq_concat */
2831};
2832
Raymond Hettinger1021c442003-11-07 15:38:09 +00002833PyTypeObject PyListRevIter_Type = {
2834 PyObject_HEAD_INIT(&PyType_Type)
2835 0, /* ob_size */
2836 "listreverseiterator", /* tp_name */
2837 sizeof(listreviterobject), /* tp_basicsize */
2838 0, /* tp_itemsize */
2839 /* methods */
2840 (destructor)listreviter_dealloc, /* tp_dealloc */
2841 0, /* tp_print */
2842 0, /* tp_getattr */
2843 0, /* tp_setattr */
2844 0, /* tp_compare */
2845 0, /* tp_repr */
2846 0, /* tp_as_number */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002847 &listreviter_as_sequence, /* tp_as_sequence */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002848 0, /* tp_as_mapping */
2849 0, /* tp_hash */
2850 0, /* tp_call */
2851 0, /* tp_str */
2852 PyObject_GenericGetAttr, /* tp_getattro */
2853 0, /* tp_setattro */
2854 0, /* tp_as_buffer */
2855 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2856 0, /* tp_doc */
2857 (traverseproc)listreviter_traverse, /* tp_traverse */
2858 0, /* tp_clear */
2859 0, /* tp_richcompare */
2860 0, /* tp_weaklistoffset */
2861 PyObject_SelfIter, /* tp_iter */
2862 (iternextfunc)listreviter_next, /* tp_iternext */
2863 0,
2864};