blob: f34ca70abcbea874c676a912953131ff9ae151c1 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* List object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
4
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00005#ifdef STDC_HEADERS
6#include <stddef.h>
7#else
8#include <sys/types.h> /* For size_t */
9#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000010
Guido van Rossuma46d51d1995-01-26 22:59:43 +000011static int
Raymond Hettingerd4ff7412004-03-15 09:01:31 +000012list_resize(PyListObject *self, int newsize)
Guido van Rossuma46d51d1995-01-26 22:59:43 +000013{
Raymond Hettinger4bb95402004-02-13 11:36:39 +000014 PyObject **items;
15 size_t _new_size;
Tim Peters65b8b842001-05-26 05:28:40 +000016
Raymond Hettinger4bb95402004-02-13 11:36:39 +000017 /* Bypass realloc() when a previous overallocation is large enough
18 to accommodate the newsize. If the newsize is 16 smaller than the
19 current size, then proceed with the realloc() to shrink the list.
20 */
21
22 if (self->allocated >= newsize &&
23 self->ob_size < newsize + 16 &&
24 self->ob_item != NULL) {
25 self->ob_size = newsize;
26 return 0;
27 }
28
29 /* This over-allocates proportional to the list size, making room
Tim Peters65b8b842001-05-26 05:28:40 +000030 * for additional growth. The over-allocation is mild, but is
31 * enough to give linear-time amortized behavior over a long
32 * sequence of appends() in the presence of a poorly-performing
Raymond Hettingerab517d22004-02-14 18:34:46 +000033 * system realloc().
34 * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
Tim Peters65b8b842001-05-26 05:28:40 +000035 */
Raymond Hettingerd4ff7412004-03-15 09:01:31 +000036 _new_size = (newsize >> 3) + (self->ob_size < 8 ? 3 : 6) + newsize;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000037 items = self->ob_item;
38 if (_new_size <= ((~(size_t)0) / sizeof(PyObject *)))
39 PyMem_RESIZE(items, PyObject *, _new_size);
40 else
41 items = NULL;
42 if (items == NULL) {
43 PyErr_NoMemory();
44 return -1;
45 }
46 self->ob_item = items;
47 self->ob_size = newsize;
48 self->allocated = _new_size;
49 return 0;
50}
Guido van Rossuma46d51d1995-01-26 22:59:43 +000051
Guido van Rossumc0b618a1997-05-02 03:12:38 +000052PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +000053PyList_New(int size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000054{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000055 PyListObject *op;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +000056 size_t nbytes;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000057 if (size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000058 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000059 return NULL;
60 }
Tim Peters7049d812004-01-18 20:31:02 +000061 nbytes = size * sizeof(PyObject *);
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000062 /* Check for overflow */
Tim Peters7049d812004-01-18 20:31:02 +000063 if (nbytes / sizeof(PyObject *) != (size_t)size) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000064 return PyErr_NoMemory();
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000065 }
Neil Schemenauere83c00e2001-08-29 23:54:21 +000066 op = PyObject_GC_New(PyListObject, &PyList_Type);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000067 if (op == NULL) {
Neil Schemenauere83c00e2001-08-29 23:54:21 +000068 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000069 }
70 if (size <= 0) {
71 op->ob_item = NULL;
72 }
73 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +000074 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000075 if (op->ob_item == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000076 return PyErr_NoMemory();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000077 }
Tim Peters7049d812004-01-18 20:31:02 +000078 memset(op->ob_item, 0, sizeof(*op->ob_item) * size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000079 }
Neil Schemenauere83c00e2001-08-29 23:54:21 +000080 op->ob_size = size;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000081 op->allocated = size;
Neil Schemenauere83c00e2001-08-29 23:54:21 +000082 _PyObject_GC_TRACK(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +000083 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000084}
85
86int
Fred Drakea2f55112000-07-09 15:16:51 +000087PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000088{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000089 if (!PyList_Check(op)) {
90 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000091 return -1;
92 }
93 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000094 return ((PyListObject *)op) -> ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000095}
96
Guido van Rossumc0b618a1997-05-02 03:12:38 +000097static PyObject *indexerr;
Guido van Rossum929f1b81996-08-09 20:51:27 +000098
Guido van Rossumc0b618a1997-05-02 03:12:38 +000099PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000100PyList_GetItem(PyObject *op, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000101{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000102 if (!PyList_Check(op)) {
103 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000104 return NULL;
105 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000106 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000107 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000108 indexerr = PyString_FromString(
109 "list index out of range");
110 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000111 return NULL;
112 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000113 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000114}
115
116int
Fred Drakea2f55112000-07-09 15:16:51 +0000117PyList_SetItem(register PyObject *op, register int i,
118 register PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000119{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000120 register PyObject *olditem;
121 register PyObject **p;
122 if (!PyList_Check(op)) {
123 Py_XDECREF(newitem);
124 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000125 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000126 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000127 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
128 Py_XDECREF(newitem);
129 PyErr_SetString(PyExc_IndexError,
130 "list assignment index out of range");
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000131 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000132 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000133 p = ((PyListObject *)op) -> ob_item + i;
Guido van Rossum5fe60581995-03-09 12:12:50 +0000134 olditem = *p;
135 *p = newitem;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000136 Py_XDECREF(olditem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000137 return 0;
138}
139
140static int
Fred Drakea2f55112000-07-09 15:16:51 +0000141ins1(PyListObject *self, int where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000142{
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000143 int i, n = self->ob_size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000144 PyObject **items;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000145 if (v == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000146 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000147 return -1;
148 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000149 if (n == INT_MAX) {
Trent Micka5846642000-08-13 22:47:45 +0000150 PyErr_SetString(PyExc_OverflowError,
151 "cannot add more objects to list");
152 return -1;
153 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000154
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000155 if (list_resize(self, n+1) == -1)
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000156 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000157
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000158 if (where < 0) {
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000159 where += n;
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000160 if (where < 0)
161 where = 0;
162 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000163 if (where > n)
164 where = n;
165 items = self->ob_item;
166 for (i = n; --i >= where; )
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000167 items[i+1] = items[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000168 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000169 items[where] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000170 return 0;
171}
172
173int
Fred Drakea2f55112000-07-09 15:16:51 +0000174PyList_Insert(PyObject *op, int where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000175{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000176 if (!PyList_Check(op)) {
177 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000178 return -1;
179 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000180 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000181}
182
183int
Fred Drakea2f55112000-07-09 15:16:51 +0000184PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000185{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000186 if (!PyList_Check(op)) {
187 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000188 return -1;
189 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000190 return ins1((PyListObject *)op,
191 (int) ((PyListObject *)op)->ob_size, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000192}
193
194/* Methods */
195
196static void
Fred Drakea2f55112000-07-09 15:16:51 +0000197list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000198{
199 int i;
Guido van Rossumff413af2002-03-28 20:34:59 +0000200 PyObject_GC_UnTrack(op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000201 Py_TRASHCAN_SAFE_BEGIN(op)
Jack Jansen7874d1f1995-01-19 12:09:27 +0000202 if (op->ob_item != NULL) {
Guido van Rossumfa717011999-06-09 15:19:34 +0000203 /* Do it backwards, for Christian Tismer.
204 There's a simple test case where somehow this reduces
205 thrashing when a *very* large list is created and
206 immediately deleted. */
207 i = op->ob_size;
208 while (--i >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000209 Py_XDECREF(op->ob_item[i]);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000210 }
Guido van Rossumb18618d2000-05-03 23:44:39 +0000211 PyMem_FREE(op->ob_item);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000212 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000213 op->ob_type->tp_free((PyObject *)op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000214 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000215}
216
Guido van Rossum90933611991-06-07 16:10:43 +0000217static int
Fred Drakea2f55112000-07-09 15:16:51 +0000218list_print(PyListObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000219{
220 int i;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000221
222 i = Py_ReprEnter((PyObject*)op);
223 if (i != 0) {
224 if (i < 0)
225 return i;
226 fprintf(fp, "[...]");
227 return 0;
228 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000229 fprintf(fp, "[");
Guido van Rossum90933611991-06-07 16:10:43 +0000230 for (i = 0; i < op->ob_size; i++) {
231 if (i > 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000232 fprintf(fp, ", ");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000233 if (PyObject_Print(op->ob_item[i], fp, 0) != 0) {
234 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000235 return -1;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000236 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000237 }
238 fprintf(fp, "]");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000239 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000240 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000241}
242
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000243static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000244list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000245{
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000246 int i;
Tim Petersa7259592001-06-16 05:11:17 +0000247 PyObject *s, *temp;
248 PyObject *pieces = NULL, *result = NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000249
250 i = Py_ReprEnter((PyObject*)v);
251 if (i != 0) {
Tim Petersa7259592001-06-16 05:11:17 +0000252 return i > 0 ? PyString_FromString("[...]") : NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000253 }
Tim Petersa7259592001-06-16 05:11:17 +0000254
255 if (v->ob_size == 0) {
256 result = PyString_FromString("[]");
257 goto Done;
258 }
259
260 pieces = PyList_New(0);
261 if (pieces == NULL)
262 goto Done;
263
264 /* Do repr() on each element. Note that this may mutate the list,
265 so must refetch the list size on each iteration. */
266 for (i = 0; i < v->ob_size; ++i) {
267 int status;
268 s = PyObject_Repr(v->ob_item[i]);
269 if (s == NULL)
270 goto Done;
271 status = PyList_Append(pieces, s);
272 Py_DECREF(s); /* append created a new ref */
273 if (status < 0)
274 goto Done;
275 }
276
277 /* Add "[]" decorations to the first and last items. */
278 assert(PyList_GET_SIZE(pieces) > 0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000279 s = PyString_FromString("[");
Tim Petersa7259592001-06-16 05:11:17 +0000280 if (s == NULL)
281 goto Done;
282 temp = PyList_GET_ITEM(pieces, 0);
283 PyString_ConcatAndDel(&s, temp);
284 PyList_SET_ITEM(pieces, 0, s);
285 if (s == NULL)
286 goto Done;
287
288 s = PyString_FromString("]");
289 if (s == NULL)
290 goto Done;
291 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
292 PyString_ConcatAndDel(&temp, s);
293 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
294 if (temp == NULL)
295 goto Done;
296
297 /* Paste them all together with ", " between. */
298 s = PyString_FromString(", ");
299 if (s == NULL)
300 goto Done;
301 result = _PyString_Join(s, pieces);
Tim Peters3b01a122002-07-19 02:35:45 +0000302 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +0000303
304Done:
305 Py_XDECREF(pieces);
Guido van Rossumfb376de1998-04-10 22:47:27 +0000306 Py_ReprLeave((PyObject *)v);
Tim Petersa7259592001-06-16 05:11:17 +0000307 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000308}
309
310static int
Fred Drakea2f55112000-07-09 15:16:51 +0000311list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000312{
313 return a->ob_size;
314}
315
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000316static int
Fred Drakea2f55112000-07-09 15:16:51 +0000317list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000318{
Raymond Hettingeraae59992002-09-05 14:23:49 +0000319 int i, cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000320
Raymond Hettingeraae59992002-09-05 14:23:49 +0000321 for (i = 0, cmp = 0 ; cmp == 0 && i < a->ob_size; ++i)
322 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000323 Py_EQ);
Neal Norwitzbb9c5f52002-09-05 21:32:55 +0000324 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000325}
326
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000327static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000328list_item(PyListObject *a, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000329{
330 if (i < 0 || i >= a->ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000331 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000332 indexerr = PyString_FromString(
333 "list index out of range");
334 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000335 return NULL;
336 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000337 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000338 return a->ob_item[i];
339}
340
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000341static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000342list_slice(PyListObject *a, int ilow, int ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000343{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000344 PyListObject *np;
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000345 PyObject **src, **dest;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000346 int i, len;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000347 if (ilow < 0)
348 ilow = 0;
349 else if (ilow > a->ob_size)
350 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000351 if (ihigh < ilow)
352 ihigh = ilow;
353 else if (ihigh > a->ob_size)
354 ihigh = a->ob_size;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000355 len = ihigh - ilow;
356 np = (PyListObject *) PyList_New(len);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000357 if (np == NULL)
358 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000359
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000360 src = a->ob_item + ilow;
361 dest = np->ob_item;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000362 for (i = 0; i < len; i++) {
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000363 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000364 Py_INCREF(v);
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000365 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000366 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000367 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000368}
369
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000370PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000371PyList_GetSlice(PyObject *a, int ilow, int ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000372{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000373 if (!PyList_Check(a)) {
374 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000375 return NULL;
376 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000377 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000378}
379
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000380static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000381list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000382{
383 int size;
384 int i;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000385 PyObject **src, **dest;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000386 PyListObject *np;
387 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000388 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000389 "can only concatenate list (not \"%.200s\") to list",
390 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000391 return NULL;
392 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000393#define b ((PyListObject *)bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000394 size = a->ob_size + b->ob_size;
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000395 if (size < 0)
396 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000397 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000398 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000399 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000400 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000401 src = a->ob_item;
402 dest = np->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000403 for (i = 0; i < a->ob_size; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000404 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000405 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000406 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000407 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000408 src = b->ob_item;
409 dest = np->ob_item + a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000410 for (i = 0; i < b->ob_size; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000411 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000412 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000413 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000414 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000415 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000416#undef b
417}
418
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000419static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000420list_repeat(PyListObject *a, int n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000421{
422 int i, j;
423 int size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000424 PyListObject *np;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000425 PyObject **p, **items;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000426 PyObject *elem;
Guido van Rossumed98d481991-03-06 13:07:53 +0000427 if (n < 0)
428 n = 0;
429 size = a->ob_size * n;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000430 if (size == 0)
431 return PyList_New(0);
Guido van Rossumbfa5a142002-10-11 23:39:35 +0000432 if (n && size/n != a->ob_size)
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000433 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000434 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000435 if (np == NULL)
436 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000437
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000438 items = np->ob_item;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000439 if (a->ob_size == 1) {
440 elem = a->ob_item[0];
441 for (i = 0; i < n; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000442 items[i] = elem;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000443 Py_INCREF(elem);
444 }
445 return (PyObject *) np;
446 }
Guido van Rossumed98d481991-03-06 13:07:53 +0000447 p = np->ob_item;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000448 items = a->ob_item;
Guido van Rossumed98d481991-03-06 13:07:53 +0000449 for (i = 0; i < n; i++) {
450 for (j = 0; j < a->ob_size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000451 *p = items[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000452 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000453 p++;
454 }
455 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000456 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000457}
458
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000459static int
Fred Drakea2f55112000-07-09 15:16:51 +0000460list_ass_slice(PyListObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000461{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000462 /* Because [X]DECREF can recursively invoke list operations on
463 this list, we must postpone all [X]DECREF activity until
464 after the list is back in its canonical shape. Therefore
465 we must allocate an additional array, 'recycle', into which
466 we temporarily copy the items that are deleted from the
467 list. :-( */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000468 PyObject **recycle, **p;
469 PyObject **item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000470 PyObject **vitem = NULL;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000471 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000472 int n; /* Size of replacement list */
473 int d; /* Change in size */
474 int k; /* Loop index */
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000475 int s;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000476#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000477 if (v == NULL)
478 n = 0;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000479 else {
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000480 if (a == b) {
481 /* Special case "a[i:j] = a" -- copy b first */
482 int ret;
Michael W. Hudsonda0a0672003-08-15 12:06:41 +0000483 v = list_slice(b, 0, b->ob_size);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000484 if (v == NULL)
485 return -1;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000486 ret = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000487 Py_DECREF(v);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000488 return ret;
489 }
Raymond Hettingerf889e102004-03-09 08:04:33 +0000490 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000491 if(v_as_SF == NULL)
492 return -1;
493 n = PySequence_Fast_GET_SIZE(v_as_SF);
Raymond Hettinger42bec932004-03-12 16:38:17 +0000494 vitem = PySequence_Fast_ITEMS(v_as_SF);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000495 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000496 if (ilow < 0)
497 ilow = 0;
498 else if (ilow > a->ob_size)
499 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000500 if (ihigh < ilow)
501 ihigh = ilow;
502 else if (ihigh > a->ob_size)
503 ihigh = a->ob_size;
504 item = a->ob_item;
505 d = n - (ihigh-ilow);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000506 if (ihigh > ilow) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000507 p = recycle = PyMem_NEW(PyObject *, (ihigh-ilow));
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000508 if (recycle == NULL) {
509 PyErr_NoMemory();
510 return -1;
511 }
512 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000513 else
514 p = recycle = NULL;
515 if (d <= 0) { /* Delete -d items; recycle ihigh-ilow items */
Raymond Hettinger66d31f82004-03-10 11:44:04 +0000516 memcpy(p, &item[ilow], (ihigh - ilow)*sizeof(PyObject *));
Raymond Hettingerf889e102004-03-09 08:04:33 +0000517 p += ihigh - ilow;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000518 if (d < 0) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000519 memmove(&item[ihigh+d], &item[ihigh],
520 (a->ob_size - ihigh)*sizeof(PyObject *));
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000521 list_resize(a, a->ob_size + d);
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000522 item = a->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000523 }
524 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000525 else { /* Insert d items; recycle ihigh-ilow items */
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000526 s = a->ob_size;
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000527 if (list_resize(a, s+d) == -1) {
Guido van Rossumb18618d2000-05-03 23:44:39 +0000528 if (recycle != NULL)
529 PyMem_DEL(recycle);
Raymond Hettinger2731ae42004-02-14 03:07:21 +0000530 return -1;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000531 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000532 item = a->ob_item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000533 memmove(&item[ihigh+d], &item[ihigh],
534 (s - ihigh)*sizeof(PyObject *));
Raymond Hettinger66d31f82004-03-10 11:44:04 +0000535 memcpy(p, &item[ilow], (ihigh - ilow)*sizeof(PyObject *));
Raymond Hettingerf889e102004-03-09 08:04:33 +0000536 p += ihigh - ilow;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000537 }
538 for (k = 0; k < n; k++, ilow++) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000539 PyObject *w = vitem[k];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000540 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000541 item[ilow] = w;
542 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000543 if (recycle) {
544 while (--p >= recycle)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000545 Py_XDECREF(*p);
546 PyMem_DEL(recycle);
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000547 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000548 if (a->ob_size == 0 && a->ob_item != NULL) {
549 PyMem_FREE(a->ob_item);
550 a->ob_item = NULL;
551 }
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000552 Py_XDECREF(v_as_SF);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000553 return 0;
554#undef b
555}
556
Guido van Rossum234f9421993-06-17 12:35:49 +0000557int
Fred Drakea2f55112000-07-09 15:16:51 +0000558PyList_SetSlice(PyObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000559{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000560 if (!PyList_Check(a)) {
561 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000562 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000563 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000564 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000565}
566
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000567static PyObject *
568list_inplace_repeat(PyListObject *self, int n)
569{
570 PyObject **items;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000571 int size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000572
573
574 size = PyList_GET_SIZE(self);
575 if (size == 0) {
576 Py_INCREF(self);
577 return (PyObject *)self;
578 }
579
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000580 if (n < 1) {
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000581 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000582 self->ob_item = NULL;
583 self->ob_size = 0;
584 for (i = 0; i < size; i++)
585 Py_XDECREF(items[i]);
586 PyMem_DEL(items);
587 Py_INCREF(self);
588 return (PyObject *)self;
589 }
590
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000591 if (list_resize(self, size*n) == -1)
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000592 return NULL;
593
594 p = size;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000595 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000596 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
597 for (j = 0; j < size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000598 PyObject *o = items[j];
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000599 Py_INCREF(o);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000600 items[p++] = o;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000601 }
602 }
603 Py_INCREF(self);
604 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000605}
606
Guido van Rossum4a450d01991-04-03 19:05:18 +0000607static int
Fred Drakea2f55112000-07-09 15:16:51 +0000608list_ass_item(PyListObject *a, int i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000609{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000610 PyObject *old_value;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000611 if (i < 0 || i >= a->ob_size) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000612 PyErr_SetString(PyExc_IndexError,
613 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000614 return -1;
615 }
616 if (v == NULL)
617 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000618 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000619 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000620 a->ob_item[i] = v;
Tim Peters3b01a122002-07-19 02:35:45 +0000621 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000622 return 0;
623}
624
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000625static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000626ins(PyListObject *self, int where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000627{
628 if (ins1(self, where, v) != 0)
629 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000630 Py_INCREF(Py_None);
631 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000632}
633
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000634static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000635listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000636{
637 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000638 PyObject *v;
Guido van Rossumc00a9382000-02-24 21:48:29 +0000639 if (!PyArg_ParseTuple(args, "iO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000640 return NULL;
Guido van Rossumbf80e541993-02-08 15:49:17 +0000641 return ins(self, i, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000642}
643
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000644static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000645listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000646{
Guido van Rossumbf80e541993-02-08 15:49:17 +0000647 return ins(self, (int) self->ob_size, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000648}
649
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000650static int
651listextend_internal(PyListObject *self, PyObject *b)
Barry Warsawdedf6d61998-10-09 16:37:25 +0000652{
Raymond Hettinger6e058d72004-03-12 15:30:38 +0000653 int selflen = PyList_GET_SIZE(self);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000654 int blen;
655 register int i;
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000656 PyObject **src, **dest;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000657
Raymond Hettinger6e058d72004-03-12 15:30:38 +0000658 blen = PyObject_Size(b);
659 if (blen == 0) {
Barry Warsawdedf6d61998-10-09 16:37:25 +0000660 /* short circuit when b is empty */
Jeremy Hyltondb60bb52001-01-03 22:32:16 +0000661 Py_DECREF(b);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000662 return 0;
Jeremy Hyltondb60bb52001-01-03 22:32:16 +0000663 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000664
Barry Warsawdedf6d61998-10-09 16:37:25 +0000665 if (self == (PyListObject*)b) {
666 /* as in list_ass_slice() we must special case the
667 * situation: a.extend(a)
668 *
669 * XXX: I think this way ought to be faster than using
670 * list_slice() the way list_ass_slice() does.
671 */
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000672 Py_DECREF(b);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000673 b = PyList_New(selflen);
674 if (!b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000675 return -1;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000676 for (i = 0; i < selflen; i++) {
677 PyObject *o = PyList_GET_ITEM(self, i);
678 Py_INCREF(o);
679 PyList_SET_ITEM(b, i, o);
680 }
681 }
Barry Warsawdedf6d61998-10-09 16:37:25 +0000682
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000683 if (list_resize(self, selflen + blen) == -1) {
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000684 Py_DECREF(b);
685 return -1;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000686 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000687
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000688 /* populate the end of self with b's items */
Raymond Hettinger42bec932004-03-12 16:38:17 +0000689 src = PySequence_Fast_ITEMS(b);
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000690 dest = self->ob_item + selflen;
691 for (i = 0; i < blen; i++) {
692 PyObject *o = src[i];
693 Py_INCREF(o);
694 dest[i] = o;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000695 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000696 Py_DECREF(b);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000697 return 0;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000698}
699
Barry Warsawdedf6d61998-10-09 16:37:25 +0000700static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000701listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000702{
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000703 PyObject *it; /* iter(v) */
704 int m; /* size of self */
705 int n; /* guess for size of b */
706 int mn; /* m + n */
707 int i;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000708 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000709
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000710 /* Special cases:
711 1) lists and tuples which can use PySequence_Fast ops
712 2) extending self to self requires making a copy first
713 */
714 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
715 b = PySequence_Fast(b, "argument must be iterable");
716 if (!b)
717 return NULL;
718 if (listextend_internal(self, b) < 0)
719 return NULL;
720 Py_RETURN_NONE;
721 }
722
723 it = PyObject_GetIter(b);
724 if (it == NULL)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000725 return NULL;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000726 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000727
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000728 /* Guess a result list size. */
729 n = PyObject_Size(b);
730 if (n < 0) {
731 PyErr_Clear();
732 n = 8; /* arbitrary */
733 }
734 m = self->ob_size;
735 mn = m + n;
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000736 if (list_resize(self, mn) == -1)
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000737 goto error;
738 memset(&(self->ob_item[m]), 0, sizeof(*self->ob_item) * n);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000739
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000740 /* Run iterator to exhaustion. */
741 for (i = m; ; i++) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000742 PyObject *item = iternext(it);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000743 if (item == NULL) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000744 if (PyErr_Occurred()) {
745 if (PyErr_ExceptionMatches(PyExc_StopIteration))
746 PyErr_Clear();
747 else
748 goto error;
749 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000750 break;
751 }
752 if (i < mn)
753 PyList_SET_ITEM(self, i, item); /* steals ref */
754 else {
755 int status = ins1(self, self->ob_size, item);
756 Py_DECREF(item); /* append creates a new ref */
757 if (status < 0)
758 goto error;
759 }
760 }
761
762 /* Cut back result list if initial guess was too large. */
763 if (i < mn && self != NULL) {
764 if (list_ass_slice(self, i, mn, (PyObject *)NULL) != 0)
765 goto error;
766 }
767 Py_DECREF(it);
768 Py_RETURN_NONE;
769
770 error:
771 Py_DECREF(it);
772 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000773}
774
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000775PyObject *
776_PyList_Extend(PyListObject *self, PyObject *b)
777{
778 return listextend(self, b);
779}
780
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000781static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000782list_inplace_concat(PyListObject *self, PyObject *other)
783{
784 PyObject *result;
785
786 result = listextend(self, other);
787 if (result == NULL)
788 return result;
789 Py_DECREF(result);
790 Py_INCREF(self);
791 return (PyObject *)self;
792}
793
794static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000795listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000796{
797 int i = -1;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000798 PyObject *v, *arg = NULL;
799
800 if (!PyArg_UnpackTuple(args, "pop", 0, 1, &arg))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000801 return NULL;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000802 if (arg != NULL) {
803 if (PyInt_Check(arg))
804 i = (int)(PyInt_AS_LONG((PyIntObject*) arg));
Raymond Hettingerfa6c6f82004-02-19 06:12:06 +0000805 else if (!PyArg_ParseTuple(args, "|i:pop", &i))
806 return NULL;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000807 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000808 if (self->ob_size == 0) {
809 /* Special-case most common failure cause */
810 PyErr_SetString(PyExc_IndexError, "pop from empty list");
811 return NULL;
812 }
813 if (i < 0)
814 i += self->ob_size;
815 if (i < 0 || i >= self->ob_size) {
816 PyErr_SetString(PyExc_IndexError, "pop index out of range");
817 return NULL;
818 }
819 v = self->ob_item[i];
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000820 if (i == self->ob_size - 1) {
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000821 if (list_resize(self, self->ob_size - 1) == -1)
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000822 return NULL;
823 return v;
824 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000825 Py_INCREF(v);
826 if (list_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) {
827 Py_DECREF(v);
828 return NULL;
829 }
830 return v;
831}
832
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000833/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
834static void
835reverse_slice(PyObject **lo, PyObject **hi)
836{
837 assert(lo && hi);
838
839 --hi;
840 while (lo < hi) {
841 PyObject *t = *lo;
842 *lo = *hi;
843 *hi = t;
844 ++lo;
845 --hi;
846 }
847}
848
Tim Petersa64dc242002-08-01 02:13:36 +0000849/* Lots of code for an adaptive, stable, natural mergesort. There are many
850 * pieces to this algorithm; read listsort.txt for overviews and details.
851 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000852
Guido van Rossum3f236de1996-12-10 23:55:39 +0000853/* Comparison function. Takes care of calling a user-supplied
Tim Peters66860f62002-08-04 17:47:26 +0000854 * comparison function (any callable Python object), which must not be
855 * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool
856 * with Py_LT if you know it's NULL).
Tim Petersa64dc242002-08-01 02:13:36 +0000857 * Returns -1 on error, 1 if x < y, 0 if x >= y.
858 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000859static int
Tim Petersa8c974c2002-07-19 03:30:57 +0000860islt(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000861{
Tim Petersf2a04732002-07-11 21:46:16 +0000862 PyObject *res;
863 PyObject *args;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000864 int i;
865
Tim Peters66860f62002-08-04 17:47:26 +0000866 assert(compare != NULL);
Tim Petersa8c974c2002-07-19 03:30:57 +0000867 /* Call the user's comparison function and translate the 3-way
868 * result into true or false (or error).
869 */
Tim Petersf2a04732002-07-11 21:46:16 +0000870 args = PyTuple_New(2);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000871 if (args == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000872 return -1;
Tim Petersf2a04732002-07-11 21:46:16 +0000873 Py_INCREF(x);
874 Py_INCREF(y);
875 PyTuple_SET_ITEM(args, 0, x);
876 PyTuple_SET_ITEM(args, 1, y);
Tim Peters58cf3612002-07-15 05:16:13 +0000877 res = PyObject_Call(compare, args, NULL);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000878 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000879 if (res == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000880 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000881 if (!PyInt_Check(res)) {
882 Py_DECREF(res);
883 PyErr_SetString(PyExc_TypeError,
Guido van Rossum9bcd1d71999-04-19 17:44:39 +0000884 "comparison function must return int");
Tim Petersa8c974c2002-07-19 03:30:57 +0000885 return -1;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000886 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000887 i = PyInt_AsLong(res);
888 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +0000889 return i < 0;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000890}
891
Tim Peters66860f62002-08-04 17:47:26 +0000892/* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
893 * islt. This avoids a layer of function call in the usual case, and
894 * sorting does many comparisons.
895 * Returns -1 on error, 1 if x < y, 0 if x >= y.
896 */
897#define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
898 PyObject_RichCompareBool(X, Y, Py_LT) : \
899 islt(X, Y, COMPARE))
900
901/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +0000902 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
903 started. It makes more sense in context <wink>. X and Y are PyObject*s.
904*/
Tim Peters66860f62002-08-04 17:47:26 +0000905#define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
Tim Petersa8c974c2002-07-19 03:30:57 +0000906 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000907
908/* binarysort is the best method for sorting small arrays: it does
909 few compares, but can do data movement quadratic in the number of
910 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000911 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +0000912 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000913 On entry, must have lo <= start <= hi, and that [lo, start) is already
914 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +0000915 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000916 Even in case of error, the output slice will be some permutation of
917 the input (nothing is lost or duplicated).
918*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000919static int
Fred Drakea2f55112000-07-09 15:16:51 +0000920binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
921 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000922{
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000923 register int k;
924 register PyObject **l, **p, **r;
925 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000926
Tim Petersa8c974c2002-07-19 03:30:57 +0000927 assert(lo <= start && start <= hi);
928 /* assert [lo, start) is sorted */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000929 if (lo == start)
930 ++start;
931 for (; start < hi; ++start) {
932 /* set l to where *start belongs */
933 l = lo;
934 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000935 pivot = *r;
Tim Peters0fe977c2002-07-19 06:12:32 +0000936 /* Invariants:
937 * pivot >= all in [lo, l).
938 * pivot < all in [r, start).
939 * The second is vacuously true at the start.
940 */
941 assert(l < r);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000942 do {
943 p = l + ((r - l) >> 1);
Tim Petersa8c974c2002-07-19 03:30:57 +0000944 IFLT(pivot, *p)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000945 r = p;
946 else
Tim Peters0fe977c2002-07-19 06:12:32 +0000947 l = p+1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000948 } while (l < r);
Tim Peters0fe977c2002-07-19 06:12:32 +0000949 assert(l == r);
950 /* The invariants still hold, so pivot >= all in [lo, l) and
951 pivot < all in [l, start), so pivot belongs at l. Note
952 that if there are elements equal to pivot, l points to the
953 first slot after them -- that's why this sort is stable.
954 Slide over to make room.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000955 Caution: using memmove is much slower under MSVC 5;
956 we're not usually moving many slots. */
957 for (p = start; p > l; --p)
958 *p = *(p-1);
959 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000960 }
Guido van Rossum3f236de1996-12-10 23:55:39 +0000961 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000962
963 fail:
964 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000965}
966
Tim Petersa64dc242002-08-01 02:13:36 +0000967/*
968Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
969is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000970
Tim Petersa64dc242002-08-01 02:13:36 +0000971 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000972
Tim Petersa64dc242002-08-01 02:13:36 +0000973or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000974
Tim Petersa64dc242002-08-01 02:13:36 +0000975 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +0000976
Tim Petersa64dc242002-08-01 02:13:36 +0000977Boolean *descending is set to 0 in the former case, or to 1 in the latter.
978For its intended use in a stable mergesort, the strictness of the defn of
979"descending" is needed so that the caller can safely reverse a descending
980sequence without violating stability (strict > ensures there are no equal
981elements to get out of order).
982
983Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000984*/
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000985static int
Tim Petersa64dc242002-08-01 02:13:36 +0000986count_run(PyObject **lo, PyObject **hi, PyObject *compare, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000987{
Tim Petersa64dc242002-08-01 02:13:36 +0000988 int k;
989 int n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000990
Tim Petersa64dc242002-08-01 02:13:36 +0000991 assert(lo < hi);
992 *descending = 0;
993 ++lo;
994 if (lo == hi)
995 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000996
Tim Petersa64dc242002-08-01 02:13:36 +0000997 n = 2;
998 IFLT(*lo, *(lo-1)) {
999 *descending = 1;
1000 for (lo = lo+1; lo < hi; ++lo, ++n) {
1001 IFLT(*lo, *(lo-1))
1002 ;
1003 else
1004 break;
1005 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001006 }
Tim Petersa64dc242002-08-01 02:13:36 +00001007 else {
1008 for (lo = lo+1; lo < hi; ++lo, ++n) {
1009 IFLT(*lo, *(lo-1))
1010 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001011 }
1012 }
1013
Tim Petersa64dc242002-08-01 02:13:36 +00001014 return n;
1015fail:
1016 return -1;
1017}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001018
Tim Petersa64dc242002-08-01 02:13:36 +00001019/*
1020Locate the proper position of key in a sorted vector; if the vector contains
1021an element equal to key, return the position immediately to the left of
1022the leftmost equal element. [gallop_right() does the same except returns
1023the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001024
Tim Petersa64dc242002-08-01 02:13:36 +00001025"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001026
Tim Petersa64dc242002-08-01 02:13:36 +00001027"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1028hint is to the final result, the faster this runs.
1029
1030The return value is the int k in 0..n such that
1031
1032 a[k-1] < key <= a[k]
1033
1034pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1035key belongs at index k; or, IOW, the first k elements of a should precede
1036key, and the last n-k should follow key.
1037
1038Returns -1 on error. See listsort.txt for info on the method.
1039*/
1040static int
1041gallop_left(PyObject *key, PyObject **a, int n, int hint, PyObject *compare)
1042{
1043 int ofs;
1044 int lastofs;
1045 int k;
1046
1047 assert(key && a && n > 0 && hint >= 0 && hint < n);
1048
1049 a += hint;
1050 lastofs = 0;
1051 ofs = 1;
1052 IFLT(*a, key) {
1053 /* a[hint] < key -- gallop right, until
1054 * a[hint + lastofs] < key <= a[hint + ofs]
1055 */
1056 const int maxofs = n - hint; /* &a[n-1] is highest */
1057 while (ofs < maxofs) {
1058 IFLT(a[ofs], key) {
1059 lastofs = ofs;
1060 ofs = (ofs << 1) + 1;
1061 if (ofs <= 0) /* int overflow */
1062 ofs = maxofs;
1063 }
1064 else /* key <= a[hint + ofs] */
1065 break;
1066 }
1067 if (ofs > maxofs)
1068 ofs = maxofs;
1069 /* Translate back to offsets relative to &a[0]. */
1070 lastofs += hint;
1071 ofs += hint;
1072 }
1073 else {
1074 /* key <= a[hint] -- gallop left, until
1075 * a[hint - ofs] < key <= a[hint - lastofs]
1076 */
1077 const int maxofs = hint + 1; /* &a[0] is lowest */
1078 while (ofs < maxofs) {
1079 IFLT(*(a-ofs), key)
1080 break;
1081 /* key <= a[hint - ofs] */
1082 lastofs = ofs;
1083 ofs = (ofs << 1) + 1;
1084 if (ofs <= 0) /* int overflow */
1085 ofs = maxofs;
1086 }
1087 if (ofs > maxofs)
1088 ofs = maxofs;
1089 /* Translate back to positive offsets relative to &a[0]. */
1090 k = lastofs;
1091 lastofs = hint - ofs;
1092 ofs = hint - k;
1093 }
1094 a -= hint;
1095
1096 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1097 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1098 * right of lastofs but no farther right than ofs. Do a binary
1099 * search, with invariant a[lastofs-1] < key <= a[ofs].
1100 */
1101 ++lastofs;
1102 while (lastofs < ofs) {
1103 int m = lastofs + ((ofs - lastofs) >> 1);
1104
1105 IFLT(a[m], key)
1106 lastofs = m+1; /* a[m] < key */
1107 else
1108 ofs = m; /* key <= a[m] */
1109 }
1110 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1111 return ofs;
1112
1113fail:
1114 return -1;
1115}
1116
1117/*
1118Exactly like gallop_left(), except that if key already exists in a[0:n],
1119finds the position immediately to the right of the rightmost equal value.
1120
1121The return value is the int k in 0..n such that
1122
1123 a[k-1] <= key < a[k]
1124
1125or -1 if error.
1126
1127The code duplication is massive, but this is enough different given that
1128we're sticking to "<" comparisons that it's much harder to follow if
1129written as one routine with yet another "left or right?" flag.
1130*/
1131static int
1132gallop_right(PyObject *key, PyObject **a, int n, int hint, PyObject *compare)
1133{
1134 int ofs;
1135 int lastofs;
1136 int k;
1137
1138 assert(key && a && n > 0 && hint >= 0 && hint < n);
1139
1140 a += hint;
1141 lastofs = 0;
1142 ofs = 1;
1143 IFLT(key, *a) {
1144 /* key < a[hint] -- gallop left, until
1145 * a[hint - ofs] <= key < a[hint - lastofs]
1146 */
1147 const int maxofs = hint + 1; /* &a[0] is lowest */
1148 while (ofs < maxofs) {
1149 IFLT(key, *(a-ofs)) {
1150 lastofs = ofs;
1151 ofs = (ofs << 1) + 1;
1152 if (ofs <= 0) /* int overflow */
1153 ofs = maxofs;
1154 }
1155 else /* a[hint - ofs] <= key */
1156 break;
1157 }
1158 if (ofs > maxofs)
1159 ofs = maxofs;
1160 /* Translate back to positive offsets relative to &a[0]. */
1161 k = lastofs;
1162 lastofs = hint - ofs;
1163 ofs = hint - k;
1164 }
1165 else {
1166 /* a[hint] <= key -- gallop right, until
1167 * a[hint + lastofs] <= key < a[hint + ofs]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001168 */
Tim Petersa64dc242002-08-01 02:13:36 +00001169 const int maxofs = n - hint; /* &a[n-1] is highest */
1170 while (ofs < maxofs) {
1171 IFLT(key, a[ofs])
1172 break;
1173 /* a[hint + ofs] <= key */
1174 lastofs = ofs;
1175 ofs = (ofs << 1) + 1;
1176 if (ofs <= 0) /* int overflow */
1177 ofs = maxofs;
1178 }
1179 if (ofs > maxofs)
1180 ofs = maxofs;
1181 /* Translate back to offsets relative to &a[0]. */
1182 lastofs += hint;
1183 ofs += hint;
1184 }
1185 a -= hint;
1186
1187 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1188 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1189 * right of lastofs but no farther right than ofs. Do a binary
1190 * search, with invariant a[lastofs-1] <= key < a[ofs].
1191 */
1192 ++lastofs;
1193 while (lastofs < ofs) {
1194 int m = lastofs + ((ofs - lastofs) >> 1);
1195
1196 IFLT(key, a[m])
1197 ofs = m; /* key < a[m] */
1198 else
1199 lastofs = m+1; /* a[m] <= key */
1200 }
1201 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1202 return ofs;
1203
1204fail:
1205 return -1;
1206}
1207
1208/* The maximum number of entries in a MergeState's pending-runs stack.
1209 * This is enough to sort arrays of size up to about
1210 * 32 * phi ** MAX_MERGE_PENDING
1211 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1212 * with 2**64 elements.
1213 */
1214#define MAX_MERGE_PENDING 85
1215
Tim Peterse05f65a2002-08-10 05:21:15 +00001216/* When we get into galloping mode, we stay there until both runs win less
1217 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001218 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001219#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001220
1221/* Avoid malloc for small temp arrays. */
1222#define MERGESTATE_TEMP_SIZE 256
1223
1224/* One MergeState exists on the stack per invocation of mergesort. It's just
1225 * a convenient way to pass state around among the helper functions.
1226 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001227struct s_slice {
1228 PyObject **base;
1229 int len;
1230};
1231
Tim Petersa64dc242002-08-01 02:13:36 +00001232typedef struct s_MergeState {
1233 /* The user-supplied comparison function. or NULL if none given. */
1234 PyObject *compare;
1235
Tim Peterse05f65a2002-08-10 05:21:15 +00001236 /* This controls when we get *into* galloping mode. It's initialized
1237 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1238 * random data, and lower for highly structured data.
1239 */
1240 int min_gallop;
1241
Tim Petersa64dc242002-08-01 02:13:36 +00001242 /* 'a' is temp storage to help with merges. It contains room for
1243 * alloced entries.
1244 */
1245 PyObject **a; /* may point to temparray below */
1246 int alloced;
1247
1248 /* A stack of n pending runs yet to be merged. Run #i starts at
1249 * address base[i] and extends for len[i] elements. It's always
1250 * true (so long as the indices are in bounds) that
1251 *
Tim Peterse05f65a2002-08-10 05:21:15 +00001252 * pending[i].base + pending[i].len == pending[i+1].base
Tim Petersa64dc242002-08-01 02:13:36 +00001253 *
1254 * so we could cut the storage for this, but it's a minor amount,
1255 * and keeping all the info explicit simplifies the code.
1256 */
1257 int n;
Tim Peterse05f65a2002-08-10 05:21:15 +00001258 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001259
1260 /* 'a' points to this when possible, rather than muck with malloc. */
1261 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1262} MergeState;
1263
1264/* Conceptually a MergeState's constructor. */
1265static void
1266merge_init(MergeState *ms, PyObject *compare)
1267{
1268 assert(ms != NULL);
1269 ms->compare = compare;
1270 ms->a = ms->temparray;
1271 ms->alloced = MERGESTATE_TEMP_SIZE;
1272 ms->n = 0;
Tim Peterse05f65a2002-08-10 05:21:15 +00001273 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001274}
1275
1276/* Free all the temp memory owned by the MergeState. This must be called
1277 * when you're done with a MergeState, and may be called before then if
1278 * you want to free the temp memory early.
1279 */
1280static void
1281merge_freemem(MergeState *ms)
1282{
1283 assert(ms != NULL);
1284 if (ms->a != ms->temparray)
1285 PyMem_Free(ms->a);
1286 ms->a = ms->temparray;
1287 ms->alloced = MERGESTATE_TEMP_SIZE;
1288}
1289
1290/* Ensure enough temp memory for 'need' array slots is available.
1291 * Returns 0 on success and -1 if the memory can't be gotten.
1292 */
1293static int
1294merge_getmem(MergeState *ms, int need)
1295{
1296 assert(ms != NULL);
1297 if (need <= ms->alloced)
1298 return 0;
1299 /* Don't realloc! That can cost cycles to copy the old data, but
1300 * we don't care what's in the block.
1301 */
1302 merge_freemem(ms);
1303 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1304 if (ms->a) {
1305 ms->alloced = need;
1306 return 0;
1307 }
1308 PyErr_NoMemory();
1309 merge_freemem(ms); /* reset to sane state */
1310 return -1;
1311}
1312#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1313 merge_getmem(MS, NEED))
1314
1315/* Merge the na elements starting at pa with the nb elements starting at pb
1316 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1317 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1318 * merge, and should have na <= nb. See listsort.txt for more info.
1319 * Return 0 if successful, -1 if error.
1320 */
1321static int
1322merge_lo(MergeState *ms, PyObject **pa, int na, PyObject **pb, int nb)
1323{
1324 int k;
1325 PyObject *compare;
1326 PyObject **dest;
1327 int result = -1; /* guilty until proved innocent */
Tim Peterse05f65a2002-08-10 05:21:15 +00001328 int min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001329
1330 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1331 if (MERGE_GETMEM(ms, na) < 0)
1332 return -1;
1333 memcpy(ms->a, pa, na * sizeof(PyObject*));
1334 dest = pa;
1335 pa = ms->a;
1336
1337 *dest++ = *pb++;
1338 --nb;
1339 if (nb == 0)
1340 goto Succeed;
1341 if (na == 1)
1342 goto CopyB;
1343
1344 compare = ms->compare;
1345 for (;;) {
1346 int acount = 0; /* # of times A won in a row */
1347 int bcount = 0; /* # of times B won in a row */
1348
1349 /* Do the straightforward thing until (if ever) one run
1350 * appears to win consistently.
1351 */
1352 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001353 assert(na > 1 && nb > 0);
Tim Peters66860f62002-08-04 17:47:26 +00001354 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001355 if (k) {
1356 if (k < 0)
1357 goto Fail;
1358 *dest++ = *pb++;
1359 ++bcount;
1360 acount = 0;
1361 --nb;
1362 if (nb == 0)
1363 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001364 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001365 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001366 }
1367 else {
Tim Petersa64dc242002-08-01 02:13:36 +00001368 *dest++ = *pa++;
1369 ++acount;
1370 bcount = 0;
1371 --na;
1372 if (na == 1)
1373 goto CopyB;
Tim Peterse05f65a2002-08-10 05:21:15 +00001374 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001375 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001376 }
Tim Petersa64dc242002-08-01 02:13:36 +00001377 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001378
Tim Petersa64dc242002-08-01 02:13:36 +00001379 /* One run is winning so consistently that galloping may
1380 * be a huge win. So try that, and continue galloping until
1381 * (if ever) neither run appears to be winning consistently
1382 * anymore.
1383 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001384 ++min_gallop;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001385 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001386 assert(na > 1 && nb > 0);
1387 min_gallop -= min_gallop > 1;
1388 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001389 k = gallop_right(*pb, pa, na, 0, compare);
1390 acount = k;
1391 if (k) {
1392 if (k < 0)
1393 goto Fail;
1394 memcpy(dest, pa, k * sizeof(PyObject *));
1395 dest += k;
1396 pa += k;
1397 na -= k;
1398 if (na == 1)
1399 goto CopyB;
1400 /* na==0 is impossible now if the comparison
1401 * function is consistent, but we can't assume
1402 * that it is.
1403 */
1404 if (na == 0)
1405 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001406 }
Tim Petersa64dc242002-08-01 02:13:36 +00001407 *dest++ = *pb++;
1408 --nb;
1409 if (nb == 0)
1410 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001411
Tim Petersa64dc242002-08-01 02:13:36 +00001412 k = gallop_left(*pa, pb, nb, 0, compare);
1413 bcount = k;
1414 if (k) {
1415 if (k < 0)
1416 goto Fail;
1417 memmove(dest, pb, k * sizeof(PyObject *));
1418 dest += k;
1419 pb += k;
1420 nb -= k;
1421 if (nb == 0)
1422 goto Succeed;
1423 }
1424 *dest++ = *pa++;
1425 --na;
1426 if (na == 1)
1427 goto CopyB;
1428 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001429 ++min_gallop; /* penalize it for leaving galloping mode */
1430 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001431 }
1432Succeed:
1433 result = 0;
1434Fail:
1435 if (na)
1436 memcpy(dest, pa, na * sizeof(PyObject*));
1437 return result;
1438CopyB:
1439 assert(na == 1 && nb > 0);
1440 /* The last element of pa belongs at the end of the merge. */
1441 memmove(dest, pb, nb * sizeof(PyObject *));
1442 dest[nb] = *pa;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001443 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001444}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001445
Tim Petersa64dc242002-08-01 02:13:36 +00001446/* Merge the na elements starting at pa with the nb elements starting at pb
1447 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1448 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1449 * merge, and should have na >= nb. See listsort.txt for more info.
1450 * Return 0 if successful, -1 if error.
1451 */
1452static int
1453merge_hi(MergeState *ms, PyObject **pa, int na, PyObject **pb, int nb)
1454{
1455 int k;
1456 PyObject *compare;
1457 PyObject **dest;
1458 int result = -1; /* guilty until proved innocent */
1459 PyObject **basea;
1460 PyObject **baseb;
Tim Peterse05f65a2002-08-10 05:21:15 +00001461 int min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001462
1463 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1464 if (MERGE_GETMEM(ms, nb) < 0)
1465 return -1;
1466 dest = pb + nb - 1;
1467 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1468 basea = pa;
1469 baseb = ms->a;
1470 pb = ms->a + nb - 1;
1471 pa += na - 1;
1472
1473 *dest-- = *pa--;
1474 --na;
1475 if (na == 0)
1476 goto Succeed;
1477 if (nb == 1)
1478 goto CopyA;
1479
1480 compare = ms->compare;
1481 for (;;) {
1482 int acount = 0; /* # of times A won in a row */
1483 int bcount = 0; /* # of times B won in a row */
1484
1485 /* Do the straightforward thing until (if ever) one run
1486 * appears to win consistently.
1487 */
1488 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001489 assert(na > 0 && nb > 1);
Tim Peters66860f62002-08-04 17:47:26 +00001490 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001491 if (k) {
1492 if (k < 0)
1493 goto Fail;
1494 *dest-- = *pa--;
1495 ++acount;
1496 bcount = 0;
1497 --na;
1498 if (na == 0)
1499 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001500 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001501 break;
1502 }
1503 else {
1504 *dest-- = *pb--;
1505 ++bcount;
1506 acount = 0;
1507 --nb;
1508 if (nb == 1)
1509 goto CopyA;
Tim Peterse05f65a2002-08-10 05:21:15 +00001510 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001511 break;
1512 }
1513 }
1514
1515 /* One run is winning so consistently that galloping may
1516 * be a huge win. So try that, and continue galloping until
1517 * (if ever) neither run appears to be winning consistently
1518 * anymore.
1519 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001520 ++min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001521 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001522 assert(na > 0 && nb > 1);
1523 min_gallop -= min_gallop > 1;
1524 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001525 k = gallop_right(*pb, basea, na, na-1, compare);
1526 if (k < 0)
1527 goto Fail;
1528 k = na - k;
1529 acount = k;
1530 if (k) {
1531 dest -= k;
1532 pa -= k;
1533 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1534 na -= k;
1535 if (na == 0)
1536 goto Succeed;
1537 }
1538 *dest-- = *pb--;
1539 --nb;
1540 if (nb == 1)
1541 goto CopyA;
1542
1543 k = gallop_left(*pa, baseb, nb, nb-1, compare);
1544 if (k < 0)
1545 goto Fail;
1546 k = nb - k;
1547 bcount = k;
1548 if (k) {
1549 dest -= k;
1550 pb -= k;
1551 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1552 nb -= k;
1553 if (nb == 1)
1554 goto CopyA;
1555 /* nb==0 is impossible now if the comparison
1556 * function is consistent, but we can't assume
1557 * that it is.
1558 */
1559 if (nb == 0)
1560 goto Succeed;
1561 }
1562 *dest-- = *pa--;
1563 --na;
1564 if (na == 0)
1565 goto Succeed;
1566 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001567 ++min_gallop; /* penalize it for leaving galloping mode */
1568 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001569 }
1570Succeed:
1571 result = 0;
1572Fail:
1573 if (nb)
1574 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1575 return result;
1576CopyA:
1577 assert(nb == 1 && na > 0);
1578 /* The first element of pb belongs at the front of the merge. */
1579 dest -= na;
1580 pa -= na;
1581 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1582 *dest = *pb;
1583 return 0;
1584}
1585
1586/* Merge the two runs at stack indices i and i+1.
1587 * Returns 0 on success, -1 on error.
1588 */
1589static int
1590merge_at(MergeState *ms, int i)
1591{
1592 PyObject **pa, **pb;
1593 int na, nb;
1594 int k;
1595 PyObject *compare;
1596
1597 assert(ms != NULL);
1598 assert(ms->n >= 2);
1599 assert(i >= 0);
1600 assert(i == ms->n - 2 || i == ms->n - 3);
1601
Tim Peterse05f65a2002-08-10 05:21:15 +00001602 pa = ms->pending[i].base;
1603 na = ms->pending[i].len;
1604 pb = ms->pending[i+1].base;
1605 nb = ms->pending[i+1].len;
Tim Petersa64dc242002-08-01 02:13:36 +00001606 assert(na > 0 && nb > 0);
1607 assert(pa + na == pb);
1608
1609 /* Record the length of the combined runs; if i is the 3rd-last
1610 * run now, also slide over the last run (which isn't involved
1611 * in this merge). The current run i+1 goes away in any case.
1612 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001613 ms->pending[i].len = na + nb;
1614 if (i == ms->n - 3)
1615 ms->pending[i+1] = ms->pending[i+2];
Tim Petersa64dc242002-08-01 02:13:36 +00001616 --ms->n;
1617
1618 /* Where does b start in a? Elements in a before that can be
1619 * ignored (already in place).
1620 */
1621 compare = ms->compare;
1622 k = gallop_right(*pb, pa, na, 0, compare);
1623 if (k < 0)
1624 return -1;
1625 pa += k;
1626 na -= k;
1627 if (na == 0)
1628 return 0;
1629
1630 /* Where does a end in b? Elements in b after that can be
1631 * ignored (already in place).
1632 */
1633 nb = gallop_left(pa[na-1], pb, nb, nb-1, compare);
1634 if (nb <= 0)
1635 return nb;
1636
1637 /* Merge what remains of the runs, using a temp array with
1638 * min(na, nb) elements.
1639 */
1640 if (na <= nb)
1641 return merge_lo(ms, pa, na, pb, nb);
1642 else
1643 return merge_hi(ms, pa, na, pb, nb);
1644}
1645
1646/* Examine the stack of runs waiting to be merged, merging adjacent runs
1647 * until the stack invariants are re-established:
1648 *
1649 * 1. len[-3] > len[-2] + len[-1]
1650 * 2. len[-2] > len[-1]
1651 *
1652 * See listsort.txt for more info.
1653 *
1654 * Returns 0 on success, -1 on error.
1655 */
1656static int
1657merge_collapse(MergeState *ms)
1658{
Tim Peterse05f65a2002-08-10 05:21:15 +00001659 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001660
1661 assert(ms);
1662 while (ms->n > 1) {
1663 int n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001664 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1665 if (p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001666 --n;
1667 if (merge_at(ms, n) < 0)
1668 return -1;
1669 }
Tim Peterse05f65a2002-08-10 05:21:15 +00001670 else if (p[n].len <= p[n+1].len) {
Tim Petersa64dc242002-08-01 02:13:36 +00001671 if (merge_at(ms, n) < 0)
1672 return -1;
1673 }
1674 else
1675 break;
1676 }
1677 return 0;
1678}
1679
1680/* Regardless of invariants, merge all runs on the stack until only one
1681 * remains. This is used at the end of the mergesort.
1682 *
1683 * Returns 0 on success, -1 on error.
1684 */
1685static int
1686merge_force_collapse(MergeState *ms)
1687{
Tim Peterse05f65a2002-08-10 05:21:15 +00001688 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001689
1690 assert(ms);
1691 while (ms->n > 1) {
1692 int n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001693 if (n > 0 && p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001694 --n;
1695 if (merge_at(ms, n) < 0)
1696 return -1;
1697 }
1698 return 0;
1699}
1700
1701/* Compute a good value for the minimum run length; natural runs shorter
1702 * than this are boosted artificially via binary insertion.
1703 *
1704 * If n < 64, return n (it's too small to bother with fancy stuff).
1705 * Else if n is an exact power of 2, return 32.
1706 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1707 * strictly less than, an exact power of 2.
1708 *
1709 * See listsort.txt for more info.
1710 */
1711static int
1712merge_compute_minrun(int n)
1713{
1714 int r = 0; /* becomes 1 if any 1 bits are shifted off */
1715
1716 assert(n >= 0);
1717 while (n >= 64) {
1718 r |= n & 1;
1719 n >>= 1;
1720 }
1721 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001722}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001723
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001724/* Special wrapper to support stable sorting using the decorate-sort-undecorate
1725 pattern. Holds a key which is used for comparisions and the original record
1726 which is returned during the undecorate phase. By exposing only the key
1727 during comparisons, the underlying sort stability characteristics are left
1728 unchanged. Also, if a custom comparison function is used, it will only see
1729 the key instead of a full record. */
1730
1731typedef struct {
1732 PyObject_HEAD
1733 PyObject *key;
1734 PyObject *value;
1735} sortwrapperobject;
1736
1737static PyTypeObject sortwrapper_type;
1738
1739static PyObject *
1740sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
1741{
1742 if (!PyObject_TypeCheck(b, &sortwrapper_type)) {
1743 PyErr_SetString(PyExc_TypeError,
1744 "expected a sortwrapperobject");
1745 return NULL;
1746 }
1747 return PyObject_RichCompare(a->key, b->key, op);
1748}
1749
1750static void
1751sortwrapper_dealloc(sortwrapperobject *so)
1752{
1753 Py_XDECREF(so->key);
1754 Py_XDECREF(so->value);
1755 PyObject_Del(so);
1756}
1757
1758PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
1759
1760static PyTypeObject sortwrapper_type = {
1761 PyObject_HEAD_INIT(&PyType_Type)
1762 0, /* ob_size */
1763 "sortwrapper", /* tp_name */
1764 sizeof(sortwrapperobject), /* tp_basicsize */
1765 0, /* tp_itemsize */
1766 /* methods */
1767 (destructor)sortwrapper_dealloc, /* tp_dealloc */
1768 0, /* tp_print */
1769 0, /* tp_getattr */
1770 0, /* tp_setattr */
1771 0, /* tp_compare */
1772 0, /* tp_repr */
1773 0, /* tp_as_number */
1774 0, /* tp_as_sequence */
1775 0, /* tp_as_mapping */
1776 0, /* tp_hash */
1777 0, /* tp_call */
1778 0, /* tp_str */
1779 PyObject_GenericGetAttr, /* tp_getattro */
1780 0, /* tp_setattro */
1781 0, /* tp_as_buffer */
1782 Py_TPFLAGS_DEFAULT |
1783 Py_TPFLAGS_HAVE_RICHCOMPARE, /* tp_flags */
1784 sortwrapper_doc, /* tp_doc */
1785 0, /* tp_traverse */
1786 0, /* tp_clear */
1787 (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
1788};
1789
1790/* Returns a new reference to a sortwrapper.
1791 Consumes the references to the two underlying objects. */
1792
1793static PyObject *
1794build_sortwrapper(PyObject *key, PyObject *value)
1795{
1796 sortwrapperobject *so;
1797
1798 so = PyObject_New(sortwrapperobject, &sortwrapper_type);
1799 if (so == NULL)
1800 return NULL;
1801 so->key = key;
1802 so->value = value;
1803 return (PyObject *)so;
1804}
1805
1806/* Returns a new reference to the value underlying the wrapper. */
1807static PyObject *
1808sortwrapper_getvalue(PyObject *so)
1809{
1810 PyObject *value;
1811
1812 if (!PyObject_TypeCheck(so, &sortwrapper_type)) {
1813 PyErr_SetString(PyExc_TypeError,
1814 "expected a sortwrapperobject");
1815 return NULL;
1816 }
1817 value = ((sortwrapperobject *)so)->value;
1818 Py_INCREF(value);
1819 return value;
1820}
1821
1822/* Wrapper for user specified cmp functions in combination with a
1823 specified key function. Makes sure the cmp function is presented
1824 with the actual key instead of the sortwrapper */
1825
1826typedef struct {
1827 PyObject_HEAD
1828 PyObject *func;
1829} cmpwrapperobject;
1830
1831static void
1832cmpwrapper_dealloc(cmpwrapperobject *co)
1833{
1834 Py_XDECREF(co->func);
1835 PyObject_Del(co);
1836}
1837
1838static PyObject *
1839cmpwrapper_call(cmpwrapperobject *co, PyObject *args, PyObject *kwds)
1840{
1841 PyObject *x, *y, *xx, *yy;
1842
1843 if (!PyArg_UnpackTuple(args, "", 2, 2, &x, &y))
1844 return NULL;
1845 if (!PyObject_TypeCheck(x, &sortwrapper_type) ||
Raymond Hettingerae4a2992003-10-16 17:16:30 +00001846 !PyObject_TypeCheck(y, &sortwrapper_type)) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001847 PyErr_SetString(PyExc_TypeError,
1848 "expected a sortwrapperobject");
1849 return NULL;
1850 }
1851 xx = ((sortwrapperobject *)x)->key;
1852 yy = ((sortwrapperobject *)y)->key;
1853 return PyObject_CallFunctionObjArgs(co->func, xx, yy, NULL);
1854}
1855
1856PyDoc_STRVAR(cmpwrapper_doc, "cmp() wrapper for sort with custom keys.");
1857
1858static PyTypeObject cmpwrapper_type = {
1859 PyObject_HEAD_INIT(&PyType_Type)
1860 0, /* ob_size */
1861 "cmpwrapper", /* tp_name */
1862 sizeof(cmpwrapperobject), /* tp_basicsize */
1863 0, /* tp_itemsize */
1864 /* methods */
1865 (destructor)cmpwrapper_dealloc, /* tp_dealloc */
1866 0, /* tp_print */
1867 0, /* tp_getattr */
1868 0, /* tp_setattr */
1869 0, /* tp_compare */
1870 0, /* tp_repr */
1871 0, /* tp_as_number */
1872 0, /* tp_as_sequence */
1873 0, /* tp_as_mapping */
1874 0, /* tp_hash */
1875 (ternaryfunc)cmpwrapper_call, /* tp_call */
1876 0, /* tp_str */
1877 PyObject_GenericGetAttr, /* tp_getattro */
1878 0, /* tp_setattro */
1879 0, /* tp_as_buffer */
1880 Py_TPFLAGS_DEFAULT, /* tp_flags */
1881 cmpwrapper_doc, /* tp_doc */
1882};
1883
1884static PyObject *
1885build_cmpwrapper(PyObject *cmpfunc)
1886{
1887 cmpwrapperobject *co;
1888
1889 co = PyObject_New(cmpwrapperobject, &cmpwrapper_type);
1890 if (co == NULL)
1891 return NULL;
1892 Py_INCREF(cmpfunc);
1893 co->func = cmpfunc;
1894 return (PyObject *)co;
1895}
1896
Tim Petersa64dc242002-08-01 02:13:36 +00001897/* An adaptive, stable, natural mergesort. See listsort.txt.
1898 * Returns Py_None on success, NULL on error. Even in case of error, the
1899 * list will be some permutation of its input state (nothing is lost or
1900 * duplicated).
1901 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001902static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001903listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001904{
Tim Petersa64dc242002-08-01 02:13:36 +00001905 MergeState ms;
1906 PyObject **lo, **hi;
1907 int nremaining;
1908 int minrun;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001909 int saved_ob_size, saved_allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00001910 PyObject **saved_ob_item;
1911 PyObject **empty_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001912 PyObject *compare = NULL;
1913 PyObject *result = NULL; /* guilty until proved innocent */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001914 int reverse = 0;
1915 PyObject *keyfunc = NULL;
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001916 int i;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001917 PyObject *key, *value, *kvpair;
1918 static char *kwlist[] = {"cmp", "key", "reverse", 0};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001919
Tim Petersa64dc242002-08-01 02:13:36 +00001920 assert(self != NULL);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001921 assert (PyList_Check(self));
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001922 if (args != NULL) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001923 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:sort",
1924 kwlist, &compare, &keyfunc, &reverse))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001925 return NULL;
1926 }
Skip Montanaro4abd5f02003-01-02 20:51:08 +00001927 if (compare == Py_None)
1928 compare = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001929 if (keyfunc == Py_None)
1930 keyfunc = NULL;
1931 if (compare != NULL && keyfunc != NULL) {
1932 compare = build_cmpwrapper(compare);
1933 if (compare == NULL)
Hye-Shik Chang19cb1932003-12-10 07:31:08 +00001934 return NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001935 } else
1936 Py_XINCREF(compare);
1937
Tim Petersb9099c32002-11-12 22:08:10 +00001938 /* The list is temporarily made empty, so that mutations performed
1939 * by comparison functions can't affect the slice of memory we're
1940 * sorting (allowing mutations during sorting is a core-dump
1941 * factory, since ob_item may change).
1942 */
1943 saved_ob_size = self->ob_size;
1944 saved_ob_item = self->ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001945 saved_allocated = self->allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00001946 self->ob_size = 0;
Tim Peters7049d812004-01-18 20:31:02 +00001947 self->ob_item = empty_ob_item = PyMem_NEW(PyObject *, 0);
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001948 self->allocated = 0;
Tim Peters330f9e92002-07-19 07:05:44 +00001949
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001950 if (keyfunc != NULL) {
1951 for (i=0 ; i < saved_ob_size ; i++) {
1952 value = saved_ob_item[i];
1953 key = PyObject_CallFunctionObjArgs(keyfunc, value,
1954 NULL);
1955 if (key == NULL) {
1956 for (i=i-1 ; i>=0 ; i--) {
1957 kvpair = saved_ob_item[i];
1958 value = sortwrapper_getvalue(kvpair);
1959 saved_ob_item[i] = value;
1960 Py_DECREF(kvpair);
1961 }
1962 if (self->ob_item != empty_ob_item
1963 || self->ob_size) {
1964 /* If the list changed *as well* we
1965 have two errors. We let the first
1966 one "win", but we shouldn't let
1967 what's in the list currently
1968 leak. */
1969 (void)list_ass_slice(
1970 self, 0, self->ob_size,
1971 (PyObject *)NULL);
1972 }
1973
1974 goto dsu_fail;
1975 }
1976 kvpair = build_sortwrapper(key, value);
1977 if (kvpair == NULL)
1978 goto dsu_fail;
1979 saved_ob_item[i] = kvpair;
1980 }
1981 }
1982
1983 /* Reverse sort stability achieved by initially reversing the list,
1984 applying a stable forward sort, then reversing the final result. */
1985 if (reverse && saved_ob_size > 1)
1986 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
1987
1988 merge_init(&ms, compare);
1989
Tim Petersb9099c32002-11-12 22:08:10 +00001990 nremaining = saved_ob_size;
Tim Petersa64dc242002-08-01 02:13:36 +00001991 if (nremaining < 2)
1992 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00001993
Tim Petersa64dc242002-08-01 02:13:36 +00001994 /* March over the array once, left to right, finding natural runs,
1995 * and extending short natural runs to minrun elements.
1996 */
Tim Petersb9099c32002-11-12 22:08:10 +00001997 lo = saved_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001998 hi = lo + nremaining;
1999 minrun = merge_compute_minrun(nremaining);
2000 do {
2001 int descending;
2002 int n;
Tim Peters330f9e92002-07-19 07:05:44 +00002003
Tim Petersa64dc242002-08-01 02:13:36 +00002004 /* Identify next run. */
2005 n = count_run(lo, hi, compare, &descending);
2006 if (n < 0)
2007 goto fail;
2008 if (descending)
2009 reverse_slice(lo, lo + n);
2010 /* If short, extend to min(minrun, nremaining). */
2011 if (n < minrun) {
2012 const int force = nremaining <= minrun ?
2013 nremaining : minrun;
2014 if (binarysort(lo, lo + force, lo + n, compare) < 0)
2015 goto fail;
2016 n = force;
2017 }
2018 /* Push run onto pending-runs stack, and maybe merge. */
2019 assert(ms.n < MAX_MERGE_PENDING);
Tim Peterse05f65a2002-08-10 05:21:15 +00002020 ms.pending[ms.n].base = lo;
2021 ms.pending[ms.n].len = n;
Tim Petersa64dc242002-08-01 02:13:36 +00002022 ++ms.n;
2023 if (merge_collapse(&ms) < 0)
2024 goto fail;
2025 /* Advance to find next run. */
2026 lo += n;
2027 nremaining -= n;
2028 } while (nremaining);
2029 assert(lo == hi);
Tim Peters330f9e92002-07-19 07:05:44 +00002030
Tim Petersa64dc242002-08-01 02:13:36 +00002031 if (merge_force_collapse(&ms) < 0)
2032 goto fail;
2033 assert(ms.n == 1);
Tim Petersb9099c32002-11-12 22:08:10 +00002034 assert(ms.pending[0].base == saved_ob_item);
2035 assert(ms.pending[0].len == saved_ob_size);
Tim Petersa64dc242002-08-01 02:13:36 +00002036
2037succeed:
2038 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002039fail:
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002040 if (keyfunc != NULL) {
2041 for (i=0 ; i < saved_ob_size ; i++) {
2042 kvpair = saved_ob_item[i];
2043 value = sortwrapper_getvalue(kvpair);
2044 saved_ob_item[i] = value;
2045 Py_DECREF(kvpair);
2046 }
2047 }
2048
Tim Petersb9099c32002-11-12 22:08:10 +00002049 if (self->ob_item != empty_ob_item || self->ob_size) {
2050 /* The user mucked with the list during the sort. */
2051 (void)list_ass_slice(self, 0, self->ob_size, (PyObject *)NULL);
2052 if (result != NULL) {
2053 PyErr_SetString(PyExc_ValueError,
2054 "list modified during sort");
2055 result = NULL;
2056 }
2057 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002058
2059 if (reverse && saved_ob_size > 1)
2060 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2061
2062 merge_freemem(&ms);
2063
2064dsu_fail:
Tim Petersb9099c32002-11-12 22:08:10 +00002065 if (self->ob_item == empty_ob_item)
2066 PyMem_FREE(empty_ob_item);
2067 self->ob_size = saved_ob_size;
2068 self->ob_item = saved_ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002069 self->allocated = saved_allocated;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002070 Py_XDECREF(compare);
Tim Petersa64dc242002-08-01 02:13:36 +00002071 Py_XINCREF(result);
2072 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002073}
Tim Peters330f9e92002-07-19 07:05:44 +00002074#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002075#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002076
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002077int
Fred Drakea2f55112000-07-09 15:16:51 +00002078PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002079{
2080 if (v == NULL || !PyList_Check(v)) {
2081 PyErr_BadInternalCall();
2082 return -1;
2083 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002084 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002085 if (v == NULL)
2086 return -1;
2087 Py_DECREF(v);
2088 return 0;
2089}
2090
Guido van Rossumb86c5492001-02-12 22:06:02 +00002091static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002092listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002093{
Tim Peters326b4482002-07-19 04:04:16 +00002094 if (self->ob_size > 1)
2095 reverse_slice(self->ob_item, self->ob_item + self->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002096 Py_INCREF(Py_None);
2097 return Py_None;
Guido van Rossumed98d481991-03-06 13:07:53 +00002098}
2099
Guido van Rossum84c76f51990-10-30 13:32:20 +00002100int
Fred Drakea2f55112000-07-09 15:16:51 +00002101PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002102{
Tim Peters6063e262002-08-08 01:06:39 +00002103 PyListObject *self = (PyListObject *)v;
2104
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002105 if (v == NULL || !PyList_Check(v)) {
2106 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002107 return -1;
2108 }
Tim Peters6063e262002-08-08 01:06:39 +00002109 if (self->ob_size > 1)
2110 reverse_slice(self->ob_item, self->ob_item + self->ob_size);
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002111 return 0;
2112}
2113
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002114PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002115PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002116{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002117 PyObject *w;
2118 PyObject **p;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002119 int n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002120 if (v == NULL || !PyList_Check(v)) {
2121 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002122 return NULL;
2123 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002124 n = ((PyListObject *)v)->ob_size;
2125 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002126 if (w == NULL)
2127 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002128 p = ((PyTupleObject *)w)->ob_item;
Thomas Wouters334fb892000-07-25 12:56:38 +00002129 memcpy((void *)p,
2130 (void *)((PyListObject *)v)->ob_item,
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002131 n*sizeof(PyObject *));
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002132 while (--n >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002133 Py_INCREF(*p);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002134 p++;
2135 }
2136 return w;
2137}
2138
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002139static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002140listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002141{
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002142 int i, start=0, stop=self->ob_size;
2143 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002144
Walter Dörwalde8049bef2003-06-17 19:27:39 +00002145 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2146 _PyEval_SliceIndex, &start,
2147 _PyEval_SliceIndex, &stop))
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002148 return NULL;
Guido van Rossum2743d872003-06-17 14:25:14 +00002149 if (start < 0) {
2150 start += self->ob_size;
2151 if (start < 0)
2152 start = 0;
2153 }
2154 if (stop < 0) {
2155 stop += self->ob_size;
2156 if (stop < 0)
2157 stop = 0;
2158 }
2159 else if (stop > self->ob_size)
2160 stop = self->ob_size;
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002161 for (i = start; i < stop; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002162 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2163 if (cmp > 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002164 return PyInt_FromLong((long)i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002165 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002166 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002167 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002168 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002169 return NULL;
2170}
2171
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002172static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002173listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002174{
2175 int count = 0;
2176 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002177
Guido van Rossume6f7d181991-10-20 20:20:40 +00002178 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002179 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2180 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002181 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002182 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002183 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00002184 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002185 return PyInt_FromLong((long)count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002186}
2187
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002188static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002189listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002190{
2191 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002192
Guido van Rossumed98d481991-03-06 13:07:53 +00002193 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002194 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2195 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002196 if (list_ass_slice(self, i, i+1,
2197 (PyObject *)NULL) != 0)
Guido van Rossumed98d481991-03-06 13:07:53 +00002198 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002199 Py_INCREF(Py_None);
2200 return Py_None;
Guido van Rossumed98d481991-03-06 13:07:53 +00002201 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002202 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002203 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002204 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002205 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002206 return NULL;
2207}
2208
Jeremy Hylton8caad492000-06-23 14:18:11 +00002209static int
2210list_traverse(PyListObject *o, visitproc visit, void *arg)
2211{
2212 int i, err;
2213 PyObject *x;
2214
2215 for (i = o->ob_size; --i >= 0; ) {
2216 x = o->ob_item[i];
2217 if (x != NULL) {
2218 err = visit(x, arg);
2219 if (err)
2220 return err;
2221 }
2222 }
2223 return 0;
2224}
2225
2226static int
2227list_clear(PyListObject *lp)
2228{
2229 (void) PyList_SetSlice((PyObject *)lp, 0, lp->ob_size, 0);
2230 return 0;
2231}
2232
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002233static PyObject *
2234list_richcompare(PyObject *v, PyObject *w, int op)
2235{
2236 PyListObject *vl, *wl;
2237 int i;
2238
2239 if (!PyList_Check(v) || !PyList_Check(w)) {
2240 Py_INCREF(Py_NotImplemented);
2241 return Py_NotImplemented;
2242 }
2243
2244 vl = (PyListObject *)v;
2245 wl = (PyListObject *)w;
2246
2247 if (vl->ob_size != wl->ob_size && (op == Py_EQ || op == Py_NE)) {
2248 /* Shortcut: if the lengths differ, the lists differ */
2249 PyObject *res;
2250 if (op == Py_EQ)
2251 res = Py_False;
2252 else
2253 res = Py_True;
2254 Py_INCREF(res);
2255 return res;
2256 }
2257
2258 /* Search for the first index where items are different */
2259 for (i = 0; i < vl->ob_size && i < wl->ob_size; i++) {
2260 int k = PyObject_RichCompareBool(vl->ob_item[i],
2261 wl->ob_item[i], Py_EQ);
2262 if (k < 0)
2263 return NULL;
2264 if (!k)
2265 break;
2266 }
2267
2268 if (i >= vl->ob_size || i >= wl->ob_size) {
2269 /* No more items to compare -- compare sizes */
2270 int vs = vl->ob_size;
2271 int ws = wl->ob_size;
2272 int cmp;
2273 PyObject *res;
2274 switch (op) {
2275 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00002276 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002277 case Py_EQ: cmp = vs == ws; break;
2278 case Py_NE: cmp = vs != ws; break;
2279 case Py_GT: cmp = vs > ws; break;
2280 case Py_GE: cmp = vs >= ws; break;
2281 default: return NULL; /* cannot happen */
2282 }
2283 if (cmp)
2284 res = Py_True;
2285 else
2286 res = Py_False;
2287 Py_INCREF(res);
2288 return res;
2289 }
2290
2291 /* We have an item that differs -- shortcuts for EQ/NE */
2292 if (op == Py_EQ) {
2293 Py_INCREF(Py_False);
2294 return Py_False;
2295 }
2296 if (op == Py_NE) {
2297 Py_INCREF(Py_True);
2298 return Py_True;
2299 }
2300
2301 /* Compare the final item again using the proper operator */
2302 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
2303}
2304
Tim Peters6d6c1a32001-08-02 04:15:00 +00002305static int
2306list_init(PyListObject *self, PyObject *args, PyObject *kw)
2307{
2308 PyObject *arg = NULL;
2309 static char *kwlist[] = {"sequence", 0};
2310
2311 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2312 return -1;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002313 /* Empty previous contents */
2314 if (self->ob_size != 0) {
2315 if (list_ass_slice(self, 0, self->ob_size, (PyObject *)NULL) != 0)
2316 return -1;
2317 }
2318 if (arg != NULL) {
2319 PyObject *rv = listextend(self, arg);
2320 if (rv == NULL)
2321 return -1;
2322 Py_DECREF(rv);
2323 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002324 return 0;
2325}
2326
Guido van Rossumdbb53d92001-12-03 16:32:18 +00002327static long
2328list_nohash(PyObject *self)
2329{
2330 PyErr_SetString(PyExc_TypeError, "list objects are unhashable");
2331 return -1;
2332}
2333
Raymond Hettinger1021c442003-11-07 15:38:09 +00002334static PyObject *list_iter(PyObject *seq);
2335static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2336
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002337PyDoc_STRVAR(getitem_doc,
2338"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002339PyDoc_STRVAR(reversed_doc,
2340"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002341PyDoc_STRVAR(append_doc,
2342"L.append(object) -- append object to end");
2343PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002344"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002345PyDoc_STRVAR(insert_doc,
2346"L.insert(index, object) -- insert object before index");
2347PyDoc_STRVAR(pop_doc,
2348"L.pop([index]) -> item -- remove and return item at index (default last)");
2349PyDoc_STRVAR(remove_doc,
2350"L.remove(value) -- remove first occurrence of value");
2351PyDoc_STRVAR(index_doc,
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002352"L.index(value, [start, [stop]]) -> integer -- return first index of value");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002353PyDoc_STRVAR(count_doc,
2354"L.count(value) -> integer -- return number of occurrences of value");
2355PyDoc_STRVAR(reverse_doc,
2356"L.reverse() -- reverse *IN PLACE*");
2357PyDoc_STRVAR(sort_doc,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002358"L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n\
2359cmp(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002360
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002361static PyObject *list_subscript(PyListObject*, PyObject*);
2362
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002363static PyMethodDef list_methods[] = {
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002364 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
Raymond Hettinger1021c442003-11-07 15:38:09 +00002365 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002366 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002367 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002368 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002369 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002370 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002371 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002372 {"count", (PyCFunction)listcount, METH_O, count_doc},
2373 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002374 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
Tim Petersa64dc242002-08-01 02:13:36 +00002375 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002376};
2377
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002378static PySequenceMethods list_as_sequence = {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002379 (inquiry)list_length, /* sq_length */
2380 (binaryfunc)list_concat, /* sq_concat */
2381 (intargfunc)list_repeat, /* sq_repeat */
2382 (intargfunc)list_item, /* sq_item */
2383 (intintargfunc)list_slice, /* sq_slice */
2384 (intobjargproc)list_ass_item, /* sq_ass_item */
2385 (intintobjargproc)list_ass_slice, /* sq_ass_slice */
2386 (objobjproc)list_contains, /* sq_contains */
2387 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2388 (intargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002389};
2390
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002391PyDoc_STRVAR(list_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002392"list() -> new list\n"
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002393"list(sequence) -> new list initialized from sequence's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002394
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002395static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002396list_subscript(PyListObject* self, PyObject* item)
2397{
2398 if (PyInt_Check(item)) {
2399 long i = PyInt_AS_LONG(item);
2400 if (i < 0)
2401 i += PyList_GET_SIZE(self);
2402 return list_item(self, i);
2403 }
2404 else if (PyLong_Check(item)) {
2405 long i = PyLong_AsLong(item);
2406 if (i == -1 && PyErr_Occurred())
2407 return NULL;
2408 if (i < 0)
2409 i += PyList_GET_SIZE(self);
2410 return list_item(self, i);
2411 }
2412 else if (PySlice_Check(item)) {
2413 int start, stop, step, slicelength, cur, i;
2414 PyObject* result;
2415 PyObject* it;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002416 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002417
2418 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
2419 &start, &stop, &step, &slicelength) < 0) {
2420 return NULL;
2421 }
2422
2423 if (slicelength <= 0) {
2424 return PyList_New(0);
2425 }
2426 else {
2427 result = PyList_New(slicelength);
2428 if (!result) return NULL;
2429
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002430 src = self->ob_item;
2431 dest = ((PyListObject *)result)->ob_item;
Tim Peters3b01a122002-07-19 02:35:45 +00002432 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002433 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002434 it = src[cur];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002435 Py_INCREF(it);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002436 dest[i] = it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002437 }
Tim Peters3b01a122002-07-19 02:35:45 +00002438
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002439 return result;
2440 }
2441 }
2442 else {
2443 PyErr_SetString(PyExc_TypeError,
2444 "list indices must be integers");
2445 return NULL;
2446 }
2447}
2448
Tim Peters3b01a122002-07-19 02:35:45 +00002449static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002450list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2451{
2452 if (PyInt_Check(item)) {
2453 long i = PyInt_AS_LONG(item);
2454 if (i < 0)
2455 i += PyList_GET_SIZE(self);
2456 return list_ass_item(self, i, value);
2457 }
2458 else if (PyLong_Check(item)) {
2459 long i = PyLong_AsLong(item);
2460 if (i == -1 && PyErr_Occurred())
2461 return -1;
2462 if (i < 0)
2463 i += PyList_GET_SIZE(self);
2464 return list_ass_item(self, i, value);
2465 }
2466 else if (PySlice_Check(item)) {
2467 int start, stop, step, slicelength;
2468
2469 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
2470 &start, &stop, &step, &slicelength) < 0) {
2471 return -1;
2472 }
2473
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002474 /* treat L[slice(a,b)] = v _exactly_ like L[a:b] = v */
2475 if (step == 1 && ((PySliceObject*)item)->step == Py_None)
2476 return list_ass_slice(self, start, stop, value);
2477
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002478 if (value == NULL) {
2479 /* delete slice */
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002480 PyObject **garbage;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002481 int cur, i;
Tim Peters3b01a122002-07-19 02:35:45 +00002482
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002483 if (slicelength <= 0)
2484 return 0;
2485
2486 if (step < 0) {
2487 stop = start + 1;
2488 start = stop + step*(slicelength - 1) - 1;
2489 step = -step;
2490 }
2491
2492 garbage = (PyObject**)
2493 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Tim Peters3b01a122002-07-19 02:35:45 +00002494
2495 /* drawing pictures might help
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002496 understand these for loops */
Guido van Rossum75a20b12002-06-11 12:22:28 +00002497 for (cur = start, i = 0;
2498 cur < stop;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002499 cur += step, i++) {
2500 int lim = step;
2501
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002502 garbage[i] = PyList_GET_ITEM(self, cur);
2503
Michael W. Hudson56796f62002-07-29 14:35:04 +00002504 if (cur + step >= self->ob_size) {
2505 lim = self->ob_size - cur - 1;
2506 }
2507
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002508 memmove(self->ob_item + cur - i,
2509 self->ob_item + cur + 1,
2510 lim * sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002511 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002512
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002513 for (cur = start + slicelength*step + 1;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002514 cur < self->ob_size; cur++) {
2515 PyList_SET_ITEM(self, cur - slicelength,
2516 PyList_GET_ITEM(self, cur));
2517 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002518
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002519 self->ob_size -= slicelength;
Raymond Hettingerd4ff7412004-03-15 09:01:31 +00002520 list_resize(self, self->ob_size);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002521
2522 for (i = 0; i < slicelength; i++) {
2523 Py_DECREF(garbage[i]);
2524 }
2525 PyMem_FREE(garbage);
2526
2527 return 0;
2528 }
2529 else {
2530 /* assign slice */
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002531 PyObject **garbage, *ins, *seq, **seqitems, **selfitems;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002532 int cur, i;
2533
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002534 /* protect against a[::-1] = a */
Tim Peters3b01a122002-07-19 02:35:45 +00002535 if (self == (PyListObject*)value) {
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002536 seq = list_slice((PyListObject*)value, 0,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002537 PyList_GET_SIZE(value));
Tim Peters3b01a122002-07-19 02:35:45 +00002538 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002539 else {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002540 seq = PySequence_Fast(value,
2541 "must assign iterable to extended slice");
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002542 if (!seq)
2543 return -1;
2544 }
2545
2546 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2547 PyErr_Format(PyExc_ValueError,
2548 "attempt to assign sequence of size %d to extended slice of size %d",
2549 PySequence_Fast_GET_SIZE(seq),
2550 slicelength);
2551 Py_DECREF(seq);
2552 return -1;
2553 }
2554
2555 if (!slicelength) {
2556 Py_DECREF(seq);
2557 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002558 }
2559
2560 garbage = (PyObject**)
2561 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Tim Peters3b01a122002-07-19 02:35:45 +00002562
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002563 selfitems = self->ob_item;
Raymond Hettinger42bec932004-03-12 16:38:17 +00002564 seqitems = PySequence_Fast_ITEMS(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002565 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002566 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002567 garbage[i] = selfitems[cur];
2568 ins = seqitems[i];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002569 Py_INCREF(ins);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002570 selfitems[cur] = ins;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002571 }
2572
2573 for (i = 0; i < slicelength; i++) {
2574 Py_DECREF(garbage[i]);
2575 }
Tim Peters3b01a122002-07-19 02:35:45 +00002576
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002577 PyMem_FREE(garbage);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002578 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002579
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002580 return 0;
2581 }
Tim Peters3b01a122002-07-19 02:35:45 +00002582 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002583 else {
Tim Peters3b01a122002-07-19 02:35:45 +00002584 PyErr_SetString(PyExc_TypeError,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002585 "list indices must be integers");
2586 return -1;
2587 }
2588}
2589
2590static PyMappingMethods list_as_mapping = {
2591 (inquiry)list_length,
2592 (binaryfunc)list_subscript,
2593 (objobjargproc)list_ass_subscript
2594};
2595
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002596PyTypeObject PyList_Type = {
2597 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002598 0,
2599 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002600 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002601 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002602 (destructor)list_dealloc, /* tp_dealloc */
2603 (printfunc)list_print, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002604 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002605 0, /* tp_setattr */
2606 0, /* tp_compare */
2607 (reprfunc)list_repr, /* tp_repr */
2608 0, /* tp_as_number */
2609 &list_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002610 &list_as_mapping, /* tp_as_mapping */
Guido van Rossumdbb53d92001-12-03 16:32:18 +00002611 list_nohash, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002612 0, /* tp_call */
2613 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002614 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002615 0, /* tp_setattro */
2616 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002617 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Tim Peters6d6c1a32001-08-02 04:15:00 +00002618 Py_TPFLAGS_BASETYPE, /* tp_flags */
2619 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002620 (traverseproc)list_traverse, /* tp_traverse */
2621 (inquiry)list_clear, /* tp_clear */
2622 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002623 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002624 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002625 0, /* tp_iternext */
2626 list_methods, /* tp_methods */
2627 0, /* tp_members */
2628 0, /* tp_getset */
2629 0, /* tp_base */
2630 0, /* tp_dict */
2631 0, /* tp_descr_get */
2632 0, /* tp_descr_set */
2633 0, /* tp_dictoffset */
2634 (initproc)list_init, /* tp_init */
2635 PyType_GenericAlloc, /* tp_alloc */
2636 PyType_GenericNew, /* tp_new */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002637 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002638};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002639
2640
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002641/*********************** List Iterator **************************/
2642
2643typedef struct {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002644 PyObject_HEAD
2645 long it_index;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002646 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002647} listiterobject;
2648
2649PyTypeObject PyListIter_Type;
2650
Guido van Rossum5086e492002-07-16 15:56:52 +00002651static PyObject *
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002652list_iter(PyObject *seq)
2653{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002654 listiterobject *it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002655
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002656 if (!PyList_Check(seq)) {
2657 PyErr_BadInternalCall();
2658 return NULL;
2659 }
2660 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2661 if (it == NULL)
2662 return NULL;
2663 it->it_index = 0;
2664 Py_INCREF(seq);
2665 it->it_seq = (PyListObject *)seq;
2666 _PyObject_GC_TRACK(it);
2667 return (PyObject *)it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002668}
2669
2670static void
2671listiter_dealloc(listiterobject *it)
2672{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002673 _PyObject_GC_UNTRACK(it);
Guido van Rossum86103ae2002-07-16 20:07:32 +00002674 Py_XDECREF(it->it_seq);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002675 PyObject_GC_Del(it);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002676}
2677
2678static int
2679listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2680{
Guido van Rossum86103ae2002-07-16 20:07:32 +00002681 if (it->it_seq == NULL)
2682 return 0;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002683 return visit((PyObject *)it->it_seq, arg);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002684}
2685
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002686static PyObject *
Tim Peters93b2cc42002-06-01 05:22:55 +00002687listiter_next(listiterobject *it)
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002688{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002689 PyListObject *seq;
2690 PyObject *item;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002691
Tim Peters93b2cc42002-06-01 05:22:55 +00002692 assert(it != NULL);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002693 seq = it->it_seq;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002694 if (seq == NULL)
2695 return NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002696 assert(PyList_Check(seq));
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002697
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002698 if (it->it_index < PyList_GET_SIZE(seq)) {
Tim Peters93b2cc42002-06-01 05:22:55 +00002699 item = PyList_GET_ITEM(seq, it->it_index);
2700 ++it->it_index;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002701 Py_INCREF(item);
2702 return item;
2703 }
Guido van Rossum86103ae2002-07-16 20:07:32 +00002704
2705 Py_DECREF(seq);
2706 it->it_seq = NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002707 return NULL;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002708}
2709
Raymond Hettinger435bf582004-03-18 22:43:10 +00002710static int
2711listiter_len(listiterobject *it)
2712{
2713 if (it->it_seq)
2714 return PyList_GET_SIZE(it->it_seq) - it->it_index;
2715 return 0;
2716}
2717
2718static PySequenceMethods listiter_as_sequence = {
2719 (inquiry)listiter_len, /* sq_length */
2720 0, /* sq_concat */
2721};
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 */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002737 &listiter_as_sequence, /* tp_as_sequence */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002738 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};