blob: 2f2097d0d5aac0b766c7a7f9a2296316e06128c8 [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 Hettinger4bb95402004-02-13 11:36:39 +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 Hettingerab517d22004-02-14 18:34:46 +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
155 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 Hettingerf889e102004-03-09 08:04:33 +0000494 if (PyList_Check(v_as_SF))
495 vitem = ((PyListObject *)v_as_SF)->ob_item;
496 else {
497 assert (PyTuple_Check(v_as_SF));
498 vitem = ((PyTupleObject *)v_as_SF)->ob_item;
499 }
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000500 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000501 if (ilow < 0)
502 ilow = 0;
503 else if (ilow > a->ob_size)
504 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000505 if (ihigh < ilow)
506 ihigh = ilow;
507 else if (ihigh > a->ob_size)
508 ihigh = a->ob_size;
509 item = a->ob_item;
510 d = n - (ihigh-ilow);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000511 if (ihigh > ilow) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000512 p = recycle = PyMem_NEW(PyObject *, (ihigh-ilow));
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000513 if (recycle == NULL) {
514 PyErr_NoMemory();
515 return -1;
516 }
517 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000518 else
519 p = recycle = NULL;
520 if (d <= 0) { /* Delete -d items; recycle ihigh-ilow items */
Raymond Hettinger66d31f82004-03-10 11:44:04 +0000521 memcpy(p, &item[ilow], (ihigh - ilow)*sizeof(PyObject *));
Raymond Hettingerf889e102004-03-09 08:04:33 +0000522 p += ihigh - ilow;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000523 if (d < 0) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000524 memmove(&item[ihigh+d], &item[ihigh],
525 (a->ob_size - ihigh)*sizeof(PyObject *));
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000526 list_resize(a, a->ob_size + d);
527 item = a->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000528 }
529 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000530 else { /* Insert d items; recycle ihigh-ilow items */
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000531 s = a->ob_size;
532 if (list_resize(a, s+d) == -1) {
Guido van Rossumb18618d2000-05-03 23:44:39 +0000533 if (recycle != NULL)
534 PyMem_DEL(recycle);
Raymond Hettinger2731ae42004-02-14 03:07:21 +0000535 return -1;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000536 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000537 item = a->ob_item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000538 memmove(&item[ihigh+d], &item[ihigh],
539 (s - ihigh)*sizeof(PyObject *));
Raymond Hettinger66d31f82004-03-10 11:44:04 +0000540 memcpy(p, &item[ilow], (ihigh - ilow)*sizeof(PyObject *));
Raymond Hettingerf889e102004-03-09 08:04:33 +0000541 p += ihigh - ilow;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000542 }
543 for (k = 0; k < n; k++, ilow++) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000544 PyObject *w = vitem[k];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000545 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000546 item[ilow] = w;
547 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000548 if (recycle) {
549 while (--p >= recycle)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000550 Py_XDECREF(*p);
551 PyMem_DEL(recycle);
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000552 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000553 if (a->ob_size == 0 && a->ob_item != NULL) {
554 PyMem_FREE(a->ob_item);
555 a->ob_item = NULL;
556 }
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000557 Py_XDECREF(v_as_SF);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000558 return 0;
559#undef b
560}
561
Guido van Rossum234f9421993-06-17 12:35:49 +0000562int
Fred Drakea2f55112000-07-09 15:16:51 +0000563PyList_SetSlice(PyObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000564{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000565 if (!PyList_Check(a)) {
566 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000567 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000568 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000569 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000570}
571
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000572static PyObject *
573list_inplace_repeat(PyListObject *self, int n)
574{
575 PyObject **items;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000576 int size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000577
578
579 size = PyList_GET_SIZE(self);
580 if (size == 0) {
581 Py_INCREF(self);
582 return (PyObject *)self;
583 }
584
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000585 if (n < 1) {
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000586 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000587 self->ob_item = NULL;
588 self->ob_size = 0;
589 for (i = 0; i < size; i++)
590 Py_XDECREF(items[i]);
591 PyMem_DEL(items);
592 Py_INCREF(self);
593 return (PyObject *)self;
594 }
595
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000596 if (list_resize(self, size*n) == -1)
597 return NULL;
598
599 p = size;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000600 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000601 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
602 for (j = 0; j < size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000603 PyObject *o = items[j];
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000604 Py_INCREF(o);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000605 items[p++] = o;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000606 }
607 }
608 Py_INCREF(self);
609 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000610}
611
Guido van Rossum4a450d01991-04-03 19:05:18 +0000612static int
Fred Drakea2f55112000-07-09 15:16:51 +0000613list_ass_item(PyListObject *a, int i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000614{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000615 PyObject *old_value;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000616 if (i < 0 || i >= a->ob_size) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000617 PyErr_SetString(PyExc_IndexError,
618 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000619 return -1;
620 }
621 if (v == NULL)
622 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000623 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000624 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000625 a->ob_item[i] = v;
Tim Peters3b01a122002-07-19 02:35:45 +0000626 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000627 return 0;
628}
629
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000630static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000631ins(PyListObject *self, int where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000632{
633 if (ins1(self, where, v) != 0)
634 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000635 Py_INCREF(Py_None);
636 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000637}
638
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000639static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000640listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000641{
642 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000643 PyObject *v;
Guido van Rossumc00a9382000-02-24 21:48:29 +0000644 if (!PyArg_ParseTuple(args, "iO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000645 return NULL;
Guido van Rossumbf80e541993-02-08 15:49:17 +0000646 return ins(self, i, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000647}
648
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000649static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000650listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000651{
Guido van Rossumbf80e541993-02-08 15:49:17 +0000652 return ins(self, (int) self->ob_size, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000653}
654
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000655static int
656listextend_internal(PyListObject *self, PyObject *b)
Barry Warsawdedf6d61998-10-09 16:37:25 +0000657{
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000658 register int selflen = PyList_GET_SIZE(self);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000659 int blen;
660 register int i;
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000661 PyObject **src, **dest;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000662
Jeremy Hyltondb60bb52001-01-03 22:32:16 +0000663 if (PyObject_Size(b) == 0) {
Barry Warsawdedf6d61998-10-09 16:37:25 +0000664 /* short circuit when b is empty */
Jeremy Hyltondb60bb52001-01-03 22:32:16 +0000665 Py_DECREF(b);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000666 return 0;
Jeremy Hyltondb60bb52001-01-03 22:32:16 +0000667 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000668
Barry Warsawdedf6d61998-10-09 16:37:25 +0000669 if (self == (PyListObject*)b) {
670 /* as in list_ass_slice() we must special case the
671 * situation: a.extend(a)
672 *
673 * XXX: I think this way ought to be faster than using
674 * list_slice() the way list_ass_slice() does.
675 */
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000676 Py_DECREF(b);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000677 b = PyList_New(selflen);
678 if (!b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000679 return -1;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000680 for (i = 0; i < selflen; i++) {
681 PyObject *o = PyList_GET_ITEM(self, i);
682 Py_INCREF(o);
683 PyList_SET_ITEM(b, i, o);
684 }
685 }
Barry Warsawdedf6d61998-10-09 16:37:25 +0000686
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000687 blen = PyObject_Size(b);
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000688 if (list_resize(self, selflen + blen) == -1) {
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000689 Py_DECREF(b);
690 return -1;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000691 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000692
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000693 /* populate the end of self with b's items */
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000694 if (PyList_Check(b))
695 src = ((PyListObject *)b)->ob_item;
696 else {
Raymond Hettinger99842b62004-03-08 05:56:15 +0000697 assert (PyTuple_Check(b));
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000698 src = ((PyTupleObject *)b)->ob_item;
699 }
700 dest = self->ob_item + selflen;
701 for (i = 0; i < blen; i++) {
702 PyObject *o = src[i];
703 Py_INCREF(o);
704 dest[i] = o;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000705 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000706 Py_DECREF(b);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000707 return 0;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000708}
709
Barry Warsawdedf6d61998-10-09 16:37:25 +0000710static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000711listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000712{
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000713 PyObject *it; /* iter(v) */
714 int m; /* size of self */
715 int n; /* guess for size of b */
716 int mn; /* m + n */
717 int i;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000718 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000719
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000720 /* Special cases:
721 1) lists and tuples which can use PySequence_Fast ops
722 2) extending self to self requires making a copy first
723 */
724 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
725 b = PySequence_Fast(b, "argument must be iterable");
726 if (!b)
727 return NULL;
728 if (listextend_internal(self, b) < 0)
729 return NULL;
730 Py_RETURN_NONE;
731 }
732
733 it = PyObject_GetIter(b);
734 if (it == NULL)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000735 return NULL;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000736 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000737
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000738 /* Guess a result list size. */
739 n = PyObject_Size(b);
740 if (n < 0) {
741 PyErr_Clear();
742 n = 8; /* arbitrary */
743 }
744 m = self->ob_size;
745 mn = m + n;
746 if (list_resize(self, mn) == -1)
747 goto error;
748 memset(&(self->ob_item[m]), 0, sizeof(*self->ob_item) * n);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000749
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000750 /* Run iterator to exhaustion. */
751 for (i = m; ; i++) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000752 PyObject *item = iternext(it);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000753 if (item == NULL) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000754 if (PyErr_Occurred()) {
755 if (PyErr_ExceptionMatches(PyExc_StopIteration))
756 PyErr_Clear();
757 else
758 goto error;
759 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000760 break;
761 }
762 if (i < mn)
763 PyList_SET_ITEM(self, i, item); /* steals ref */
764 else {
765 int status = ins1(self, self->ob_size, item);
766 Py_DECREF(item); /* append creates a new ref */
767 if (status < 0)
768 goto error;
769 }
770 }
771
772 /* Cut back result list if initial guess was too large. */
773 if (i < mn && self != NULL) {
774 if (list_ass_slice(self, i, mn, (PyObject *)NULL) != 0)
775 goto error;
776 }
777 Py_DECREF(it);
778 Py_RETURN_NONE;
779
780 error:
781 Py_DECREF(it);
782 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000783}
784
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000785PyObject *
786_PyList_Extend(PyListObject *self, PyObject *b)
787{
788 return listextend(self, b);
789}
790
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000791static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000792list_inplace_concat(PyListObject *self, PyObject *other)
793{
794 PyObject *result;
795
796 result = listextend(self, other);
797 if (result == NULL)
798 return result;
799 Py_DECREF(result);
800 Py_INCREF(self);
801 return (PyObject *)self;
802}
803
804static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000805listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000806{
807 int i = -1;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000808 PyObject *v, *arg = NULL;
809
810 if (!PyArg_UnpackTuple(args, "pop", 0, 1, &arg))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000811 return NULL;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000812 if (arg != NULL) {
813 if (PyInt_Check(arg))
814 i = (int)(PyInt_AS_LONG((PyIntObject*) arg));
Raymond Hettingerfa6c6f82004-02-19 06:12:06 +0000815 else if (!PyArg_ParseTuple(args, "|i:pop", &i))
816 return NULL;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000817 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000818 if (self->ob_size == 0) {
819 /* Special-case most common failure cause */
820 PyErr_SetString(PyExc_IndexError, "pop from empty list");
821 return NULL;
822 }
823 if (i < 0)
824 i += self->ob_size;
825 if (i < 0 || i >= self->ob_size) {
826 PyErr_SetString(PyExc_IndexError, "pop index out of range");
827 return NULL;
828 }
829 v = self->ob_item[i];
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000830 if (i == self->ob_size - 1) {
831 if (list_resize(self, self->ob_size - 1) == -1)
832 return NULL;
833 return v;
834 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000835 Py_INCREF(v);
836 if (list_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) {
837 Py_DECREF(v);
838 return NULL;
839 }
840 return v;
841}
842
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000843/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
844static void
845reverse_slice(PyObject **lo, PyObject **hi)
846{
847 assert(lo && hi);
848
849 --hi;
850 while (lo < hi) {
851 PyObject *t = *lo;
852 *lo = *hi;
853 *hi = t;
854 ++lo;
855 --hi;
856 }
857}
858
Tim Petersa64dc242002-08-01 02:13:36 +0000859/* Lots of code for an adaptive, stable, natural mergesort. There are many
860 * pieces to this algorithm; read listsort.txt for overviews and details.
861 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000862
Guido van Rossum3f236de1996-12-10 23:55:39 +0000863/* Comparison function. Takes care of calling a user-supplied
Tim Peters66860f62002-08-04 17:47:26 +0000864 * comparison function (any callable Python object), which must not be
865 * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool
866 * with Py_LT if you know it's NULL).
Tim Petersa64dc242002-08-01 02:13:36 +0000867 * Returns -1 on error, 1 if x < y, 0 if x >= y.
868 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000869static int
Tim Petersa8c974c2002-07-19 03:30:57 +0000870islt(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000871{
Tim Petersf2a04732002-07-11 21:46:16 +0000872 PyObject *res;
873 PyObject *args;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000874 int i;
875
Tim Peters66860f62002-08-04 17:47:26 +0000876 assert(compare != NULL);
Tim Petersa8c974c2002-07-19 03:30:57 +0000877 /* Call the user's comparison function and translate the 3-way
878 * result into true or false (or error).
879 */
Tim Petersf2a04732002-07-11 21:46:16 +0000880 args = PyTuple_New(2);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000881 if (args == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000882 return -1;
Tim Petersf2a04732002-07-11 21:46:16 +0000883 Py_INCREF(x);
884 Py_INCREF(y);
885 PyTuple_SET_ITEM(args, 0, x);
886 PyTuple_SET_ITEM(args, 1, y);
Tim Peters58cf3612002-07-15 05:16:13 +0000887 res = PyObject_Call(compare, args, NULL);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000888 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000889 if (res == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000890 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000891 if (!PyInt_Check(res)) {
892 Py_DECREF(res);
893 PyErr_SetString(PyExc_TypeError,
Guido van Rossum9bcd1d71999-04-19 17:44:39 +0000894 "comparison function must return int");
Tim Petersa8c974c2002-07-19 03:30:57 +0000895 return -1;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000896 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000897 i = PyInt_AsLong(res);
898 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +0000899 return i < 0;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000900}
901
Tim Peters66860f62002-08-04 17:47:26 +0000902/* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
903 * islt. This avoids a layer of function call in the usual case, and
904 * sorting does many comparisons.
905 * Returns -1 on error, 1 if x < y, 0 if x >= y.
906 */
907#define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
908 PyObject_RichCompareBool(X, Y, Py_LT) : \
909 islt(X, Y, COMPARE))
910
911/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +0000912 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
913 started. It makes more sense in context <wink>. X and Y are PyObject*s.
914*/
Tim Peters66860f62002-08-04 17:47:26 +0000915#define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
Tim Petersa8c974c2002-07-19 03:30:57 +0000916 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000917
918/* binarysort is the best method for sorting small arrays: it does
919 few compares, but can do data movement quadratic in the number of
920 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000921 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +0000922 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000923 On entry, must have lo <= start <= hi, and that [lo, start) is already
924 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +0000925 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000926 Even in case of error, the output slice will be some permutation of
927 the input (nothing is lost or duplicated).
928*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000929static int
Fred Drakea2f55112000-07-09 15:16:51 +0000930binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
931 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000932{
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000933 register int k;
934 register PyObject **l, **p, **r;
935 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000936
Tim Petersa8c974c2002-07-19 03:30:57 +0000937 assert(lo <= start && start <= hi);
938 /* assert [lo, start) is sorted */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000939 if (lo == start)
940 ++start;
941 for (; start < hi; ++start) {
942 /* set l to where *start belongs */
943 l = lo;
944 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000945 pivot = *r;
Tim Peters0fe977c2002-07-19 06:12:32 +0000946 /* Invariants:
947 * pivot >= all in [lo, l).
948 * pivot < all in [r, start).
949 * The second is vacuously true at the start.
950 */
951 assert(l < r);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000952 do {
953 p = l + ((r - l) >> 1);
Tim Petersa8c974c2002-07-19 03:30:57 +0000954 IFLT(pivot, *p)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000955 r = p;
956 else
Tim Peters0fe977c2002-07-19 06:12:32 +0000957 l = p+1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000958 } while (l < r);
Tim Peters0fe977c2002-07-19 06:12:32 +0000959 assert(l == r);
960 /* The invariants still hold, so pivot >= all in [lo, l) and
961 pivot < all in [l, start), so pivot belongs at l. Note
962 that if there are elements equal to pivot, l points to the
963 first slot after them -- that's why this sort is stable.
964 Slide over to make room.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000965 Caution: using memmove is much slower under MSVC 5;
966 we're not usually moving many slots. */
967 for (p = start; p > l; --p)
968 *p = *(p-1);
969 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000970 }
Guido van Rossum3f236de1996-12-10 23:55:39 +0000971 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000972
973 fail:
974 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000975}
976
Tim Petersa64dc242002-08-01 02:13:36 +0000977/*
978Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
979is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000980
Tim Petersa64dc242002-08-01 02:13:36 +0000981 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000982
Tim Petersa64dc242002-08-01 02:13:36 +0000983or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000984
Tim Petersa64dc242002-08-01 02:13:36 +0000985 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +0000986
Tim Petersa64dc242002-08-01 02:13:36 +0000987Boolean *descending is set to 0 in the former case, or to 1 in the latter.
988For its intended use in a stable mergesort, the strictness of the defn of
989"descending" is needed so that the caller can safely reverse a descending
990sequence without violating stability (strict > ensures there are no equal
991elements to get out of order).
992
993Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000994*/
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000995static int
Tim Petersa64dc242002-08-01 02:13:36 +0000996count_run(PyObject **lo, PyObject **hi, PyObject *compare, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000997{
Tim Petersa64dc242002-08-01 02:13:36 +0000998 int k;
999 int n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001000
Tim Petersa64dc242002-08-01 02:13:36 +00001001 assert(lo < hi);
1002 *descending = 0;
1003 ++lo;
1004 if (lo == hi)
1005 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001006
Tim Petersa64dc242002-08-01 02:13:36 +00001007 n = 2;
1008 IFLT(*lo, *(lo-1)) {
1009 *descending = 1;
1010 for (lo = lo+1; lo < hi; ++lo, ++n) {
1011 IFLT(*lo, *(lo-1))
1012 ;
1013 else
1014 break;
1015 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001016 }
Tim Petersa64dc242002-08-01 02:13:36 +00001017 else {
1018 for (lo = lo+1; lo < hi; ++lo, ++n) {
1019 IFLT(*lo, *(lo-1))
1020 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001021 }
1022 }
1023
Tim Petersa64dc242002-08-01 02:13:36 +00001024 return n;
1025fail:
1026 return -1;
1027}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001028
Tim Petersa64dc242002-08-01 02:13:36 +00001029/*
1030Locate the proper position of key in a sorted vector; if the vector contains
1031an element equal to key, return the position immediately to the left of
1032the leftmost equal element. [gallop_right() does the same except returns
1033the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001034
Tim Petersa64dc242002-08-01 02:13:36 +00001035"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001036
Tim Petersa64dc242002-08-01 02:13:36 +00001037"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1038hint is to the final result, the faster this runs.
1039
1040The return value is the int k in 0..n such that
1041
1042 a[k-1] < key <= a[k]
1043
1044pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1045key belongs at index k; or, IOW, the first k elements of a should precede
1046key, and the last n-k should follow key.
1047
1048Returns -1 on error. See listsort.txt for info on the method.
1049*/
1050static int
1051gallop_left(PyObject *key, PyObject **a, int n, int hint, PyObject *compare)
1052{
1053 int ofs;
1054 int lastofs;
1055 int k;
1056
1057 assert(key && a && n > 0 && hint >= 0 && hint < n);
1058
1059 a += hint;
1060 lastofs = 0;
1061 ofs = 1;
1062 IFLT(*a, key) {
1063 /* a[hint] < key -- gallop right, until
1064 * a[hint + lastofs] < key <= a[hint + ofs]
1065 */
1066 const int maxofs = n - hint; /* &a[n-1] is highest */
1067 while (ofs < maxofs) {
1068 IFLT(a[ofs], key) {
1069 lastofs = ofs;
1070 ofs = (ofs << 1) + 1;
1071 if (ofs <= 0) /* int overflow */
1072 ofs = maxofs;
1073 }
1074 else /* key <= a[hint + ofs] */
1075 break;
1076 }
1077 if (ofs > maxofs)
1078 ofs = maxofs;
1079 /* Translate back to offsets relative to &a[0]. */
1080 lastofs += hint;
1081 ofs += hint;
1082 }
1083 else {
1084 /* key <= a[hint] -- gallop left, until
1085 * a[hint - ofs] < key <= a[hint - lastofs]
1086 */
1087 const int maxofs = hint + 1; /* &a[0] is lowest */
1088 while (ofs < maxofs) {
1089 IFLT(*(a-ofs), key)
1090 break;
1091 /* key <= a[hint - ofs] */
1092 lastofs = ofs;
1093 ofs = (ofs << 1) + 1;
1094 if (ofs <= 0) /* int overflow */
1095 ofs = maxofs;
1096 }
1097 if (ofs > maxofs)
1098 ofs = maxofs;
1099 /* Translate back to positive offsets relative to &a[0]. */
1100 k = lastofs;
1101 lastofs = hint - ofs;
1102 ofs = hint - k;
1103 }
1104 a -= hint;
1105
1106 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1107 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1108 * right of lastofs but no farther right than ofs. Do a binary
1109 * search, with invariant a[lastofs-1] < key <= a[ofs].
1110 */
1111 ++lastofs;
1112 while (lastofs < ofs) {
1113 int m = lastofs + ((ofs - lastofs) >> 1);
1114
1115 IFLT(a[m], key)
1116 lastofs = m+1; /* a[m] < key */
1117 else
1118 ofs = m; /* key <= a[m] */
1119 }
1120 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1121 return ofs;
1122
1123fail:
1124 return -1;
1125}
1126
1127/*
1128Exactly like gallop_left(), except that if key already exists in a[0:n],
1129finds the position immediately to the right of the rightmost equal value.
1130
1131The return value is the int k in 0..n such that
1132
1133 a[k-1] <= key < a[k]
1134
1135or -1 if error.
1136
1137The code duplication is massive, but this is enough different given that
1138we're sticking to "<" comparisons that it's much harder to follow if
1139written as one routine with yet another "left or right?" flag.
1140*/
1141static int
1142gallop_right(PyObject *key, PyObject **a, int n, int hint, PyObject *compare)
1143{
1144 int ofs;
1145 int lastofs;
1146 int k;
1147
1148 assert(key && a && n > 0 && hint >= 0 && hint < n);
1149
1150 a += hint;
1151 lastofs = 0;
1152 ofs = 1;
1153 IFLT(key, *a) {
1154 /* key < a[hint] -- gallop left, until
1155 * a[hint - ofs] <= key < a[hint - lastofs]
1156 */
1157 const int maxofs = hint + 1; /* &a[0] is lowest */
1158 while (ofs < maxofs) {
1159 IFLT(key, *(a-ofs)) {
1160 lastofs = ofs;
1161 ofs = (ofs << 1) + 1;
1162 if (ofs <= 0) /* int overflow */
1163 ofs = maxofs;
1164 }
1165 else /* a[hint - ofs] <= key */
1166 break;
1167 }
1168 if (ofs > maxofs)
1169 ofs = maxofs;
1170 /* Translate back to positive offsets relative to &a[0]. */
1171 k = lastofs;
1172 lastofs = hint - ofs;
1173 ofs = hint - k;
1174 }
1175 else {
1176 /* a[hint] <= key -- gallop right, until
1177 * a[hint + lastofs] <= key < a[hint + ofs]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001178 */
Tim Petersa64dc242002-08-01 02:13:36 +00001179 const int maxofs = n - hint; /* &a[n-1] is highest */
1180 while (ofs < maxofs) {
1181 IFLT(key, a[ofs])
1182 break;
1183 /* a[hint + ofs] <= key */
1184 lastofs = ofs;
1185 ofs = (ofs << 1) + 1;
1186 if (ofs <= 0) /* int overflow */
1187 ofs = maxofs;
1188 }
1189 if (ofs > maxofs)
1190 ofs = maxofs;
1191 /* Translate back to offsets relative to &a[0]. */
1192 lastofs += hint;
1193 ofs += hint;
1194 }
1195 a -= hint;
1196
1197 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1198 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1199 * right of lastofs but no farther right than ofs. Do a binary
1200 * search, with invariant a[lastofs-1] <= key < a[ofs].
1201 */
1202 ++lastofs;
1203 while (lastofs < ofs) {
1204 int m = lastofs + ((ofs - lastofs) >> 1);
1205
1206 IFLT(key, a[m])
1207 ofs = m; /* key < a[m] */
1208 else
1209 lastofs = m+1; /* a[m] <= key */
1210 }
1211 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1212 return ofs;
1213
1214fail:
1215 return -1;
1216}
1217
1218/* The maximum number of entries in a MergeState's pending-runs stack.
1219 * This is enough to sort arrays of size up to about
1220 * 32 * phi ** MAX_MERGE_PENDING
1221 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1222 * with 2**64 elements.
1223 */
1224#define MAX_MERGE_PENDING 85
1225
Tim Peterse05f65a2002-08-10 05:21:15 +00001226/* When we get into galloping mode, we stay there until both runs win less
1227 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001228 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001229#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001230
1231/* Avoid malloc for small temp arrays. */
1232#define MERGESTATE_TEMP_SIZE 256
1233
1234/* One MergeState exists on the stack per invocation of mergesort. It's just
1235 * a convenient way to pass state around among the helper functions.
1236 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001237struct s_slice {
1238 PyObject **base;
1239 int len;
1240};
1241
Tim Petersa64dc242002-08-01 02:13:36 +00001242typedef struct s_MergeState {
1243 /* The user-supplied comparison function. or NULL if none given. */
1244 PyObject *compare;
1245
Tim Peterse05f65a2002-08-10 05:21:15 +00001246 /* This controls when we get *into* galloping mode. It's initialized
1247 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1248 * random data, and lower for highly structured data.
1249 */
1250 int min_gallop;
1251
Tim Petersa64dc242002-08-01 02:13:36 +00001252 /* 'a' is temp storage to help with merges. It contains room for
1253 * alloced entries.
1254 */
1255 PyObject **a; /* may point to temparray below */
1256 int alloced;
1257
1258 /* A stack of n pending runs yet to be merged. Run #i starts at
1259 * address base[i] and extends for len[i] elements. It's always
1260 * true (so long as the indices are in bounds) that
1261 *
Tim Peterse05f65a2002-08-10 05:21:15 +00001262 * pending[i].base + pending[i].len == pending[i+1].base
Tim Petersa64dc242002-08-01 02:13:36 +00001263 *
1264 * so we could cut the storage for this, but it's a minor amount,
1265 * and keeping all the info explicit simplifies the code.
1266 */
1267 int n;
Tim Peterse05f65a2002-08-10 05:21:15 +00001268 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001269
1270 /* 'a' points to this when possible, rather than muck with malloc. */
1271 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1272} MergeState;
1273
1274/* Conceptually a MergeState's constructor. */
1275static void
1276merge_init(MergeState *ms, PyObject *compare)
1277{
1278 assert(ms != NULL);
1279 ms->compare = compare;
1280 ms->a = ms->temparray;
1281 ms->alloced = MERGESTATE_TEMP_SIZE;
1282 ms->n = 0;
Tim Peterse05f65a2002-08-10 05:21:15 +00001283 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001284}
1285
1286/* Free all the temp memory owned by the MergeState. This must be called
1287 * when you're done with a MergeState, and may be called before then if
1288 * you want to free the temp memory early.
1289 */
1290static void
1291merge_freemem(MergeState *ms)
1292{
1293 assert(ms != NULL);
1294 if (ms->a != ms->temparray)
1295 PyMem_Free(ms->a);
1296 ms->a = ms->temparray;
1297 ms->alloced = MERGESTATE_TEMP_SIZE;
1298}
1299
1300/* Ensure enough temp memory for 'need' array slots is available.
1301 * Returns 0 on success and -1 if the memory can't be gotten.
1302 */
1303static int
1304merge_getmem(MergeState *ms, int need)
1305{
1306 assert(ms != NULL);
1307 if (need <= ms->alloced)
1308 return 0;
1309 /* Don't realloc! That can cost cycles to copy the old data, but
1310 * we don't care what's in the block.
1311 */
1312 merge_freemem(ms);
1313 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1314 if (ms->a) {
1315 ms->alloced = need;
1316 return 0;
1317 }
1318 PyErr_NoMemory();
1319 merge_freemem(ms); /* reset to sane state */
1320 return -1;
1321}
1322#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1323 merge_getmem(MS, NEED))
1324
1325/* Merge the na elements starting at pa with the nb elements starting at pb
1326 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1327 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1328 * merge, and should have na <= nb. See listsort.txt for more info.
1329 * Return 0 if successful, -1 if error.
1330 */
1331static int
1332merge_lo(MergeState *ms, PyObject **pa, int na, PyObject **pb, int nb)
1333{
1334 int k;
1335 PyObject *compare;
1336 PyObject **dest;
1337 int result = -1; /* guilty until proved innocent */
Tim Peterse05f65a2002-08-10 05:21:15 +00001338 int min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001339
1340 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1341 if (MERGE_GETMEM(ms, na) < 0)
1342 return -1;
1343 memcpy(ms->a, pa, na * sizeof(PyObject*));
1344 dest = pa;
1345 pa = ms->a;
1346
1347 *dest++ = *pb++;
1348 --nb;
1349 if (nb == 0)
1350 goto Succeed;
1351 if (na == 1)
1352 goto CopyB;
1353
1354 compare = ms->compare;
1355 for (;;) {
1356 int acount = 0; /* # of times A won in a row */
1357 int bcount = 0; /* # of times B won in a row */
1358
1359 /* Do the straightforward thing until (if ever) one run
1360 * appears to win consistently.
1361 */
1362 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001363 assert(na > 1 && nb > 0);
Tim Peters66860f62002-08-04 17:47:26 +00001364 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001365 if (k) {
1366 if (k < 0)
1367 goto Fail;
1368 *dest++ = *pb++;
1369 ++bcount;
1370 acount = 0;
1371 --nb;
1372 if (nb == 0)
1373 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001374 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001375 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001376 }
1377 else {
Tim Petersa64dc242002-08-01 02:13:36 +00001378 *dest++ = *pa++;
1379 ++acount;
1380 bcount = 0;
1381 --na;
1382 if (na == 1)
1383 goto CopyB;
Tim Peterse05f65a2002-08-10 05:21:15 +00001384 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001385 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001386 }
Tim Petersa64dc242002-08-01 02:13:36 +00001387 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001388
Tim Petersa64dc242002-08-01 02:13:36 +00001389 /* One run is winning so consistently that galloping may
1390 * be a huge win. So try that, and continue galloping until
1391 * (if ever) neither run appears to be winning consistently
1392 * anymore.
1393 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001394 ++min_gallop;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001395 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001396 assert(na > 1 && nb > 0);
1397 min_gallop -= min_gallop > 1;
1398 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001399 k = gallop_right(*pb, pa, na, 0, compare);
1400 acount = k;
1401 if (k) {
1402 if (k < 0)
1403 goto Fail;
1404 memcpy(dest, pa, k * sizeof(PyObject *));
1405 dest += k;
1406 pa += k;
1407 na -= k;
1408 if (na == 1)
1409 goto CopyB;
1410 /* na==0 is impossible now if the comparison
1411 * function is consistent, but we can't assume
1412 * that it is.
1413 */
1414 if (na == 0)
1415 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001416 }
Tim Petersa64dc242002-08-01 02:13:36 +00001417 *dest++ = *pb++;
1418 --nb;
1419 if (nb == 0)
1420 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001421
Tim Petersa64dc242002-08-01 02:13:36 +00001422 k = gallop_left(*pa, pb, nb, 0, compare);
1423 bcount = k;
1424 if (k) {
1425 if (k < 0)
1426 goto Fail;
1427 memmove(dest, pb, k * sizeof(PyObject *));
1428 dest += k;
1429 pb += k;
1430 nb -= k;
1431 if (nb == 0)
1432 goto Succeed;
1433 }
1434 *dest++ = *pa++;
1435 --na;
1436 if (na == 1)
1437 goto CopyB;
1438 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001439 ++min_gallop; /* penalize it for leaving galloping mode */
1440 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001441 }
1442Succeed:
1443 result = 0;
1444Fail:
1445 if (na)
1446 memcpy(dest, pa, na * sizeof(PyObject*));
1447 return result;
1448CopyB:
1449 assert(na == 1 && nb > 0);
1450 /* The last element of pa belongs at the end of the merge. */
1451 memmove(dest, pb, nb * sizeof(PyObject *));
1452 dest[nb] = *pa;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001453 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001454}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001455
Tim Petersa64dc242002-08-01 02:13:36 +00001456/* Merge the na elements starting at pa with the nb elements starting at pb
1457 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1458 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1459 * merge, and should have na >= nb. See listsort.txt for more info.
1460 * Return 0 if successful, -1 if error.
1461 */
1462static int
1463merge_hi(MergeState *ms, PyObject **pa, int na, PyObject **pb, int nb)
1464{
1465 int k;
1466 PyObject *compare;
1467 PyObject **dest;
1468 int result = -1; /* guilty until proved innocent */
1469 PyObject **basea;
1470 PyObject **baseb;
Tim Peterse05f65a2002-08-10 05:21:15 +00001471 int min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001472
1473 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1474 if (MERGE_GETMEM(ms, nb) < 0)
1475 return -1;
1476 dest = pb + nb - 1;
1477 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1478 basea = pa;
1479 baseb = ms->a;
1480 pb = ms->a + nb - 1;
1481 pa += na - 1;
1482
1483 *dest-- = *pa--;
1484 --na;
1485 if (na == 0)
1486 goto Succeed;
1487 if (nb == 1)
1488 goto CopyA;
1489
1490 compare = ms->compare;
1491 for (;;) {
1492 int acount = 0; /* # of times A won in a row */
1493 int bcount = 0; /* # of times B won in a row */
1494
1495 /* Do the straightforward thing until (if ever) one run
1496 * appears to win consistently.
1497 */
1498 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001499 assert(na > 0 && nb > 1);
Tim Peters66860f62002-08-04 17:47:26 +00001500 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001501 if (k) {
1502 if (k < 0)
1503 goto Fail;
1504 *dest-- = *pa--;
1505 ++acount;
1506 bcount = 0;
1507 --na;
1508 if (na == 0)
1509 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001510 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001511 break;
1512 }
1513 else {
1514 *dest-- = *pb--;
1515 ++bcount;
1516 acount = 0;
1517 --nb;
1518 if (nb == 1)
1519 goto CopyA;
Tim Peterse05f65a2002-08-10 05:21:15 +00001520 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001521 break;
1522 }
1523 }
1524
1525 /* One run is winning so consistently that galloping may
1526 * be a huge win. So try that, and continue galloping until
1527 * (if ever) neither run appears to be winning consistently
1528 * anymore.
1529 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001530 ++min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001531 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001532 assert(na > 0 && nb > 1);
1533 min_gallop -= min_gallop > 1;
1534 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001535 k = gallop_right(*pb, basea, na, na-1, compare);
1536 if (k < 0)
1537 goto Fail;
1538 k = na - k;
1539 acount = k;
1540 if (k) {
1541 dest -= k;
1542 pa -= k;
1543 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1544 na -= k;
1545 if (na == 0)
1546 goto Succeed;
1547 }
1548 *dest-- = *pb--;
1549 --nb;
1550 if (nb == 1)
1551 goto CopyA;
1552
1553 k = gallop_left(*pa, baseb, nb, nb-1, compare);
1554 if (k < 0)
1555 goto Fail;
1556 k = nb - k;
1557 bcount = k;
1558 if (k) {
1559 dest -= k;
1560 pb -= k;
1561 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1562 nb -= k;
1563 if (nb == 1)
1564 goto CopyA;
1565 /* nb==0 is impossible now if the comparison
1566 * function is consistent, but we can't assume
1567 * that it is.
1568 */
1569 if (nb == 0)
1570 goto Succeed;
1571 }
1572 *dest-- = *pa--;
1573 --na;
1574 if (na == 0)
1575 goto Succeed;
1576 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001577 ++min_gallop; /* penalize it for leaving galloping mode */
1578 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001579 }
1580Succeed:
1581 result = 0;
1582Fail:
1583 if (nb)
1584 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1585 return result;
1586CopyA:
1587 assert(nb == 1 && na > 0);
1588 /* The first element of pb belongs at the front of the merge. */
1589 dest -= na;
1590 pa -= na;
1591 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1592 *dest = *pb;
1593 return 0;
1594}
1595
1596/* Merge the two runs at stack indices i and i+1.
1597 * Returns 0 on success, -1 on error.
1598 */
1599static int
1600merge_at(MergeState *ms, int i)
1601{
1602 PyObject **pa, **pb;
1603 int na, nb;
1604 int k;
1605 PyObject *compare;
1606
1607 assert(ms != NULL);
1608 assert(ms->n >= 2);
1609 assert(i >= 0);
1610 assert(i == ms->n - 2 || i == ms->n - 3);
1611
Tim Peterse05f65a2002-08-10 05:21:15 +00001612 pa = ms->pending[i].base;
1613 na = ms->pending[i].len;
1614 pb = ms->pending[i+1].base;
1615 nb = ms->pending[i+1].len;
Tim Petersa64dc242002-08-01 02:13:36 +00001616 assert(na > 0 && nb > 0);
1617 assert(pa + na == pb);
1618
1619 /* Record the length of the combined runs; if i is the 3rd-last
1620 * run now, also slide over the last run (which isn't involved
1621 * in this merge). The current run i+1 goes away in any case.
1622 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001623 ms->pending[i].len = na + nb;
1624 if (i == ms->n - 3)
1625 ms->pending[i+1] = ms->pending[i+2];
Tim Petersa64dc242002-08-01 02:13:36 +00001626 --ms->n;
1627
1628 /* Where does b start in a? Elements in a before that can be
1629 * ignored (already in place).
1630 */
1631 compare = ms->compare;
1632 k = gallop_right(*pb, pa, na, 0, compare);
1633 if (k < 0)
1634 return -1;
1635 pa += k;
1636 na -= k;
1637 if (na == 0)
1638 return 0;
1639
1640 /* Where does a end in b? Elements in b after that can be
1641 * ignored (already in place).
1642 */
1643 nb = gallop_left(pa[na-1], pb, nb, nb-1, compare);
1644 if (nb <= 0)
1645 return nb;
1646
1647 /* Merge what remains of the runs, using a temp array with
1648 * min(na, nb) elements.
1649 */
1650 if (na <= nb)
1651 return merge_lo(ms, pa, na, pb, nb);
1652 else
1653 return merge_hi(ms, pa, na, pb, nb);
1654}
1655
1656/* Examine the stack of runs waiting to be merged, merging adjacent runs
1657 * until the stack invariants are re-established:
1658 *
1659 * 1. len[-3] > len[-2] + len[-1]
1660 * 2. len[-2] > len[-1]
1661 *
1662 * See listsort.txt for more info.
1663 *
1664 * Returns 0 on success, -1 on error.
1665 */
1666static int
1667merge_collapse(MergeState *ms)
1668{
Tim Peterse05f65a2002-08-10 05:21:15 +00001669 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001670
1671 assert(ms);
1672 while (ms->n > 1) {
1673 int n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001674 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1675 if (p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001676 --n;
1677 if (merge_at(ms, n) < 0)
1678 return -1;
1679 }
Tim Peterse05f65a2002-08-10 05:21:15 +00001680 else if (p[n].len <= p[n+1].len) {
Tim Petersa64dc242002-08-01 02:13:36 +00001681 if (merge_at(ms, n) < 0)
1682 return -1;
1683 }
1684 else
1685 break;
1686 }
1687 return 0;
1688}
1689
1690/* Regardless of invariants, merge all runs on the stack until only one
1691 * remains. This is used at the end of the mergesort.
1692 *
1693 * Returns 0 on success, -1 on error.
1694 */
1695static int
1696merge_force_collapse(MergeState *ms)
1697{
Tim Peterse05f65a2002-08-10 05:21:15 +00001698 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001699
1700 assert(ms);
1701 while (ms->n > 1) {
1702 int n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001703 if (n > 0 && p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001704 --n;
1705 if (merge_at(ms, n) < 0)
1706 return -1;
1707 }
1708 return 0;
1709}
1710
1711/* Compute a good value for the minimum run length; natural runs shorter
1712 * than this are boosted artificially via binary insertion.
1713 *
1714 * If n < 64, return n (it's too small to bother with fancy stuff).
1715 * Else if n is an exact power of 2, return 32.
1716 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1717 * strictly less than, an exact power of 2.
1718 *
1719 * See listsort.txt for more info.
1720 */
1721static int
1722merge_compute_minrun(int n)
1723{
1724 int r = 0; /* becomes 1 if any 1 bits are shifted off */
1725
1726 assert(n >= 0);
1727 while (n >= 64) {
1728 r |= n & 1;
1729 n >>= 1;
1730 }
1731 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001732}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001733
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001734/* Special wrapper to support stable sorting using the decorate-sort-undecorate
1735 pattern. Holds a key which is used for comparisions and the original record
1736 which is returned during the undecorate phase. By exposing only the key
1737 during comparisons, the underlying sort stability characteristics are left
1738 unchanged. Also, if a custom comparison function is used, it will only see
1739 the key instead of a full record. */
1740
1741typedef struct {
1742 PyObject_HEAD
1743 PyObject *key;
1744 PyObject *value;
1745} sortwrapperobject;
1746
1747static PyTypeObject sortwrapper_type;
1748
1749static PyObject *
1750sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
1751{
1752 if (!PyObject_TypeCheck(b, &sortwrapper_type)) {
1753 PyErr_SetString(PyExc_TypeError,
1754 "expected a sortwrapperobject");
1755 return NULL;
1756 }
1757 return PyObject_RichCompare(a->key, b->key, op);
1758}
1759
1760static void
1761sortwrapper_dealloc(sortwrapperobject *so)
1762{
1763 Py_XDECREF(so->key);
1764 Py_XDECREF(so->value);
1765 PyObject_Del(so);
1766}
1767
1768PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
1769
1770static PyTypeObject sortwrapper_type = {
1771 PyObject_HEAD_INIT(&PyType_Type)
1772 0, /* ob_size */
1773 "sortwrapper", /* tp_name */
1774 sizeof(sortwrapperobject), /* tp_basicsize */
1775 0, /* tp_itemsize */
1776 /* methods */
1777 (destructor)sortwrapper_dealloc, /* tp_dealloc */
1778 0, /* tp_print */
1779 0, /* tp_getattr */
1780 0, /* tp_setattr */
1781 0, /* tp_compare */
1782 0, /* tp_repr */
1783 0, /* tp_as_number */
1784 0, /* tp_as_sequence */
1785 0, /* tp_as_mapping */
1786 0, /* tp_hash */
1787 0, /* tp_call */
1788 0, /* tp_str */
1789 PyObject_GenericGetAttr, /* tp_getattro */
1790 0, /* tp_setattro */
1791 0, /* tp_as_buffer */
1792 Py_TPFLAGS_DEFAULT |
1793 Py_TPFLAGS_HAVE_RICHCOMPARE, /* tp_flags */
1794 sortwrapper_doc, /* tp_doc */
1795 0, /* tp_traverse */
1796 0, /* tp_clear */
1797 (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
1798};
1799
1800/* Returns a new reference to a sortwrapper.
1801 Consumes the references to the two underlying objects. */
1802
1803static PyObject *
1804build_sortwrapper(PyObject *key, PyObject *value)
1805{
1806 sortwrapperobject *so;
1807
1808 so = PyObject_New(sortwrapperobject, &sortwrapper_type);
1809 if (so == NULL)
1810 return NULL;
1811 so->key = key;
1812 so->value = value;
1813 return (PyObject *)so;
1814}
1815
1816/* Returns a new reference to the value underlying the wrapper. */
1817static PyObject *
1818sortwrapper_getvalue(PyObject *so)
1819{
1820 PyObject *value;
1821
1822 if (!PyObject_TypeCheck(so, &sortwrapper_type)) {
1823 PyErr_SetString(PyExc_TypeError,
1824 "expected a sortwrapperobject");
1825 return NULL;
1826 }
1827 value = ((sortwrapperobject *)so)->value;
1828 Py_INCREF(value);
1829 return value;
1830}
1831
1832/* Wrapper for user specified cmp functions in combination with a
1833 specified key function. Makes sure the cmp function is presented
1834 with the actual key instead of the sortwrapper */
1835
1836typedef struct {
1837 PyObject_HEAD
1838 PyObject *func;
1839} cmpwrapperobject;
1840
1841static void
1842cmpwrapper_dealloc(cmpwrapperobject *co)
1843{
1844 Py_XDECREF(co->func);
1845 PyObject_Del(co);
1846}
1847
1848static PyObject *
1849cmpwrapper_call(cmpwrapperobject *co, PyObject *args, PyObject *kwds)
1850{
1851 PyObject *x, *y, *xx, *yy;
1852
1853 if (!PyArg_UnpackTuple(args, "", 2, 2, &x, &y))
1854 return NULL;
1855 if (!PyObject_TypeCheck(x, &sortwrapper_type) ||
Raymond Hettingerae4a2992003-10-16 17:16:30 +00001856 !PyObject_TypeCheck(y, &sortwrapper_type)) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001857 PyErr_SetString(PyExc_TypeError,
1858 "expected a sortwrapperobject");
1859 return NULL;
1860 }
1861 xx = ((sortwrapperobject *)x)->key;
1862 yy = ((sortwrapperobject *)y)->key;
1863 return PyObject_CallFunctionObjArgs(co->func, xx, yy, NULL);
1864}
1865
1866PyDoc_STRVAR(cmpwrapper_doc, "cmp() wrapper for sort with custom keys.");
1867
1868static PyTypeObject cmpwrapper_type = {
1869 PyObject_HEAD_INIT(&PyType_Type)
1870 0, /* ob_size */
1871 "cmpwrapper", /* tp_name */
1872 sizeof(cmpwrapperobject), /* tp_basicsize */
1873 0, /* tp_itemsize */
1874 /* methods */
1875 (destructor)cmpwrapper_dealloc, /* tp_dealloc */
1876 0, /* tp_print */
1877 0, /* tp_getattr */
1878 0, /* tp_setattr */
1879 0, /* tp_compare */
1880 0, /* tp_repr */
1881 0, /* tp_as_number */
1882 0, /* tp_as_sequence */
1883 0, /* tp_as_mapping */
1884 0, /* tp_hash */
1885 (ternaryfunc)cmpwrapper_call, /* tp_call */
1886 0, /* tp_str */
1887 PyObject_GenericGetAttr, /* tp_getattro */
1888 0, /* tp_setattro */
1889 0, /* tp_as_buffer */
1890 Py_TPFLAGS_DEFAULT, /* tp_flags */
1891 cmpwrapper_doc, /* tp_doc */
1892};
1893
1894static PyObject *
1895build_cmpwrapper(PyObject *cmpfunc)
1896{
1897 cmpwrapperobject *co;
1898
1899 co = PyObject_New(cmpwrapperobject, &cmpwrapper_type);
1900 if (co == NULL)
1901 return NULL;
1902 Py_INCREF(cmpfunc);
1903 co->func = cmpfunc;
1904 return (PyObject *)co;
1905}
1906
Tim Petersa64dc242002-08-01 02:13:36 +00001907/* An adaptive, stable, natural mergesort. See listsort.txt.
1908 * Returns Py_None on success, NULL on error. Even in case of error, the
1909 * list will be some permutation of its input state (nothing is lost or
1910 * duplicated).
1911 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001912static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001913listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001914{
Tim Petersa64dc242002-08-01 02:13:36 +00001915 MergeState ms;
1916 PyObject **lo, **hi;
1917 int nremaining;
1918 int minrun;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001919 int saved_ob_size, saved_allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00001920 PyObject **saved_ob_item;
1921 PyObject **empty_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001922 PyObject *compare = NULL;
1923 PyObject *result = NULL; /* guilty until proved innocent */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001924 int reverse = 0;
1925 PyObject *keyfunc = NULL;
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001926 int i;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001927 PyObject *key, *value, *kvpair;
1928 static char *kwlist[] = {"cmp", "key", "reverse", 0};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001929
Tim Petersa64dc242002-08-01 02:13:36 +00001930 assert(self != NULL);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001931 assert (PyList_Check(self));
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001932 if (args != NULL) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001933 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:sort",
1934 kwlist, &compare, &keyfunc, &reverse))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001935 return NULL;
1936 }
Skip Montanaro4abd5f02003-01-02 20:51:08 +00001937 if (compare == Py_None)
1938 compare = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001939 if (keyfunc == Py_None)
1940 keyfunc = NULL;
1941 if (compare != NULL && keyfunc != NULL) {
1942 compare = build_cmpwrapper(compare);
1943 if (compare == NULL)
Hye-Shik Chang19cb1932003-12-10 07:31:08 +00001944 return NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001945 } else
1946 Py_XINCREF(compare);
1947
Tim Petersb9099c32002-11-12 22:08:10 +00001948 /* The list is temporarily made empty, so that mutations performed
1949 * by comparison functions can't affect the slice of memory we're
1950 * sorting (allowing mutations during sorting is a core-dump
1951 * factory, since ob_item may change).
1952 */
1953 saved_ob_size = self->ob_size;
1954 saved_ob_item = self->ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001955 saved_allocated = self->allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00001956 self->ob_size = 0;
Tim Peters7049d812004-01-18 20:31:02 +00001957 self->ob_item = empty_ob_item = PyMem_NEW(PyObject *, 0);
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001958 self->allocated = 0;
Tim Peters330f9e92002-07-19 07:05:44 +00001959
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001960 if (keyfunc != NULL) {
1961 for (i=0 ; i < saved_ob_size ; i++) {
1962 value = saved_ob_item[i];
1963 key = PyObject_CallFunctionObjArgs(keyfunc, value,
1964 NULL);
1965 if (key == NULL) {
1966 for (i=i-1 ; i>=0 ; i--) {
1967 kvpair = saved_ob_item[i];
1968 value = sortwrapper_getvalue(kvpair);
1969 saved_ob_item[i] = value;
1970 Py_DECREF(kvpair);
1971 }
1972 if (self->ob_item != empty_ob_item
1973 || self->ob_size) {
1974 /* If the list changed *as well* we
1975 have two errors. We let the first
1976 one "win", but we shouldn't let
1977 what's in the list currently
1978 leak. */
1979 (void)list_ass_slice(
1980 self, 0, self->ob_size,
1981 (PyObject *)NULL);
1982 }
1983
1984 goto dsu_fail;
1985 }
1986 kvpair = build_sortwrapper(key, value);
1987 if (kvpair == NULL)
1988 goto dsu_fail;
1989 saved_ob_item[i] = kvpair;
1990 }
1991 }
1992
1993 /* Reverse sort stability achieved by initially reversing the list,
1994 applying a stable forward sort, then reversing the final result. */
1995 if (reverse && saved_ob_size > 1)
1996 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
1997
1998 merge_init(&ms, compare);
1999
Tim Petersb9099c32002-11-12 22:08:10 +00002000 nremaining = saved_ob_size;
Tim Petersa64dc242002-08-01 02:13:36 +00002001 if (nremaining < 2)
2002 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00002003
Tim Petersa64dc242002-08-01 02:13:36 +00002004 /* March over the array once, left to right, finding natural runs,
2005 * and extending short natural runs to minrun elements.
2006 */
Tim Petersb9099c32002-11-12 22:08:10 +00002007 lo = saved_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00002008 hi = lo + nremaining;
2009 minrun = merge_compute_minrun(nremaining);
2010 do {
2011 int descending;
2012 int n;
Tim Peters330f9e92002-07-19 07:05:44 +00002013
Tim Petersa64dc242002-08-01 02:13:36 +00002014 /* Identify next run. */
2015 n = count_run(lo, hi, compare, &descending);
2016 if (n < 0)
2017 goto fail;
2018 if (descending)
2019 reverse_slice(lo, lo + n);
2020 /* If short, extend to min(minrun, nremaining). */
2021 if (n < minrun) {
2022 const int force = nremaining <= minrun ?
2023 nremaining : minrun;
2024 if (binarysort(lo, lo + force, lo + n, compare) < 0)
2025 goto fail;
2026 n = force;
2027 }
2028 /* Push run onto pending-runs stack, and maybe merge. */
2029 assert(ms.n < MAX_MERGE_PENDING);
Tim Peterse05f65a2002-08-10 05:21:15 +00002030 ms.pending[ms.n].base = lo;
2031 ms.pending[ms.n].len = n;
Tim Petersa64dc242002-08-01 02:13:36 +00002032 ++ms.n;
2033 if (merge_collapse(&ms) < 0)
2034 goto fail;
2035 /* Advance to find next run. */
2036 lo += n;
2037 nremaining -= n;
2038 } while (nremaining);
2039 assert(lo == hi);
Tim Peters330f9e92002-07-19 07:05:44 +00002040
Tim Petersa64dc242002-08-01 02:13:36 +00002041 if (merge_force_collapse(&ms) < 0)
2042 goto fail;
2043 assert(ms.n == 1);
Tim Petersb9099c32002-11-12 22:08:10 +00002044 assert(ms.pending[0].base == saved_ob_item);
2045 assert(ms.pending[0].len == saved_ob_size);
Tim Petersa64dc242002-08-01 02:13:36 +00002046
2047succeed:
2048 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002049fail:
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002050 if (keyfunc != NULL) {
2051 for (i=0 ; i < saved_ob_size ; i++) {
2052 kvpair = saved_ob_item[i];
2053 value = sortwrapper_getvalue(kvpair);
2054 saved_ob_item[i] = value;
2055 Py_DECREF(kvpair);
2056 }
2057 }
2058
Tim Petersb9099c32002-11-12 22:08:10 +00002059 if (self->ob_item != empty_ob_item || self->ob_size) {
2060 /* The user mucked with the list during the sort. */
2061 (void)list_ass_slice(self, 0, self->ob_size, (PyObject *)NULL);
2062 if (result != NULL) {
2063 PyErr_SetString(PyExc_ValueError,
2064 "list modified during sort");
2065 result = NULL;
2066 }
2067 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002068
2069 if (reverse && saved_ob_size > 1)
2070 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2071
2072 merge_freemem(&ms);
2073
2074dsu_fail:
Tim Petersb9099c32002-11-12 22:08:10 +00002075 if (self->ob_item == empty_ob_item)
2076 PyMem_FREE(empty_ob_item);
2077 self->ob_size = saved_ob_size;
2078 self->ob_item = saved_ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002079 self->allocated = saved_allocated;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002080 Py_XDECREF(compare);
Tim Petersa64dc242002-08-01 02:13:36 +00002081 Py_XINCREF(result);
2082 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002083}
Tim Peters330f9e92002-07-19 07:05:44 +00002084#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002085#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002086
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002087int
Fred Drakea2f55112000-07-09 15:16:51 +00002088PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002089{
2090 if (v == NULL || !PyList_Check(v)) {
2091 PyErr_BadInternalCall();
2092 return -1;
2093 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002094 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002095 if (v == NULL)
2096 return -1;
2097 Py_DECREF(v);
2098 return 0;
2099}
2100
Guido van Rossumb86c5492001-02-12 22:06:02 +00002101static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002102listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002103{
Tim Peters326b4482002-07-19 04:04:16 +00002104 if (self->ob_size > 1)
2105 reverse_slice(self->ob_item, self->ob_item + self->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002106 Py_INCREF(Py_None);
2107 return Py_None;
Guido van Rossumed98d481991-03-06 13:07:53 +00002108}
2109
Guido van Rossum84c76f51990-10-30 13:32:20 +00002110int
Fred Drakea2f55112000-07-09 15:16:51 +00002111PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002112{
Tim Peters6063e262002-08-08 01:06:39 +00002113 PyListObject *self = (PyListObject *)v;
2114
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002115 if (v == NULL || !PyList_Check(v)) {
2116 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002117 return -1;
2118 }
Tim Peters6063e262002-08-08 01:06:39 +00002119 if (self->ob_size > 1)
2120 reverse_slice(self->ob_item, self->ob_item + self->ob_size);
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002121 return 0;
2122}
2123
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002124PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002125PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002126{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002127 PyObject *w;
2128 PyObject **p;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002129 int n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002130 if (v == NULL || !PyList_Check(v)) {
2131 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002132 return NULL;
2133 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002134 n = ((PyListObject *)v)->ob_size;
2135 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002136 if (w == NULL)
2137 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002138 p = ((PyTupleObject *)w)->ob_item;
Thomas Wouters334fb892000-07-25 12:56:38 +00002139 memcpy((void *)p,
2140 (void *)((PyListObject *)v)->ob_item,
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002141 n*sizeof(PyObject *));
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002142 while (--n >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002143 Py_INCREF(*p);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002144 p++;
2145 }
2146 return w;
2147}
2148
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002149static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002150listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002151{
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002152 int i, start=0, stop=self->ob_size;
2153 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002154
Walter Dörwalde8049bef2003-06-17 19:27:39 +00002155 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2156 _PyEval_SliceIndex, &start,
2157 _PyEval_SliceIndex, &stop))
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002158 return NULL;
Guido van Rossum2743d872003-06-17 14:25:14 +00002159 if (start < 0) {
2160 start += self->ob_size;
2161 if (start < 0)
2162 start = 0;
2163 }
2164 if (stop < 0) {
2165 stop += self->ob_size;
2166 if (stop < 0)
2167 stop = 0;
2168 }
2169 else if (stop > self->ob_size)
2170 stop = self->ob_size;
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002171 for (i = start; i < stop; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002172 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2173 if (cmp > 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002174 return PyInt_FromLong((long)i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002175 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002176 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002177 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002178 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002179 return NULL;
2180}
2181
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002182static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002183listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002184{
2185 int count = 0;
2186 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002187
Guido van Rossume6f7d181991-10-20 20:20:40 +00002188 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002189 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2190 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002191 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002192 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002193 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00002194 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002195 return PyInt_FromLong((long)count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002196}
2197
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002198static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002199listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002200{
2201 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002202
Guido van Rossumed98d481991-03-06 13:07:53 +00002203 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002204 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2205 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002206 if (list_ass_slice(self, i, i+1,
2207 (PyObject *)NULL) != 0)
Guido van Rossumed98d481991-03-06 13:07:53 +00002208 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002209 Py_INCREF(Py_None);
2210 return Py_None;
Guido van Rossumed98d481991-03-06 13:07:53 +00002211 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002212 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002213 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002214 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002215 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002216 return NULL;
2217}
2218
Jeremy Hylton8caad492000-06-23 14:18:11 +00002219static int
2220list_traverse(PyListObject *o, visitproc visit, void *arg)
2221{
2222 int i, err;
2223 PyObject *x;
2224
2225 for (i = o->ob_size; --i >= 0; ) {
2226 x = o->ob_item[i];
2227 if (x != NULL) {
2228 err = visit(x, arg);
2229 if (err)
2230 return err;
2231 }
2232 }
2233 return 0;
2234}
2235
2236static int
2237list_clear(PyListObject *lp)
2238{
2239 (void) PyList_SetSlice((PyObject *)lp, 0, lp->ob_size, 0);
2240 return 0;
2241}
2242
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002243static PyObject *
2244list_richcompare(PyObject *v, PyObject *w, int op)
2245{
2246 PyListObject *vl, *wl;
2247 int i;
2248
2249 if (!PyList_Check(v) || !PyList_Check(w)) {
2250 Py_INCREF(Py_NotImplemented);
2251 return Py_NotImplemented;
2252 }
2253
2254 vl = (PyListObject *)v;
2255 wl = (PyListObject *)w;
2256
2257 if (vl->ob_size != wl->ob_size && (op == Py_EQ || op == Py_NE)) {
2258 /* Shortcut: if the lengths differ, the lists differ */
2259 PyObject *res;
2260 if (op == Py_EQ)
2261 res = Py_False;
2262 else
2263 res = Py_True;
2264 Py_INCREF(res);
2265 return res;
2266 }
2267
2268 /* Search for the first index where items are different */
2269 for (i = 0; i < vl->ob_size && i < wl->ob_size; i++) {
2270 int k = PyObject_RichCompareBool(vl->ob_item[i],
2271 wl->ob_item[i], Py_EQ);
2272 if (k < 0)
2273 return NULL;
2274 if (!k)
2275 break;
2276 }
2277
2278 if (i >= vl->ob_size || i >= wl->ob_size) {
2279 /* No more items to compare -- compare sizes */
2280 int vs = vl->ob_size;
2281 int ws = wl->ob_size;
2282 int cmp;
2283 PyObject *res;
2284 switch (op) {
2285 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00002286 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002287 case Py_EQ: cmp = vs == ws; break;
2288 case Py_NE: cmp = vs != ws; break;
2289 case Py_GT: cmp = vs > ws; break;
2290 case Py_GE: cmp = vs >= ws; break;
2291 default: return NULL; /* cannot happen */
2292 }
2293 if (cmp)
2294 res = Py_True;
2295 else
2296 res = Py_False;
2297 Py_INCREF(res);
2298 return res;
2299 }
2300
2301 /* We have an item that differs -- shortcuts for EQ/NE */
2302 if (op == Py_EQ) {
2303 Py_INCREF(Py_False);
2304 return Py_False;
2305 }
2306 if (op == Py_NE) {
2307 Py_INCREF(Py_True);
2308 return Py_True;
2309 }
2310
2311 /* Compare the final item again using the proper operator */
2312 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
2313}
2314
Tim Peters6d6c1a32001-08-02 04:15:00 +00002315static int
2316list_init(PyListObject *self, PyObject *args, PyObject *kw)
2317{
2318 PyObject *arg = NULL;
2319 static char *kwlist[] = {"sequence", 0};
2320
2321 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2322 return -1;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002323 /* Empty previous contents */
2324 if (self->ob_size != 0) {
2325 if (list_ass_slice(self, 0, self->ob_size, (PyObject *)NULL) != 0)
2326 return -1;
2327 }
2328 if (arg != NULL) {
2329 PyObject *rv = listextend(self, arg);
2330 if (rv == NULL)
2331 return -1;
2332 Py_DECREF(rv);
2333 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002334 return 0;
2335}
2336
Guido van Rossumdbb53d92001-12-03 16:32:18 +00002337static long
2338list_nohash(PyObject *self)
2339{
2340 PyErr_SetString(PyExc_TypeError, "list objects are unhashable");
2341 return -1;
2342}
2343
Raymond Hettinger1021c442003-11-07 15:38:09 +00002344static PyObject *list_iter(PyObject *seq);
2345static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2346
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002347PyDoc_STRVAR(getitem_doc,
2348"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002349PyDoc_STRVAR(reversed_doc,
2350"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002351PyDoc_STRVAR(append_doc,
2352"L.append(object) -- append object to end");
2353PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002354"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002355PyDoc_STRVAR(insert_doc,
2356"L.insert(index, object) -- insert object before index");
2357PyDoc_STRVAR(pop_doc,
2358"L.pop([index]) -> item -- remove and return item at index (default last)");
2359PyDoc_STRVAR(remove_doc,
2360"L.remove(value) -- remove first occurrence of value");
2361PyDoc_STRVAR(index_doc,
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002362"L.index(value, [start, [stop]]) -> integer -- return first index of value");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002363PyDoc_STRVAR(count_doc,
2364"L.count(value) -> integer -- return number of occurrences of value");
2365PyDoc_STRVAR(reverse_doc,
2366"L.reverse() -- reverse *IN PLACE*");
2367PyDoc_STRVAR(sort_doc,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002368"L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n\
2369cmp(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002370
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002371static PyObject *list_subscript(PyListObject*, PyObject*);
2372
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002373static PyMethodDef list_methods[] = {
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002374 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
Raymond Hettinger1021c442003-11-07 15:38:09 +00002375 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002376 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002377 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002378 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002379 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002380 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002381 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002382 {"count", (PyCFunction)listcount, METH_O, count_doc},
2383 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002384 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
Tim Petersa64dc242002-08-01 02:13:36 +00002385 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002386};
2387
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002388static PySequenceMethods list_as_sequence = {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002389 (inquiry)list_length, /* sq_length */
2390 (binaryfunc)list_concat, /* sq_concat */
2391 (intargfunc)list_repeat, /* sq_repeat */
2392 (intargfunc)list_item, /* sq_item */
2393 (intintargfunc)list_slice, /* sq_slice */
2394 (intobjargproc)list_ass_item, /* sq_ass_item */
2395 (intintobjargproc)list_ass_slice, /* sq_ass_slice */
2396 (objobjproc)list_contains, /* sq_contains */
2397 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2398 (intargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002399};
2400
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002401PyDoc_STRVAR(list_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002402"list() -> new list\n"
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002403"list(sequence) -> new list initialized from sequence's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002404
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002405static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002406list_subscript(PyListObject* self, PyObject* item)
2407{
2408 if (PyInt_Check(item)) {
2409 long i = PyInt_AS_LONG(item);
2410 if (i < 0)
2411 i += PyList_GET_SIZE(self);
2412 return list_item(self, i);
2413 }
2414 else if (PyLong_Check(item)) {
2415 long i = PyLong_AsLong(item);
2416 if (i == -1 && PyErr_Occurred())
2417 return NULL;
2418 if (i < 0)
2419 i += PyList_GET_SIZE(self);
2420 return list_item(self, i);
2421 }
2422 else if (PySlice_Check(item)) {
2423 int start, stop, step, slicelength, cur, i;
2424 PyObject* result;
2425 PyObject* it;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002426 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002427
2428 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
2429 &start, &stop, &step, &slicelength) < 0) {
2430 return NULL;
2431 }
2432
2433 if (slicelength <= 0) {
2434 return PyList_New(0);
2435 }
2436 else {
2437 result = PyList_New(slicelength);
2438 if (!result) return NULL;
2439
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002440 src = self->ob_item;
2441 dest = ((PyListObject *)result)->ob_item;
Tim Peters3b01a122002-07-19 02:35:45 +00002442 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002443 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002444 it = src[cur];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002445 Py_INCREF(it);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002446 dest[i] = it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002447 }
Tim Peters3b01a122002-07-19 02:35:45 +00002448
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002449 return result;
2450 }
2451 }
2452 else {
2453 PyErr_SetString(PyExc_TypeError,
2454 "list indices must be integers");
2455 return NULL;
2456 }
2457}
2458
Tim Peters3b01a122002-07-19 02:35:45 +00002459static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002460list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2461{
2462 if (PyInt_Check(item)) {
2463 long i = PyInt_AS_LONG(item);
2464 if (i < 0)
2465 i += PyList_GET_SIZE(self);
2466 return list_ass_item(self, i, value);
2467 }
2468 else if (PyLong_Check(item)) {
2469 long i = PyLong_AsLong(item);
2470 if (i == -1 && PyErr_Occurred())
2471 return -1;
2472 if (i < 0)
2473 i += PyList_GET_SIZE(self);
2474 return list_ass_item(self, i, value);
2475 }
2476 else if (PySlice_Check(item)) {
2477 int start, stop, step, slicelength;
2478
2479 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
2480 &start, &stop, &step, &slicelength) < 0) {
2481 return -1;
2482 }
2483
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002484 /* treat L[slice(a,b)] = v _exactly_ like L[a:b] = v */
2485 if (step == 1 && ((PySliceObject*)item)->step == Py_None)
2486 return list_ass_slice(self, start, stop, value);
2487
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002488 if (value == NULL) {
2489 /* delete slice */
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002490 PyObject **garbage;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002491 int cur, i;
Tim Peters3b01a122002-07-19 02:35:45 +00002492
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002493 if (slicelength <= 0)
2494 return 0;
2495
2496 if (step < 0) {
2497 stop = start + 1;
2498 start = stop + step*(slicelength - 1) - 1;
2499 step = -step;
2500 }
2501
2502 garbage = (PyObject**)
2503 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Tim Peters3b01a122002-07-19 02:35:45 +00002504
2505 /* drawing pictures might help
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002506 understand these for loops */
Guido van Rossum75a20b12002-06-11 12:22:28 +00002507 for (cur = start, i = 0;
2508 cur < stop;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002509 cur += step, i++) {
2510 int lim = step;
2511
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002512 garbage[i] = PyList_GET_ITEM(self, cur);
2513
Michael W. Hudson56796f62002-07-29 14:35:04 +00002514 if (cur + step >= self->ob_size) {
2515 lim = self->ob_size - cur - 1;
2516 }
2517
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002518 memmove(self->ob_item + cur - i,
2519 self->ob_item + cur + 1,
2520 lim * sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002521 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002522
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002523 for (cur = start + slicelength*step + 1;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002524 cur < self->ob_size; cur++) {
2525 PyList_SET_ITEM(self, cur - slicelength,
2526 PyList_GET_ITEM(self, cur));
2527 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002528
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002529 self->ob_size -= slicelength;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002530 list_resize(self, self->ob_size);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002531
2532 for (i = 0; i < slicelength; i++) {
2533 Py_DECREF(garbage[i]);
2534 }
2535 PyMem_FREE(garbage);
2536
2537 return 0;
2538 }
2539 else {
2540 /* assign slice */
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002541 PyObject **garbage, *ins, *seq, **seqitems, **selfitems;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002542 int cur, i;
2543
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002544 /* protect against a[::-1] = a */
Tim Peters3b01a122002-07-19 02:35:45 +00002545 if (self == (PyListObject*)value) {
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002546 seq = list_slice((PyListObject*)value, 0,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002547 PyList_GET_SIZE(value));
Tim Peters3b01a122002-07-19 02:35:45 +00002548 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002549 else {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002550 seq = PySequence_Fast(value,
2551 "must assign iterable to extended slice");
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002552 if (!seq)
2553 return -1;
2554 }
2555
2556 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2557 PyErr_Format(PyExc_ValueError,
2558 "attempt to assign sequence of size %d to extended slice of size %d",
2559 PySequence_Fast_GET_SIZE(seq),
2560 slicelength);
2561 Py_DECREF(seq);
2562 return -1;
2563 }
2564
2565 if (!slicelength) {
2566 Py_DECREF(seq);
2567 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002568 }
2569
2570 garbage = (PyObject**)
2571 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Tim Peters3b01a122002-07-19 02:35:45 +00002572
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002573 selfitems = self->ob_item;
2574 if (PyList_Check(seq))
2575 seqitems = ((PyListObject *)seq)->ob_item;
2576 else
2577 seqitems = ((PyTupleObject *)seq)->ob_item;
Tim Peters3b01a122002-07-19 02:35:45 +00002578 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002579 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002580 garbage[i] = selfitems[cur];
2581 ins = seqitems[i];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002582 Py_INCREF(ins);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002583 selfitems[cur] = ins;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002584 }
2585
2586 for (i = 0; i < slicelength; i++) {
2587 Py_DECREF(garbage[i]);
2588 }
Tim Peters3b01a122002-07-19 02:35:45 +00002589
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002590 PyMem_FREE(garbage);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002591 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002592
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002593 return 0;
2594 }
Tim Peters3b01a122002-07-19 02:35:45 +00002595 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002596 else {
Tim Peters3b01a122002-07-19 02:35:45 +00002597 PyErr_SetString(PyExc_TypeError,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002598 "list indices must be integers");
2599 return -1;
2600 }
2601}
2602
2603static PyMappingMethods list_as_mapping = {
2604 (inquiry)list_length,
2605 (binaryfunc)list_subscript,
2606 (objobjargproc)list_ass_subscript
2607};
2608
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002609PyTypeObject PyList_Type = {
2610 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002611 0,
2612 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002613 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002614 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002615 (destructor)list_dealloc, /* tp_dealloc */
2616 (printfunc)list_print, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002617 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002618 0, /* tp_setattr */
2619 0, /* tp_compare */
2620 (reprfunc)list_repr, /* tp_repr */
2621 0, /* tp_as_number */
2622 &list_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002623 &list_as_mapping, /* tp_as_mapping */
Guido van Rossumdbb53d92001-12-03 16:32:18 +00002624 list_nohash, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002625 0, /* tp_call */
2626 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002627 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002628 0, /* tp_setattro */
2629 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002630 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Tim Peters6d6c1a32001-08-02 04:15:00 +00002631 Py_TPFLAGS_BASETYPE, /* tp_flags */
2632 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002633 (traverseproc)list_traverse, /* tp_traverse */
2634 (inquiry)list_clear, /* tp_clear */
2635 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002636 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002637 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002638 0, /* tp_iternext */
2639 list_methods, /* tp_methods */
2640 0, /* tp_members */
2641 0, /* tp_getset */
2642 0, /* tp_base */
2643 0, /* tp_dict */
2644 0, /* tp_descr_get */
2645 0, /* tp_descr_set */
2646 0, /* tp_dictoffset */
2647 (initproc)list_init, /* tp_init */
2648 PyType_GenericAlloc, /* tp_alloc */
2649 PyType_GenericNew, /* tp_new */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002650 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002651};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002652
2653
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002654/*********************** List Iterator **************************/
2655
2656typedef struct {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002657 PyObject_HEAD
2658 long it_index;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002659 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002660} listiterobject;
2661
2662PyTypeObject PyListIter_Type;
2663
Guido van Rossum5086e492002-07-16 15:56:52 +00002664static PyObject *
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002665list_iter(PyObject *seq)
2666{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002667 listiterobject *it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002668
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002669 if (!PyList_Check(seq)) {
2670 PyErr_BadInternalCall();
2671 return NULL;
2672 }
2673 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2674 if (it == NULL)
2675 return NULL;
2676 it->it_index = 0;
2677 Py_INCREF(seq);
2678 it->it_seq = (PyListObject *)seq;
2679 _PyObject_GC_TRACK(it);
2680 return (PyObject *)it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002681}
2682
2683static void
2684listiter_dealloc(listiterobject *it)
2685{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002686 _PyObject_GC_UNTRACK(it);
Guido van Rossum86103ae2002-07-16 20:07:32 +00002687 Py_XDECREF(it->it_seq);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002688 PyObject_GC_Del(it);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002689}
2690
2691static int
2692listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2693{
Guido van Rossum86103ae2002-07-16 20:07:32 +00002694 if (it->it_seq == NULL)
2695 return 0;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002696 return visit((PyObject *)it->it_seq, arg);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002697}
2698
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002699static PyObject *
Tim Peters93b2cc42002-06-01 05:22:55 +00002700listiter_next(listiterobject *it)
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002701{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002702 PyListObject *seq;
2703 PyObject *item;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002704
Tim Peters93b2cc42002-06-01 05:22:55 +00002705 assert(it != NULL);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002706 seq = it->it_seq;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002707 if (seq == NULL)
2708 return NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002709 assert(PyList_Check(seq));
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002710
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002711 if (it->it_index < PyList_GET_SIZE(seq)) {
Tim Peters93b2cc42002-06-01 05:22:55 +00002712 item = PyList_GET_ITEM(seq, it->it_index);
2713 ++it->it_index;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002714 Py_INCREF(item);
2715 return item;
2716 }
Guido van Rossum86103ae2002-07-16 20:07:32 +00002717
2718 Py_DECREF(seq);
2719 it->it_seq = NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002720 return NULL;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002721}
2722
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002723PyTypeObject PyListIter_Type = {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002724 PyObject_HEAD_INIT(&PyType_Type)
2725 0, /* ob_size */
2726 "listiterator", /* tp_name */
2727 sizeof(listiterobject), /* tp_basicsize */
2728 0, /* tp_itemsize */
2729 /* methods */
2730 (destructor)listiter_dealloc, /* tp_dealloc */
2731 0, /* tp_print */
2732 0, /* tp_getattr */
2733 0, /* tp_setattr */
2734 0, /* tp_compare */
2735 0, /* tp_repr */
2736 0, /* tp_as_number */
2737 0, /* tp_as_sequence */
2738 0, /* tp_as_mapping */
2739 0, /* tp_hash */
2740 0, /* tp_call */
2741 0, /* tp_str */
2742 PyObject_GenericGetAttr, /* tp_getattro */
2743 0, /* tp_setattro */
2744 0, /* tp_as_buffer */
2745 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2746 0, /* tp_doc */
2747 (traverseproc)listiter_traverse, /* tp_traverse */
2748 0, /* tp_clear */
2749 0, /* tp_richcompare */
2750 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00002751 PyObject_SelfIter, /* tp_iter */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002752 (iternextfunc)listiter_next, /* tp_iternext */
Guido van Rossum86103ae2002-07-16 20:07:32 +00002753 0, /* tp_methods */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002754 0, /* tp_members */
2755 0, /* tp_getset */
2756 0, /* tp_base */
2757 0, /* tp_dict */
2758 0, /* tp_descr_get */
2759 0, /* tp_descr_set */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002760};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002761
2762/*********************** List Reverse Iterator **************************/
2763
2764typedef struct {
2765 PyObject_HEAD
2766 long it_index;
Raymond Hettinger001f2282003-11-08 11:58:44 +00002767 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002768} listreviterobject;
2769
2770PyTypeObject PyListRevIter_Type;
2771
2772static PyObject *
2773list_reversed(PyListObject *seq, PyObject *unused)
2774{
2775 listreviterobject *it;
2776
2777 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2778 if (it == NULL)
2779 return NULL;
2780 assert(PyList_Check(seq));
2781 it->it_index = PyList_GET_SIZE(seq) - 1;
2782 Py_INCREF(seq);
2783 it->it_seq = seq;
2784 PyObject_GC_Track(it);
2785 return (PyObject *)it;
2786}
2787
2788static void
2789listreviter_dealloc(listreviterobject *it)
2790{
2791 PyObject_GC_UnTrack(it);
2792 Py_XDECREF(it->it_seq);
2793 PyObject_GC_Del(it);
2794}
2795
2796static int
2797listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2798{
2799 if (it->it_seq == NULL)
2800 return 0;
2801 return visit((PyObject *)it->it_seq, arg);
2802}
2803
2804static PyObject *
2805listreviter_next(listreviterobject *it)
2806{
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002807 PyObject *item;
2808 long index = it->it_index;
2809 PyListObject *seq = it->it_seq;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002810
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002811 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2812 item = PyList_GET_ITEM(seq, index);
Raymond Hettinger1021c442003-11-07 15:38:09 +00002813 it->it_index--;
2814 Py_INCREF(item);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002815 return item;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002816 }
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002817 it->it_index = -1;
2818 if (seq != NULL) {
2819 it->it_seq = NULL;
2820 Py_DECREF(seq);
2821 }
2822 return NULL;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002823}
2824
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002825static int
2826listreviter_len(listreviterobject *it)
2827{
2828 return it->it_index + 1;
2829}
2830
2831static PySequenceMethods listreviter_as_sequence = {
2832 (inquiry)listreviter_len, /* sq_length */
2833 0, /* sq_concat */
2834};
2835
Raymond Hettinger1021c442003-11-07 15:38:09 +00002836PyTypeObject PyListRevIter_Type = {
2837 PyObject_HEAD_INIT(&PyType_Type)
2838 0, /* ob_size */
2839 "listreverseiterator", /* tp_name */
2840 sizeof(listreviterobject), /* tp_basicsize */
2841 0, /* tp_itemsize */
2842 /* methods */
2843 (destructor)listreviter_dealloc, /* tp_dealloc */
2844 0, /* tp_print */
2845 0, /* tp_getattr */
2846 0, /* tp_setattr */
2847 0, /* tp_compare */
2848 0, /* tp_repr */
2849 0, /* tp_as_number */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002850 &listreviter_as_sequence, /* tp_as_sequence */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002851 0, /* tp_as_mapping */
2852 0, /* tp_hash */
2853 0, /* tp_call */
2854 0, /* tp_str */
2855 PyObject_GenericGetAttr, /* tp_getattro */
2856 0, /* tp_setattro */
2857 0, /* tp_as_buffer */
2858 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2859 0, /* tp_doc */
2860 (traverseproc)listreviter_traverse, /* tp_traverse */
2861 0, /* tp_clear */
2862 0, /* tp_richcompare */
2863 0, /* tp_weaklistoffset */
2864 PyObject_SelfIter, /* tp_iter */
2865 (iternextfunc)listreviter_next, /* tp_iternext */
2866 0,
2867};