blob: 500f823a9c56c7fc48f5b6a50dfb8b7973812e41 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* List object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
4
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00005#ifdef STDC_HEADERS
6#include <stddef.h>
7#else
8#include <sys/types.h> /* For size_t */
9#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000010
Guido van Rossuma46d51d1995-01-26 22:59:43 +000011static int
Raymond Hettinger4bb95402004-02-13 11:36:39 +000012list_resize(PyListObject *self, int newsize)
Guido van Rossuma46d51d1995-01-26 22:59:43 +000013{
Raymond Hettinger4bb95402004-02-13 11:36:39 +000014 PyObject **items;
15 size_t _new_size;
Tim Peters65b8b842001-05-26 05:28:40 +000016
Raymond Hettinger4bb95402004-02-13 11:36:39 +000017 /* Bypass realloc() when a previous overallocation is large enough
18 to accommodate the newsize. If the newsize is 16 smaller than the
19 current size, then proceed with the realloc() to shrink the list.
20 */
21
22 if (self->allocated >= newsize &&
23 self->ob_size < newsize + 16 &&
24 self->ob_item != NULL) {
25 self->ob_size = newsize;
26 return 0;
27 }
28
29 /* This over-allocates proportional to the list size, making room
Tim Peters65b8b842001-05-26 05:28:40 +000030 * for additional growth. The over-allocation is mild, but is
31 * enough to give linear-time amortized behavior over a long
32 * sequence of appends() in the presence of a poorly-performing
Raymond Hettingerab517d22004-02-14 18:34:46 +000033 * system realloc().
34 * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
Tim Peters65b8b842001-05-26 05:28:40 +000035 */
Raymond Hettingerab517d22004-02-14 18:34:46 +000036 _new_size = (newsize >> 3) + (self->ob_size < 8 ? 3 : 6) + newsize;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000037 items = self->ob_item;
38 if (_new_size <= ((~(size_t)0) / sizeof(PyObject *)))
39 PyMem_RESIZE(items, PyObject *, _new_size);
40 else
41 items = NULL;
42 if (items == NULL) {
43 PyErr_NoMemory();
44 return -1;
45 }
46 self->ob_item = items;
47 self->ob_size = newsize;
48 self->allocated = _new_size;
49 return 0;
50}
Guido van Rossuma46d51d1995-01-26 22:59:43 +000051
Guido van Rossumc0b618a1997-05-02 03:12:38 +000052PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +000053PyList_New(int size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000054{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000055 PyListObject *op;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +000056 size_t nbytes;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000057 if (size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000058 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000059 return NULL;
60 }
Tim Peters7049d812004-01-18 20:31:02 +000061 nbytes = size * sizeof(PyObject *);
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000062 /* Check for overflow */
Tim Peters7049d812004-01-18 20:31:02 +000063 if (nbytes / sizeof(PyObject *) != (size_t)size) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000064 return PyErr_NoMemory();
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000065 }
Neil Schemenauere83c00e2001-08-29 23:54:21 +000066 op = PyObject_GC_New(PyListObject, &PyList_Type);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000067 if (op == NULL) {
Neil Schemenauere83c00e2001-08-29 23:54:21 +000068 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000069 }
70 if (size <= 0) {
71 op->ob_item = NULL;
72 }
73 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +000074 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000075 if (op->ob_item == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000076 return PyErr_NoMemory();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000077 }
Tim Peters7049d812004-01-18 20:31:02 +000078 memset(op->ob_item, 0, sizeof(*op->ob_item) * size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000079 }
Neil Schemenauere83c00e2001-08-29 23:54:21 +000080 op->ob_size = size;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000081 op->allocated = size;
Neil Schemenauere83c00e2001-08-29 23:54:21 +000082 _PyObject_GC_TRACK(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +000083 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000084}
85
86int
Fred Drakea2f55112000-07-09 15:16:51 +000087PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000088{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000089 if (!PyList_Check(op)) {
90 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000091 return -1;
92 }
93 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000094 return ((PyListObject *)op) -> ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000095}
96
Guido van Rossumc0b618a1997-05-02 03:12:38 +000097static PyObject *indexerr;
Guido van Rossum929f1b81996-08-09 20:51:27 +000098
Guido van Rossumc0b618a1997-05-02 03:12:38 +000099PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000100PyList_GetItem(PyObject *op, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000101{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000102 if (!PyList_Check(op)) {
103 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000104 return NULL;
105 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000106 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000107 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000108 indexerr = PyString_FromString(
109 "list index out of range");
110 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000111 return NULL;
112 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000113 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000114}
115
116int
Fred Drakea2f55112000-07-09 15:16:51 +0000117PyList_SetItem(register PyObject *op, register int i,
118 register PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000119{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000120 register PyObject *olditem;
121 register PyObject **p;
122 if (!PyList_Check(op)) {
123 Py_XDECREF(newitem);
124 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000125 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000126 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000127 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
128 Py_XDECREF(newitem);
129 PyErr_SetString(PyExc_IndexError,
130 "list assignment index out of range");
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000131 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000132 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000133 p = ((PyListObject *)op) -> ob_item + i;
Guido van Rossum5fe60581995-03-09 12:12:50 +0000134 olditem = *p;
135 *p = newitem;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000136 Py_XDECREF(olditem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000137 return 0;
138}
139
140static int
Fred Drakea2f55112000-07-09 15:16:51 +0000141ins1(PyListObject *self, int where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000142{
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000143 int i, n = self->ob_size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000144 PyObject **items;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000145 if (v == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000146 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000147 return -1;
148 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000149 if (n == INT_MAX) {
Trent Micka5846642000-08-13 22:47:45 +0000150 PyErr_SetString(PyExc_OverflowError,
151 "cannot add more objects to list");
152 return -1;
153 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000154
155 if (list_resize(self, n+1) == -1)
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000156 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000157
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000158 if (where < 0) {
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000159 where += n;
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000160 if (where < 0)
161 where = 0;
162 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000163 if (where > n)
164 where = n;
165 items = self->ob_item;
166 for (i = n; --i >= where; )
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000167 items[i+1] = items[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000168 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000169 items[where] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000170 return 0;
171}
172
173int
Fred Drakea2f55112000-07-09 15:16:51 +0000174PyList_Insert(PyObject *op, int where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000175{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000176 if (!PyList_Check(op)) {
177 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000178 return -1;
179 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000180 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000181}
182
183int
Fred Drakea2f55112000-07-09 15:16:51 +0000184PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000185{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000186 if (!PyList_Check(op)) {
187 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000188 return -1;
189 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000190 return ins1((PyListObject *)op,
191 (int) ((PyListObject *)op)->ob_size, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000192}
193
194/* Methods */
195
196static void
Fred Drakea2f55112000-07-09 15:16:51 +0000197list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000198{
199 int i;
Guido van Rossumff413af2002-03-28 20:34:59 +0000200 PyObject_GC_UnTrack(op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000201 Py_TRASHCAN_SAFE_BEGIN(op)
Jack Jansen7874d1f1995-01-19 12:09:27 +0000202 if (op->ob_item != NULL) {
Guido van Rossumfa717011999-06-09 15:19:34 +0000203 /* Do it backwards, for Christian Tismer.
204 There's a simple test case where somehow this reduces
205 thrashing when a *very* large list is created and
206 immediately deleted. */
207 i = op->ob_size;
208 while (--i >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000209 Py_XDECREF(op->ob_item[i]);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000210 }
Guido van Rossumb18618d2000-05-03 23:44:39 +0000211 PyMem_FREE(op->ob_item);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000212 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000213 op->ob_type->tp_free((PyObject *)op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000214 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000215}
216
Guido van Rossum90933611991-06-07 16:10:43 +0000217static int
Fred Drakea2f55112000-07-09 15:16:51 +0000218list_print(PyListObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000219{
220 int i;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000221
222 i = Py_ReprEnter((PyObject*)op);
223 if (i != 0) {
224 if (i < 0)
225 return i;
226 fprintf(fp, "[...]");
227 return 0;
228 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000229 fprintf(fp, "[");
Guido van Rossum90933611991-06-07 16:10:43 +0000230 for (i = 0; i < op->ob_size; i++) {
231 if (i > 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000232 fprintf(fp, ", ");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000233 if (PyObject_Print(op->ob_item[i], fp, 0) != 0) {
234 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000235 return -1;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000236 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000237 }
238 fprintf(fp, "]");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000239 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000240 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000241}
242
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000243static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000244list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000245{
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000246 int i;
Tim Petersa7259592001-06-16 05:11:17 +0000247 PyObject *s, *temp;
248 PyObject *pieces = NULL, *result = NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000249
250 i = Py_ReprEnter((PyObject*)v);
251 if (i != 0) {
Tim Petersa7259592001-06-16 05:11:17 +0000252 return i > 0 ? PyString_FromString("[...]") : NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000253 }
Tim Petersa7259592001-06-16 05:11:17 +0000254
255 if (v->ob_size == 0) {
256 result = PyString_FromString("[]");
257 goto Done;
258 }
259
260 pieces = PyList_New(0);
261 if (pieces == NULL)
262 goto Done;
263
264 /* Do repr() on each element. Note that this may mutate the list,
265 so must refetch the list size on each iteration. */
266 for (i = 0; i < v->ob_size; ++i) {
267 int status;
268 s = PyObject_Repr(v->ob_item[i]);
269 if (s == NULL)
270 goto Done;
271 status = PyList_Append(pieces, s);
272 Py_DECREF(s); /* append created a new ref */
273 if (status < 0)
274 goto Done;
275 }
276
277 /* Add "[]" decorations to the first and last items. */
278 assert(PyList_GET_SIZE(pieces) > 0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000279 s = PyString_FromString("[");
Tim Petersa7259592001-06-16 05:11:17 +0000280 if (s == NULL)
281 goto Done;
282 temp = PyList_GET_ITEM(pieces, 0);
283 PyString_ConcatAndDel(&s, temp);
284 PyList_SET_ITEM(pieces, 0, s);
285 if (s == NULL)
286 goto Done;
287
288 s = PyString_FromString("]");
289 if (s == NULL)
290 goto Done;
291 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
292 PyString_ConcatAndDel(&temp, s);
293 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
294 if (temp == NULL)
295 goto Done;
296
297 /* Paste them all together with ", " between. */
298 s = PyString_FromString(", ");
299 if (s == NULL)
300 goto Done;
301 result = _PyString_Join(s, pieces);
Tim Peters3b01a122002-07-19 02:35:45 +0000302 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +0000303
304Done:
305 Py_XDECREF(pieces);
Guido van Rossumfb376de1998-04-10 22:47:27 +0000306 Py_ReprLeave((PyObject *)v);
Tim Petersa7259592001-06-16 05:11:17 +0000307 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000308}
309
310static int
Fred Drakea2f55112000-07-09 15:16:51 +0000311list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000312{
313 return a->ob_size;
314}
315
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000316static int
Fred Drakea2f55112000-07-09 15:16:51 +0000317list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000318{
Raymond Hettingeraae59992002-09-05 14:23:49 +0000319 int i, cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000320
Raymond Hettingeraae59992002-09-05 14:23:49 +0000321 for (i = 0, cmp = 0 ; cmp == 0 && i < a->ob_size; ++i)
322 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000323 Py_EQ);
Neal Norwitzbb9c5f52002-09-05 21:32:55 +0000324 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000325}
326
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000327static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000328list_item(PyListObject *a, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000329{
330 if (i < 0 || i >= a->ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000331 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000332 indexerr = PyString_FromString(
333 "list index out of range");
334 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000335 return NULL;
336 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000337 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000338 return a->ob_item[i];
339}
340
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000341static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000342list_slice(PyListObject *a, int ilow, int ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000343{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000344 PyListObject *np;
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000345 PyObject **src, **dest;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000346 int i, len;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000347 if (ilow < 0)
348 ilow = 0;
349 else if (ilow > a->ob_size)
350 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000351 if (ihigh < ilow)
352 ihigh = ilow;
353 else if (ihigh > a->ob_size)
354 ihigh = a->ob_size;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000355 len = ihigh - ilow;
356 np = (PyListObject *) PyList_New(len);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000357 if (np == NULL)
358 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000359
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000360 src = a->ob_item + ilow;
361 dest = np->ob_item;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000362 for (i = 0; i < len; i++) {
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000363 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000364 Py_INCREF(v);
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000365 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000366 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000367 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000368}
369
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000370PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000371PyList_GetSlice(PyObject *a, int ilow, int ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000372{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000373 if (!PyList_Check(a)) {
374 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000375 return NULL;
376 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000377 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000378}
379
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000380static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000381list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000382{
383 int size;
384 int i;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000385 PyObject **src, **dest;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000386 PyListObject *np;
387 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000388 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000389 "can only concatenate list (not \"%.200s\") to list",
390 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000391 return NULL;
392 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000393#define b ((PyListObject *)bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000394 size = a->ob_size + b->ob_size;
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000395 if (size < 0)
396 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000397 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000398 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000399 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000400 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000401 src = a->ob_item;
402 dest = np->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000403 for (i = 0; i < a->ob_size; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000404 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000405 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000406 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000407 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000408 src = b->ob_item;
409 dest = np->ob_item + a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000410 for (i = 0; i < b->ob_size; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000411 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000412 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000413 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000414 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000415 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000416#undef b
417}
418
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000419static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000420list_repeat(PyListObject *a, int n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000421{
422 int i, j;
423 int size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000424 PyListObject *np;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000425 PyObject **p, **items;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000426 PyObject *elem;
Guido van Rossumed98d481991-03-06 13:07:53 +0000427 if (n < 0)
428 n = 0;
429 size = a->ob_size * n;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000430 if (size == 0)
431 return PyList_New(0);
Guido van Rossumbfa5a142002-10-11 23:39:35 +0000432 if (n && size/n != a->ob_size)
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000433 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000434 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000435 if (np == NULL)
436 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000437
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000438 items = np->ob_item;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000439 if (a->ob_size == 1) {
440 elem = a->ob_item[0];
441 for (i = 0; i < n; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000442 items[i] = elem;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000443 Py_INCREF(elem);
444 }
445 return (PyObject *) np;
446 }
Guido van Rossumed98d481991-03-06 13:07:53 +0000447 p = np->ob_item;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000448 items = a->ob_item;
Guido van Rossumed98d481991-03-06 13:07:53 +0000449 for (i = 0; i < n; i++) {
450 for (j = 0; j < a->ob_size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000451 *p = items[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000452 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000453 p++;
454 }
455 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000456 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000457}
458
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000459static int
Fred Drakea2f55112000-07-09 15:16:51 +0000460list_ass_slice(PyListObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000461{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000462 /* Because [X]DECREF can recursively invoke list operations on
463 this list, we must postpone all [X]DECREF activity until
464 after the list is back in its canonical shape. Therefore
465 we must allocate an additional array, 'recycle', into which
466 we temporarily copy the items that are deleted from the
467 list. :-( */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000468 PyObject **recycle, **p;
469 PyObject **item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000470 PyObject **vitem = NULL;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000471 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000472 int n; /* Size of replacement list */
473 int d; /* Change in size */
474 int k; /* Loop index */
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000475 int s;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000476#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000477 if (v == NULL)
478 n = 0;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000479 else {
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000480 if (a == b) {
481 /* Special case "a[i:j] = a" -- copy b first */
482 int ret;
Michael W. Hudsonda0a0672003-08-15 12:06:41 +0000483 v = list_slice(b, 0, b->ob_size);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000484 if (v == NULL)
485 return -1;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000486 ret = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000487 Py_DECREF(v);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000488 return ret;
489 }
Raymond Hettingerf889e102004-03-09 08:04:33 +0000490 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000491 if(v_as_SF == NULL)
492 return -1;
493 n = PySequence_Fast_GET_SIZE(v_as_SF);
Raymond Hettingerf889e102004-03-09 08:04:33 +0000494 if (PyList_Check(v_as_SF))
495 vitem = ((PyListObject *)v_as_SF)->ob_item;
496 else {
497 assert (PyTuple_Check(v_as_SF));
498 vitem = ((PyTupleObject *)v_as_SF)->ob_item;
499 }
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000500 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000501 if (ilow < 0)
502 ilow = 0;
503 else if (ilow > a->ob_size)
504 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000505 if (ihigh < ilow)
506 ihigh = ilow;
507 else if (ihigh > a->ob_size)
508 ihigh = a->ob_size;
509 item = a->ob_item;
510 d = n - (ihigh-ilow);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000511 if (ihigh > ilow) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000512 p = recycle = PyMem_NEW(PyObject *, (ihigh-ilow));
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000513 if (recycle == NULL) {
514 PyErr_NoMemory();
515 return -1;
516 }
517 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000518 else
519 p = recycle = NULL;
520 if (d <= 0) { /* Delete -d items; recycle ihigh-ilow items */
Raymond Hettingerf889e102004-03-09 08:04:33 +0000521 memmove(p, &item[ilow], (ihigh - ilow)*sizeof(PyObject *));
522 p += ihigh - ilow;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000523 if (d < 0) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000524 memmove(&item[ihigh+d], &item[ihigh],
525 (a->ob_size - ihigh)*sizeof(PyObject *));
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000526 list_resize(a, a->ob_size + d);
527 item = a->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000528 }
529 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000530 else { /* Insert d items; recycle ihigh-ilow items */
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000531 s = a->ob_size;
532 if (list_resize(a, s+d) == -1) {
Guido van Rossumb18618d2000-05-03 23:44:39 +0000533 if (recycle != NULL)
534 PyMem_DEL(recycle);
Raymond Hettinger2731ae42004-02-14 03:07:21 +0000535 return -1;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000536 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000537 item = a->ob_item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000538 memmove(&item[ihigh+d], &item[ihigh],
539 (s - ihigh)*sizeof(PyObject *));
540 memmove(p, &item[ilow], (ihigh - ilow)*sizeof(PyObject *));
541 p += ihigh - ilow;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000542 }
543 for (k = 0; k < n; k++, ilow++) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000544 PyObject *w = vitem[k];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000545 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000546 item[ilow] = w;
547 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000548 if (recycle) {
549 while (--p >= recycle)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000550 Py_XDECREF(*p);
551 PyMem_DEL(recycle);
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000552 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000553 if (a->ob_size == 0 && a->ob_item != NULL) {
554 PyMem_FREE(a->ob_item);
555 a->ob_item = NULL;
556 }
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000557 Py_XDECREF(v_as_SF);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000558 return 0;
559#undef b
560}
561
Guido van Rossum234f9421993-06-17 12:35:49 +0000562int
Fred Drakea2f55112000-07-09 15:16:51 +0000563PyList_SetSlice(PyObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000564{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000565 if (!PyList_Check(a)) {
566 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000567 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000568 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000569 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000570}
571
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000572static PyObject *
573list_inplace_repeat(PyListObject *self, int n)
574{
575 PyObject **items;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000576 int size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000577
578
579 size = PyList_GET_SIZE(self);
580 if (size == 0) {
581 Py_INCREF(self);
582 return (PyObject *)self;
583 }
584
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000585 if (n < 1) {
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000586 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000587 self->ob_item = NULL;
588 self->ob_size = 0;
589 for (i = 0; i < size; i++)
590 Py_XDECREF(items[i]);
591 PyMem_DEL(items);
592 Py_INCREF(self);
593 return (PyObject *)self;
594 }
595
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000596 if (list_resize(self, size*n) == -1)
597 return NULL;
598
599 p = size;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000600 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000601 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
602 for (j = 0; j < size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000603 PyObject *o = items[j];
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000604 Py_INCREF(o);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000605 items[p++] = o;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000606 }
607 }
608 Py_INCREF(self);
609 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000610}
611
Guido van Rossum4a450d01991-04-03 19:05:18 +0000612static int
Fred Drakea2f55112000-07-09 15:16:51 +0000613list_ass_item(PyListObject *a, int i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000614{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000615 PyObject *old_value;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000616 if (i < 0 || i >= a->ob_size) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000617 PyErr_SetString(PyExc_IndexError,
618 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000619 return -1;
620 }
621 if (v == NULL)
622 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000623 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000624 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000625 a->ob_item[i] = v;
Tim Peters3b01a122002-07-19 02:35:45 +0000626 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000627 return 0;
628}
629
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000630static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000631ins(PyListObject *self, int where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000632{
633 if (ins1(self, where, v) != 0)
634 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000635 Py_INCREF(Py_None);
636 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000637}
638
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000639static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000640listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000641{
642 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000643 PyObject *v;
Guido van Rossumc00a9382000-02-24 21:48:29 +0000644 if (!PyArg_ParseTuple(args, "iO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000645 return NULL;
Guido van Rossumbf80e541993-02-08 15:49:17 +0000646 return ins(self, i, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000647}
648
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000649static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000650listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000651{
Guido van Rossumbf80e541993-02-08 15:49:17 +0000652 return ins(self, (int) self->ob_size, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000653}
654
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000655static int
656listextend_internal(PyListObject *self, PyObject *b)
Barry Warsawdedf6d61998-10-09 16:37:25 +0000657{
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000658 register int selflen = PyList_GET_SIZE(self);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000659 int blen;
660 register int i;
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000661 PyObject **src, **dest;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000662
Jeremy Hyltondb60bb52001-01-03 22:32:16 +0000663 if (PyObject_Size(b) == 0) {
Barry Warsawdedf6d61998-10-09 16:37:25 +0000664 /* short circuit when b is empty */
Jeremy Hyltondb60bb52001-01-03 22:32:16 +0000665 Py_DECREF(b);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000666 return 0;
Jeremy Hyltondb60bb52001-01-03 22:32:16 +0000667 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000668
Barry Warsawdedf6d61998-10-09 16:37:25 +0000669 if (self == (PyListObject*)b) {
670 /* as in list_ass_slice() we must special case the
671 * situation: a.extend(a)
672 *
673 * XXX: I think this way ought to be faster than using
674 * list_slice() the way list_ass_slice() does.
675 */
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000676 Py_DECREF(b);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000677 b = PyList_New(selflen);
678 if (!b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000679 return -1;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000680 for (i = 0; i < selflen; i++) {
681 PyObject *o = PyList_GET_ITEM(self, i);
682 Py_INCREF(o);
683 PyList_SET_ITEM(b, i, o);
684 }
685 }
Barry Warsawdedf6d61998-10-09 16:37:25 +0000686
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000687 blen = PyObject_Size(b);
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000688 if (list_resize(self, selflen + blen) == -1) {
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000689 Py_DECREF(b);
690 return -1;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000691 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000692
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000693 /* populate the end of self with b's items */
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000694 if (PyList_Check(b))
695 src = ((PyListObject *)b)->ob_item;
696 else {
Raymond Hettinger99842b62004-03-08 05:56:15 +0000697 assert (PyTuple_Check(b));
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000698 src = ((PyTupleObject *)b)->ob_item;
699 }
700 dest = self->ob_item + selflen;
701 for (i = 0; i < blen; i++) {
702 PyObject *o = src[i];
703 Py_INCREF(o);
704 dest[i] = o;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000705 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000706 Py_DECREF(b);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000707 return 0;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000708}
709
Barry Warsawdedf6d61998-10-09 16:37:25 +0000710static PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000711list_inplace_concat(PyListObject *self, PyObject *other)
712{
Tim Peters1af03e92001-05-26 19:37:54 +0000713 other = PySequence_Fast(other, "argument to += must be iterable");
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000714 if (!other)
715 return NULL;
716
717 if (listextend_internal(self, other) < 0)
718 return NULL;
719
720 Py_INCREF(self);
721 return (PyObject *)self;
722}
723
724static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000725listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000726{
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000727 PyObject *it; /* iter(v) */
728 int m; /* size of self */
729 int n; /* guess for size of b */
730 int mn; /* m + n */
731 int i;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000732
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000733 /* Special cases:
734 1) lists and tuples which can use PySequence_Fast ops
735 2) extending self to self requires making a copy first
736 */
737 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
738 b = PySequence_Fast(b, "argument must be iterable");
739 if (!b)
740 return NULL;
741 if (listextend_internal(self, b) < 0)
742 return NULL;
743 Py_RETURN_NONE;
744 }
745
746 it = PyObject_GetIter(b);
747 if (it == NULL)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000748 return NULL;
749
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000750 /* Guess a result list size. */
751 n = PyObject_Size(b);
752 if (n < 0) {
753 PyErr_Clear();
754 n = 8; /* arbitrary */
755 }
756 m = self->ob_size;
757 mn = m + n;
758 if (list_resize(self, mn) == -1)
759 goto error;
760 memset(&(self->ob_item[m]), 0, sizeof(*self->ob_item) * n);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000761
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000762 /* Run iterator to exhaustion. */
763 for (i = m; ; i++) {
764 PyObject *item = PyIter_Next(it);
765 if (item == NULL) {
766 if (PyErr_Occurred())
767 goto error;
768 break;
769 }
770 if (i < mn)
771 PyList_SET_ITEM(self, i, item); /* steals ref */
772 else {
773 int status = ins1(self, self->ob_size, item);
774 Py_DECREF(item); /* append creates a new ref */
775 if (status < 0)
776 goto error;
777 }
778 }
779
780 /* Cut back result list if initial guess was too large. */
781 if (i < mn && self != NULL) {
782 if (list_ass_slice(self, i, mn, (PyObject *)NULL) != 0)
783 goto error;
784 }
785 Py_DECREF(it);
786 Py_RETURN_NONE;
787
788 error:
789 Py_DECREF(it);
790 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000791}
792
793static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000794listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000795{
796 int i = -1;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000797 PyObject *v, *arg = NULL;
798
799 if (!PyArg_UnpackTuple(args, "pop", 0, 1, &arg))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000800 return NULL;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000801 if (arg != NULL) {
802 if (PyInt_Check(arg))
803 i = (int)(PyInt_AS_LONG((PyIntObject*) arg));
Raymond Hettingerfa6c6f82004-02-19 06:12:06 +0000804 else if (!PyArg_ParseTuple(args, "|i:pop", &i))
805 return NULL;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000806 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000807 if (self->ob_size == 0) {
808 /* Special-case most common failure cause */
809 PyErr_SetString(PyExc_IndexError, "pop from empty list");
810 return NULL;
811 }
812 if (i < 0)
813 i += self->ob_size;
814 if (i < 0 || i >= self->ob_size) {
815 PyErr_SetString(PyExc_IndexError, "pop index out of range");
816 return NULL;
817 }
818 v = self->ob_item[i];
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000819 if (i == self->ob_size - 1) {
820 if (list_resize(self, self->ob_size - 1) == -1)
821 return NULL;
822 return v;
823 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000824 Py_INCREF(v);
825 if (list_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) {
826 Py_DECREF(v);
827 return NULL;
828 }
829 return v;
830}
831
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000832/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
833static void
834reverse_slice(PyObject **lo, PyObject **hi)
835{
836 assert(lo && hi);
837
838 --hi;
839 while (lo < hi) {
840 PyObject *t = *lo;
841 *lo = *hi;
842 *hi = t;
843 ++lo;
844 --hi;
845 }
846}
847
Tim Petersa64dc242002-08-01 02:13:36 +0000848/* Lots of code for an adaptive, stable, natural mergesort. There are many
849 * pieces to this algorithm; read listsort.txt for overviews and details.
850 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000851
Guido van Rossum3f236de1996-12-10 23:55:39 +0000852/* Comparison function. Takes care of calling a user-supplied
Tim Peters66860f62002-08-04 17:47:26 +0000853 * comparison function (any callable Python object), which must not be
854 * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool
855 * with Py_LT if you know it's NULL).
Tim Petersa64dc242002-08-01 02:13:36 +0000856 * Returns -1 on error, 1 if x < y, 0 if x >= y.
857 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000858static int
Tim Petersa8c974c2002-07-19 03:30:57 +0000859islt(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000860{
Tim Petersf2a04732002-07-11 21:46:16 +0000861 PyObject *res;
862 PyObject *args;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000863 int i;
864
Tim Peters66860f62002-08-04 17:47:26 +0000865 assert(compare != NULL);
Tim Petersa8c974c2002-07-19 03:30:57 +0000866 /* Call the user's comparison function and translate the 3-way
867 * result into true or false (or error).
868 */
Tim Petersf2a04732002-07-11 21:46:16 +0000869 args = PyTuple_New(2);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000870 if (args == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000871 return -1;
Tim Petersf2a04732002-07-11 21:46:16 +0000872 Py_INCREF(x);
873 Py_INCREF(y);
874 PyTuple_SET_ITEM(args, 0, x);
875 PyTuple_SET_ITEM(args, 1, y);
Tim Peters58cf3612002-07-15 05:16:13 +0000876 res = PyObject_Call(compare, args, NULL);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000877 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000878 if (res == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000879 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000880 if (!PyInt_Check(res)) {
881 Py_DECREF(res);
882 PyErr_SetString(PyExc_TypeError,
Guido van Rossum9bcd1d71999-04-19 17:44:39 +0000883 "comparison function must return int");
Tim Petersa8c974c2002-07-19 03:30:57 +0000884 return -1;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000885 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000886 i = PyInt_AsLong(res);
887 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +0000888 return i < 0;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000889}
890
Tim Peters66860f62002-08-04 17:47:26 +0000891/* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
892 * islt. This avoids a layer of function call in the usual case, and
893 * sorting does many comparisons.
894 * Returns -1 on error, 1 if x < y, 0 if x >= y.
895 */
896#define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
897 PyObject_RichCompareBool(X, Y, Py_LT) : \
898 islt(X, Y, COMPARE))
899
900/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +0000901 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
902 started. It makes more sense in context <wink>. X and Y are PyObject*s.
903*/
Tim Peters66860f62002-08-04 17:47:26 +0000904#define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
Tim Petersa8c974c2002-07-19 03:30:57 +0000905 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000906
907/* binarysort is the best method for sorting small arrays: it does
908 few compares, but can do data movement quadratic in the number of
909 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000910 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +0000911 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000912 On entry, must have lo <= start <= hi, and that [lo, start) is already
913 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +0000914 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000915 Even in case of error, the output slice will be some permutation of
916 the input (nothing is lost or duplicated).
917*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000918static int
Fred Drakea2f55112000-07-09 15:16:51 +0000919binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
920 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000921{
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000922 register int k;
923 register PyObject **l, **p, **r;
924 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000925
Tim Petersa8c974c2002-07-19 03:30:57 +0000926 assert(lo <= start && start <= hi);
927 /* assert [lo, start) is sorted */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000928 if (lo == start)
929 ++start;
930 for (; start < hi; ++start) {
931 /* set l to where *start belongs */
932 l = lo;
933 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000934 pivot = *r;
Tim Peters0fe977c2002-07-19 06:12:32 +0000935 /* Invariants:
936 * pivot >= all in [lo, l).
937 * pivot < all in [r, start).
938 * The second is vacuously true at the start.
939 */
940 assert(l < r);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000941 do {
942 p = l + ((r - l) >> 1);
Tim Petersa8c974c2002-07-19 03:30:57 +0000943 IFLT(pivot, *p)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000944 r = p;
945 else
Tim Peters0fe977c2002-07-19 06:12:32 +0000946 l = p+1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000947 } while (l < r);
Tim Peters0fe977c2002-07-19 06:12:32 +0000948 assert(l == r);
949 /* The invariants still hold, so pivot >= all in [lo, l) and
950 pivot < all in [l, start), so pivot belongs at l. Note
951 that if there are elements equal to pivot, l points to the
952 first slot after them -- that's why this sort is stable.
953 Slide over to make room.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000954 Caution: using memmove is much slower under MSVC 5;
955 we're not usually moving many slots. */
956 for (p = start; p > l; --p)
957 *p = *(p-1);
958 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000959 }
Guido van Rossum3f236de1996-12-10 23:55:39 +0000960 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000961
962 fail:
963 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000964}
965
Tim Petersa64dc242002-08-01 02:13:36 +0000966/*
967Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
968is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000969
Tim Petersa64dc242002-08-01 02:13:36 +0000970 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000971
Tim Petersa64dc242002-08-01 02:13:36 +0000972or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000973
Tim Petersa64dc242002-08-01 02:13:36 +0000974 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +0000975
Tim Petersa64dc242002-08-01 02:13:36 +0000976Boolean *descending is set to 0 in the former case, or to 1 in the latter.
977For its intended use in a stable mergesort, the strictness of the defn of
978"descending" is needed so that the caller can safely reverse a descending
979sequence without violating stability (strict > ensures there are no equal
980elements to get out of order).
981
982Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000983*/
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000984static int
Tim Petersa64dc242002-08-01 02:13:36 +0000985count_run(PyObject **lo, PyObject **hi, PyObject *compare, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000986{
Tim Petersa64dc242002-08-01 02:13:36 +0000987 int k;
988 int n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000989
Tim Petersa64dc242002-08-01 02:13:36 +0000990 assert(lo < hi);
991 *descending = 0;
992 ++lo;
993 if (lo == hi)
994 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000995
Tim Petersa64dc242002-08-01 02:13:36 +0000996 n = 2;
997 IFLT(*lo, *(lo-1)) {
998 *descending = 1;
999 for (lo = lo+1; lo < hi; ++lo, ++n) {
1000 IFLT(*lo, *(lo-1))
1001 ;
1002 else
1003 break;
1004 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001005 }
Tim Petersa64dc242002-08-01 02:13:36 +00001006 else {
1007 for (lo = lo+1; lo < hi; ++lo, ++n) {
1008 IFLT(*lo, *(lo-1))
1009 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001010 }
1011 }
1012
Tim Petersa64dc242002-08-01 02:13:36 +00001013 return n;
1014fail:
1015 return -1;
1016}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001017
Tim Petersa64dc242002-08-01 02:13:36 +00001018/*
1019Locate the proper position of key in a sorted vector; if the vector contains
1020an element equal to key, return the position immediately to the left of
1021the leftmost equal element. [gallop_right() does the same except returns
1022the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001023
Tim Petersa64dc242002-08-01 02:13:36 +00001024"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001025
Tim Petersa64dc242002-08-01 02:13:36 +00001026"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1027hint is to the final result, the faster this runs.
1028
1029The return value is the int k in 0..n such that
1030
1031 a[k-1] < key <= a[k]
1032
1033pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1034key belongs at index k; or, IOW, the first k elements of a should precede
1035key, and the last n-k should follow key.
1036
1037Returns -1 on error. See listsort.txt for info on the method.
1038*/
1039static int
1040gallop_left(PyObject *key, PyObject **a, int n, int hint, PyObject *compare)
1041{
1042 int ofs;
1043 int lastofs;
1044 int k;
1045
1046 assert(key && a && n > 0 && hint >= 0 && hint < n);
1047
1048 a += hint;
1049 lastofs = 0;
1050 ofs = 1;
1051 IFLT(*a, key) {
1052 /* a[hint] < key -- gallop right, until
1053 * a[hint + lastofs] < key <= a[hint + ofs]
1054 */
1055 const int maxofs = n - hint; /* &a[n-1] is highest */
1056 while (ofs < maxofs) {
1057 IFLT(a[ofs], key) {
1058 lastofs = ofs;
1059 ofs = (ofs << 1) + 1;
1060 if (ofs <= 0) /* int overflow */
1061 ofs = maxofs;
1062 }
1063 else /* key <= a[hint + ofs] */
1064 break;
1065 }
1066 if (ofs > maxofs)
1067 ofs = maxofs;
1068 /* Translate back to offsets relative to &a[0]. */
1069 lastofs += hint;
1070 ofs += hint;
1071 }
1072 else {
1073 /* key <= a[hint] -- gallop left, until
1074 * a[hint - ofs] < key <= a[hint - lastofs]
1075 */
1076 const int maxofs = hint + 1; /* &a[0] is lowest */
1077 while (ofs < maxofs) {
1078 IFLT(*(a-ofs), key)
1079 break;
1080 /* key <= a[hint - ofs] */
1081 lastofs = ofs;
1082 ofs = (ofs << 1) + 1;
1083 if (ofs <= 0) /* int overflow */
1084 ofs = maxofs;
1085 }
1086 if (ofs > maxofs)
1087 ofs = maxofs;
1088 /* Translate back to positive offsets relative to &a[0]. */
1089 k = lastofs;
1090 lastofs = hint - ofs;
1091 ofs = hint - k;
1092 }
1093 a -= hint;
1094
1095 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1096 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1097 * right of lastofs but no farther right than ofs. Do a binary
1098 * search, with invariant a[lastofs-1] < key <= a[ofs].
1099 */
1100 ++lastofs;
1101 while (lastofs < ofs) {
1102 int m = lastofs + ((ofs - lastofs) >> 1);
1103
1104 IFLT(a[m], key)
1105 lastofs = m+1; /* a[m] < key */
1106 else
1107 ofs = m; /* key <= a[m] */
1108 }
1109 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1110 return ofs;
1111
1112fail:
1113 return -1;
1114}
1115
1116/*
1117Exactly like gallop_left(), except that if key already exists in a[0:n],
1118finds the position immediately to the right of the rightmost equal value.
1119
1120The return value is the int k in 0..n such that
1121
1122 a[k-1] <= key < a[k]
1123
1124or -1 if error.
1125
1126The code duplication is massive, but this is enough different given that
1127we're sticking to "<" comparisons that it's much harder to follow if
1128written as one routine with yet another "left or right?" flag.
1129*/
1130static int
1131gallop_right(PyObject *key, PyObject **a, int n, int hint, PyObject *compare)
1132{
1133 int ofs;
1134 int lastofs;
1135 int k;
1136
1137 assert(key && a && n > 0 && hint >= 0 && hint < n);
1138
1139 a += hint;
1140 lastofs = 0;
1141 ofs = 1;
1142 IFLT(key, *a) {
1143 /* key < a[hint] -- gallop left, until
1144 * a[hint - ofs] <= key < a[hint - lastofs]
1145 */
1146 const int maxofs = hint + 1; /* &a[0] is lowest */
1147 while (ofs < maxofs) {
1148 IFLT(key, *(a-ofs)) {
1149 lastofs = ofs;
1150 ofs = (ofs << 1) + 1;
1151 if (ofs <= 0) /* int overflow */
1152 ofs = maxofs;
1153 }
1154 else /* a[hint - ofs] <= key */
1155 break;
1156 }
1157 if (ofs > maxofs)
1158 ofs = maxofs;
1159 /* Translate back to positive offsets relative to &a[0]. */
1160 k = lastofs;
1161 lastofs = hint - ofs;
1162 ofs = hint - k;
1163 }
1164 else {
1165 /* a[hint] <= key -- gallop right, until
1166 * a[hint + lastofs] <= key < a[hint + ofs]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001167 */
Tim Petersa64dc242002-08-01 02:13:36 +00001168 const int maxofs = n - hint; /* &a[n-1] is highest */
1169 while (ofs < maxofs) {
1170 IFLT(key, a[ofs])
1171 break;
1172 /* a[hint + ofs] <= key */
1173 lastofs = ofs;
1174 ofs = (ofs << 1) + 1;
1175 if (ofs <= 0) /* int overflow */
1176 ofs = maxofs;
1177 }
1178 if (ofs > maxofs)
1179 ofs = maxofs;
1180 /* Translate back to offsets relative to &a[0]. */
1181 lastofs += hint;
1182 ofs += hint;
1183 }
1184 a -= hint;
1185
1186 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1187 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1188 * right of lastofs but no farther right than ofs. Do a binary
1189 * search, with invariant a[lastofs-1] <= key < a[ofs].
1190 */
1191 ++lastofs;
1192 while (lastofs < ofs) {
1193 int m = lastofs + ((ofs - lastofs) >> 1);
1194
1195 IFLT(key, a[m])
1196 ofs = m; /* key < a[m] */
1197 else
1198 lastofs = m+1; /* a[m] <= key */
1199 }
1200 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1201 return ofs;
1202
1203fail:
1204 return -1;
1205}
1206
1207/* The maximum number of entries in a MergeState's pending-runs stack.
1208 * This is enough to sort arrays of size up to about
1209 * 32 * phi ** MAX_MERGE_PENDING
1210 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1211 * with 2**64 elements.
1212 */
1213#define MAX_MERGE_PENDING 85
1214
Tim Peterse05f65a2002-08-10 05:21:15 +00001215/* When we get into galloping mode, we stay there until both runs win less
1216 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001217 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001218#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001219
1220/* Avoid malloc for small temp arrays. */
1221#define MERGESTATE_TEMP_SIZE 256
1222
1223/* One MergeState exists on the stack per invocation of mergesort. It's just
1224 * a convenient way to pass state around among the helper functions.
1225 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001226struct s_slice {
1227 PyObject **base;
1228 int len;
1229};
1230
Tim Petersa64dc242002-08-01 02:13:36 +00001231typedef struct s_MergeState {
1232 /* The user-supplied comparison function. or NULL if none given. */
1233 PyObject *compare;
1234
Tim Peterse05f65a2002-08-10 05:21:15 +00001235 /* This controls when we get *into* galloping mode. It's initialized
1236 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1237 * random data, and lower for highly structured data.
1238 */
1239 int min_gallop;
1240
Tim Petersa64dc242002-08-01 02:13:36 +00001241 /* 'a' is temp storage to help with merges. It contains room for
1242 * alloced entries.
1243 */
1244 PyObject **a; /* may point to temparray below */
1245 int alloced;
1246
1247 /* A stack of n pending runs yet to be merged. Run #i starts at
1248 * address base[i] and extends for len[i] elements. It's always
1249 * true (so long as the indices are in bounds) that
1250 *
Tim Peterse05f65a2002-08-10 05:21:15 +00001251 * pending[i].base + pending[i].len == pending[i+1].base
Tim Petersa64dc242002-08-01 02:13:36 +00001252 *
1253 * so we could cut the storage for this, but it's a minor amount,
1254 * and keeping all the info explicit simplifies the code.
1255 */
1256 int n;
Tim Peterse05f65a2002-08-10 05:21:15 +00001257 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001258
1259 /* 'a' points to this when possible, rather than muck with malloc. */
1260 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1261} MergeState;
1262
1263/* Conceptually a MergeState's constructor. */
1264static void
1265merge_init(MergeState *ms, PyObject *compare)
1266{
1267 assert(ms != NULL);
1268 ms->compare = compare;
1269 ms->a = ms->temparray;
1270 ms->alloced = MERGESTATE_TEMP_SIZE;
1271 ms->n = 0;
Tim Peterse05f65a2002-08-10 05:21:15 +00001272 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001273}
1274
1275/* Free all the temp memory owned by the MergeState. This must be called
1276 * when you're done with a MergeState, and may be called before then if
1277 * you want to free the temp memory early.
1278 */
1279static void
1280merge_freemem(MergeState *ms)
1281{
1282 assert(ms != NULL);
1283 if (ms->a != ms->temparray)
1284 PyMem_Free(ms->a);
1285 ms->a = ms->temparray;
1286 ms->alloced = MERGESTATE_TEMP_SIZE;
1287}
1288
1289/* Ensure enough temp memory for 'need' array slots is available.
1290 * Returns 0 on success and -1 if the memory can't be gotten.
1291 */
1292static int
1293merge_getmem(MergeState *ms, int need)
1294{
1295 assert(ms != NULL);
1296 if (need <= ms->alloced)
1297 return 0;
1298 /* Don't realloc! That can cost cycles to copy the old data, but
1299 * we don't care what's in the block.
1300 */
1301 merge_freemem(ms);
1302 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1303 if (ms->a) {
1304 ms->alloced = need;
1305 return 0;
1306 }
1307 PyErr_NoMemory();
1308 merge_freemem(ms); /* reset to sane state */
1309 return -1;
1310}
1311#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1312 merge_getmem(MS, NEED))
1313
1314/* Merge the na elements starting at pa with the nb elements starting at pb
1315 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1316 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1317 * merge, and should have na <= nb. See listsort.txt for more info.
1318 * Return 0 if successful, -1 if error.
1319 */
1320static int
1321merge_lo(MergeState *ms, PyObject **pa, int na, PyObject **pb, int nb)
1322{
1323 int k;
1324 PyObject *compare;
1325 PyObject **dest;
1326 int result = -1; /* guilty until proved innocent */
Tim Peterse05f65a2002-08-10 05:21:15 +00001327 int min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001328
1329 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1330 if (MERGE_GETMEM(ms, na) < 0)
1331 return -1;
1332 memcpy(ms->a, pa, na * sizeof(PyObject*));
1333 dest = pa;
1334 pa = ms->a;
1335
1336 *dest++ = *pb++;
1337 --nb;
1338 if (nb == 0)
1339 goto Succeed;
1340 if (na == 1)
1341 goto CopyB;
1342
1343 compare = ms->compare;
1344 for (;;) {
1345 int acount = 0; /* # of times A won in a row */
1346 int bcount = 0; /* # of times B won in a row */
1347
1348 /* Do the straightforward thing until (if ever) one run
1349 * appears to win consistently.
1350 */
1351 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001352 assert(na > 1 && nb > 0);
Tim Peters66860f62002-08-04 17:47:26 +00001353 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001354 if (k) {
1355 if (k < 0)
1356 goto Fail;
1357 *dest++ = *pb++;
1358 ++bcount;
1359 acount = 0;
1360 --nb;
1361 if (nb == 0)
1362 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001363 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001364 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001365 }
1366 else {
Tim Petersa64dc242002-08-01 02:13:36 +00001367 *dest++ = *pa++;
1368 ++acount;
1369 bcount = 0;
1370 --na;
1371 if (na == 1)
1372 goto CopyB;
Tim Peterse05f65a2002-08-10 05:21:15 +00001373 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001374 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001375 }
Tim Petersa64dc242002-08-01 02:13:36 +00001376 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001377
Tim Petersa64dc242002-08-01 02:13:36 +00001378 /* One run is winning so consistently that galloping may
1379 * be a huge win. So try that, and continue galloping until
1380 * (if ever) neither run appears to be winning consistently
1381 * anymore.
1382 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001383 ++min_gallop;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001384 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001385 assert(na > 1 && nb > 0);
1386 min_gallop -= min_gallop > 1;
1387 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001388 k = gallop_right(*pb, pa, na, 0, compare);
1389 acount = k;
1390 if (k) {
1391 if (k < 0)
1392 goto Fail;
1393 memcpy(dest, pa, k * sizeof(PyObject *));
1394 dest += k;
1395 pa += k;
1396 na -= k;
1397 if (na == 1)
1398 goto CopyB;
1399 /* na==0 is impossible now if the comparison
1400 * function is consistent, but we can't assume
1401 * that it is.
1402 */
1403 if (na == 0)
1404 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001405 }
Tim Petersa64dc242002-08-01 02:13:36 +00001406 *dest++ = *pb++;
1407 --nb;
1408 if (nb == 0)
1409 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001410
Tim Petersa64dc242002-08-01 02:13:36 +00001411 k = gallop_left(*pa, pb, nb, 0, compare);
1412 bcount = k;
1413 if (k) {
1414 if (k < 0)
1415 goto Fail;
1416 memmove(dest, pb, k * sizeof(PyObject *));
1417 dest += k;
1418 pb += k;
1419 nb -= k;
1420 if (nb == 0)
1421 goto Succeed;
1422 }
1423 *dest++ = *pa++;
1424 --na;
1425 if (na == 1)
1426 goto CopyB;
1427 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001428 ++min_gallop; /* penalize it for leaving galloping mode */
1429 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001430 }
1431Succeed:
1432 result = 0;
1433Fail:
1434 if (na)
1435 memcpy(dest, pa, na * sizeof(PyObject*));
1436 return result;
1437CopyB:
1438 assert(na == 1 && nb > 0);
1439 /* The last element of pa belongs at the end of the merge. */
1440 memmove(dest, pb, nb * sizeof(PyObject *));
1441 dest[nb] = *pa;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001442 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001443}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001444
Tim Petersa64dc242002-08-01 02:13:36 +00001445/* Merge the na elements starting at pa with the nb elements starting at pb
1446 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1447 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1448 * merge, and should have na >= nb. See listsort.txt for more info.
1449 * Return 0 if successful, -1 if error.
1450 */
1451static int
1452merge_hi(MergeState *ms, PyObject **pa, int na, PyObject **pb, int nb)
1453{
1454 int k;
1455 PyObject *compare;
1456 PyObject **dest;
1457 int result = -1; /* guilty until proved innocent */
1458 PyObject **basea;
1459 PyObject **baseb;
Tim Peterse05f65a2002-08-10 05:21:15 +00001460 int min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001461
1462 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1463 if (MERGE_GETMEM(ms, nb) < 0)
1464 return -1;
1465 dest = pb + nb - 1;
1466 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1467 basea = pa;
1468 baseb = ms->a;
1469 pb = ms->a + nb - 1;
1470 pa += na - 1;
1471
1472 *dest-- = *pa--;
1473 --na;
1474 if (na == 0)
1475 goto Succeed;
1476 if (nb == 1)
1477 goto CopyA;
1478
1479 compare = ms->compare;
1480 for (;;) {
1481 int acount = 0; /* # of times A won in a row */
1482 int bcount = 0; /* # of times B won in a row */
1483
1484 /* Do the straightforward thing until (if ever) one run
1485 * appears to win consistently.
1486 */
1487 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001488 assert(na > 0 && nb > 1);
Tim Peters66860f62002-08-04 17:47:26 +00001489 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001490 if (k) {
1491 if (k < 0)
1492 goto Fail;
1493 *dest-- = *pa--;
1494 ++acount;
1495 bcount = 0;
1496 --na;
1497 if (na == 0)
1498 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001499 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001500 break;
1501 }
1502 else {
1503 *dest-- = *pb--;
1504 ++bcount;
1505 acount = 0;
1506 --nb;
1507 if (nb == 1)
1508 goto CopyA;
Tim Peterse05f65a2002-08-10 05:21:15 +00001509 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001510 break;
1511 }
1512 }
1513
1514 /* One run is winning so consistently that galloping may
1515 * be a huge win. So try that, and continue galloping until
1516 * (if ever) neither run appears to be winning consistently
1517 * anymore.
1518 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001519 ++min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001520 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001521 assert(na > 0 && nb > 1);
1522 min_gallop -= min_gallop > 1;
1523 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001524 k = gallop_right(*pb, basea, na, na-1, compare);
1525 if (k < 0)
1526 goto Fail;
1527 k = na - k;
1528 acount = k;
1529 if (k) {
1530 dest -= k;
1531 pa -= k;
1532 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1533 na -= k;
1534 if (na == 0)
1535 goto Succeed;
1536 }
1537 *dest-- = *pb--;
1538 --nb;
1539 if (nb == 1)
1540 goto CopyA;
1541
1542 k = gallop_left(*pa, baseb, nb, nb-1, compare);
1543 if (k < 0)
1544 goto Fail;
1545 k = nb - k;
1546 bcount = k;
1547 if (k) {
1548 dest -= k;
1549 pb -= k;
1550 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1551 nb -= k;
1552 if (nb == 1)
1553 goto CopyA;
1554 /* nb==0 is impossible now if the comparison
1555 * function is consistent, but we can't assume
1556 * that it is.
1557 */
1558 if (nb == 0)
1559 goto Succeed;
1560 }
1561 *dest-- = *pa--;
1562 --na;
1563 if (na == 0)
1564 goto Succeed;
1565 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001566 ++min_gallop; /* penalize it for leaving galloping mode */
1567 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001568 }
1569Succeed:
1570 result = 0;
1571Fail:
1572 if (nb)
1573 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1574 return result;
1575CopyA:
1576 assert(nb == 1 && na > 0);
1577 /* The first element of pb belongs at the front of the merge. */
1578 dest -= na;
1579 pa -= na;
1580 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1581 *dest = *pb;
1582 return 0;
1583}
1584
1585/* Merge the two runs at stack indices i and i+1.
1586 * Returns 0 on success, -1 on error.
1587 */
1588static int
1589merge_at(MergeState *ms, int i)
1590{
1591 PyObject **pa, **pb;
1592 int na, nb;
1593 int k;
1594 PyObject *compare;
1595
1596 assert(ms != NULL);
1597 assert(ms->n >= 2);
1598 assert(i >= 0);
1599 assert(i == ms->n - 2 || i == ms->n - 3);
1600
Tim Peterse05f65a2002-08-10 05:21:15 +00001601 pa = ms->pending[i].base;
1602 na = ms->pending[i].len;
1603 pb = ms->pending[i+1].base;
1604 nb = ms->pending[i+1].len;
Tim Petersa64dc242002-08-01 02:13:36 +00001605 assert(na > 0 && nb > 0);
1606 assert(pa + na == pb);
1607
1608 /* Record the length of the combined runs; if i is the 3rd-last
1609 * run now, also slide over the last run (which isn't involved
1610 * in this merge). The current run i+1 goes away in any case.
1611 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001612 ms->pending[i].len = na + nb;
1613 if (i == ms->n - 3)
1614 ms->pending[i+1] = ms->pending[i+2];
Tim Petersa64dc242002-08-01 02:13:36 +00001615 --ms->n;
1616
1617 /* Where does b start in a? Elements in a before that can be
1618 * ignored (already in place).
1619 */
1620 compare = ms->compare;
1621 k = gallop_right(*pb, pa, na, 0, compare);
1622 if (k < 0)
1623 return -1;
1624 pa += k;
1625 na -= k;
1626 if (na == 0)
1627 return 0;
1628
1629 /* Where does a end in b? Elements in b after that can be
1630 * ignored (already in place).
1631 */
1632 nb = gallop_left(pa[na-1], pb, nb, nb-1, compare);
1633 if (nb <= 0)
1634 return nb;
1635
1636 /* Merge what remains of the runs, using a temp array with
1637 * min(na, nb) elements.
1638 */
1639 if (na <= nb)
1640 return merge_lo(ms, pa, na, pb, nb);
1641 else
1642 return merge_hi(ms, pa, na, pb, nb);
1643}
1644
1645/* Examine the stack of runs waiting to be merged, merging adjacent runs
1646 * until the stack invariants are re-established:
1647 *
1648 * 1. len[-3] > len[-2] + len[-1]
1649 * 2. len[-2] > len[-1]
1650 *
1651 * See listsort.txt for more info.
1652 *
1653 * Returns 0 on success, -1 on error.
1654 */
1655static int
1656merge_collapse(MergeState *ms)
1657{
Tim Peterse05f65a2002-08-10 05:21:15 +00001658 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001659
1660 assert(ms);
1661 while (ms->n > 1) {
1662 int n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001663 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1664 if (p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001665 --n;
1666 if (merge_at(ms, n) < 0)
1667 return -1;
1668 }
Tim Peterse05f65a2002-08-10 05:21:15 +00001669 else if (p[n].len <= p[n+1].len) {
Tim Petersa64dc242002-08-01 02:13:36 +00001670 if (merge_at(ms, n) < 0)
1671 return -1;
1672 }
1673 else
1674 break;
1675 }
1676 return 0;
1677}
1678
1679/* Regardless of invariants, merge all runs on the stack until only one
1680 * remains. This is used at the end of the mergesort.
1681 *
1682 * Returns 0 on success, -1 on error.
1683 */
1684static int
1685merge_force_collapse(MergeState *ms)
1686{
Tim Peterse05f65a2002-08-10 05:21:15 +00001687 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001688
1689 assert(ms);
1690 while (ms->n > 1) {
1691 int n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001692 if (n > 0 && p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001693 --n;
1694 if (merge_at(ms, n) < 0)
1695 return -1;
1696 }
1697 return 0;
1698}
1699
1700/* Compute a good value for the minimum run length; natural runs shorter
1701 * than this are boosted artificially via binary insertion.
1702 *
1703 * If n < 64, return n (it's too small to bother with fancy stuff).
1704 * Else if n is an exact power of 2, return 32.
1705 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1706 * strictly less than, an exact power of 2.
1707 *
1708 * See listsort.txt for more info.
1709 */
1710static int
1711merge_compute_minrun(int n)
1712{
1713 int r = 0; /* becomes 1 if any 1 bits are shifted off */
1714
1715 assert(n >= 0);
1716 while (n >= 64) {
1717 r |= n & 1;
1718 n >>= 1;
1719 }
1720 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001721}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001722
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001723/* Special wrapper to support stable sorting using the decorate-sort-undecorate
1724 pattern. Holds a key which is used for comparisions and the original record
1725 which is returned during the undecorate phase. By exposing only the key
1726 during comparisons, the underlying sort stability characteristics are left
1727 unchanged. Also, if a custom comparison function is used, it will only see
1728 the key instead of a full record. */
1729
1730typedef struct {
1731 PyObject_HEAD
1732 PyObject *key;
1733 PyObject *value;
1734} sortwrapperobject;
1735
1736static PyTypeObject sortwrapper_type;
1737
1738static PyObject *
1739sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
1740{
1741 if (!PyObject_TypeCheck(b, &sortwrapper_type)) {
1742 PyErr_SetString(PyExc_TypeError,
1743 "expected a sortwrapperobject");
1744 return NULL;
1745 }
1746 return PyObject_RichCompare(a->key, b->key, op);
1747}
1748
1749static void
1750sortwrapper_dealloc(sortwrapperobject *so)
1751{
1752 Py_XDECREF(so->key);
1753 Py_XDECREF(so->value);
1754 PyObject_Del(so);
1755}
1756
1757PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
1758
1759static PyTypeObject sortwrapper_type = {
1760 PyObject_HEAD_INIT(&PyType_Type)
1761 0, /* ob_size */
1762 "sortwrapper", /* tp_name */
1763 sizeof(sortwrapperobject), /* tp_basicsize */
1764 0, /* tp_itemsize */
1765 /* methods */
1766 (destructor)sortwrapper_dealloc, /* tp_dealloc */
1767 0, /* tp_print */
1768 0, /* tp_getattr */
1769 0, /* tp_setattr */
1770 0, /* tp_compare */
1771 0, /* tp_repr */
1772 0, /* tp_as_number */
1773 0, /* tp_as_sequence */
1774 0, /* tp_as_mapping */
1775 0, /* tp_hash */
1776 0, /* tp_call */
1777 0, /* tp_str */
1778 PyObject_GenericGetAttr, /* tp_getattro */
1779 0, /* tp_setattro */
1780 0, /* tp_as_buffer */
1781 Py_TPFLAGS_DEFAULT |
1782 Py_TPFLAGS_HAVE_RICHCOMPARE, /* tp_flags */
1783 sortwrapper_doc, /* tp_doc */
1784 0, /* tp_traverse */
1785 0, /* tp_clear */
1786 (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
1787};
1788
1789/* Returns a new reference to a sortwrapper.
1790 Consumes the references to the two underlying objects. */
1791
1792static PyObject *
1793build_sortwrapper(PyObject *key, PyObject *value)
1794{
1795 sortwrapperobject *so;
1796
1797 so = PyObject_New(sortwrapperobject, &sortwrapper_type);
1798 if (so == NULL)
1799 return NULL;
1800 so->key = key;
1801 so->value = value;
1802 return (PyObject *)so;
1803}
1804
1805/* Returns a new reference to the value underlying the wrapper. */
1806static PyObject *
1807sortwrapper_getvalue(PyObject *so)
1808{
1809 PyObject *value;
1810
1811 if (!PyObject_TypeCheck(so, &sortwrapper_type)) {
1812 PyErr_SetString(PyExc_TypeError,
1813 "expected a sortwrapperobject");
1814 return NULL;
1815 }
1816 value = ((sortwrapperobject *)so)->value;
1817 Py_INCREF(value);
1818 return value;
1819}
1820
1821/* Wrapper for user specified cmp functions in combination with a
1822 specified key function. Makes sure the cmp function is presented
1823 with the actual key instead of the sortwrapper */
1824
1825typedef struct {
1826 PyObject_HEAD
1827 PyObject *func;
1828} cmpwrapperobject;
1829
1830static void
1831cmpwrapper_dealloc(cmpwrapperobject *co)
1832{
1833 Py_XDECREF(co->func);
1834 PyObject_Del(co);
1835}
1836
1837static PyObject *
1838cmpwrapper_call(cmpwrapperobject *co, PyObject *args, PyObject *kwds)
1839{
1840 PyObject *x, *y, *xx, *yy;
1841
1842 if (!PyArg_UnpackTuple(args, "", 2, 2, &x, &y))
1843 return NULL;
1844 if (!PyObject_TypeCheck(x, &sortwrapper_type) ||
Raymond Hettingerae4a2992003-10-16 17:16:30 +00001845 !PyObject_TypeCheck(y, &sortwrapper_type)) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001846 PyErr_SetString(PyExc_TypeError,
1847 "expected a sortwrapperobject");
1848 return NULL;
1849 }
1850 xx = ((sortwrapperobject *)x)->key;
1851 yy = ((sortwrapperobject *)y)->key;
1852 return PyObject_CallFunctionObjArgs(co->func, xx, yy, NULL);
1853}
1854
1855PyDoc_STRVAR(cmpwrapper_doc, "cmp() wrapper for sort with custom keys.");
1856
1857static PyTypeObject cmpwrapper_type = {
1858 PyObject_HEAD_INIT(&PyType_Type)
1859 0, /* ob_size */
1860 "cmpwrapper", /* tp_name */
1861 sizeof(cmpwrapperobject), /* tp_basicsize */
1862 0, /* tp_itemsize */
1863 /* methods */
1864 (destructor)cmpwrapper_dealloc, /* tp_dealloc */
1865 0, /* tp_print */
1866 0, /* tp_getattr */
1867 0, /* tp_setattr */
1868 0, /* tp_compare */
1869 0, /* tp_repr */
1870 0, /* tp_as_number */
1871 0, /* tp_as_sequence */
1872 0, /* tp_as_mapping */
1873 0, /* tp_hash */
1874 (ternaryfunc)cmpwrapper_call, /* tp_call */
1875 0, /* tp_str */
1876 PyObject_GenericGetAttr, /* tp_getattro */
1877 0, /* tp_setattro */
1878 0, /* tp_as_buffer */
1879 Py_TPFLAGS_DEFAULT, /* tp_flags */
1880 cmpwrapper_doc, /* tp_doc */
1881};
1882
1883static PyObject *
1884build_cmpwrapper(PyObject *cmpfunc)
1885{
1886 cmpwrapperobject *co;
1887
1888 co = PyObject_New(cmpwrapperobject, &cmpwrapper_type);
1889 if (co == NULL)
1890 return NULL;
1891 Py_INCREF(cmpfunc);
1892 co->func = cmpfunc;
1893 return (PyObject *)co;
1894}
1895
Tim Petersa64dc242002-08-01 02:13:36 +00001896/* An adaptive, stable, natural mergesort. See listsort.txt.
1897 * Returns Py_None on success, NULL on error. Even in case of error, the
1898 * list will be some permutation of its input state (nothing is lost or
1899 * duplicated).
1900 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001901static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001902listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001903{
Tim Petersa64dc242002-08-01 02:13:36 +00001904 MergeState ms;
1905 PyObject **lo, **hi;
1906 int nremaining;
1907 int minrun;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001908 int saved_ob_size, saved_allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00001909 PyObject **saved_ob_item;
1910 PyObject **empty_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001911 PyObject *compare = NULL;
1912 PyObject *result = NULL; /* guilty until proved innocent */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001913 int reverse = 0;
1914 PyObject *keyfunc = NULL;
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001915 int i;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001916 PyObject *key, *value, *kvpair;
1917 static char *kwlist[] = {"cmp", "key", "reverse", 0};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001918
Tim Petersa64dc242002-08-01 02:13:36 +00001919 assert(self != NULL);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001920 assert (PyList_Check(self));
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001921 if (args != NULL) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001922 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:sort",
1923 kwlist, &compare, &keyfunc, &reverse))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001924 return NULL;
1925 }
Skip Montanaro4abd5f02003-01-02 20:51:08 +00001926 if (compare == Py_None)
1927 compare = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001928 if (keyfunc == Py_None)
1929 keyfunc = NULL;
1930 if (compare != NULL && keyfunc != NULL) {
1931 compare = build_cmpwrapper(compare);
1932 if (compare == NULL)
Hye-Shik Chang19cb1932003-12-10 07:31:08 +00001933 return NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001934 } else
1935 Py_XINCREF(compare);
1936
Tim Petersb9099c32002-11-12 22:08:10 +00001937 /* The list is temporarily made empty, so that mutations performed
1938 * by comparison functions can't affect the slice of memory we're
1939 * sorting (allowing mutations during sorting is a core-dump
1940 * factory, since ob_item may change).
1941 */
1942 saved_ob_size = self->ob_size;
1943 saved_ob_item = self->ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001944 saved_allocated = self->allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00001945 self->ob_size = 0;
Tim Peters7049d812004-01-18 20:31:02 +00001946 self->ob_item = empty_ob_item = PyMem_NEW(PyObject *, 0);
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001947 self->allocated = 0;
Tim Peters330f9e92002-07-19 07:05:44 +00001948
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001949 if (keyfunc != NULL) {
1950 for (i=0 ; i < saved_ob_size ; i++) {
1951 value = saved_ob_item[i];
1952 key = PyObject_CallFunctionObjArgs(keyfunc, value,
1953 NULL);
1954 if (key == NULL) {
1955 for (i=i-1 ; i>=0 ; i--) {
1956 kvpair = saved_ob_item[i];
1957 value = sortwrapper_getvalue(kvpair);
1958 saved_ob_item[i] = value;
1959 Py_DECREF(kvpair);
1960 }
1961 if (self->ob_item != empty_ob_item
1962 || self->ob_size) {
1963 /* If the list changed *as well* we
1964 have two errors. We let the first
1965 one "win", but we shouldn't let
1966 what's in the list currently
1967 leak. */
1968 (void)list_ass_slice(
1969 self, 0, self->ob_size,
1970 (PyObject *)NULL);
1971 }
1972
1973 goto dsu_fail;
1974 }
1975 kvpair = build_sortwrapper(key, value);
1976 if (kvpair == NULL)
1977 goto dsu_fail;
1978 saved_ob_item[i] = kvpair;
1979 }
1980 }
1981
1982 /* Reverse sort stability achieved by initially reversing the list,
1983 applying a stable forward sort, then reversing the final result. */
1984 if (reverse && saved_ob_size > 1)
1985 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
1986
1987 merge_init(&ms, compare);
1988
Tim Petersb9099c32002-11-12 22:08:10 +00001989 nremaining = saved_ob_size;
Tim Petersa64dc242002-08-01 02:13:36 +00001990 if (nremaining < 2)
1991 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00001992
Tim Petersa64dc242002-08-01 02:13:36 +00001993 /* March over the array once, left to right, finding natural runs,
1994 * and extending short natural runs to minrun elements.
1995 */
Tim Petersb9099c32002-11-12 22:08:10 +00001996 lo = saved_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001997 hi = lo + nremaining;
1998 minrun = merge_compute_minrun(nremaining);
1999 do {
2000 int descending;
2001 int n;
Tim Peters330f9e92002-07-19 07:05:44 +00002002
Tim Petersa64dc242002-08-01 02:13:36 +00002003 /* Identify next run. */
2004 n = count_run(lo, hi, compare, &descending);
2005 if (n < 0)
2006 goto fail;
2007 if (descending)
2008 reverse_slice(lo, lo + n);
2009 /* If short, extend to min(minrun, nremaining). */
2010 if (n < minrun) {
2011 const int force = nremaining <= minrun ?
2012 nremaining : minrun;
2013 if (binarysort(lo, lo + force, lo + n, compare) < 0)
2014 goto fail;
2015 n = force;
2016 }
2017 /* Push run onto pending-runs stack, and maybe merge. */
2018 assert(ms.n < MAX_MERGE_PENDING);
Tim Peterse05f65a2002-08-10 05:21:15 +00002019 ms.pending[ms.n].base = lo;
2020 ms.pending[ms.n].len = n;
Tim Petersa64dc242002-08-01 02:13:36 +00002021 ++ms.n;
2022 if (merge_collapse(&ms) < 0)
2023 goto fail;
2024 /* Advance to find next run. */
2025 lo += n;
2026 nremaining -= n;
2027 } while (nremaining);
2028 assert(lo == hi);
Tim Peters330f9e92002-07-19 07:05:44 +00002029
Tim Petersa64dc242002-08-01 02:13:36 +00002030 if (merge_force_collapse(&ms) < 0)
2031 goto fail;
2032 assert(ms.n == 1);
Tim Petersb9099c32002-11-12 22:08:10 +00002033 assert(ms.pending[0].base == saved_ob_item);
2034 assert(ms.pending[0].len == saved_ob_size);
Tim Petersa64dc242002-08-01 02:13:36 +00002035
2036succeed:
2037 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002038fail:
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002039 if (keyfunc != NULL) {
2040 for (i=0 ; i < saved_ob_size ; i++) {
2041 kvpair = saved_ob_item[i];
2042 value = sortwrapper_getvalue(kvpair);
2043 saved_ob_item[i] = value;
2044 Py_DECREF(kvpair);
2045 }
2046 }
2047
Tim Petersb9099c32002-11-12 22:08:10 +00002048 if (self->ob_item != empty_ob_item || self->ob_size) {
2049 /* The user mucked with the list during the sort. */
2050 (void)list_ass_slice(self, 0, self->ob_size, (PyObject *)NULL);
2051 if (result != NULL) {
2052 PyErr_SetString(PyExc_ValueError,
2053 "list modified during sort");
2054 result = NULL;
2055 }
2056 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002057
2058 if (reverse && saved_ob_size > 1)
2059 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2060
2061 merge_freemem(&ms);
2062
2063dsu_fail:
Tim Petersb9099c32002-11-12 22:08:10 +00002064 if (self->ob_item == empty_ob_item)
2065 PyMem_FREE(empty_ob_item);
2066 self->ob_size = saved_ob_size;
2067 self->ob_item = saved_ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002068 self->allocated = saved_allocated;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002069 Py_XDECREF(compare);
Tim Petersa64dc242002-08-01 02:13:36 +00002070 Py_XINCREF(result);
2071 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002072}
Tim Peters330f9e92002-07-19 07:05:44 +00002073#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002074#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002075
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002076int
Fred Drakea2f55112000-07-09 15:16:51 +00002077PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002078{
2079 if (v == NULL || !PyList_Check(v)) {
2080 PyErr_BadInternalCall();
2081 return -1;
2082 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002083 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002084 if (v == NULL)
2085 return -1;
2086 Py_DECREF(v);
2087 return 0;
2088}
2089
Guido van Rossumb86c5492001-02-12 22:06:02 +00002090static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002091listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002092{
Tim Peters326b4482002-07-19 04:04:16 +00002093 if (self->ob_size > 1)
2094 reverse_slice(self->ob_item, self->ob_item + self->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002095 Py_INCREF(Py_None);
2096 return Py_None;
Guido van Rossumed98d481991-03-06 13:07:53 +00002097}
2098
Guido van Rossum84c76f51990-10-30 13:32:20 +00002099int
Fred Drakea2f55112000-07-09 15:16:51 +00002100PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002101{
Tim Peters6063e262002-08-08 01:06:39 +00002102 PyListObject *self = (PyListObject *)v;
2103
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002104 if (v == NULL || !PyList_Check(v)) {
2105 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002106 return -1;
2107 }
Tim Peters6063e262002-08-08 01:06:39 +00002108 if (self->ob_size > 1)
2109 reverse_slice(self->ob_item, self->ob_item + self->ob_size);
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002110 return 0;
2111}
2112
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002113PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002114PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002115{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002116 PyObject *w;
2117 PyObject **p;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002118 int n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002119 if (v == NULL || !PyList_Check(v)) {
2120 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002121 return NULL;
2122 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002123 n = ((PyListObject *)v)->ob_size;
2124 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002125 if (w == NULL)
2126 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002127 p = ((PyTupleObject *)w)->ob_item;
Thomas Wouters334fb892000-07-25 12:56:38 +00002128 memcpy((void *)p,
2129 (void *)((PyListObject *)v)->ob_item,
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002130 n*sizeof(PyObject *));
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002131 while (--n >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002132 Py_INCREF(*p);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002133 p++;
2134 }
2135 return w;
2136}
2137
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002138static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002139listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002140{
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002141 int i, start=0, stop=self->ob_size;
2142 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002143
Walter Dörwalde8049bef2003-06-17 19:27:39 +00002144 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2145 _PyEval_SliceIndex, &start,
2146 _PyEval_SliceIndex, &stop))
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002147 return NULL;
Guido van Rossum2743d872003-06-17 14:25:14 +00002148 if (start < 0) {
2149 start += self->ob_size;
2150 if (start < 0)
2151 start = 0;
2152 }
2153 if (stop < 0) {
2154 stop += self->ob_size;
2155 if (stop < 0)
2156 stop = 0;
2157 }
2158 else if (stop > self->ob_size)
2159 stop = self->ob_size;
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002160 for (i = start; i < stop; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002161 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2162 if (cmp > 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002163 return PyInt_FromLong((long)i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002164 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002165 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002166 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002167 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002168 return NULL;
2169}
2170
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002171static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002172listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002173{
2174 int count = 0;
2175 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002176
Guido van Rossume6f7d181991-10-20 20:20:40 +00002177 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002178 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2179 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002180 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002181 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002182 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00002183 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002184 return PyInt_FromLong((long)count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002185}
2186
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002187static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002188listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002189{
2190 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002191
Guido van Rossumed98d481991-03-06 13:07:53 +00002192 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002193 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2194 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002195 if (list_ass_slice(self, i, i+1,
2196 (PyObject *)NULL) != 0)
Guido van Rossumed98d481991-03-06 13:07:53 +00002197 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002198 Py_INCREF(Py_None);
2199 return Py_None;
Guido van Rossumed98d481991-03-06 13:07:53 +00002200 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002201 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002202 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002203 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002204 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002205 return NULL;
2206}
2207
Jeremy Hylton8caad492000-06-23 14:18:11 +00002208static int
2209list_traverse(PyListObject *o, visitproc visit, void *arg)
2210{
2211 int i, err;
2212 PyObject *x;
2213
2214 for (i = o->ob_size; --i >= 0; ) {
2215 x = o->ob_item[i];
2216 if (x != NULL) {
2217 err = visit(x, arg);
2218 if (err)
2219 return err;
2220 }
2221 }
2222 return 0;
2223}
2224
2225static int
2226list_clear(PyListObject *lp)
2227{
2228 (void) PyList_SetSlice((PyObject *)lp, 0, lp->ob_size, 0);
2229 return 0;
2230}
2231
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002232static PyObject *
2233list_richcompare(PyObject *v, PyObject *w, int op)
2234{
2235 PyListObject *vl, *wl;
2236 int i;
2237
2238 if (!PyList_Check(v) || !PyList_Check(w)) {
2239 Py_INCREF(Py_NotImplemented);
2240 return Py_NotImplemented;
2241 }
2242
2243 vl = (PyListObject *)v;
2244 wl = (PyListObject *)w;
2245
2246 if (vl->ob_size != wl->ob_size && (op == Py_EQ || op == Py_NE)) {
2247 /* Shortcut: if the lengths differ, the lists differ */
2248 PyObject *res;
2249 if (op == Py_EQ)
2250 res = Py_False;
2251 else
2252 res = Py_True;
2253 Py_INCREF(res);
2254 return res;
2255 }
2256
2257 /* Search for the first index where items are different */
2258 for (i = 0; i < vl->ob_size && i < wl->ob_size; i++) {
2259 int k = PyObject_RichCompareBool(vl->ob_item[i],
2260 wl->ob_item[i], Py_EQ);
2261 if (k < 0)
2262 return NULL;
2263 if (!k)
2264 break;
2265 }
2266
2267 if (i >= vl->ob_size || i >= wl->ob_size) {
2268 /* No more items to compare -- compare sizes */
2269 int vs = vl->ob_size;
2270 int ws = wl->ob_size;
2271 int cmp;
2272 PyObject *res;
2273 switch (op) {
2274 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00002275 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002276 case Py_EQ: cmp = vs == ws; break;
2277 case Py_NE: cmp = vs != ws; break;
2278 case Py_GT: cmp = vs > ws; break;
2279 case Py_GE: cmp = vs >= ws; break;
2280 default: return NULL; /* cannot happen */
2281 }
2282 if (cmp)
2283 res = Py_True;
2284 else
2285 res = Py_False;
2286 Py_INCREF(res);
2287 return res;
2288 }
2289
2290 /* We have an item that differs -- shortcuts for EQ/NE */
2291 if (op == Py_EQ) {
2292 Py_INCREF(Py_False);
2293 return Py_False;
2294 }
2295 if (op == Py_NE) {
2296 Py_INCREF(Py_True);
2297 return Py_True;
2298 }
2299
2300 /* Compare the final item again using the proper operator */
2301 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
2302}
2303
Tim Peters6d6c1a32001-08-02 04:15:00 +00002304static int
2305list_init(PyListObject *self, PyObject *args, PyObject *kw)
2306{
2307 PyObject *arg = NULL;
2308 static char *kwlist[] = {"sequence", 0};
2309
2310 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2311 return -1;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002312 /* Empty previous contents */
2313 if (self->ob_size != 0) {
2314 if (list_ass_slice(self, 0, self->ob_size, (PyObject *)NULL) != 0)
2315 return -1;
2316 }
2317 if (arg != NULL) {
2318 PyObject *rv = listextend(self, arg);
2319 if (rv == NULL)
2320 return -1;
2321 Py_DECREF(rv);
2322 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002323 return 0;
2324}
2325
Guido van Rossumdbb53d92001-12-03 16:32:18 +00002326static long
2327list_nohash(PyObject *self)
2328{
2329 PyErr_SetString(PyExc_TypeError, "list objects are unhashable");
2330 return -1;
2331}
2332
Raymond Hettinger1021c442003-11-07 15:38:09 +00002333static PyObject *list_iter(PyObject *seq);
2334static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2335
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002336PyDoc_STRVAR(getitem_doc,
2337"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002338PyDoc_STRVAR(reversed_doc,
2339"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002340PyDoc_STRVAR(append_doc,
2341"L.append(object) -- append object to end");
2342PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002343"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002344PyDoc_STRVAR(insert_doc,
2345"L.insert(index, object) -- insert object before index");
2346PyDoc_STRVAR(pop_doc,
2347"L.pop([index]) -> item -- remove and return item at index (default last)");
2348PyDoc_STRVAR(remove_doc,
2349"L.remove(value) -- remove first occurrence of value");
2350PyDoc_STRVAR(index_doc,
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002351"L.index(value, [start, [stop]]) -> integer -- return first index of value");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002352PyDoc_STRVAR(count_doc,
2353"L.count(value) -> integer -- return number of occurrences of value");
2354PyDoc_STRVAR(reverse_doc,
2355"L.reverse() -- reverse *IN PLACE*");
2356PyDoc_STRVAR(sort_doc,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002357"L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n\
2358cmp(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002359
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002360static PyObject *list_subscript(PyListObject*, PyObject*);
2361
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002362static PyMethodDef list_methods[] = {
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002363 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
Raymond Hettinger1021c442003-11-07 15:38:09 +00002364 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002365 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002366 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002367 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002368 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002369 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002370 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002371 {"count", (PyCFunction)listcount, METH_O, count_doc},
2372 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002373 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
Tim Petersa64dc242002-08-01 02:13:36 +00002374 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002375};
2376
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002377static PySequenceMethods list_as_sequence = {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002378 (inquiry)list_length, /* sq_length */
2379 (binaryfunc)list_concat, /* sq_concat */
2380 (intargfunc)list_repeat, /* sq_repeat */
2381 (intargfunc)list_item, /* sq_item */
2382 (intintargfunc)list_slice, /* sq_slice */
2383 (intobjargproc)list_ass_item, /* sq_ass_item */
2384 (intintobjargproc)list_ass_slice, /* sq_ass_slice */
2385 (objobjproc)list_contains, /* sq_contains */
2386 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2387 (intargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002388};
2389
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002390PyDoc_STRVAR(list_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002391"list() -> new list\n"
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002392"list(sequence) -> new list initialized from sequence's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002393
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002394static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002395list_subscript(PyListObject* self, PyObject* item)
2396{
2397 if (PyInt_Check(item)) {
2398 long i = PyInt_AS_LONG(item);
2399 if (i < 0)
2400 i += PyList_GET_SIZE(self);
2401 return list_item(self, i);
2402 }
2403 else if (PyLong_Check(item)) {
2404 long i = PyLong_AsLong(item);
2405 if (i == -1 && PyErr_Occurred())
2406 return NULL;
2407 if (i < 0)
2408 i += PyList_GET_SIZE(self);
2409 return list_item(self, i);
2410 }
2411 else if (PySlice_Check(item)) {
2412 int start, stop, step, slicelength, cur, i;
2413 PyObject* result;
2414 PyObject* it;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002415 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002416
2417 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
2418 &start, &stop, &step, &slicelength) < 0) {
2419 return NULL;
2420 }
2421
2422 if (slicelength <= 0) {
2423 return PyList_New(0);
2424 }
2425 else {
2426 result = PyList_New(slicelength);
2427 if (!result) return NULL;
2428
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002429 src = self->ob_item;
2430 dest = ((PyListObject *)result)->ob_item;
Tim Peters3b01a122002-07-19 02:35:45 +00002431 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002432 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002433 it = src[cur];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002434 Py_INCREF(it);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002435 dest[i] = it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002436 }
Tim Peters3b01a122002-07-19 02:35:45 +00002437
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002438 return result;
2439 }
2440 }
2441 else {
2442 PyErr_SetString(PyExc_TypeError,
2443 "list indices must be integers");
2444 return NULL;
2445 }
2446}
2447
Tim Peters3b01a122002-07-19 02:35:45 +00002448static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002449list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2450{
2451 if (PyInt_Check(item)) {
2452 long i = PyInt_AS_LONG(item);
2453 if (i < 0)
2454 i += PyList_GET_SIZE(self);
2455 return list_ass_item(self, i, value);
2456 }
2457 else if (PyLong_Check(item)) {
2458 long i = PyLong_AsLong(item);
2459 if (i == -1 && PyErr_Occurred())
2460 return -1;
2461 if (i < 0)
2462 i += PyList_GET_SIZE(self);
2463 return list_ass_item(self, i, value);
2464 }
2465 else if (PySlice_Check(item)) {
2466 int start, stop, step, slicelength;
2467
2468 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
2469 &start, &stop, &step, &slicelength) < 0) {
2470 return -1;
2471 }
2472
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002473 /* treat L[slice(a,b)] = v _exactly_ like L[a:b] = v */
2474 if (step == 1 && ((PySliceObject*)item)->step == Py_None)
2475 return list_ass_slice(self, start, stop, value);
2476
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002477 if (value == NULL) {
2478 /* delete slice */
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002479 PyObject **garbage;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002480 int cur, i;
Tim Peters3b01a122002-07-19 02:35:45 +00002481
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002482 if (slicelength <= 0)
2483 return 0;
2484
2485 if (step < 0) {
2486 stop = start + 1;
2487 start = stop + step*(slicelength - 1) - 1;
2488 step = -step;
2489 }
2490
2491 garbage = (PyObject**)
2492 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Tim Peters3b01a122002-07-19 02:35:45 +00002493
2494 /* drawing pictures might help
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002495 understand these for loops */
Guido van Rossum75a20b12002-06-11 12:22:28 +00002496 for (cur = start, i = 0;
2497 cur < stop;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002498 cur += step, i++) {
2499 int lim = step;
2500
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002501 garbage[i] = PyList_GET_ITEM(self, cur);
2502
Michael W. Hudson56796f62002-07-29 14:35:04 +00002503 if (cur + step >= self->ob_size) {
2504 lim = self->ob_size - cur - 1;
2505 }
2506
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002507 memmove(self->ob_item + cur - i,
2508 self->ob_item + cur + 1,
2509 lim * sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002510 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002511
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002512 for (cur = start + slicelength*step + 1;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002513 cur < self->ob_size; cur++) {
2514 PyList_SET_ITEM(self, cur - slicelength,
2515 PyList_GET_ITEM(self, cur));
2516 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002517
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002518 self->ob_size -= slicelength;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002519 list_resize(self, self->ob_size);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002520
2521 for (i = 0; i < slicelength; i++) {
2522 Py_DECREF(garbage[i]);
2523 }
2524 PyMem_FREE(garbage);
2525
2526 return 0;
2527 }
2528 else {
2529 /* assign slice */
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002530 PyObject **garbage, *ins, *seq, **seqitems, **selfitems;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002531 int cur, i;
2532
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002533 /* protect against a[::-1] = a */
Tim Peters3b01a122002-07-19 02:35:45 +00002534 if (self == (PyListObject*)value) {
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002535 seq = list_slice((PyListObject*)value, 0,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002536 PyList_GET_SIZE(value));
Tim Peters3b01a122002-07-19 02:35:45 +00002537 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002538 else {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002539 seq = PySequence_Fast(value,
2540 "must assign iterable to extended slice");
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002541 if (!seq)
2542 return -1;
2543 }
2544
2545 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2546 PyErr_Format(PyExc_ValueError,
2547 "attempt to assign sequence of size %d to extended slice of size %d",
2548 PySequence_Fast_GET_SIZE(seq),
2549 slicelength);
2550 Py_DECREF(seq);
2551 return -1;
2552 }
2553
2554 if (!slicelength) {
2555 Py_DECREF(seq);
2556 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002557 }
2558
2559 garbage = (PyObject**)
2560 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Tim Peters3b01a122002-07-19 02:35:45 +00002561
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002562 selfitems = self->ob_item;
2563 if (PyList_Check(seq))
2564 seqitems = ((PyListObject *)seq)->ob_item;
2565 else
2566 seqitems = ((PyTupleObject *)seq)->ob_item;
Tim Peters3b01a122002-07-19 02:35:45 +00002567 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002568 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002569 garbage[i] = selfitems[cur];
2570 ins = seqitems[i];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002571 Py_INCREF(ins);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002572 selfitems[cur] = ins;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002573 }
2574
2575 for (i = 0; i < slicelength; i++) {
2576 Py_DECREF(garbage[i]);
2577 }
Tim Peters3b01a122002-07-19 02:35:45 +00002578
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002579 PyMem_FREE(garbage);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002580 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002581
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002582 return 0;
2583 }
Tim Peters3b01a122002-07-19 02:35:45 +00002584 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002585 else {
Tim Peters3b01a122002-07-19 02:35:45 +00002586 PyErr_SetString(PyExc_TypeError,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002587 "list indices must be integers");
2588 return -1;
2589 }
2590}
2591
2592static PyMappingMethods list_as_mapping = {
2593 (inquiry)list_length,
2594 (binaryfunc)list_subscript,
2595 (objobjargproc)list_ass_subscript
2596};
2597
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002598PyTypeObject PyList_Type = {
2599 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002600 0,
2601 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002602 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002603 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002604 (destructor)list_dealloc, /* tp_dealloc */
2605 (printfunc)list_print, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002606 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002607 0, /* tp_setattr */
2608 0, /* tp_compare */
2609 (reprfunc)list_repr, /* tp_repr */
2610 0, /* tp_as_number */
2611 &list_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002612 &list_as_mapping, /* tp_as_mapping */
Guido van Rossumdbb53d92001-12-03 16:32:18 +00002613 list_nohash, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002614 0, /* tp_call */
2615 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002616 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002617 0, /* tp_setattro */
2618 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002619 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Tim Peters6d6c1a32001-08-02 04:15:00 +00002620 Py_TPFLAGS_BASETYPE, /* tp_flags */
2621 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002622 (traverseproc)list_traverse, /* tp_traverse */
2623 (inquiry)list_clear, /* tp_clear */
2624 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002625 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002626 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002627 0, /* tp_iternext */
2628 list_methods, /* tp_methods */
2629 0, /* tp_members */
2630 0, /* tp_getset */
2631 0, /* tp_base */
2632 0, /* tp_dict */
2633 0, /* tp_descr_get */
2634 0, /* tp_descr_set */
2635 0, /* tp_dictoffset */
2636 (initproc)list_init, /* tp_init */
2637 PyType_GenericAlloc, /* tp_alloc */
2638 PyType_GenericNew, /* tp_new */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002639 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002640};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002641
2642
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002643/*********************** List Iterator **************************/
2644
2645typedef struct {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002646 PyObject_HEAD
2647 long it_index;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002648 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002649} listiterobject;
2650
2651PyTypeObject PyListIter_Type;
2652
Guido van Rossum5086e492002-07-16 15:56:52 +00002653static PyObject *
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002654list_iter(PyObject *seq)
2655{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002656 listiterobject *it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002657
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002658 if (!PyList_Check(seq)) {
2659 PyErr_BadInternalCall();
2660 return NULL;
2661 }
2662 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2663 if (it == NULL)
2664 return NULL;
2665 it->it_index = 0;
2666 Py_INCREF(seq);
2667 it->it_seq = (PyListObject *)seq;
2668 _PyObject_GC_TRACK(it);
2669 return (PyObject *)it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002670}
2671
2672static void
2673listiter_dealloc(listiterobject *it)
2674{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002675 _PyObject_GC_UNTRACK(it);
Guido van Rossum86103ae2002-07-16 20:07:32 +00002676 Py_XDECREF(it->it_seq);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002677 PyObject_GC_Del(it);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002678}
2679
2680static int
2681listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2682{
Guido van Rossum86103ae2002-07-16 20:07:32 +00002683 if (it->it_seq == NULL)
2684 return 0;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002685 return visit((PyObject *)it->it_seq, arg);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002686}
2687
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002688static PyObject *
Tim Peters93b2cc42002-06-01 05:22:55 +00002689listiter_next(listiterobject *it)
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002690{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002691 PyListObject *seq;
2692 PyObject *item;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002693
Tim Peters93b2cc42002-06-01 05:22:55 +00002694 assert(it != NULL);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002695 seq = it->it_seq;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002696 if (seq == NULL)
2697 return NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002698 assert(PyList_Check(seq));
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002699
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002700 if (it->it_index < PyList_GET_SIZE(seq)) {
Tim Peters93b2cc42002-06-01 05:22:55 +00002701 item = PyList_GET_ITEM(seq, it->it_index);
2702 ++it->it_index;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002703 Py_INCREF(item);
2704 return item;
2705 }
Guido van Rossum86103ae2002-07-16 20:07:32 +00002706
2707 Py_DECREF(seq);
2708 it->it_seq = NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002709 return NULL;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002710}
2711
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002712PyTypeObject PyListIter_Type = {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002713 PyObject_HEAD_INIT(&PyType_Type)
2714 0, /* ob_size */
2715 "listiterator", /* tp_name */
2716 sizeof(listiterobject), /* tp_basicsize */
2717 0, /* tp_itemsize */
2718 /* methods */
2719 (destructor)listiter_dealloc, /* tp_dealloc */
2720 0, /* tp_print */
2721 0, /* tp_getattr */
2722 0, /* tp_setattr */
2723 0, /* tp_compare */
2724 0, /* tp_repr */
2725 0, /* tp_as_number */
2726 0, /* tp_as_sequence */
2727 0, /* tp_as_mapping */
2728 0, /* tp_hash */
2729 0, /* tp_call */
2730 0, /* tp_str */
2731 PyObject_GenericGetAttr, /* tp_getattro */
2732 0, /* tp_setattro */
2733 0, /* tp_as_buffer */
2734 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2735 0, /* tp_doc */
2736 (traverseproc)listiter_traverse, /* tp_traverse */
2737 0, /* tp_clear */
2738 0, /* tp_richcompare */
2739 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00002740 PyObject_SelfIter, /* tp_iter */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002741 (iternextfunc)listiter_next, /* tp_iternext */
Guido van Rossum86103ae2002-07-16 20:07:32 +00002742 0, /* tp_methods */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002743 0, /* tp_members */
2744 0, /* tp_getset */
2745 0, /* tp_base */
2746 0, /* tp_dict */
2747 0, /* tp_descr_get */
2748 0, /* tp_descr_set */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002749};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002750
2751/*********************** List Reverse Iterator **************************/
2752
2753typedef struct {
2754 PyObject_HEAD
2755 long it_index;
Raymond Hettinger001f2282003-11-08 11:58:44 +00002756 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002757} listreviterobject;
2758
2759PyTypeObject PyListRevIter_Type;
2760
2761static PyObject *
2762list_reversed(PyListObject *seq, PyObject *unused)
2763{
2764 listreviterobject *it;
2765
2766 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2767 if (it == NULL)
2768 return NULL;
2769 assert(PyList_Check(seq));
2770 it->it_index = PyList_GET_SIZE(seq) - 1;
2771 Py_INCREF(seq);
2772 it->it_seq = seq;
2773 PyObject_GC_Track(it);
2774 return (PyObject *)it;
2775}
2776
2777static void
2778listreviter_dealloc(listreviterobject *it)
2779{
2780 PyObject_GC_UnTrack(it);
2781 Py_XDECREF(it->it_seq);
2782 PyObject_GC_Del(it);
2783}
2784
2785static int
2786listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2787{
2788 if (it->it_seq == NULL)
2789 return 0;
2790 return visit((PyObject *)it->it_seq, arg);
2791}
2792
2793static PyObject *
2794listreviter_next(listreviterobject *it)
2795{
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002796 PyObject *item;
2797 long index = it->it_index;
2798 PyListObject *seq = it->it_seq;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002799
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002800 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2801 item = PyList_GET_ITEM(seq, index);
Raymond Hettinger1021c442003-11-07 15:38:09 +00002802 it->it_index--;
2803 Py_INCREF(item);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002804 return item;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002805 }
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002806 it->it_index = -1;
2807 if (seq != NULL) {
2808 it->it_seq = NULL;
2809 Py_DECREF(seq);
2810 }
2811 return NULL;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002812}
2813
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002814static int
2815listreviter_len(listreviterobject *it)
2816{
2817 return it->it_index + 1;
2818}
2819
2820static PySequenceMethods listreviter_as_sequence = {
2821 (inquiry)listreviter_len, /* sq_length */
2822 0, /* sq_concat */
2823};
2824
Raymond Hettinger1021c442003-11-07 15:38:09 +00002825PyTypeObject PyListRevIter_Type = {
2826 PyObject_HEAD_INIT(&PyType_Type)
2827 0, /* ob_size */
2828 "listreverseiterator", /* tp_name */
2829 sizeof(listreviterobject), /* tp_basicsize */
2830 0, /* tp_itemsize */
2831 /* methods */
2832 (destructor)listreviter_dealloc, /* tp_dealloc */
2833 0, /* tp_print */
2834 0, /* tp_getattr */
2835 0, /* tp_setattr */
2836 0, /* tp_compare */
2837 0, /* tp_repr */
2838 0, /* tp_as_number */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002839 &listreviter_as_sequence, /* tp_as_sequence */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002840 0, /* tp_as_mapping */
2841 0, /* tp_hash */
2842 0, /* tp_call */
2843 0, /* tp_str */
2844 PyObject_GenericGetAttr, /* tp_getattro */
2845 0, /* tp_setattro */
2846 0, /* tp_as_buffer */
2847 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2848 0, /* tp_doc */
2849 (traverseproc)listreviter_traverse, /* tp_traverse */
2850 0, /* tp_clear */
2851 0, /* tp_richcompare */
2852 0, /* tp_weaklistoffset */
2853 PyObject_SelfIter, /* tp_iter */
2854 (iternextfunc)listreviter_next, /* tp_iternext */
2855 0,
2856};