blob: 890c279dbd93ae460e5a245a7e7cf458c4f4b623 [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
183int
Fred Drakea2f55112000-07-09 15:16:51 +0000184PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000185{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000186 if (!PyList_Check(op)) {
187 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000188 return -1;
189 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000190 return ins1((PyListObject *)op,
191 (int) ((PyListObject *)op)->ob_size, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000192}
193
194/* Methods */
195
196static void
Fred Drakea2f55112000-07-09 15:16:51 +0000197list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000198{
199 int i;
Guido van Rossumff413af2002-03-28 20:34:59 +0000200 PyObject_GC_UnTrack(op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000201 Py_TRASHCAN_SAFE_BEGIN(op)
Jack Jansen7874d1f1995-01-19 12:09:27 +0000202 if (op->ob_item != NULL) {
Guido van Rossumfa717011999-06-09 15:19:34 +0000203 /* Do it backwards, for Christian Tismer.
204 There's a simple test case where somehow this reduces
205 thrashing when a *very* large list is created and
206 immediately deleted. */
207 i = op->ob_size;
208 while (--i >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000209 Py_XDECREF(op->ob_item[i]);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000210 }
Guido van Rossumb18618d2000-05-03 23:44:39 +0000211 PyMem_FREE(op->ob_item);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000212 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000213 op->ob_type->tp_free((PyObject *)op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000214 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000215}
216
Guido van Rossum90933611991-06-07 16:10:43 +0000217static int
Fred Drakea2f55112000-07-09 15:16:51 +0000218list_print(PyListObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000219{
220 int i;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000221
222 i = Py_ReprEnter((PyObject*)op);
223 if (i != 0) {
224 if (i < 0)
225 return i;
226 fprintf(fp, "[...]");
227 return 0;
228 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000229 fprintf(fp, "[");
Guido van Rossum90933611991-06-07 16:10:43 +0000230 for (i = 0; i < op->ob_size; i++) {
231 if (i > 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000232 fprintf(fp, ", ");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000233 if (PyObject_Print(op->ob_item[i], fp, 0) != 0) {
234 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000235 return -1;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000236 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000237 }
238 fprintf(fp, "]");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000239 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000240 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000241}
242
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000243static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000244list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000245{
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000246 int i;
Tim Petersa7259592001-06-16 05:11:17 +0000247 PyObject *s, *temp;
248 PyObject *pieces = NULL, *result = NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000249
250 i = Py_ReprEnter((PyObject*)v);
251 if (i != 0) {
Tim Petersa7259592001-06-16 05:11:17 +0000252 return i > 0 ? PyString_FromString("[...]") : NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000253 }
Tim Petersa7259592001-06-16 05:11:17 +0000254
255 if (v->ob_size == 0) {
256 result = PyString_FromString("[]");
257 goto Done;
258 }
259
260 pieces = PyList_New(0);
261 if (pieces == NULL)
262 goto Done;
263
264 /* Do repr() on each element. Note that this may mutate the list,
265 so must refetch the list size on each iteration. */
266 for (i = 0; i < v->ob_size; ++i) {
267 int status;
268 s = PyObject_Repr(v->ob_item[i]);
269 if (s == NULL)
270 goto Done;
271 status = PyList_Append(pieces, s);
272 Py_DECREF(s); /* append created a new ref */
273 if (status < 0)
274 goto Done;
275 }
276
277 /* Add "[]" decorations to the first and last items. */
278 assert(PyList_GET_SIZE(pieces) > 0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000279 s = PyString_FromString("[");
Tim Petersa7259592001-06-16 05:11:17 +0000280 if (s == NULL)
281 goto Done;
282 temp = PyList_GET_ITEM(pieces, 0);
283 PyString_ConcatAndDel(&s, temp);
284 PyList_SET_ITEM(pieces, 0, s);
285 if (s == NULL)
286 goto Done;
287
288 s = PyString_FromString("]");
289 if (s == NULL)
290 goto Done;
291 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
292 PyString_ConcatAndDel(&temp, s);
293 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
294 if (temp == NULL)
295 goto Done;
296
297 /* Paste them all together with ", " between. */
298 s = PyString_FromString(", ");
299 if (s == NULL)
300 goto Done;
301 result = _PyString_Join(s, pieces);
Tim Peters3b01a122002-07-19 02:35:45 +0000302 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +0000303
304Done:
305 Py_XDECREF(pieces);
Guido van Rossumfb376de1998-04-10 22:47:27 +0000306 Py_ReprLeave((PyObject *)v);
Tim Petersa7259592001-06-16 05:11:17 +0000307 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000308}
309
310static int
Fred Drakea2f55112000-07-09 15:16:51 +0000311list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000312{
313 return a->ob_size;
314}
315
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000316static int
Fred Drakea2f55112000-07-09 15:16:51 +0000317list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000318{
Raymond Hettingeraae59992002-09-05 14:23:49 +0000319 int i, cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000320
Raymond Hettingeraae59992002-09-05 14:23:49 +0000321 for (i = 0, cmp = 0 ; cmp == 0 && i < a->ob_size; ++i)
322 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000323 Py_EQ);
Neal Norwitzbb9c5f52002-09-05 21:32:55 +0000324 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000325}
326
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000327static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000328list_item(PyListObject *a, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000329{
330 if (i < 0 || i >= a->ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000331 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000332 indexerr = PyString_FromString(
333 "list index out of range");
334 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000335 return NULL;
336 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000337 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000338 return a->ob_item[i];
339}
340
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000341static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000342list_slice(PyListObject *a, int ilow, int ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000343{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000344 PyListObject *np;
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000345 PyObject **src, **dest;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000346 int i, len;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000347 if (ilow < 0)
348 ilow = 0;
349 else if (ilow > a->ob_size)
350 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000351 if (ihigh < ilow)
352 ihigh = ilow;
353 else if (ihigh > a->ob_size)
354 ihigh = a->ob_size;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000355 len = ihigh - ilow;
356 np = (PyListObject *) PyList_New(len);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000357 if (np == NULL)
358 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000359
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000360 src = a->ob_item + ilow;
361 dest = np->ob_item;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000362 for (i = 0; i < len; i++) {
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000363 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000364 Py_INCREF(v);
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000365 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000366 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000367 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000368}
369
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000370PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000371PyList_GetSlice(PyObject *a, int ilow, int ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000372{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000373 if (!PyList_Check(a)) {
374 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000375 return NULL;
376 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000377 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000378}
379
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000380static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000381list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000382{
383 int size;
384 int i;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000385 PyObject **src, **dest;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000386 PyListObject *np;
387 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000388 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000389 "can only concatenate list (not \"%.200s\") to list",
390 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000391 return NULL;
392 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000393#define b ((PyListObject *)bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000394 size = a->ob_size + b->ob_size;
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000395 if (size < 0)
396 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000397 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000398 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000399 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000400 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000401 src = a->ob_item;
402 dest = np->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000403 for (i = 0; i < a->ob_size; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000404 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000405 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000406 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000407 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000408 src = b->ob_item;
409 dest = np->ob_item + a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000410 for (i = 0; i < b->ob_size; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000411 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000412 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000413 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000414 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000415 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000416#undef b
417}
418
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000419static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000420list_repeat(PyListObject *a, int n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000421{
422 int i, j;
423 int size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000424 PyListObject *np;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000425 PyObject **p, **items;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000426 PyObject *elem;
Guido van Rossumed98d481991-03-06 13:07:53 +0000427 if (n < 0)
428 n = 0;
429 size = a->ob_size * n;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000430 if (size == 0)
431 return PyList_New(0);
Guido van Rossumbfa5a142002-10-11 23:39:35 +0000432 if (n && size/n != a->ob_size)
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000433 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000434 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000435 if (np == NULL)
436 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000437
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000438 items = np->ob_item;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000439 if (a->ob_size == 1) {
440 elem = a->ob_item[0];
441 for (i = 0; i < n; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000442 items[i] = elem;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000443 Py_INCREF(elem);
444 }
445 return (PyObject *) np;
446 }
Guido van Rossumed98d481991-03-06 13:07:53 +0000447 p = np->ob_item;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000448 items = a->ob_item;
Guido van Rossumed98d481991-03-06 13:07:53 +0000449 for (i = 0; i < n; i++) {
450 for (j = 0; j < a->ob_size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000451 *p = items[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000452 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000453 p++;
454 }
455 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000456 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000457}
458
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000459static int
Fred Drakea2f55112000-07-09 15:16:51 +0000460list_ass_slice(PyListObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000461{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000462 /* Because [X]DECREF can recursively invoke list operations on
463 this list, we must postpone all [X]DECREF activity until
464 after the list is back in its canonical shape. Therefore
465 we must allocate an additional array, 'recycle', into which
466 we temporarily copy the items that are deleted from the
467 list. :-( */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000468 PyObject **recycle, **p;
469 PyObject **item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000470 PyObject **vitem = NULL;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000471 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000472 int n; /* Size of replacement list */
473 int d; /* Change in size */
474 int k; /* Loop index */
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000475 int s;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000476#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000477 if (v == NULL)
478 n = 0;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000479 else {
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000480 if (a == b) {
481 /* Special case "a[i:j] = a" -- copy b first */
482 int ret;
Michael W. Hudsonda0a0672003-08-15 12:06:41 +0000483 v = list_slice(b, 0, b->ob_size);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000484 if (v == NULL)
485 return -1;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000486 ret = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000487 Py_DECREF(v);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000488 return ret;
489 }
Raymond Hettingerf889e102004-03-09 08:04:33 +0000490 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000491 if(v_as_SF == NULL)
492 return -1;
493 n = PySequence_Fast_GET_SIZE(v_as_SF);
Raymond Hettinger42bec932004-03-12 16:38:17 +0000494 vitem = PySequence_Fast_ITEMS(v_as_SF);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000495 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000496 if (ilow < 0)
497 ilow = 0;
498 else if (ilow > a->ob_size)
499 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000500 if (ihigh < ilow)
501 ihigh = ilow;
502 else if (ihigh > a->ob_size)
503 ihigh = a->ob_size;
504 item = a->ob_item;
505 d = n - (ihigh-ilow);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000506 if (ihigh > ilow) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000507 p = recycle = PyMem_NEW(PyObject *, (ihigh-ilow));
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000508 if (recycle == NULL) {
509 PyErr_NoMemory();
510 return -1;
511 }
512 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000513 else
514 p = recycle = NULL;
515 if (d <= 0) { /* Delete -d items; recycle ihigh-ilow items */
Raymond Hettinger66d31f82004-03-10 11:44:04 +0000516 memcpy(p, &item[ilow], (ihigh - ilow)*sizeof(PyObject *));
Raymond Hettingerf889e102004-03-09 08:04:33 +0000517 p += ihigh - ilow;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000518 if (d < 0) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000519 memmove(&item[ihigh+d], &item[ihigh],
520 (a->ob_size - ihigh)*sizeof(PyObject *));
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000521 list_resize(a, a->ob_size + d);
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000522 item = a->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000523 }
524 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000525 else { /* Insert d items; recycle ihigh-ilow items */
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000526 s = a->ob_size;
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000527 if (list_resize(a, s+d) == -1) {
Guido van Rossumb18618d2000-05-03 23:44:39 +0000528 if (recycle != NULL)
529 PyMem_DEL(recycle);
Raymond Hettinger2731ae42004-02-14 03:07:21 +0000530 return -1;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000531 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000532 item = a->ob_item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000533 memmove(&item[ihigh+d], &item[ihigh],
534 (s - ihigh)*sizeof(PyObject *));
Raymond Hettinger66d31f82004-03-10 11:44:04 +0000535 memcpy(p, &item[ilow], (ihigh - ilow)*sizeof(PyObject *));
Raymond Hettingerf889e102004-03-09 08:04:33 +0000536 p += ihigh - ilow;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000537 }
538 for (k = 0; k < n; k++, ilow++) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000539 PyObject *w = vitem[k];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000540 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000541 item[ilow] = w;
542 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000543 if (recycle) {
544 while (--p >= recycle)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000545 Py_XDECREF(*p);
546 PyMem_DEL(recycle);
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000547 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000548 if (a->ob_size == 0 && a->ob_item != NULL) {
549 PyMem_FREE(a->ob_item);
550 a->ob_item = NULL;
551 }
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000552 Py_XDECREF(v_as_SF);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000553 return 0;
554#undef b
555}
556
Guido van Rossum234f9421993-06-17 12:35:49 +0000557int
Fred Drakea2f55112000-07-09 15:16:51 +0000558PyList_SetSlice(PyObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000559{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000560 if (!PyList_Check(a)) {
561 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000562 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000563 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000564 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000565}
566
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000567static PyObject *
568list_inplace_repeat(PyListObject *self, int n)
569{
570 PyObject **items;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000571 int size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000572
573
574 size = PyList_GET_SIZE(self);
575 if (size == 0) {
576 Py_INCREF(self);
577 return (PyObject *)self;
578 }
579
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000580 if (n < 1) {
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000581 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000582 self->ob_item = NULL;
583 self->ob_size = 0;
584 for (i = 0; i < size; i++)
585 Py_XDECREF(items[i]);
586 PyMem_DEL(items);
587 Py_INCREF(self);
588 return (PyObject *)self;
589 }
590
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000591 if (list_resize(self, size*n) == -1)
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000592 return NULL;
593
594 p = size;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000595 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000596 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
597 for (j = 0; j < size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000598 PyObject *o = items[j];
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000599 Py_INCREF(o);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000600 items[p++] = o;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000601 }
602 }
603 Py_INCREF(self);
604 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000605}
606
Guido van Rossum4a450d01991-04-03 19:05:18 +0000607static int
Fred Drakea2f55112000-07-09 15:16:51 +0000608list_ass_item(PyListObject *a, int i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000609{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000610 PyObject *old_value;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000611 if (i < 0 || i >= a->ob_size) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000612 PyErr_SetString(PyExc_IndexError,
613 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000614 return -1;
615 }
616 if (v == NULL)
617 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000618 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000619 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000620 a->ob_item[i] = v;
Tim Peters3b01a122002-07-19 02:35:45 +0000621 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000622 return 0;
623}
624
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000625static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000626ins(PyListObject *self, int where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000627{
628 if (ins1(self, where, v) != 0)
629 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000630 Py_INCREF(Py_None);
631 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000632}
633
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000634static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000635listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000636{
637 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000638 PyObject *v;
Guido van Rossumc00a9382000-02-24 21:48:29 +0000639 if (!PyArg_ParseTuple(args, "iO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000640 return NULL;
Guido van Rossumbf80e541993-02-08 15:49:17 +0000641 return ins(self, i, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000642}
643
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000644static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000645listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000646{
Guido van Rossumbf80e541993-02-08 15:49:17 +0000647 return ins(self, (int) self->ob_size, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000648}
649
Barry Warsawdedf6d61998-10-09 16:37:25 +0000650static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000651listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000652{
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000653 PyObject *it; /* iter(v) */
654 int m; /* size of self */
655 int n; /* guess for size of b */
656 int mn; /* m + n */
657 int i;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000658 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000659
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000660 /* Special cases:
661 1) lists and tuples which can use PySequence_Fast ops
662 2) extending self to self requires making a copy first
663 */
664 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
Armin Rigo70d172d2004-03-20 22:19:23 +0000665 PyObject **src, **dest;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000666 b = PySequence_Fast(b, "argument must be iterable");
667 if (!b)
668 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000669 n = PySequence_Fast_GET_SIZE(b);
670 if (n == 0) {
671 /* short circuit when b is empty */
672 Py_DECREF(b);
673 Py_RETURN_NONE;
674 }
675 m = self->ob_size;
676 if (list_resize(self, m + n) == -1) {
677 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000678 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000679 }
680 /* note that we may still have self == b here for the
681 * situation a.extend(a), but the following code works
682 * in that case too. Just make sure to resize self
683 * before calling PySequence_Fast_ITEMS.
684 */
685 /* populate the end of self with b's items */
686 src = PySequence_Fast_ITEMS(b);
687 dest = self->ob_item + m;
688 for (i = 0; i < n; i++) {
689 PyObject *o = src[i];
690 Py_INCREF(o);
691 dest[i] = o;
692 }
693 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000694 Py_RETURN_NONE;
695 }
696
697 it = PyObject_GetIter(b);
698 if (it == NULL)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000699 return NULL;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000700 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000701
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000702 /* Guess a result list size. */
703 n = PyObject_Size(b);
704 if (n < 0) {
705 PyErr_Clear();
706 n = 8; /* arbitrary */
707 }
708 m = self->ob_size;
709 mn = m + n;
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000710 if (list_resize(self, mn) == -1)
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000711 goto error;
712 memset(&(self->ob_item[m]), 0, sizeof(*self->ob_item) * n);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000713
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000714 /* Run iterator to exhaustion. */
715 for (i = m; ; i++) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000716 PyObject *item = iternext(it);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000717 if (item == NULL) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000718 if (PyErr_Occurred()) {
719 if (PyErr_ExceptionMatches(PyExc_StopIteration))
720 PyErr_Clear();
721 else
722 goto error;
723 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000724 break;
725 }
726 if (i < mn)
727 PyList_SET_ITEM(self, i, item); /* steals ref */
728 else {
729 int status = ins1(self, self->ob_size, item);
730 Py_DECREF(item); /* append creates a new ref */
731 if (status < 0)
732 goto error;
733 }
734 }
735
736 /* Cut back result list if initial guess was too large. */
737 if (i < mn && self != NULL) {
738 if (list_ass_slice(self, i, mn, (PyObject *)NULL) != 0)
739 goto error;
740 }
741 Py_DECREF(it);
742 Py_RETURN_NONE;
743
744 error:
745 Py_DECREF(it);
746 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000747}
748
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000749PyObject *
750_PyList_Extend(PyListObject *self, PyObject *b)
751{
752 return listextend(self, b);
753}
754
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000755static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000756list_inplace_concat(PyListObject *self, PyObject *other)
757{
758 PyObject *result;
759
760 result = listextend(self, other);
761 if (result == NULL)
762 return result;
763 Py_DECREF(result);
764 Py_INCREF(self);
765 return (PyObject *)self;
766}
767
768static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000769listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000770{
771 int i = -1;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000772 PyObject *v, *arg = NULL;
773
774 if (!PyArg_UnpackTuple(args, "pop", 0, 1, &arg))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000775 return NULL;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000776 if (arg != NULL) {
777 if (PyInt_Check(arg))
778 i = (int)(PyInt_AS_LONG((PyIntObject*) arg));
Raymond Hettingerfa6c6f82004-02-19 06:12:06 +0000779 else if (!PyArg_ParseTuple(args, "|i:pop", &i))
780 return NULL;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000781 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000782 if (self->ob_size == 0) {
783 /* Special-case most common failure cause */
784 PyErr_SetString(PyExc_IndexError, "pop from empty list");
785 return NULL;
786 }
787 if (i < 0)
788 i += self->ob_size;
789 if (i < 0 || i >= self->ob_size) {
790 PyErr_SetString(PyExc_IndexError, "pop index out of range");
791 return NULL;
792 }
793 v = self->ob_item[i];
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000794 if (i == self->ob_size - 1) {
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000795 if (list_resize(self, self->ob_size - 1) == -1)
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000796 return NULL;
797 return v;
798 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000799 Py_INCREF(v);
800 if (list_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) {
801 Py_DECREF(v);
802 return NULL;
803 }
804 return v;
805}
806
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000807/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
808static void
809reverse_slice(PyObject **lo, PyObject **hi)
810{
811 assert(lo && hi);
812
813 --hi;
814 while (lo < hi) {
815 PyObject *t = *lo;
816 *lo = *hi;
817 *hi = t;
818 ++lo;
819 --hi;
820 }
821}
822
Tim Petersa64dc242002-08-01 02:13:36 +0000823/* Lots of code for an adaptive, stable, natural mergesort. There are many
824 * pieces to this algorithm; read listsort.txt for overviews and details.
825 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000826
Guido van Rossum3f236de1996-12-10 23:55:39 +0000827/* Comparison function. Takes care of calling a user-supplied
Tim Peters66860f62002-08-04 17:47:26 +0000828 * comparison function (any callable Python object), which must not be
829 * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool
830 * with Py_LT if you know it's NULL).
Tim Petersa64dc242002-08-01 02:13:36 +0000831 * Returns -1 on error, 1 if x < y, 0 if x >= y.
832 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000833static int
Tim Petersa8c974c2002-07-19 03:30:57 +0000834islt(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000835{
Tim Petersf2a04732002-07-11 21:46:16 +0000836 PyObject *res;
837 PyObject *args;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000838 int i;
839
Tim Peters66860f62002-08-04 17:47:26 +0000840 assert(compare != NULL);
Tim Petersa8c974c2002-07-19 03:30:57 +0000841 /* Call the user's comparison function and translate the 3-way
842 * result into true or false (or error).
843 */
Tim Petersf2a04732002-07-11 21:46:16 +0000844 args = PyTuple_New(2);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000845 if (args == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000846 return -1;
Tim Petersf2a04732002-07-11 21:46:16 +0000847 Py_INCREF(x);
848 Py_INCREF(y);
849 PyTuple_SET_ITEM(args, 0, x);
850 PyTuple_SET_ITEM(args, 1, y);
Tim Peters58cf3612002-07-15 05:16:13 +0000851 res = PyObject_Call(compare, args, NULL);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000852 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000853 if (res == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000854 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000855 if (!PyInt_Check(res)) {
856 Py_DECREF(res);
857 PyErr_SetString(PyExc_TypeError,
Guido van Rossum9bcd1d71999-04-19 17:44:39 +0000858 "comparison function must return int");
Tim Petersa8c974c2002-07-19 03:30:57 +0000859 return -1;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000860 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000861 i = PyInt_AsLong(res);
862 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +0000863 return i < 0;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000864}
865
Tim Peters66860f62002-08-04 17:47:26 +0000866/* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
867 * islt. This avoids a layer of function call in the usual case, and
868 * sorting does many comparisons.
869 * Returns -1 on error, 1 if x < y, 0 if x >= y.
870 */
871#define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
872 PyObject_RichCompareBool(X, Y, Py_LT) : \
873 islt(X, Y, COMPARE))
874
875/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +0000876 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
877 started. It makes more sense in context <wink>. X and Y are PyObject*s.
878*/
Tim Peters66860f62002-08-04 17:47:26 +0000879#define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
Tim Petersa8c974c2002-07-19 03:30:57 +0000880 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000881
882/* binarysort is the best method for sorting small arrays: it does
883 few compares, but can do data movement quadratic in the number of
884 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000885 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +0000886 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000887 On entry, must have lo <= start <= hi, and that [lo, start) is already
888 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +0000889 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000890 Even in case of error, the output slice will be some permutation of
891 the input (nothing is lost or duplicated).
892*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000893static int
Fred Drakea2f55112000-07-09 15:16:51 +0000894binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
895 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000896{
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000897 register int k;
898 register PyObject **l, **p, **r;
899 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000900
Tim Petersa8c974c2002-07-19 03:30:57 +0000901 assert(lo <= start && start <= hi);
902 /* assert [lo, start) is sorted */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000903 if (lo == start)
904 ++start;
905 for (; start < hi; ++start) {
906 /* set l to where *start belongs */
907 l = lo;
908 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000909 pivot = *r;
Tim Peters0fe977c2002-07-19 06:12:32 +0000910 /* Invariants:
911 * pivot >= all in [lo, l).
912 * pivot < all in [r, start).
913 * The second is vacuously true at the start.
914 */
915 assert(l < r);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000916 do {
917 p = l + ((r - l) >> 1);
Tim Petersa8c974c2002-07-19 03:30:57 +0000918 IFLT(pivot, *p)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000919 r = p;
920 else
Tim Peters0fe977c2002-07-19 06:12:32 +0000921 l = p+1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000922 } while (l < r);
Tim Peters0fe977c2002-07-19 06:12:32 +0000923 assert(l == r);
924 /* The invariants still hold, so pivot >= all in [lo, l) and
925 pivot < all in [l, start), so pivot belongs at l. Note
926 that if there are elements equal to pivot, l points to the
927 first slot after them -- that's why this sort is stable.
928 Slide over to make room.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000929 Caution: using memmove is much slower under MSVC 5;
930 we're not usually moving many slots. */
931 for (p = start; p > l; --p)
932 *p = *(p-1);
933 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000934 }
Guido van Rossum3f236de1996-12-10 23:55:39 +0000935 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000936
937 fail:
938 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000939}
940
Tim Petersa64dc242002-08-01 02:13:36 +0000941/*
942Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
943is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000944
Tim Petersa64dc242002-08-01 02:13:36 +0000945 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000946
Tim Petersa64dc242002-08-01 02:13:36 +0000947or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000948
Tim Petersa64dc242002-08-01 02:13:36 +0000949 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +0000950
Tim Petersa64dc242002-08-01 02:13:36 +0000951Boolean *descending is set to 0 in the former case, or to 1 in the latter.
952For its intended use in a stable mergesort, the strictness of the defn of
953"descending" is needed so that the caller can safely reverse a descending
954sequence without violating stability (strict > ensures there are no equal
955elements to get out of order).
956
957Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000958*/
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000959static int
Tim Petersa64dc242002-08-01 02:13:36 +0000960count_run(PyObject **lo, PyObject **hi, PyObject *compare, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000961{
Tim Petersa64dc242002-08-01 02:13:36 +0000962 int k;
963 int n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000964
Tim Petersa64dc242002-08-01 02:13:36 +0000965 assert(lo < hi);
966 *descending = 0;
967 ++lo;
968 if (lo == hi)
969 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000970
Tim Petersa64dc242002-08-01 02:13:36 +0000971 n = 2;
972 IFLT(*lo, *(lo-1)) {
973 *descending = 1;
974 for (lo = lo+1; lo < hi; ++lo, ++n) {
975 IFLT(*lo, *(lo-1))
976 ;
977 else
978 break;
979 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000980 }
Tim Petersa64dc242002-08-01 02:13:36 +0000981 else {
982 for (lo = lo+1; lo < hi; ++lo, ++n) {
983 IFLT(*lo, *(lo-1))
984 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000985 }
986 }
987
Tim Petersa64dc242002-08-01 02:13:36 +0000988 return n;
989fail:
990 return -1;
991}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000992
Tim Petersa64dc242002-08-01 02:13:36 +0000993/*
994Locate the proper position of key in a sorted vector; if the vector contains
995an element equal to key, return the position immediately to the left of
996the leftmost equal element. [gallop_right() does the same except returns
997the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000998
Tim Petersa64dc242002-08-01 02:13:36 +0000999"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001000
Tim Petersa64dc242002-08-01 02:13:36 +00001001"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1002hint is to the final result, the faster this runs.
1003
1004The return value is the int k in 0..n such that
1005
1006 a[k-1] < key <= a[k]
1007
1008pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1009key belongs at index k; or, IOW, the first k elements of a should precede
1010key, and the last n-k should follow key.
1011
1012Returns -1 on error. See listsort.txt for info on the method.
1013*/
1014static int
1015gallop_left(PyObject *key, PyObject **a, int n, int hint, PyObject *compare)
1016{
1017 int ofs;
1018 int lastofs;
1019 int k;
1020
1021 assert(key && a && n > 0 && hint >= 0 && hint < n);
1022
1023 a += hint;
1024 lastofs = 0;
1025 ofs = 1;
1026 IFLT(*a, key) {
1027 /* a[hint] < key -- gallop right, until
1028 * a[hint + lastofs] < key <= a[hint + ofs]
1029 */
1030 const int maxofs = n - hint; /* &a[n-1] is highest */
1031 while (ofs < maxofs) {
1032 IFLT(a[ofs], key) {
1033 lastofs = ofs;
1034 ofs = (ofs << 1) + 1;
1035 if (ofs <= 0) /* int overflow */
1036 ofs = maxofs;
1037 }
1038 else /* key <= a[hint + ofs] */
1039 break;
1040 }
1041 if (ofs > maxofs)
1042 ofs = maxofs;
1043 /* Translate back to offsets relative to &a[0]. */
1044 lastofs += hint;
1045 ofs += hint;
1046 }
1047 else {
1048 /* key <= a[hint] -- gallop left, until
1049 * a[hint - ofs] < key <= a[hint - lastofs]
1050 */
1051 const int maxofs = hint + 1; /* &a[0] is lowest */
1052 while (ofs < maxofs) {
1053 IFLT(*(a-ofs), key)
1054 break;
1055 /* key <= a[hint - ofs] */
1056 lastofs = ofs;
1057 ofs = (ofs << 1) + 1;
1058 if (ofs <= 0) /* int overflow */
1059 ofs = maxofs;
1060 }
1061 if (ofs > maxofs)
1062 ofs = maxofs;
1063 /* Translate back to positive offsets relative to &a[0]. */
1064 k = lastofs;
1065 lastofs = hint - ofs;
1066 ofs = hint - k;
1067 }
1068 a -= hint;
1069
1070 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1071 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1072 * right of lastofs but no farther right than ofs. Do a binary
1073 * search, with invariant a[lastofs-1] < key <= a[ofs].
1074 */
1075 ++lastofs;
1076 while (lastofs < ofs) {
1077 int m = lastofs + ((ofs - lastofs) >> 1);
1078
1079 IFLT(a[m], key)
1080 lastofs = m+1; /* a[m] < key */
1081 else
1082 ofs = m; /* key <= a[m] */
1083 }
1084 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1085 return ofs;
1086
1087fail:
1088 return -1;
1089}
1090
1091/*
1092Exactly like gallop_left(), except that if key already exists in a[0:n],
1093finds the position immediately to the right of the rightmost equal value.
1094
1095The return value is the int k in 0..n such that
1096
1097 a[k-1] <= key < a[k]
1098
1099or -1 if error.
1100
1101The code duplication is massive, but this is enough different given that
1102we're sticking to "<" comparisons that it's much harder to follow if
1103written as one routine with yet another "left or right?" flag.
1104*/
1105static int
1106gallop_right(PyObject *key, PyObject **a, int n, int hint, PyObject *compare)
1107{
1108 int ofs;
1109 int lastofs;
1110 int k;
1111
1112 assert(key && a && n > 0 && hint >= 0 && hint < n);
1113
1114 a += hint;
1115 lastofs = 0;
1116 ofs = 1;
1117 IFLT(key, *a) {
1118 /* key < a[hint] -- gallop left, until
1119 * a[hint - ofs] <= key < a[hint - lastofs]
1120 */
1121 const int maxofs = hint + 1; /* &a[0] is lowest */
1122 while (ofs < maxofs) {
1123 IFLT(key, *(a-ofs)) {
1124 lastofs = ofs;
1125 ofs = (ofs << 1) + 1;
1126 if (ofs <= 0) /* int overflow */
1127 ofs = maxofs;
1128 }
1129 else /* a[hint - ofs] <= key */
1130 break;
1131 }
1132 if (ofs > maxofs)
1133 ofs = maxofs;
1134 /* Translate back to positive offsets relative to &a[0]. */
1135 k = lastofs;
1136 lastofs = hint - ofs;
1137 ofs = hint - k;
1138 }
1139 else {
1140 /* a[hint] <= key -- gallop right, until
1141 * a[hint + lastofs] <= key < a[hint + ofs]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001142 */
Tim Petersa64dc242002-08-01 02:13:36 +00001143 const int maxofs = n - hint; /* &a[n-1] is highest */
1144 while (ofs < maxofs) {
1145 IFLT(key, a[ofs])
1146 break;
1147 /* a[hint + ofs] <= key */
1148 lastofs = ofs;
1149 ofs = (ofs << 1) + 1;
1150 if (ofs <= 0) /* int overflow */
1151 ofs = maxofs;
1152 }
1153 if (ofs > maxofs)
1154 ofs = maxofs;
1155 /* Translate back to offsets relative to &a[0]. */
1156 lastofs += hint;
1157 ofs += hint;
1158 }
1159 a -= hint;
1160
1161 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1162 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1163 * right of lastofs but no farther right than ofs. Do a binary
1164 * search, with invariant a[lastofs-1] <= key < a[ofs].
1165 */
1166 ++lastofs;
1167 while (lastofs < ofs) {
1168 int m = lastofs + ((ofs - lastofs) >> 1);
1169
1170 IFLT(key, a[m])
1171 ofs = m; /* key < a[m] */
1172 else
1173 lastofs = m+1; /* a[m] <= key */
1174 }
1175 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1176 return ofs;
1177
1178fail:
1179 return -1;
1180}
1181
1182/* The maximum number of entries in a MergeState's pending-runs stack.
1183 * This is enough to sort arrays of size up to about
1184 * 32 * phi ** MAX_MERGE_PENDING
1185 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1186 * with 2**64 elements.
1187 */
1188#define MAX_MERGE_PENDING 85
1189
Tim Peterse05f65a2002-08-10 05:21:15 +00001190/* When we get into galloping mode, we stay there until both runs win less
1191 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001192 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001193#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001194
1195/* Avoid malloc for small temp arrays. */
1196#define MERGESTATE_TEMP_SIZE 256
1197
1198/* One MergeState exists on the stack per invocation of mergesort. It's just
1199 * a convenient way to pass state around among the helper functions.
1200 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001201struct s_slice {
1202 PyObject **base;
1203 int len;
1204};
1205
Tim Petersa64dc242002-08-01 02:13:36 +00001206typedef struct s_MergeState {
1207 /* The user-supplied comparison function. or NULL if none given. */
1208 PyObject *compare;
1209
Tim Peterse05f65a2002-08-10 05:21:15 +00001210 /* This controls when we get *into* galloping mode. It's initialized
1211 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1212 * random data, and lower for highly structured data.
1213 */
1214 int min_gallop;
1215
Tim Petersa64dc242002-08-01 02:13:36 +00001216 /* 'a' is temp storage to help with merges. It contains room for
1217 * alloced entries.
1218 */
1219 PyObject **a; /* may point to temparray below */
1220 int alloced;
1221
1222 /* A stack of n pending runs yet to be merged. Run #i starts at
1223 * address base[i] and extends for len[i] elements. It's always
1224 * true (so long as the indices are in bounds) that
1225 *
Tim Peterse05f65a2002-08-10 05:21:15 +00001226 * pending[i].base + pending[i].len == pending[i+1].base
Tim Petersa64dc242002-08-01 02:13:36 +00001227 *
1228 * so we could cut the storage for this, but it's a minor amount,
1229 * and keeping all the info explicit simplifies the code.
1230 */
1231 int n;
Tim Peterse05f65a2002-08-10 05:21:15 +00001232 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001233
1234 /* 'a' points to this when possible, rather than muck with malloc. */
1235 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1236} MergeState;
1237
1238/* Conceptually a MergeState's constructor. */
1239static void
1240merge_init(MergeState *ms, PyObject *compare)
1241{
1242 assert(ms != NULL);
1243 ms->compare = compare;
1244 ms->a = ms->temparray;
1245 ms->alloced = MERGESTATE_TEMP_SIZE;
1246 ms->n = 0;
Tim Peterse05f65a2002-08-10 05:21:15 +00001247 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001248}
1249
1250/* Free all the temp memory owned by the MergeState. This must be called
1251 * when you're done with a MergeState, and may be called before then if
1252 * you want to free the temp memory early.
1253 */
1254static void
1255merge_freemem(MergeState *ms)
1256{
1257 assert(ms != NULL);
1258 if (ms->a != ms->temparray)
1259 PyMem_Free(ms->a);
1260 ms->a = ms->temparray;
1261 ms->alloced = MERGESTATE_TEMP_SIZE;
1262}
1263
1264/* Ensure enough temp memory for 'need' array slots is available.
1265 * Returns 0 on success and -1 if the memory can't be gotten.
1266 */
1267static int
1268merge_getmem(MergeState *ms, int need)
1269{
1270 assert(ms != NULL);
1271 if (need <= ms->alloced)
1272 return 0;
1273 /* Don't realloc! That can cost cycles to copy the old data, but
1274 * we don't care what's in the block.
1275 */
1276 merge_freemem(ms);
1277 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1278 if (ms->a) {
1279 ms->alloced = need;
1280 return 0;
1281 }
1282 PyErr_NoMemory();
1283 merge_freemem(ms); /* reset to sane state */
1284 return -1;
1285}
1286#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1287 merge_getmem(MS, NEED))
1288
1289/* Merge the na elements starting at pa with the nb elements starting at pb
1290 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1291 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1292 * merge, and should have na <= nb. See listsort.txt for more info.
1293 * Return 0 if successful, -1 if error.
1294 */
1295static int
1296merge_lo(MergeState *ms, PyObject **pa, int na, PyObject **pb, int nb)
1297{
1298 int k;
1299 PyObject *compare;
1300 PyObject **dest;
1301 int result = -1; /* guilty until proved innocent */
Tim Peterse05f65a2002-08-10 05:21:15 +00001302 int min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001303
1304 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1305 if (MERGE_GETMEM(ms, na) < 0)
1306 return -1;
1307 memcpy(ms->a, pa, na * sizeof(PyObject*));
1308 dest = pa;
1309 pa = ms->a;
1310
1311 *dest++ = *pb++;
1312 --nb;
1313 if (nb == 0)
1314 goto Succeed;
1315 if (na == 1)
1316 goto CopyB;
1317
1318 compare = ms->compare;
1319 for (;;) {
1320 int acount = 0; /* # of times A won in a row */
1321 int bcount = 0; /* # of times B won in a row */
1322
1323 /* Do the straightforward thing until (if ever) one run
1324 * appears to win consistently.
1325 */
1326 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001327 assert(na > 1 && nb > 0);
Tim Peters66860f62002-08-04 17:47:26 +00001328 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001329 if (k) {
1330 if (k < 0)
1331 goto Fail;
1332 *dest++ = *pb++;
1333 ++bcount;
1334 acount = 0;
1335 --nb;
1336 if (nb == 0)
1337 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001338 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001339 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001340 }
1341 else {
Tim Petersa64dc242002-08-01 02:13:36 +00001342 *dest++ = *pa++;
1343 ++acount;
1344 bcount = 0;
1345 --na;
1346 if (na == 1)
1347 goto CopyB;
Tim Peterse05f65a2002-08-10 05:21:15 +00001348 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001349 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001350 }
Tim Petersa64dc242002-08-01 02:13:36 +00001351 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001352
Tim Petersa64dc242002-08-01 02:13:36 +00001353 /* One run is winning so consistently that galloping may
1354 * be a huge win. So try that, and continue galloping until
1355 * (if ever) neither run appears to be winning consistently
1356 * anymore.
1357 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001358 ++min_gallop;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001359 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001360 assert(na > 1 && nb > 0);
1361 min_gallop -= min_gallop > 1;
1362 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001363 k = gallop_right(*pb, pa, na, 0, compare);
1364 acount = k;
1365 if (k) {
1366 if (k < 0)
1367 goto Fail;
1368 memcpy(dest, pa, k * sizeof(PyObject *));
1369 dest += k;
1370 pa += k;
1371 na -= k;
1372 if (na == 1)
1373 goto CopyB;
1374 /* na==0 is impossible now if the comparison
1375 * function is consistent, but we can't assume
1376 * that it is.
1377 */
1378 if (na == 0)
1379 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001380 }
Tim Petersa64dc242002-08-01 02:13:36 +00001381 *dest++ = *pb++;
1382 --nb;
1383 if (nb == 0)
1384 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001385
Tim Petersa64dc242002-08-01 02:13:36 +00001386 k = gallop_left(*pa, pb, nb, 0, compare);
1387 bcount = k;
1388 if (k) {
1389 if (k < 0)
1390 goto Fail;
1391 memmove(dest, pb, k * sizeof(PyObject *));
1392 dest += k;
1393 pb += k;
1394 nb -= k;
1395 if (nb == 0)
1396 goto Succeed;
1397 }
1398 *dest++ = *pa++;
1399 --na;
1400 if (na == 1)
1401 goto CopyB;
1402 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001403 ++min_gallop; /* penalize it for leaving galloping mode */
1404 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001405 }
1406Succeed:
1407 result = 0;
1408Fail:
1409 if (na)
1410 memcpy(dest, pa, na * sizeof(PyObject*));
1411 return result;
1412CopyB:
1413 assert(na == 1 && nb > 0);
1414 /* The last element of pa belongs at the end of the merge. */
1415 memmove(dest, pb, nb * sizeof(PyObject *));
1416 dest[nb] = *pa;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001417 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001418}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001419
Tim Petersa64dc242002-08-01 02:13:36 +00001420/* Merge the na elements starting at pa with the nb elements starting at pb
1421 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1422 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1423 * merge, and should have na >= nb. See listsort.txt for more info.
1424 * Return 0 if successful, -1 if error.
1425 */
1426static int
1427merge_hi(MergeState *ms, PyObject **pa, int na, PyObject **pb, int nb)
1428{
1429 int k;
1430 PyObject *compare;
1431 PyObject **dest;
1432 int result = -1; /* guilty until proved innocent */
1433 PyObject **basea;
1434 PyObject **baseb;
Tim Peterse05f65a2002-08-10 05:21:15 +00001435 int min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001436
1437 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1438 if (MERGE_GETMEM(ms, nb) < 0)
1439 return -1;
1440 dest = pb + nb - 1;
1441 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1442 basea = pa;
1443 baseb = ms->a;
1444 pb = ms->a + nb - 1;
1445 pa += na - 1;
1446
1447 *dest-- = *pa--;
1448 --na;
1449 if (na == 0)
1450 goto Succeed;
1451 if (nb == 1)
1452 goto CopyA;
1453
1454 compare = ms->compare;
1455 for (;;) {
1456 int acount = 0; /* # of times A won in a row */
1457 int bcount = 0; /* # of times B won in a row */
1458
1459 /* Do the straightforward thing until (if ever) one run
1460 * appears to win consistently.
1461 */
1462 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001463 assert(na > 0 && nb > 1);
Tim Peters66860f62002-08-04 17:47:26 +00001464 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001465 if (k) {
1466 if (k < 0)
1467 goto Fail;
1468 *dest-- = *pa--;
1469 ++acount;
1470 bcount = 0;
1471 --na;
1472 if (na == 0)
1473 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001474 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001475 break;
1476 }
1477 else {
1478 *dest-- = *pb--;
1479 ++bcount;
1480 acount = 0;
1481 --nb;
1482 if (nb == 1)
1483 goto CopyA;
Tim Peterse05f65a2002-08-10 05:21:15 +00001484 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001485 break;
1486 }
1487 }
1488
1489 /* One run is winning so consistently that galloping may
1490 * be a huge win. So try that, and continue galloping until
1491 * (if ever) neither run appears to be winning consistently
1492 * anymore.
1493 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001494 ++min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001495 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001496 assert(na > 0 && nb > 1);
1497 min_gallop -= min_gallop > 1;
1498 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001499 k = gallop_right(*pb, basea, na, na-1, compare);
1500 if (k < 0)
1501 goto Fail;
1502 k = na - k;
1503 acount = k;
1504 if (k) {
1505 dest -= k;
1506 pa -= k;
1507 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1508 na -= k;
1509 if (na == 0)
1510 goto Succeed;
1511 }
1512 *dest-- = *pb--;
1513 --nb;
1514 if (nb == 1)
1515 goto CopyA;
1516
1517 k = gallop_left(*pa, baseb, nb, nb-1, compare);
1518 if (k < 0)
1519 goto Fail;
1520 k = nb - k;
1521 bcount = k;
1522 if (k) {
1523 dest -= k;
1524 pb -= k;
1525 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1526 nb -= k;
1527 if (nb == 1)
1528 goto CopyA;
1529 /* nb==0 is impossible now if the comparison
1530 * function is consistent, but we can't assume
1531 * that it is.
1532 */
1533 if (nb == 0)
1534 goto Succeed;
1535 }
1536 *dest-- = *pa--;
1537 --na;
1538 if (na == 0)
1539 goto Succeed;
1540 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001541 ++min_gallop; /* penalize it for leaving galloping mode */
1542 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001543 }
1544Succeed:
1545 result = 0;
1546Fail:
1547 if (nb)
1548 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1549 return result;
1550CopyA:
1551 assert(nb == 1 && na > 0);
1552 /* The first element of pb belongs at the front of the merge. */
1553 dest -= na;
1554 pa -= na;
1555 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1556 *dest = *pb;
1557 return 0;
1558}
1559
1560/* Merge the two runs at stack indices i and i+1.
1561 * Returns 0 on success, -1 on error.
1562 */
1563static int
1564merge_at(MergeState *ms, int i)
1565{
1566 PyObject **pa, **pb;
1567 int na, nb;
1568 int k;
1569 PyObject *compare;
1570
1571 assert(ms != NULL);
1572 assert(ms->n >= 2);
1573 assert(i >= 0);
1574 assert(i == ms->n - 2 || i == ms->n - 3);
1575
Tim Peterse05f65a2002-08-10 05:21:15 +00001576 pa = ms->pending[i].base;
1577 na = ms->pending[i].len;
1578 pb = ms->pending[i+1].base;
1579 nb = ms->pending[i+1].len;
Tim Petersa64dc242002-08-01 02:13:36 +00001580 assert(na > 0 && nb > 0);
1581 assert(pa + na == pb);
1582
1583 /* Record the length of the combined runs; if i is the 3rd-last
1584 * run now, also slide over the last run (which isn't involved
1585 * in this merge). The current run i+1 goes away in any case.
1586 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001587 ms->pending[i].len = na + nb;
1588 if (i == ms->n - 3)
1589 ms->pending[i+1] = ms->pending[i+2];
Tim Petersa64dc242002-08-01 02:13:36 +00001590 --ms->n;
1591
1592 /* Where does b start in a? Elements in a before that can be
1593 * ignored (already in place).
1594 */
1595 compare = ms->compare;
1596 k = gallop_right(*pb, pa, na, 0, compare);
1597 if (k < 0)
1598 return -1;
1599 pa += k;
1600 na -= k;
1601 if (na == 0)
1602 return 0;
1603
1604 /* Where does a end in b? Elements in b after that can be
1605 * ignored (already in place).
1606 */
1607 nb = gallop_left(pa[na-1], pb, nb, nb-1, compare);
1608 if (nb <= 0)
1609 return nb;
1610
1611 /* Merge what remains of the runs, using a temp array with
1612 * min(na, nb) elements.
1613 */
1614 if (na <= nb)
1615 return merge_lo(ms, pa, na, pb, nb);
1616 else
1617 return merge_hi(ms, pa, na, pb, nb);
1618}
1619
1620/* Examine the stack of runs waiting to be merged, merging adjacent runs
1621 * until the stack invariants are re-established:
1622 *
1623 * 1. len[-3] > len[-2] + len[-1]
1624 * 2. len[-2] > len[-1]
1625 *
1626 * See listsort.txt for more info.
1627 *
1628 * Returns 0 on success, -1 on error.
1629 */
1630static int
1631merge_collapse(MergeState *ms)
1632{
Tim Peterse05f65a2002-08-10 05:21:15 +00001633 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001634
1635 assert(ms);
1636 while (ms->n > 1) {
1637 int n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001638 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1639 if (p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001640 --n;
1641 if (merge_at(ms, n) < 0)
1642 return -1;
1643 }
Tim Peterse05f65a2002-08-10 05:21:15 +00001644 else if (p[n].len <= p[n+1].len) {
Tim Petersa64dc242002-08-01 02:13:36 +00001645 if (merge_at(ms, n) < 0)
1646 return -1;
1647 }
1648 else
1649 break;
1650 }
1651 return 0;
1652}
1653
1654/* Regardless of invariants, merge all runs on the stack until only one
1655 * remains. This is used at the end of the mergesort.
1656 *
1657 * Returns 0 on success, -1 on error.
1658 */
1659static int
1660merge_force_collapse(MergeState *ms)
1661{
Tim Peterse05f65a2002-08-10 05:21:15 +00001662 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001663
1664 assert(ms);
1665 while (ms->n > 1) {
1666 int n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001667 if (n > 0 && p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001668 --n;
1669 if (merge_at(ms, n) < 0)
1670 return -1;
1671 }
1672 return 0;
1673}
1674
1675/* Compute a good value for the minimum run length; natural runs shorter
1676 * than this are boosted artificially via binary insertion.
1677 *
1678 * If n < 64, return n (it's too small to bother with fancy stuff).
1679 * Else if n is an exact power of 2, return 32.
1680 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1681 * strictly less than, an exact power of 2.
1682 *
1683 * See listsort.txt for more info.
1684 */
1685static int
1686merge_compute_minrun(int n)
1687{
1688 int r = 0; /* becomes 1 if any 1 bits are shifted off */
1689
1690 assert(n >= 0);
1691 while (n >= 64) {
1692 r |= n & 1;
1693 n >>= 1;
1694 }
1695 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001696}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001697
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001698/* Special wrapper to support stable sorting using the decorate-sort-undecorate
1699 pattern. Holds a key which is used for comparisions and the original record
1700 which is returned during the undecorate phase. By exposing only the key
1701 during comparisons, the underlying sort stability characteristics are left
1702 unchanged. Also, if a custom comparison function is used, it will only see
1703 the key instead of a full record. */
1704
1705typedef struct {
1706 PyObject_HEAD
1707 PyObject *key;
1708 PyObject *value;
1709} sortwrapperobject;
1710
1711static PyTypeObject sortwrapper_type;
1712
1713static PyObject *
1714sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
1715{
1716 if (!PyObject_TypeCheck(b, &sortwrapper_type)) {
1717 PyErr_SetString(PyExc_TypeError,
1718 "expected a sortwrapperobject");
1719 return NULL;
1720 }
1721 return PyObject_RichCompare(a->key, b->key, op);
1722}
1723
1724static void
1725sortwrapper_dealloc(sortwrapperobject *so)
1726{
1727 Py_XDECREF(so->key);
1728 Py_XDECREF(so->value);
1729 PyObject_Del(so);
1730}
1731
1732PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
1733
1734static PyTypeObject sortwrapper_type = {
1735 PyObject_HEAD_INIT(&PyType_Type)
1736 0, /* ob_size */
1737 "sortwrapper", /* tp_name */
1738 sizeof(sortwrapperobject), /* tp_basicsize */
1739 0, /* tp_itemsize */
1740 /* methods */
1741 (destructor)sortwrapper_dealloc, /* tp_dealloc */
1742 0, /* tp_print */
1743 0, /* tp_getattr */
1744 0, /* tp_setattr */
1745 0, /* tp_compare */
1746 0, /* tp_repr */
1747 0, /* tp_as_number */
1748 0, /* tp_as_sequence */
1749 0, /* tp_as_mapping */
1750 0, /* tp_hash */
1751 0, /* tp_call */
1752 0, /* tp_str */
1753 PyObject_GenericGetAttr, /* tp_getattro */
1754 0, /* tp_setattro */
1755 0, /* tp_as_buffer */
1756 Py_TPFLAGS_DEFAULT |
1757 Py_TPFLAGS_HAVE_RICHCOMPARE, /* tp_flags */
1758 sortwrapper_doc, /* tp_doc */
1759 0, /* tp_traverse */
1760 0, /* tp_clear */
1761 (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
1762};
1763
1764/* Returns a new reference to a sortwrapper.
1765 Consumes the references to the two underlying objects. */
1766
1767static PyObject *
1768build_sortwrapper(PyObject *key, PyObject *value)
1769{
1770 sortwrapperobject *so;
1771
1772 so = PyObject_New(sortwrapperobject, &sortwrapper_type);
1773 if (so == NULL)
1774 return NULL;
1775 so->key = key;
1776 so->value = value;
1777 return (PyObject *)so;
1778}
1779
1780/* Returns a new reference to the value underlying the wrapper. */
1781static PyObject *
1782sortwrapper_getvalue(PyObject *so)
1783{
1784 PyObject *value;
1785
1786 if (!PyObject_TypeCheck(so, &sortwrapper_type)) {
1787 PyErr_SetString(PyExc_TypeError,
1788 "expected a sortwrapperobject");
1789 return NULL;
1790 }
1791 value = ((sortwrapperobject *)so)->value;
1792 Py_INCREF(value);
1793 return value;
1794}
1795
1796/* Wrapper for user specified cmp functions in combination with a
1797 specified key function. Makes sure the cmp function is presented
1798 with the actual key instead of the sortwrapper */
1799
1800typedef struct {
1801 PyObject_HEAD
1802 PyObject *func;
1803} cmpwrapperobject;
1804
1805static void
1806cmpwrapper_dealloc(cmpwrapperobject *co)
1807{
1808 Py_XDECREF(co->func);
1809 PyObject_Del(co);
1810}
1811
1812static PyObject *
1813cmpwrapper_call(cmpwrapperobject *co, PyObject *args, PyObject *kwds)
1814{
1815 PyObject *x, *y, *xx, *yy;
1816
1817 if (!PyArg_UnpackTuple(args, "", 2, 2, &x, &y))
1818 return NULL;
1819 if (!PyObject_TypeCheck(x, &sortwrapper_type) ||
Raymond Hettingerae4a2992003-10-16 17:16:30 +00001820 !PyObject_TypeCheck(y, &sortwrapper_type)) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001821 PyErr_SetString(PyExc_TypeError,
1822 "expected a sortwrapperobject");
1823 return NULL;
1824 }
1825 xx = ((sortwrapperobject *)x)->key;
1826 yy = ((sortwrapperobject *)y)->key;
1827 return PyObject_CallFunctionObjArgs(co->func, xx, yy, NULL);
1828}
1829
1830PyDoc_STRVAR(cmpwrapper_doc, "cmp() wrapper for sort with custom keys.");
1831
1832static PyTypeObject cmpwrapper_type = {
1833 PyObject_HEAD_INIT(&PyType_Type)
1834 0, /* ob_size */
1835 "cmpwrapper", /* tp_name */
1836 sizeof(cmpwrapperobject), /* tp_basicsize */
1837 0, /* tp_itemsize */
1838 /* methods */
1839 (destructor)cmpwrapper_dealloc, /* tp_dealloc */
1840 0, /* tp_print */
1841 0, /* tp_getattr */
1842 0, /* tp_setattr */
1843 0, /* tp_compare */
1844 0, /* tp_repr */
1845 0, /* tp_as_number */
1846 0, /* tp_as_sequence */
1847 0, /* tp_as_mapping */
1848 0, /* tp_hash */
1849 (ternaryfunc)cmpwrapper_call, /* tp_call */
1850 0, /* tp_str */
1851 PyObject_GenericGetAttr, /* tp_getattro */
1852 0, /* tp_setattro */
1853 0, /* tp_as_buffer */
1854 Py_TPFLAGS_DEFAULT, /* tp_flags */
1855 cmpwrapper_doc, /* tp_doc */
1856};
1857
1858static PyObject *
1859build_cmpwrapper(PyObject *cmpfunc)
1860{
1861 cmpwrapperobject *co;
1862
1863 co = PyObject_New(cmpwrapperobject, &cmpwrapper_type);
1864 if (co == NULL)
1865 return NULL;
1866 Py_INCREF(cmpfunc);
1867 co->func = cmpfunc;
1868 return (PyObject *)co;
1869}
1870
Tim Petersa64dc242002-08-01 02:13:36 +00001871/* An adaptive, stable, natural mergesort. See listsort.txt.
1872 * Returns Py_None on success, NULL on error. Even in case of error, the
1873 * list will be some permutation of its input state (nothing is lost or
1874 * duplicated).
1875 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001876static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001877listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001878{
Tim Petersa64dc242002-08-01 02:13:36 +00001879 MergeState ms;
1880 PyObject **lo, **hi;
1881 int nremaining;
1882 int minrun;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001883 int saved_ob_size, saved_allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00001884 PyObject **saved_ob_item;
1885 PyObject **empty_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001886 PyObject *compare = NULL;
1887 PyObject *result = NULL; /* guilty until proved innocent */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001888 int reverse = 0;
1889 PyObject *keyfunc = NULL;
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001890 int i;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001891 PyObject *key, *value, *kvpair;
1892 static char *kwlist[] = {"cmp", "key", "reverse", 0};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001893
Tim Petersa64dc242002-08-01 02:13:36 +00001894 assert(self != NULL);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001895 assert (PyList_Check(self));
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001896 if (args != NULL) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001897 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:sort",
1898 kwlist, &compare, &keyfunc, &reverse))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001899 return NULL;
1900 }
Skip Montanaro4abd5f02003-01-02 20:51:08 +00001901 if (compare == Py_None)
1902 compare = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001903 if (keyfunc == Py_None)
1904 keyfunc = NULL;
1905 if (compare != NULL && keyfunc != NULL) {
1906 compare = build_cmpwrapper(compare);
1907 if (compare == NULL)
Hye-Shik Chang19cb1932003-12-10 07:31:08 +00001908 return NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001909 } else
1910 Py_XINCREF(compare);
1911
Tim Petersb9099c32002-11-12 22:08:10 +00001912 /* The list is temporarily made empty, so that mutations performed
1913 * by comparison functions can't affect the slice of memory we're
1914 * sorting (allowing mutations during sorting is a core-dump
1915 * factory, since ob_item may change).
1916 */
1917 saved_ob_size = self->ob_size;
1918 saved_ob_item = self->ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001919 saved_allocated = self->allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00001920 self->ob_size = 0;
Tim Peters7049d812004-01-18 20:31:02 +00001921 self->ob_item = empty_ob_item = PyMem_NEW(PyObject *, 0);
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001922 self->allocated = 0;
Tim Peters330f9e92002-07-19 07:05:44 +00001923
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001924 if (keyfunc != NULL) {
1925 for (i=0 ; i < saved_ob_size ; i++) {
1926 value = saved_ob_item[i];
1927 key = PyObject_CallFunctionObjArgs(keyfunc, value,
1928 NULL);
1929 if (key == NULL) {
1930 for (i=i-1 ; i>=0 ; i--) {
1931 kvpair = saved_ob_item[i];
1932 value = sortwrapper_getvalue(kvpair);
1933 saved_ob_item[i] = value;
1934 Py_DECREF(kvpair);
1935 }
1936 if (self->ob_item != empty_ob_item
1937 || self->ob_size) {
1938 /* If the list changed *as well* we
1939 have two errors. We let the first
1940 one "win", but we shouldn't let
1941 what's in the list currently
1942 leak. */
1943 (void)list_ass_slice(
1944 self, 0, self->ob_size,
1945 (PyObject *)NULL);
1946 }
1947
1948 goto dsu_fail;
1949 }
1950 kvpair = build_sortwrapper(key, value);
1951 if (kvpair == NULL)
1952 goto dsu_fail;
1953 saved_ob_item[i] = kvpair;
1954 }
1955 }
1956
1957 /* Reverse sort stability achieved by initially reversing the list,
1958 applying a stable forward sort, then reversing the final result. */
1959 if (reverse && saved_ob_size > 1)
1960 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
1961
1962 merge_init(&ms, compare);
1963
Tim Petersb9099c32002-11-12 22:08:10 +00001964 nremaining = saved_ob_size;
Tim Petersa64dc242002-08-01 02:13:36 +00001965 if (nremaining < 2)
1966 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00001967
Tim Petersa64dc242002-08-01 02:13:36 +00001968 /* March over the array once, left to right, finding natural runs,
1969 * and extending short natural runs to minrun elements.
1970 */
Tim Petersb9099c32002-11-12 22:08:10 +00001971 lo = saved_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001972 hi = lo + nremaining;
1973 minrun = merge_compute_minrun(nremaining);
1974 do {
1975 int descending;
1976 int n;
Tim Peters330f9e92002-07-19 07:05:44 +00001977
Tim Petersa64dc242002-08-01 02:13:36 +00001978 /* Identify next run. */
1979 n = count_run(lo, hi, compare, &descending);
1980 if (n < 0)
1981 goto fail;
1982 if (descending)
1983 reverse_slice(lo, lo + n);
1984 /* If short, extend to min(minrun, nremaining). */
1985 if (n < minrun) {
1986 const int force = nremaining <= minrun ?
1987 nremaining : minrun;
1988 if (binarysort(lo, lo + force, lo + n, compare) < 0)
1989 goto fail;
1990 n = force;
1991 }
1992 /* Push run onto pending-runs stack, and maybe merge. */
1993 assert(ms.n < MAX_MERGE_PENDING);
Tim Peterse05f65a2002-08-10 05:21:15 +00001994 ms.pending[ms.n].base = lo;
1995 ms.pending[ms.n].len = n;
Tim Petersa64dc242002-08-01 02:13:36 +00001996 ++ms.n;
1997 if (merge_collapse(&ms) < 0)
1998 goto fail;
1999 /* Advance to find next run. */
2000 lo += n;
2001 nremaining -= n;
2002 } while (nremaining);
2003 assert(lo == hi);
Tim Peters330f9e92002-07-19 07:05:44 +00002004
Tim Petersa64dc242002-08-01 02:13:36 +00002005 if (merge_force_collapse(&ms) < 0)
2006 goto fail;
2007 assert(ms.n == 1);
Tim Petersb9099c32002-11-12 22:08:10 +00002008 assert(ms.pending[0].base == saved_ob_item);
2009 assert(ms.pending[0].len == saved_ob_size);
Tim Petersa64dc242002-08-01 02:13:36 +00002010
2011succeed:
2012 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002013fail:
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002014 if (keyfunc != NULL) {
2015 for (i=0 ; i < saved_ob_size ; i++) {
2016 kvpair = saved_ob_item[i];
2017 value = sortwrapper_getvalue(kvpair);
2018 saved_ob_item[i] = value;
2019 Py_DECREF(kvpair);
2020 }
2021 }
2022
Tim Petersb9099c32002-11-12 22:08:10 +00002023 if (self->ob_item != empty_ob_item || self->ob_size) {
2024 /* The user mucked with the list during the sort. */
2025 (void)list_ass_slice(self, 0, self->ob_size, (PyObject *)NULL);
2026 if (result != NULL) {
2027 PyErr_SetString(PyExc_ValueError,
2028 "list modified during sort");
2029 result = NULL;
2030 }
2031 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002032
2033 if (reverse && saved_ob_size > 1)
2034 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2035
2036 merge_freemem(&ms);
2037
2038dsu_fail:
Tim Petersb9099c32002-11-12 22:08:10 +00002039 if (self->ob_item == empty_ob_item)
2040 PyMem_FREE(empty_ob_item);
2041 self->ob_size = saved_ob_size;
2042 self->ob_item = saved_ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002043 self->allocated = saved_allocated;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002044 Py_XDECREF(compare);
Tim Petersa64dc242002-08-01 02:13:36 +00002045 Py_XINCREF(result);
2046 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002047}
Tim Peters330f9e92002-07-19 07:05:44 +00002048#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002049#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002050
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002051int
Fred Drakea2f55112000-07-09 15:16:51 +00002052PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002053{
2054 if (v == NULL || !PyList_Check(v)) {
2055 PyErr_BadInternalCall();
2056 return -1;
2057 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002058 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002059 if (v == NULL)
2060 return -1;
2061 Py_DECREF(v);
2062 return 0;
2063}
2064
Guido van Rossumb86c5492001-02-12 22:06:02 +00002065static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002066listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002067{
Tim Peters326b4482002-07-19 04:04:16 +00002068 if (self->ob_size > 1)
2069 reverse_slice(self->ob_item, self->ob_item + self->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002070 Py_INCREF(Py_None);
2071 return Py_None;
Guido van Rossumed98d481991-03-06 13:07:53 +00002072}
2073
Guido van Rossum84c76f51990-10-30 13:32:20 +00002074int
Fred Drakea2f55112000-07-09 15:16:51 +00002075PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002076{
Tim Peters6063e262002-08-08 01:06:39 +00002077 PyListObject *self = (PyListObject *)v;
2078
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002079 if (v == NULL || !PyList_Check(v)) {
2080 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002081 return -1;
2082 }
Tim Peters6063e262002-08-08 01:06:39 +00002083 if (self->ob_size > 1)
2084 reverse_slice(self->ob_item, self->ob_item + self->ob_size);
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002085 return 0;
2086}
2087
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002088PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002089PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002090{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002091 PyObject *w;
2092 PyObject **p;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002093 int n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002094 if (v == NULL || !PyList_Check(v)) {
2095 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002096 return NULL;
2097 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002098 n = ((PyListObject *)v)->ob_size;
2099 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002100 if (w == NULL)
2101 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002102 p = ((PyTupleObject *)w)->ob_item;
Thomas Wouters334fb892000-07-25 12:56:38 +00002103 memcpy((void *)p,
2104 (void *)((PyListObject *)v)->ob_item,
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002105 n*sizeof(PyObject *));
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002106 while (--n >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002107 Py_INCREF(*p);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002108 p++;
2109 }
2110 return w;
2111}
2112
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002113static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002114listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002115{
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002116 int i, start=0, stop=self->ob_size;
2117 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002118
Walter Dörwalde8049bef2003-06-17 19:27:39 +00002119 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2120 _PyEval_SliceIndex, &start,
2121 _PyEval_SliceIndex, &stop))
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002122 return NULL;
Guido van Rossum2743d872003-06-17 14:25:14 +00002123 if (start < 0) {
2124 start += self->ob_size;
2125 if (start < 0)
2126 start = 0;
2127 }
2128 if (stop < 0) {
2129 stop += self->ob_size;
2130 if (stop < 0)
2131 stop = 0;
2132 }
2133 else if (stop > self->ob_size)
2134 stop = self->ob_size;
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002135 for (i = start; i < stop; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002136 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2137 if (cmp > 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002138 return PyInt_FromLong((long)i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002139 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002140 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002141 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002142 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002143 return NULL;
2144}
2145
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002146static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002147listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002148{
2149 int count = 0;
2150 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002151
Guido van Rossume6f7d181991-10-20 20:20:40 +00002152 for (i = 0; i < self->ob_size; 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 Rossume6f7d181991-10-20 20:20:40 +00002155 count++;
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 Rossume6f7d181991-10-20 20:20:40 +00002158 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002159 return PyInt_FromLong((long)count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002160}
2161
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002162static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002163listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002164{
2165 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002166
Guido van Rossumed98d481991-03-06 13:07:53 +00002167 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002168 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2169 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002170 if (list_ass_slice(self, i, i+1,
2171 (PyObject *)NULL) != 0)
Guido van Rossumed98d481991-03-06 13:07:53 +00002172 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002173 Py_INCREF(Py_None);
2174 return Py_None;
Guido van Rossumed98d481991-03-06 13:07:53 +00002175 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002176 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002177 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002178 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002179 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002180 return NULL;
2181}
2182
Jeremy Hylton8caad492000-06-23 14:18:11 +00002183static int
2184list_traverse(PyListObject *o, visitproc visit, void *arg)
2185{
2186 int i, err;
2187 PyObject *x;
2188
2189 for (i = o->ob_size; --i >= 0; ) {
2190 x = o->ob_item[i];
2191 if (x != NULL) {
2192 err = visit(x, arg);
2193 if (err)
2194 return err;
2195 }
2196 }
2197 return 0;
2198}
2199
2200static int
2201list_clear(PyListObject *lp)
2202{
2203 (void) PyList_SetSlice((PyObject *)lp, 0, lp->ob_size, 0);
2204 return 0;
2205}
2206
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002207static PyObject *
2208list_richcompare(PyObject *v, PyObject *w, int op)
2209{
2210 PyListObject *vl, *wl;
2211 int i;
2212
2213 if (!PyList_Check(v) || !PyList_Check(w)) {
2214 Py_INCREF(Py_NotImplemented);
2215 return Py_NotImplemented;
2216 }
2217
2218 vl = (PyListObject *)v;
2219 wl = (PyListObject *)w;
2220
2221 if (vl->ob_size != wl->ob_size && (op == Py_EQ || op == Py_NE)) {
2222 /* Shortcut: if the lengths differ, the lists differ */
2223 PyObject *res;
2224 if (op == Py_EQ)
2225 res = Py_False;
2226 else
2227 res = Py_True;
2228 Py_INCREF(res);
2229 return res;
2230 }
2231
2232 /* Search for the first index where items are different */
2233 for (i = 0; i < vl->ob_size && i < wl->ob_size; i++) {
2234 int k = PyObject_RichCompareBool(vl->ob_item[i],
2235 wl->ob_item[i], Py_EQ);
2236 if (k < 0)
2237 return NULL;
2238 if (!k)
2239 break;
2240 }
2241
2242 if (i >= vl->ob_size || i >= wl->ob_size) {
2243 /* No more items to compare -- compare sizes */
2244 int vs = vl->ob_size;
2245 int ws = wl->ob_size;
2246 int cmp;
2247 PyObject *res;
2248 switch (op) {
2249 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00002250 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002251 case Py_EQ: cmp = vs == ws; break;
2252 case Py_NE: cmp = vs != ws; break;
2253 case Py_GT: cmp = vs > ws; break;
2254 case Py_GE: cmp = vs >= ws; break;
2255 default: return NULL; /* cannot happen */
2256 }
2257 if (cmp)
2258 res = Py_True;
2259 else
2260 res = Py_False;
2261 Py_INCREF(res);
2262 return res;
2263 }
2264
2265 /* We have an item that differs -- shortcuts for EQ/NE */
2266 if (op == Py_EQ) {
2267 Py_INCREF(Py_False);
2268 return Py_False;
2269 }
2270 if (op == Py_NE) {
2271 Py_INCREF(Py_True);
2272 return Py_True;
2273 }
2274
2275 /* Compare the final item again using the proper operator */
2276 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
2277}
2278
Tim Peters6d6c1a32001-08-02 04:15:00 +00002279static int
2280list_init(PyListObject *self, PyObject *args, PyObject *kw)
2281{
2282 PyObject *arg = NULL;
2283 static char *kwlist[] = {"sequence", 0};
2284
2285 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2286 return -1;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002287 /* Empty previous contents */
2288 if (self->ob_size != 0) {
2289 if (list_ass_slice(self, 0, self->ob_size, (PyObject *)NULL) != 0)
2290 return -1;
2291 }
2292 if (arg != NULL) {
2293 PyObject *rv = listextend(self, arg);
2294 if (rv == NULL)
2295 return -1;
2296 Py_DECREF(rv);
2297 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002298 return 0;
2299}
2300
Guido van Rossumdbb53d92001-12-03 16:32:18 +00002301static long
2302list_nohash(PyObject *self)
2303{
2304 PyErr_SetString(PyExc_TypeError, "list objects are unhashable");
2305 return -1;
2306}
2307
Raymond Hettinger1021c442003-11-07 15:38:09 +00002308static PyObject *list_iter(PyObject *seq);
2309static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2310
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002311PyDoc_STRVAR(getitem_doc,
2312"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002313PyDoc_STRVAR(reversed_doc,
2314"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002315PyDoc_STRVAR(append_doc,
2316"L.append(object) -- append object to end");
2317PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002318"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002319PyDoc_STRVAR(insert_doc,
2320"L.insert(index, object) -- insert object before index");
2321PyDoc_STRVAR(pop_doc,
2322"L.pop([index]) -> item -- remove and return item at index (default last)");
2323PyDoc_STRVAR(remove_doc,
2324"L.remove(value) -- remove first occurrence of value");
2325PyDoc_STRVAR(index_doc,
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002326"L.index(value, [start, [stop]]) -> integer -- return first index of value");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002327PyDoc_STRVAR(count_doc,
2328"L.count(value) -> integer -- return number of occurrences of value");
2329PyDoc_STRVAR(reverse_doc,
2330"L.reverse() -- reverse *IN PLACE*");
2331PyDoc_STRVAR(sort_doc,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002332"L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n\
2333cmp(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002334
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002335static PyObject *list_subscript(PyListObject*, PyObject*);
2336
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002337static PyMethodDef list_methods[] = {
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002338 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
Raymond Hettinger1021c442003-11-07 15:38:09 +00002339 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002340 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002341 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002342 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002343 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002344 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002345 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002346 {"count", (PyCFunction)listcount, METH_O, count_doc},
2347 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002348 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
Tim Petersa64dc242002-08-01 02:13:36 +00002349 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002350};
2351
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002352static PySequenceMethods list_as_sequence = {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002353 (inquiry)list_length, /* sq_length */
2354 (binaryfunc)list_concat, /* sq_concat */
2355 (intargfunc)list_repeat, /* sq_repeat */
2356 (intargfunc)list_item, /* sq_item */
2357 (intintargfunc)list_slice, /* sq_slice */
2358 (intobjargproc)list_ass_item, /* sq_ass_item */
2359 (intintobjargproc)list_ass_slice, /* sq_ass_slice */
2360 (objobjproc)list_contains, /* sq_contains */
2361 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2362 (intargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002363};
2364
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002365PyDoc_STRVAR(list_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002366"list() -> new list\n"
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002367"list(sequence) -> new list initialized from sequence's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002368
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002369static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002370list_subscript(PyListObject* self, PyObject* item)
2371{
2372 if (PyInt_Check(item)) {
2373 long i = PyInt_AS_LONG(item);
2374 if (i < 0)
2375 i += PyList_GET_SIZE(self);
2376 return list_item(self, i);
2377 }
2378 else if (PyLong_Check(item)) {
2379 long i = PyLong_AsLong(item);
2380 if (i == -1 && PyErr_Occurred())
2381 return NULL;
2382 if (i < 0)
2383 i += PyList_GET_SIZE(self);
2384 return list_item(self, i);
2385 }
2386 else if (PySlice_Check(item)) {
2387 int start, stop, step, slicelength, cur, i;
2388 PyObject* result;
2389 PyObject* it;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002390 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002391
2392 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
2393 &start, &stop, &step, &slicelength) < 0) {
2394 return NULL;
2395 }
2396
2397 if (slicelength <= 0) {
2398 return PyList_New(0);
2399 }
2400 else {
2401 result = PyList_New(slicelength);
2402 if (!result) return NULL;
2403
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002404 src = self->ob_item;
2405 dest = ((PyListObject *)result)->ob_item;
Tim Peters3b01a122002-07-19 02:35:45 +00002406 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002407 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002408 it = src[cur];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002409 Py_INCREF(it);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002410 dest[i] = it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002411 }
Tim Peters3b01a122002-07-19 02:35:45 +00002412
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002413 return result;
2414 }
2415 }
2416 else {
2417 PyErr_SetString(PyExc_TypeError,
2418 "list indices must be integers");
2419 return NULL;
2420 }
2421}
2422
Tim Peters3b01a122002-07-19 02:35:45 +00002423static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002424list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2425{
2426 if (PyInt_Check(item)) {
2427 long i = PyInt_AS_LONG(item);
2428 if (i < 0)
2429 i += PyList_GET_SIZE(self);
2430 return list_ass_item(self, i, value);
2431 }
2432 else if (PyLong_Check(item)) {
2433 long i = PyLong_AsLong(item);
2434 if (i == -1 && PyErr_Occurred())
2435 return -1;
2436 if (i < 0)
2437 i += PyList_GET_SIZE(self);
2438 return list_ass_item(self, i, value);
2439 }
2440 else if (PySlice_Check(item)) {
2441 int start, stop, step, slicelength;
2442
2443 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
2444 &start, &stop, &step, &slicelength) < 0) {
2445 return -1;
2446 }
2447
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002448 /* treat L[slice(a,b)] = v _exactly_ like L[a:b] = v */
2449 if (step == 1 && ((PySliceObject*)item)->step == Py_None)
2450 return list_ass_slice(self, start, stop, value);
2451
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002452 if (value == NULL) {
2453 /* delete slice */
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002454 PyObject **garbage;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002455 int cur, i;
Tim Peters3b01a122002-07-19 02:35:45 +00002456
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002457 if (slicelength <= 0)
2458 return 0;
2459
2460 if (step < 0) {
2461 stop = start + 1;
2462 start = stop + step*(slicelength - 1) - 1;
2463 step = -step;
2464 }
2465
2466 garbage = (PyObject**)
2467 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Tim Peters3b01a122002-07-19 02:35:45 +00002468
2469 /* drawing pictures might help
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002470 understand these for loops */
Guido van Rossum75a20b12002-06-11 12:22:28 +00002471 for (cur = start, i = 0;
2472 cur < stop;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002473 cur += step, i++) {
2474 int lim = step;
2475
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002476 garbage[i] = PyList_GET_ITEM(self, cur);
2477
Michael W. Hudson56796f62002-07-29 14:35:04 +00002478 if (cur + step >= self->ob_size) {
2479 lim = self->ob_size - cur - 1;
2480 }
2481
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002482 memmove(self->ob_item + cur - i,
2483 self->ob_item + cur + 1,
2484 lim * sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002485 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002486
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002487 for (cur = start + slicelength*step + 1;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002488 cur < self->ob_size; cur++) {
2489 PyList_SET_ITEM(self, cur - slicelength,
2490 PyList_GET_ITEM(self, cur));
2491 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002492
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002493 self->ob_size -= slicelength;
Raymond Hettingerd4ff7412004-03-15 09:01:31 +00002494 list_resize(self, self->ob_size);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002495
2496 for (i = 0; i < slicelength; i++) {
2497 Py_DECREF(garbage[i]);
2498 }
2499 PyMem_FREE(garbage);
2500
2501 return 0;
2502 }
2503 else {
2504 /* assign slice */
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002505 PyObject **garbage, *ins, *seq, **seqitems, **selfitems;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002506 int cur, i;
2507
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002508 /* protect against a[::-1] = a */
Tim Peters3b01a122002-07-19 02:35:45 +00002509 if (self == (PyListObject*)value) {
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002510 seq = list_slice((PyListObject*)value, 0,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002511 PyList_GET_SIZE(value));
Tim Peters3b01a122002-07-19 02:35:45 +00002512 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002513 else {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002514 seq = PySequence_Fast(value,
2515 "must assign iterable to extended slice");
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002516 if (!seq)
2517 return -1;
2518 }
2519
2520 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2521 PyErr_Format(PyExc_ValueError,
2522 "attempt to assign sequence of size %d to extended slice of size %d",
2523 PySequence_Fast_GET_SIZE(seq),
2524 slicelength);
2525 Py_DECREF(seq);
2526 return -1;
2527 }
2528
2529 if (!slicelength) {
2530 Py_DECREF(seq);
2531 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002532 }
2533
2534 garbage = (PyObject**)
2535 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Tim Peters3b01a122002-07-19 02:35:45 +00002536
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002537 selfitems = self->ob_item;
Raymond Hettinger42bec932004-03-12 16:38:17 +00002538 seqitems = PySequence_Fast_ITEMS(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002539 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002540 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002541 garbage[i] = selfitems[cur];
2542 ins = seqitems[i];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002543 Py_INCREF(ins);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002544 selfitems[cur] = ins;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002545 }
2546
2547 for (i = 0; i < slicelength; i++) {
2548 Py_DECREF(garbage[i]);
2549 }
Tim Peters3b01a122002-07-19 02:35:45 +00002550
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002551 PyMem_FREE(garbage);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002552 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002553
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002554 return 0;
2555 }
Tim Peters3b01a122002-07-19 02:35:45 +00002556 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002557 else {
Tim Peters3b01a122002-07-19 02:35:45 +00002558 PyErr_SetString(PyExc_TypeError,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002559 "list indices must be integers");
2560 return -1;
2561 }
2562}
2563
2564static PyMappingMethods list_as_mapping = {
2565 (inquiry)list_length,
2566 (binaryfunc)list_subscript,
2567 (objobjargproc)list_ass_subscript
2568};
2569
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002570PyTypeObject PyList_Type = {
2571 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002572 0,
2573 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002574 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002575 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002576 (destructor)list_dealloc, /* tp_dealloc */
2577 (printfunc)list_print, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002578 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002579 0, /* tp_setattr */
2580 0, /* tp_compare */
2581 (reprfunc)list_repr, /* tp_repr */
2582 0, /* tp_as_number */
2583 &list_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002584 &list_as_mapping, /* tp_as_mapping */
Guido van Rossumdbb53d92001-12-03 16:32:18 +00002585 list_nohash, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002586 0, /* tp_call */
2587 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002588 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002589 0, /* tp_setattro */
2590 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002591 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Tim Peters6d6c1a32001-08-02 04:15:00 +00002592 Py_TPFLAGS_BASETYPE, /* tp_flags */
2593 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002594 (traverseproc)list_traverse, /* tp_traverse */
2595 (inquiry)list_clear, /* tp_clear */
2596 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002597 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002598 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002599 0, /* tp_iternext */
2600 list_methods, /* tp_methods */
2601 0, /* tp_members */
2602 0, /* tp_getset */
2603 0, /* tp_base */
2604 0, /* tp_dict */
2605 0, /* tp_descr_get */
2606 0, /* tp_descr_set */
2607 0, /* tp_dictoffset */
2608 (initproc)list_init, /* tp_init */
2609 PyType_GenericAlloc, /* tp_alloc */
2610 PyType_GenericNew, /* tp_new */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002611 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002612};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002613
2614
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002615/*********************** List Iterator **************************/
2616
2617typedef struct {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002618 PyObject_HEAD
2619 long it_index;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002620 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002621} listiterobject;
2622
2623PyTypeObject PyListIter_Type;
2624
Guido van Rossum5086e492002-07-16 15:56:52 +00002625static PyObject *
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002626list_iter(PyObject *seq)
2627{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002628 listiterobject *it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002629
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002630 if (!PyList_Check(seq)) {
2631 PyErr_BadInternalCall();
2632 return NULL;
2633 }
2634 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2635 if (it == NULL)
2636 return NULL;
2637 it->it_index = 0;
2638 Py_INCREF(seq);
2639 it->it_seq = (PyListObject *)seq;
2640 _PyObject_GC_TRACK(it);
2641 return (PyObject *)it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002642}
2643
2644static void
2645listiter_dealloc(listiterobject *it)
2646{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002647 _PyObject_GC_UNTRACK(it);
Guido van Rossum86103ae2002-07-16 20:07:32 +00002648 Py_XDECREF(it->it_seq);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002649 PyObject_GC_Del(it);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002650}
2651
2652static int
2653listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2654{
Guido van Rossum86103ae2002-07-16 20:07:32 +00002655 if (it->it_seq == NULL)
2656 return 0;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002657 return visit((PyObject *)it->it_seq, arg);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002658}
2659
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002660static PyObject *
Tim Peters93b2cc42002-06-01 05:22:55 +00002661listiter_next(listiterobject *it)
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002662{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002663 PyListObject *seq;
2664 PyObject *item;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002665
Tim Peters93b2cc42002-06-01 05:22:55 +00002666 assert(it != NULL);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002667 seq = it->it_seq;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002668 if (seq == NULL)
2669 return NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002670 assert(PyList_Check(seq));
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002671
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002672 if (it->it_index < PyList_GET_SIZE(seq)) {
Tim Peters93b2cc42002-06-01 05:22:55 +00002673 item = PyList_GET_ITEM(seq, it->it_index);
2674 ++it->it_index;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002675 Py_INCREF(item);
2676 return item;
2677 }
Guido van Rossum86103ae2002-07-16 20:07:32 +00002678
2679 Py_DECREF(seq);
2680 it->it_seq = NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002681 return NULL;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002682}
2683
Raymond Hettinger435bf582004-03-18 22:43:10 +00002684static int
2685listiter_len(listiterobject *it)
2686{
2687 if (it->it_seq)
2688 return PyList_GET_SIZE(it->it_seq) - it->it_index;
2689 return 0;
2690}
2691
2692static PySequenceMethods listiter_as_sequence = {
2693 (inquiry)listiter_len, /* sq_length */
2694 0, /* sq_concat */
2695};
2696
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002697PyTypeObject PyListIter_Type = {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002698 PyObject_HEAD_INIT(&PyType_Type)
2699 0, /* ob_size */
2700 "listiterator", /* tp_name */
2701 sizeof(listiterobject), /* tp_basicsize */
2702 0, /* tp_itemsize */
2703 /* methods */
2704 (destructor)listiter_dealloc, /* tp_dealloc */
2705 0, /* tp_print */
2706 0, /* tp_getattr */
2707 0, /* tp_setattr */
2708 0, /* tp_compare */
2709 0, /* tp_repr */
2710 0, /* tp_as_number */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002711 &listiter_as_sequence, /* tp_as_sequence */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002712 0, /* tp_as_mapping */
2713 0, /* tp_hash */
2714 0, /* tp_call */
2715 0, /* tp_str */
2716 PyObject_GenericGetAttr, /* tp_getattro */
2717 0, /* tp_setattro */
2718 0, /* tp_as_buffer */
2719 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2720 0, /* tp_doc */
2721 (traverseproc)listiter_traverse, /* tp_traverse */
2722 0, /* tp_clear */
2723 0, /* tp_richcompare */
2724 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00002725 PyObject_SelfIter, /* tp_iter */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002726 (iternextfunc)listiter_next, /* tp_iternext */
Guido van Rossum86103ae2002-07-16 20:07:32 +00002727 0, /* tp_methods */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002728 0, /* tp_members */
2729 0, /* tp_getset */
2730 0, /* tp_base */
2731 0, /* tp_dict */
2732 0, /* tp_descr_get */
2733 0, /* tp_descr_set */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002734};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002735
2736/*********************** List Reverse Iterator **************************/
2737
2738typedef struct {
2739 PyObject_HEAD
2740 long it_index;
Raymond Hettinger001f2282003-11-08 11:58:44 +00002741 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002742} listreviterobject;
2743
2744PyTypeObject PyListRevIter_Type;
2745
2746static PyObject *
2747list_reversed(PyListObject *seq, PyObject *unused)
2748{
2749 listreviterobject *it;
2750
2751 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2752 if (it == NULL)
2753 return NULL;
2754 assert(PyList_Check(seq));
2755 it->it_index = PyList_GET_SIZE(seq) - 1;
2756 Py_INCREF(seq);
2757 it->it_seq = seq;
2758 PyObject_GC_Track(it);
2759 return (PyObject *)it;
2760}
2761
2762static void
2763listreviter_dealloc(listreviterobject *it)
2764{
2765 PyObject_GC_UnTrack(it);
2766 Py_XDECREF(it->it_seq);
2767 PyObject_GC_Del(it);
2768}
2769
2770static int
2771listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2772{
2773 if (it->it_seq == NULL)
2774 return 0;
2775 return visit((PyObject *)it->it_seq, arg);
2776}
2777
2778static PyObject *
2779listreviter_next(listreviterobject *it)
2780{
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002781 PyObject *item;
2782 long index = it->it_index;
2783 PyListObject *seq = it->it_seq;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002784
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002785 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2786 item = PyList_GET_ITEM(seq, index);
Raymond Hettinger1021c442003-11-07 15:38:09 +00002787 it->it_index--;
2788 Py_INCREF(item);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002789 return item;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002790 }
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002791 it->it_index = -1;
2792 if (seq != NULL) {
2793 it->it_seq = NULL;
2794 Py_DECREF(seq);
2795 }
2796 return NULL;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002797}
2798
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002799static int
2800listreviter_len(listreviterobject *it)
2801{
2802 return it->it_index + 1;
2803}
2804
2805static PySequenceMethods listreviter_as_sequence = {
2806 (inquiry)listreviter_len, /* sq_length */
2807 0, /* sq_concat */
2808};
2809
Raymond Hettinger1021c442003-11-07 15:38:09 +00002810PyTypeObject PyListRevIter_Type = {
2811 PyObject_HEAD_INIT(&PyType_Type)
2812 0, /* ob_size */
2813 "listreverseiterator", /* tp_name */
2814 sizeof(listreviterobject), /* tp_basicsize */
2815 0, /* tp_itemsize */
2816 /* methods */
2817 (destructor)listreviter_dealloc, /* tp_dealloc */
2818 0, /* tp_print */
2819 0, /* tp_getattr */
2820 0, /* tp_setattr */
2821 0, /* tp_compare */
2822 0, /* tp_repr */
2823 0, /* tp_as_number */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002824 &listreviter_as_sequence, /* tp_as_sequence */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002825 0, /* tp_as_mapping */
2826 0, /* tp_hash */
2827 0, /* tp_call */
2828 0, /* tp_str */
2829 PyObject_GenericGetAttr, /* tp_getattro */
2830 0, /* tp_setattro */
2831 0, /* tp_as_buffer */
2832 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2833 0, /* tp_doc */
2834 (traverseproc)listreviter_traverse, /* tp_traverse */
2835 0, /* tp_clear */
2836 0, /* tp_richcompare */
2837 0, /* tp_weaklistoffset */
2838 PyObject_SelfIter, /* tp_iter */
2839 (iternextfunc)listreviter_next, /* tp_iternext */
2840 0,
2841};