blob: 6bb6d8c797351ab6f82d01423bd6654bbc1563d8 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* List object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
4
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00005#ifdef STDC_HEADERS
6#include <stddef.h>
7#else
8#include <sys/types.h> /* For size_t */
9#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000010
Guido van Rossuma46d51d1995-01-26 22:59:43 +000011static int
Raymond Hettinger4bb95402004-02-13 11:36:39 +000012list_resize(PyListObject *self, int newsize)
Guido van Rossuma46d51d1995-01-26 22:59:43 +000013{
Raymond Hettinger4bb95402004-02-13 11:36:39 +000014 PyObject **items;
15 size_t _new_size;
Tim Peters65b8b842001-05-26 05:28:40 +000016
Raymond Hettinger4bb95402004-02-13 11:36:39 +000017 /* Bypass realloc() when a previous overallocation is large enough
18 to accommodate the newsize. If the newsize is 16 smaller than the
19 current size, then proceed with the realloc() to shrink the list.
20 */
21
22 if (self->allocated >= newsize &&
23 self->ob_size < newsize + 16 &&
24 self->ob_item != NULL) {
25 self->ob_size = newsize;
26 return 0;
27 }
28
29 /* This over-allocates proportional to the list size, making room
Tim Peters65b8b842001-05-26 05:28:40 +000030 * for additional growth. The over-allocation is mild, but is
31 * enough to give linear-time amortized behavior over a long
32 * sequence of appends() in the presence of a poorly-performing
Raymond Hettingerab517d22004-02-14 18:34:46 +000033 * system realloc().
34 * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
Tim Peters65b8b842001-05-26 05:28:40 +000035 */
Raymond Hettingerab517d22004-02-14 18:34:46 +000036 _new_size = (newsize >> 3) + (self->ob_size < 8 ? 3 : 6) + newsize;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000037 items = self->ob_item;
38 if (_new_size <= ((~(size_t)0) / sizeof(PyObject *)))
39 PyMem_RESIZE(items, PyObject *, _new_size);
40 else
41 items = NULL;
42 if (items == NULL) {
43 PyErr_NoMemory();
44 return -1;
45 }
46 self->ob_item = items;
47 self->ob_size = newsize;
48 self->allocated = _new_size;
49 return 0;
50}
Guido van Rossuma46d51d1995-01-26 22:59:43 +000051
Guido van Rossumc0b618a1997-05-02 03:12:38 +000052PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +000053PyList_New(int size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000054{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000055 PyListObject *op;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +000056 size_t nbytes;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000057 if (size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000058 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000059 return NULL;
60 }
Tim Peters7049d812004-01-18 20:31:02 +000061 nbytes = size * sizeof(PyObject *);
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000062 /* Check for overflow */
Tim Peters7049d812004-01-18 20:31:02 +000063 if (nbytes / sizeof(PyObject *) != (size_t)size) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000064 return PyErr_NoMemory();
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000065 }
Neil Schemenauere83c00e2001-08-29 23:54:21 +000066 op = PyObject_GC_New(PyListObject, &PyList_Type);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000067 if (op == NULL) {
Neil Schemenauere83c00e2001-08-29 23:54:21 +000068 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000069 }
70 if (size <= 0) {
71 op->ob_item = NULL;
72 }
73 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +000074 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000075 if (op->ob_item == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000076 return PyErr_NoMemory();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000077 }
Tim Peters7049d812004-01-18 20:31:02 +000078 memset(op->ob_item, 0, sizeof(*op->ob_item) * size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000079 }
Neil Schemenauere83c00e2001-08-29 23:54:21 +000080 op->ob_size = size;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000081 op->allocated = size;
Neil Schemenauere83c00e2001-08-29 23:54:21 +000082 _PyObject_GC_TRACK(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +000083 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000084}
85
86int
Fred Drakea2f55112000-07-09 15:16:51 +000087PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000088{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000089 if (!PyList_Check(op)) {
90 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000091 return -1;
92 }
93 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000094 return ((PyListObject *)op) -> ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000095}
96
Guido van Rossumc0b618a1997-05-02 03:12:38 +000097static PyObject *indexerr;
Guido van Rossum929f1b81996-08-09 20:51:27 +000098
Guido van Rossumc0b618a1997-05-02 03:12:38 +000099PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000100PyList_GetItem(PyObject *op, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000101{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000102 if (!PyList_Check(op)) {
103 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000104 return NULL;
105 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000106 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000107 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000108 indexerr = PyString_FromString(
109 "list index out of range");
110 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000111 return NULL;
112 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000113 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000114}
115
116int
Fred Drakea2f55112000-07-09 15:16:51 +0000117PyList_SetItem(register PyObject *op, register int i,
118 register PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000119{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000120 register PyObject *olditem;
121 register PyObject **p;
122 if (!PyList_Check(op)) {
123 Py_XDECREF(newitem);
124 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000125 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000126 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000127 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
128 Py_XDECREF(newitem);
129 PyErr_SetString(PyExc_IndexError,
130 "list assignment index out of range");
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000131 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000132 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000133 p = ((PyListObject *)op) -> ob_item + i;
Guido van Rossum5fe60581995-03-09 12:12:50 +0000134 olditem = *p;
135 *p = newitem;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000136 Py_XDECREF(olditem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000137 return 0;
138}
139
140static int
Fred Drakea2f55112000-07-09 15:16:51 +0000141ins1(PyListObject *self, int where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000142{
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000143 int i, n = self->ob_size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000144 PyObject **items;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000145 if (v == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000146 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000147 return -1;
148 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000149 if (n == INT_MAX) {
Trent Micka5846642000-08-13 22:47:45 +0000150 PyErr_SetString(PyExc_OverflowError,
151 "cannot add more objects to list");
152 return -1;
153 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000154
155 if (list_resize(self, n+1) == -1)
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000156 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000157
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000158 if (where < 0) {
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000159 where += n;
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000160 if (where < 0)
161 where = 0;
162 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000163 if (where > n)
164 where = n;
165 items = self->ob_item;
166 for (i = n; --i >= where; )
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000167 items[i+1] = items[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000168 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000169 items[where] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000170 return 0;
171}
172
173int
Fred Drakea2f55112000-07-09 15:16:51 +0000174PyList_Insert(PyObject *op, int where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000175{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000176 if (!PyList_Check(op)) {
177 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000178 return -1;
179 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000180 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000181}
182
183int
Fred Drakea2f55112000-07-09 15:16:51 +0000184PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000185{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000186 if (!PyList_Check(op)) {
187 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000188 return -1;
189 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000190 return ins1((PyListObject *)op,
191 (int) ((PyListObject *)op)->ob_size, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000192}
193
194/* Methods */
195
196static void
Fred Drakea2f55112000-07-09 15:16:51 +0000197list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000198{
199 int i;
Guido van Rossumff413af2002-03-28 20:34:59 +0000200 PyObject_GC_UnTrack(op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000201 Py_TRASHCAN_SAFE_BEGIN(op)
Jack Jansen7874d1f1995-01-19 12:09:27 +0000202 if (op->ob_item != NULL) {
Guido van Rossumfa717011999-06-09 15:19:34 +0000203 /* Do it backwards, for Christian Tismer.
204 There's a simple test case where somehow this reduces
205 thrashing when a *very* large list is created and
206 immediately deleted. */
207 i = op->ob_size;
208 while (--i >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000209 Py_XDECREF(op->ob_item[i]);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000210 }
Guido van Rossumb18618d2000-05-03 23:44:39 +0000211 PyMem_FREE(op->ob_item);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000212 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000213 op->ob_type->tp_free((PyObject *)op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000214 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000215}
216
Guido van Rossum90933611991-06-07 16:10:43 +0000217static int
Fred Drakea2f55112000-07-09 15:16:51 +0000218list_print(PyListObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000219{
220 int i;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000221
222 i = Py_ReprEnter((PyObject*)op);
223 if (i != 0) {
224 if (i < 0)
225 return i;
226 fprintf(fp, "[...]");
227 return 0;
228 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000229 fprintf(fp, "[");
Guido van Rossum90933611991-06-07 16:10:43 +0000230 for (i = 0; i < op->ob_size; i++) {
231 if (i > 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000232 fprintf(fp, ", ");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000233 if (PyObject_Print(op->ob_item[i], fp, 0) != 0) {
234 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000235 return -1;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000236 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000237 }
238 fprintf(fp, "]");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000239 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000240 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000241}
242
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000243static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000244list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000245{
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000246 int i;
Tim Petersa7259592001-06-16 05:11:17 +0000247 PyObject *s, *temp;
248 PyObject *pieces = NULL, *result = NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000249
250 i = Py_ReprEnter((PyObject*)v);
251 if (i != 0) {
Tim Petersa7259592001-06-16 05:11:17 +0000252 return i > 0 ? PyString_FromString("[...]") : NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000253 }
Tim Petersa7259592001-06-16 05:11:17 +0000254
255 if (v->ob_size == 0) {
256 result = PyString_FromString("[]");
257 goto Done;
258 }
259
260 pieces = PyList_New(0);
261 if (pieces == NULL)
262 goto Done;
263
264 /* Do repr() on each element. Note that this may mutate the list,
265 so must refetch the list size on each iteration. */
266 for (i = 0; i < v->ob_size; ++i) {
267 int status;
268 s = PyObject_Repr(v->ob_item[i]);
269 if (s == NULL)
270 goto Done;
271 status = PyList_Append(pieces, s);
272 Py_DECREF(s); /* append created a new ref */
273 if (status < 0)
274 goto Done;
275 }
276
277 /* Add "[]" decorations to the first and last items. */
278 assert(PyList_GET_SIZE(pieces) > 0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000279 s = PyString_FromString("[");
Tim Petersa7259592001-06-16 05:11:17 +0000280 if (s == NULL)
281 goto Done;
282 temp = PyList_GET_ITEM(pieces, 0);
283 PyString_ConcatAndDel(&s, temp);
284 PyList_SET_ITEM(pieces, 0, s);
285 if (s == NULL)
286 goto Done;
287
288 s = PyString_FromString("]");
289 if (s == NULL)
290 goto Done;
291 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
292 PyString_ConcatAndDel(&temp, s);
293 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
294 if (temp == NULL)
295 goto Done;
296
297 /* Paste them all together with ", " between. */
298 s = PyString_FromString(", ");
299 if (s == NULL)
300 goto Done;
301 result = _PyString_Join(s, pieces);
Tim Peters3b01a122002-07-19 02:35:45 +0000302 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +0000303
304Done:
305 Py_XDECREF(pieces);
Guido van Rossumfb376de1998-04-10 22:47:27 +0000306 Py_ReprLeave((PyObject *)v);
Tim Petersa7259592001-06-16 05:11:17 +0000307 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000308}
309
310static int
Fred Drakea2f55112000-07-09 15:16:51 +0000311list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000312{
313 return a->ob_size;
314}
315
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000316static int
Fred Drakea2f55112000-07-09 15:16:51 +0000317list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000318{
Raymond Hettingeraae59992002-09-05 14:23:49 +0000319 int i, cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000320
Raymond Hettingeraae59992002-09-05 14:23:49 +0000321 for (i = 0, cmp = 0 ; cmp == 0 && i < a->ob_size; ++i)
322 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000323 Py_EQ);
Neal Norwitzbb9c5f52002-09-05 21:32:55 +0000324 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000325}
326
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000327static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000328list_item(PyListObject *a, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000329{
330 if (i < 0 || i >= a->ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000331 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000332 indexerr = PyString_FromString(
333 "list index out of range");
334 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000335 return NULL;
336 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000337 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000338 return a->ob_item[i];
339}
340
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000341static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000342list_slice(PyListObject *a, int ilow, int ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000343{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000344 PyListObject *np;
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000345 PyObject **src, **dest;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000346 int i, len;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000347 if (ilow < 0)
348 ilow = 0;
349 else if (ilow > a->ob_size)
350 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000351 if (ihigh < ilow)
352 ihigh = ilow;
353 else if (ihigh > a->ob_size)
354 ihigh = a->ob_size;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000355 len = ihigh - ilow;
356 np = (PyListObject *) PyList_New(len);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000357 if (np == NULL)
358 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000359
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000360 src = a->ob_item + ilow;
361 dest = np->ob_item;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000362 for (i = 0; i < len; i++) {
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000363 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000364 Py_INCREF(v);
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000365 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000366 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000367 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000368}
369
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000370PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000371PyList_GetSlice(PyObject *a, int ilow, int ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000372{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000373 if (!PyList_Check(a)) {
374 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000375 return NULL;
376 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000377 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000378}
379
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000380static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000381list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000382{
383 int size;
384 int i;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000385 PyObject **src, **dest;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000386 PyListObject *np;
387 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000388 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000389 "can only concatenate list (not \"%.200s\") to list",
390 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000391 return NULL;
392 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000393#define b ((PyListObject *)bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000394 size = a->ob_size + b->ob_size;
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000395 if (size < 0)
396 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000397 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000398 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000399 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000400 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000401 src = a->ob_item;
402 dest = np->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000403 for (i = 0; i < a->ob_size; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000404 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000405 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000406 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000407 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000408 src = b->ob_item;
409 dest = np->ob_item + a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000410 for (i = 0; i < b->ob_size; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000411 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000412 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000413 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000414 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000415 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000416#undef b
417}
418
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000419static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000420list_repeat(PyListObject *a, int n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000421{
422 int i, j;
423 int size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000424 PyListObject *np;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000425 PyObject **p, **items;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000426 PyObject *elem;
Guido van Rossumed98d481991-03-06 13:07:53 +0000427 if (n < 0)
428 n = 0;
429 size = a->ob_size * n;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000430 if (size == 0)
431 return PyList_New(0);
Guido van Rossumbfa5a142002-10-11 23:39:35 +0000432 if (n && size/n != a->ob_size)
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000433 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000434 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000435 if (np == NULL)
436 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000437
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000438 items = np->ob_item;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000439 if (a->ob_size == 1) {
440 elem = a->ob_item[0];
441 for (i = 0; i < n; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000442 items[i] = elem;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000443 Py_INCREF(elem);
444 }
445 return (PyObject *) np;
446 }
Guido van Rossumed98d481991-03-06 13:07:53 +0000447 p = np->ob_item;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000448 items = a->ob_item;
Guido van Rossumed98d481991-03-06 13:07:53 +0000449 for (i = 0; i < n; i++) {
450 for (j = 0; j < a->ob_size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000451 *p = items[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000452 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000453 p++;
454 }
455 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000456 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000457}
458
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000459static int
Fred Drakea2f55112000-07-09 15:16:51 +0000460list_ass_slice(PyListObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000461{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000462 /* Because [X]DECREF can recursively invoke list operations on
463 this list, we must postpone all [X]DECREF activity until
464 after the list is back in its canonical shape. Therefore
465 we must allocate an additional array, 'recycle', into which
466 we temporarily copy the items that are deleted from the
467 list. :-( */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000468 PyObject **recycle, **p;
469 PyObject **item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000470 PyObject **vitem = NULL;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000471 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000472 int n; /* Size of replacement list */
473 int d; /* Change in size */
474 int k; /* Loop index */
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000475 int s;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000476#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000477 if (v == NULL)
478 n = 0;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000479 else {
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000480 if (a == b) {
481 /* Special case "a[i:j] = a" -- copy b first */
482 int ret;
Michael W. Hudsonda0a0672003-08-15 12:06:41 +0000483 v = list_slice(b, 0, b->ob_size);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000484 if (v == NULL)
485 return -1;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000486 ret = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000487 Py_DECREF(v);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000488 return ret;
489 }
Raymond Hettingerf889e102004-03-09 08:04:33 +0000490 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000491 if(v_as_SF == NULL)
492 return -1;
493 n = PySequence_Fast_GET_SIZE(v_as_SF);
Raymond Hettingerf889e102004-03-09 08:04:33 +0000494 if (PyList_Check(v_as_SF))
495 vitem = ((PyListObject *)v_as_SF)->ob_item;
496 else {
497 assert (PyTuple_Check(v_as_SF));
498 vitem = ((PyTupleObject *)v_as_SF)->ob_item;
499 }
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000500 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000501 if (ilow < 0)
502 ilow = 0;
503 else if (ilow > a->ob_size)
504 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000505 if (ihigh < ilow)
506 ihigh = ilow;
507 else if (ihigh > a->ob_size)
508 ihigh = a->ob_size;
509 item = a->ob_item;
510 d = n - (ihigh-ilow);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000511 if (ihigh > ilow) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000512 p = recycle = PyMem_NEW(PyObject *, (ihigh-ilow));
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000513 if (recycle == NULL) {
514 PyErr_NoMemory();
515 return -1;
516 }
517 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000518 else
519 p = recycle = NULL;
520 if (d <= 0) { /* Delete -d items; recycle ihigh-ilow items */
Raymond Hettinger66d31f82004-03-10 11:44:04 +0000521 memcpy(p, &item[ilow], (ihigh - ilow)*sizeof(PyObject *));
Raymond Hettingerf889e102004-03-09 08:04:33 +0000522 p += ihigh - ilow;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000523 if (d < 0) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000524 memmove(&item[ihigh+d], &item[ihigh],
525 (a->ob_size - ihigh)*sizeof(PyObject *));
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000526 list_resize(a, a->ob_size + d);
527 item = a->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000528 }
529 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000530 else { /* Insert d items; recycle ihigh-ilow items */
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000531 s = a->ob_size;
532 if (list_resize(a, s+d) == -1) {
Guido van Rossumb18618d2000-05-03 23:44:39 +0000533 if (recycle != NULL)
534 PyMem_DEL(recycle);
Raymond Hettinger2731ae42004-02-14 03:07:21 +0000535 return -1;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000536 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000537 item = a->ob_item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000538 memmove(&item[ihigh+d], &item[ihigh],
539 (s - ihigh)*sizeof(PyObject *));
Raymond Hettinger66d31f82004-03-10 11:44:04 +0000540 memcpy(p, &item[ilow], (ihigh - ilow)*sizeof(PyObject *));
Raymond Hettingerf889e102004-03-09 08:04:33 +0000541 p += ihigh - ilow;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000542 }
543 for (k = 0; k < n; k++, ilow++) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000544 PyObject *w = vitem[k];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000545 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000546 item[ilow] = w;
547 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000548 if (recycle) {
549 while (--p >= recycle)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000550 Py_XDECREF(*p);
551 PyMem_DEL(recycle);
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000552 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000553 if (a->ob_size == 0 && a->ob_item != NULL) {
554 PyMem_FREE(a->ob_item);
555 a->ob_item = NULL;
556 }
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000557 Py_XDECREF(v_as_SF);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000558 return 0;
559#undef b
560}
561
Guido van Rossum234f9421993-06-17 12:35:49 +0000562int
Fred Drakea2f55112000-07-09 15:16:51 +0000563PyList_SetSlice(PyObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000564{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000565 if (!PyList_Check(a)) {
566 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000567 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000568 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000569 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000570}
571
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000572static PyObject *
573list_inplace_repeat(PyListObject *self, int n)
574{
575 PyObject **items;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000576 int size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000577
578
579 size = PyList_GET_SIZE(self);
580 if (size == 0) {
581 Py_INCREF(self);
582 return (PyObject *)self;
583 }
584
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000585 if (n < 1) {
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000586 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000587 self->ob_item = NULL;
588 self->ob_size = 0;
589 for (i = 0; i < size; i++)
590 Py_XDECREF(items[i]);
591 PyMem_DEL(items);
592 Py_INCREF(self);
593 return (PyObject *)self;
594 }
595
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000596 if (list_resize(self, size*n) == -1)
597 return NULL;
598
599 p = size;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000600 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000601 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
602 for (j = 0; j < size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000603 PyObject *o = items[j];
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000604 Py_INCREF(o);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000605 items[p++] = o;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000606 }
607 }
608 Py_INCREF(self);
609 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000610}
611
Guido van Rossum4a450d01991-04-03 19:05:18 +0000612static int
Fred Drakea2f55112000-07-09 15:16:51 +0000613list_ass_item(PyListObject *a, int i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000614{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000615 PyObject *old_value;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000616 if (i < 0 || i >= a->ob_size) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000617 PyErr_SetString(PyExc_IndexError,
618 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000619 return -1;
620 }
621 if (v == NULL)
622 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000623 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000624 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000625 a->ob_item[i] = v;
Tim Peters3b01a122002-07-19 02:35:45 +0000626 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000627 return 0;
628}
629
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000630static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000631ins(PyListObject *self, int where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000632{
633 if (ins1(self, where, v) != 0)
634 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000635 Py_INCREF(Py_None);
636 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000637}
638
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000639static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000640listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000641{
642 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000643 PyObject *v;
Guido van Rossumc00a9382000-02-24 21:48:29 +0000644 if (!PyArg_ParseTuple(args, "iO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000645 return NULL;
Guido van Rossumbf80e541993-02-08 15:49:17 +0000646 return ins(self, i, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000647}
648
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000649static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000650listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000651{
Guido van Rossumbf80e541993-02-08 15:49:17 +0000652 return ins(self, (int) self->ob_size, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000653}
654
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000655static int
656listextend_internal(PyListObject *self, PyObject *b)
Barry Warsawdedf6d61998-10-09 16:37:25 +0000657{
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000658 register int selflen = PyList_GET_SIZE(self);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000659 int blen;
660 register int i;
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000661 PyObject **src, **dest;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000662
Jeremy Hyltondb60bb52001-01-03 22:32:16 +0000663 if (PyObject_Size(b) == 0) {
Barry Warsawdedf6d61998-10-09 16:37:25 +0000664 /* short circuit when b is empty */
Jeremy Hyltondb60bb52001-01-03 22:32:16 +0000665 Py_DECREF(b);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000666 return 0;
Jeremy Hyltondb60bb52001-01-03 22:32:16 +0000667 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000668
Barry Warsawdedf6d61998-10-09 16:37:25 +0000669 if (self == (PyListObject*)b) {
670 /* as in list_ass_slice() we must special case the
671 * situation: a.extend(a)
672 *
673 * XXX: I think this way ought to be faster than using
674 * list_slice() the way list_ass_slice() does.
675 */
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000676 Py_DECREF(b);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000677 b = PyList_New(selflen);
678 if (!b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000679 return -1;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000680 for (i = 0; i < selflen; i++) {
681 PyObject *o = PyList_GET_ITEM(self, i);
682 Py_INCREF(o);
683 PyList_SET_ITEM(b, i, o);
684 }
685 }
Barry Warsawdedf6d61998-10-09 16:37:25 +0000686
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000687 blen = PyObject_Size(b);
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000688 if (list_resize(self, selflen + blen) == -1) {
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000689 Py_DECREF(b);
690 return -1;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000691 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000692
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000693 /* populate the end of self with b's items */
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000694 if (PyList_Check(b))
695 src = ((PyListObject *)b)->ob_item;
696 else {
Raymond Hettinger99842b62004-03-08 05:56:15 +0000697 assert (PyTuple_Check(b));
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000698 src = ((PyTupleObject *)b)->ob_item;
699 }
700 dest = self->ob_item + selflen;
701 for (i = 0; i < blen; i++) {
702 PyObject *o = src[i];
703 Py_INCREF(o);
704 dest[i] = o;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000705 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000706 Py_DECREF(b);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000707 return 0;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000708}
709
Barry Warsawdedf6d61998-10-09 16:37:25 +0000710static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000711listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000712{
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000713 PyObject *it; /* iter(v) */
714 int m; /* size of self */
715 int n; /* guess for size of b */
716 int mn; /* m + n */
717 int i;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000718
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000719 /* Special cases:
720 1) lists and tuples which can use PySequence_Fast ops
721 2) extending self to self requires making a copy first
722 */
723 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
724 b = PySequence_Fast(b, "argument must be iterable");
725 if (!b)
726 return NULL;
727 if (listextend_internal(self, b) < 0)
728 return NULL;
729 Py_RETURN_NONE;
730 }
731
732 it = PyObject_GetIter(b);
733 if (it == NULL)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000734 return NULL;
735
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000736 /* Guess a result list size. */
737 n = PyObject_Size(b);
738 if (n < 0) {
739 PyErr_Clear();
740 n = 8; /* arbitrary */
741 }
742 m = self->ob_size;
743 mn = m + n;
744 if (list_resize(self, mn) == -1)
745 goto error;
746 memset(&(self->ob_item[m]), 0, sizeof(*self->ob_item) * n);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000747
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000748 /* Run iterator to exhaustion. */
749 for (i = m; ; i++) {
750 PyObject *item = PyIter_Next(it);
751 if (item == NULL) {
752 if (PyErr_Occurred())
753 goto error;
754 break;
755 }
756 if (i < mn)
757 PyList_SET_ITEM(self, i, item); /* steals ref */
758 else {
759 int status = ins1(self, self->ob_size, item);
760 Py_DECREF(item); /* append creates a new ref */
761 if (status < 0)
762 goto error;
763 }
764 }
765
766 /* Cut back result list if initial guess was too large. */
767 if (i < mn && self != NULL) {
768 if (list_ass_slice(self, i, mn, (PyObject *)NULL) != 0)
769 goto error;
770 }
771 Py_DECREF(it);
772 Py_RETURN_NONE;
773
774 error:
775 Py_DECREF(it);
776 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000777}
778
779static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000780list_inplace_concat(PyListObject *self, PyObject *other)
781{
782 PyObject *result;
783
784 result = listextend(self, other);
785 if (result == NULL)
786 return result;
787 Py_DECREF(result);
788 Py_INCREF(self);
789 return (PyObject *)self;
790}
791
792static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000793listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000794{
795 int i = -1;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000796 PyObject *v, *arg = NULL;
797
798 if (!PyArg_UnpackTuple(args, "pop", 0, 1, &arg))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000799 return NULL;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000800 if (arg != NULL) {
801 if (PyInt_Check(arg))
802 i = (int)(PyInt_AS_LONG((PyIntObject*) arg));
Raymond Hettingerfa6c6f82004-02-19 06:12:06 +0000803 else if (!PyArg_ParseTuple(args, "|i:pop", &i))
804 return NULL;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000805 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000806 if (self->ob_size == 0) {
807 /* Special-case most common failure cause */
808 PyErr_SetString(PyExc_IndexError, "pop from empty list");
809 return NULL;
810 }
811 if (i < 0)
812 i += self->ob_size;
813 if (i < 0 || i >= self->ob_size) {
814 PyErr_SetString(PyExc_IndexError, "pop index out of range");
815 return NULL;
816 }
817 v = self->ob_item[i];
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000818 if (i == self->ob_size - 1) {
819 if (list_resize(self, self->ob_size - 1) == -1)
820 return NULL;
821 return v;
822 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000823 Py_INCREF(v);
824 if (list_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) {
825 Py_DECREF(v);
826 return NULL;
827 }
828 return v;
829}
830
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000831/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
832static void
833reverse_slice(PyObject **lo, PyObject **hi)
834{
835 assert(lo && hi);
836
837 --hi;
838 while (lo < hi) {
839 PyObject *t = *lo;
840 *lo = *hi;
841 *hi = t;
842 ++lo;
843 --hi;
844 }
845}
846
Tim Petersa64dc242002-08-01 02:13:36 +0000847/* Lots of code for an adaptive, stable, natural mergesort. There are many
848 * pieces to this algorithm; read listsort.txt for overviews and details.
849 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000850
Guido van Rossum3f236de1996-12-10 23:55:39 +0000851/* Comparison function. Takes care of calling a user-supplied
Tim Peters66860f62002-08-04 17:47:26 +0000852 * comparison function (any callable Python object), which must not be
853 * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool
854 * with Py_LT if you know it's NULL).
Tim Petersa64dc242002-08-01 02:13:36 +0000855 * Returns -1 on error, 1 if x < y, 0 if x >= y.
856 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000857static int
Tim Petersa8c974c2002-07-19 03:30:57 +0000858islt(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000859{
Tim Petersf2a04732002-07-11 21:46:16 +0000860 PyObject *res;
861 PyObject *args;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000862 int i;
863
Tim Peters66860f62002-08-04 17:47:26 +0000864 assert(compare != NULL);
Tim Petersa8c974c2002-07-19 03:30:57 +0000865 /* Call the user's comparison function and translate the 3-way
866 * result into true or false (or error).
867 */
Tim Petersf2a04732002-07-11 21:46:16 +0000868 args = PyTuple_New(2);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000869 if (args == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000870 return -1;
Tim Petersf2a04732002-07-11 21:46:16 +0000871 Py_INCREF(x);
872 Py_INCREF(y);
873 PyTuple_SET_ITEM(args, 0, x);
874 PyTuple_SET_ITEM(args, 1, y);
Tim Peters58cf3612002-07-15 05:16:13 +0000875 res = PyObject_Call(compare, args, NULL);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000876 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000877 if (res == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000878 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000879 if (!PyInt_Check(res)) {
880 Py_DECREF(res);
881 PyErr_SetString(PyExc_TypeError,
Guido van Rossum9bcd1d71999-04-19 17:44:39 +0000882 "comparison function must return int");
Tim Petersa8c974c2002-07-19 03:30:57 +0000883 return -1;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000884 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000885 i = PyInt_AsLong(res);
886 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +0000887 return i < 0;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000888}
889
Tim Peters66860f62002-08-04 17:47:26 +0000890/* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
891 * islt. This avoids a layer of function call in the usual case, and
892 * sorting does many comparisons.
893 * Returns -1 on error, 1 if x < y, 0 if x >= y.
894 */
895#define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
896 PyObject_RichCompareBool(X, Y, Py_LT) : \
897 islt(X, Y, COMPARE))
898
899/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +0000900 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
901 started. It makes more sense in context <wink>. X and Y are PyObject*s.
902*/
Tim Peters66860f62002-08-04 17:47:26 +0000903#define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
Tim Petersa8c974c2002-07-19 03:30:57 +0000904 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000905
906/* binarysort is the best method for sorting small arrays: it does
907 few compares, but can do data movement quadratic in the number of
908 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000909 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +0000910 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000911 On entry, must have lo <= start <= hi, and that [lo, start) is already
912 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +0000913 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000914 Even in case of error, the output slice will be some permutation of
915 the input (nothing is lost or duplicated).
916*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000917static int
Fred Drakea2f55112000-07-09 15:16:51 +0000918binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
919 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000920{
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000921 register int k;
922 register PyObject **l, **p, **r;
923 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000924
Tim Petersa8c974c2002-07-19 03:30:57 +0000925 assert(lo <= start && start <= hi);
926 /* assert [lo, start) is sorted */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000927 if (lo == start)
928 ++start;
929 for (; start < hi; ++start) {
930 /* set l to where *start belongs */
931 l = lo;
932 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000933 pivot = *r;
Tim Peters0fe977c2002-07-19 06:12:32 +0000934 /* Invariants:
935 * pivot >= all in [lo, l).
936 * pivot < all in [r, start).
937 * The second is vacuously true at the start.
938 */
939 assert(l < r);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000940 do {
941 p = l + ((r - l) >> 1);
Tim Petersa8c974c2002-07-19 03:30:57 +0000942 IFLT(pivot, *p)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000943 r = p;
944 else
Tim Peters0fe977c2002-07-19 06:12:32 +0000945 l = p+1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000946 } while (l < r);
Tim Peters0fe977c2002-07-19 06:12:32 +0000947 assert(l == r);
948 /* The invariants still hold, so pivot >= all in [lo, l) and
949 pivot < all in [l, start), so pivot belongs at l. Note
950 that if there are elements equal to pivot, l points to the
951 first slot after them -- that's why this sort is stable.
952 Slide over to make room.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000953 Caution: using memmove is much slower under MSVC 5;
954 we're not usually moving many slots. */
955 for (p = start; p > l; --p)
956 *p = *(p-1);
957 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000958 }
Guido van Rossum3f236de1996-12-10 23:55:39 +0000959 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000960
961 fail:
962 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000963}
964
Tim Petersa64dc242002-08-01 02:13:36 +0000965/*
966Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
967is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000968
Tim Petersa64dc242002-08-01 02:13:36 +0000969 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000970
Tim Petersa64dc242002-08-01 02:13:36 +0000971or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000972
Tim Petersa64dc242002-08-01 02:13:36 +0000973 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +0000974
Tim Petersa64dc242002-08-01 02:13:36 +0000975Boolean *descending is set to 0 in the former case, or to 1 in the latter.
976For its intended use in a stable mergesort, the strictness of the defn of
977"descending" is needed so that the caller can safely reverse a descending
978sequence without violating stability (strict > ensures there are no equal
979elements to get out of order).
980
981Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000982*/
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000983static int
Tim Petersa64dc242002-08-01 02:13:36 +0000984count_run(PyObject **lo, PyObject **hi, PyObject *compare, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000985{
Tim Petersa64dc242002-08-01 02:13:36 +0000986 int k;
987 int n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000988
Tim Petersa64dc242002-08-01 02:13:36 +0000989 assert(lo < hi);
990 *descending = 0;
991 ++lo;
992 if (lo == hi)
993 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000994
Tim Petersa64dc242002-08-01 02:13:36 +0000995 n = 2;
996 IFLT(*lo, *(lo-1)) {
997 *descending = 1;
998 for (lo = lo+1; lo < hi; ++lo, ++n) {
999 IFLT(*lo, *(lo-1))
1000 ;
1001 else
1002 break;
1003 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001004 }
Tim Petersa64dc242002-08-01 02:13:36 +00001005 else {
1006 for (lo = lo+1; lo < hi; ++lo, ++n) {
1007 IFLT(*lo, *(lo-1))
1008 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001009 }
1010 }
1011
Tim Petersa64dc242002-08-01 02:13:36 +00001012 return n;
1013fail:
1014 return -1;
1015}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001016
Tim Petersa64dc242002-08-01 02:13:36 +00001017/*
1018Locate the proper position of key in a sorted vector; if the vector contains
1019an element equal to key, return the position immediately to the left of
1020the leftmost equal element. [gallop_right() does the same except returns
1021the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001022
Tim Petersa64dc242002-08-01 02:13:36 +00001023"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001024
Tim Petersa64dc242002-08-01 02:13:36 +00001025"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1026hint is to the final result, the faster this runs.
1027
1028The return value is the int k in 0..n such that
1029
1030 a[k-1] < key <= a[k]
1031
1032pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1033key belongs at index k; or, IOW, the first k elements of a should precede
1034key, and the last n-k should follow key.
1035
1036Returns -1 on error. See listsort.txt for info on the method.
1037*/
1038static int
1039gallop_left(PyObject *key, PyObject **a, int n, int hint, PyObject *compare)
1040{
1041 int ofs;
1042 int lastofs;
1043 int k;
1044
1045 assert(key && a && n > 0 && hint >= 0 && hint < n);
1046
1047 a += hint;
1048 lastofs = 0;
1049 ofs = 1;
1050 IFLT(*a, key) {
1051 /* a[hint] < key -- gallop right, until
1052 * a[hint + lastofs] < key <= a[hint + ofs]
1053 */
1054 const int maxofs = n - hint; /* &a[n-1] is highest */
1055 while (ofs < maxofs) {
1056 IFLT(a[ofs], key) {
1057 lastofs = ofs;
1058 ofs = (ofs << 1) + 1;
1059 if (ofs <= 0) /* int overflow */
1060 ofs = maxofs;
1061 }
1062 else /* key <= a[hint + ofs] */
1063 break;
1064 }
1065 if (ofs > maxofs)
1066 ofs = maxofs;
1067 /* Translate back to offsets relative to &a[0]. */
1068 lastofs += hint;
1069 ofs += hint;
1070 }
1071 else {
1072 /* key <= a[hint] -- gallop left, until
1073 * a[hint - ofs] < key <= a[hint - lastofs]
1074 */
1075 const int maxofs = hint + 1; /* &a[0] is lowest */
1076 while (ofs < maxofs) {
1077 IFLT(*(a-ofs), key)
1078 break;
1079 /* key <= a[hint - ofs] */
1080 lastofs = ofs;
1081 ofs = (ofs << 1) + 1;
1082 if (ofs <= 0) /* int overflow */
1083 ofs = maxofs;
1084 }
1085 if (ofs > maxofs)
1086 ofs = maxofs;
1087 /* Translate back to positive offsets relative to &a[0]. */
1088 k = lastofs;
1089 lastofs = hint - ofs;
1090 ofs = hint - k;
1091 }
1092 a -= hint;
1093
1094 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1095 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1096 * right of lastofs but no farther right than ofs. Do a binary
1097 * search, with invariant a[lastofs-1] < key <= a[ofs].
1098 */
1099 ++lastofs;
1100 while (lastofs < ofs) {
1101 int m = lastofs + ((ofs - lastofs) >> 1);
1102
1103 IFLT(a[m], key)
1104 lastofs = m+1; /* a[m] < key */
1105 else
1106 ofs = m; /* key <= a[m] */
1107 }
1108 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1109 return ofs;
1110
1111fail:
1112 return -1;
1113}
1114
1115/*
1116Exactly like gallop_left(), except that if key already exists in a[0:n],
1117finds the position immediately to the right of the rightmost equal value.
1118
1119The return value is the int k in 0..n such that
1120
1121 a[k-1] <= key < a[k]
1122
1123or -1 if error.
1124
1125The code duplication is massive, but this is enough different given that
1126we're sticking to "<" comparisons that it's much harder to follow if
1127written as one routine with yet another "left or right?" flag.
1128*/
1129static int
1130gallop_right(PyObject *key, PyObject **a, int n, int hint, PyObject *compare)
1131{
1132 int ofs;
1133 int lastofs;
1134 int k;
1135
1136 assert(key && a && n > 0 && hint >= 0 && hint < n);
1137
1138 a += hint;
1139 lastofs = 0;
1140 ofs = 1;
1141 IFLT(key, *a) {
1142 /* key < a[hint] -- gallop left, until
1143 * a[hint - ofs] <= key < a[hint - lastofs]
1144 */
1145 const int maxofs = hint + 1; /* &a[0] is lowest */
1146 while (ofs < maxofs) {
1147 IFLT(key, *(a-ofs)) {
1148 lastofs = ofs;
1149 ofs = (ofs << 1) + 1;
1150 if (ofs <= 0) /* int overflow */
1151 ofs = maxofs;
1152 }
1153 else /* a[hint - ofs] <= key */
1154 break;
1155 }
1156 if (ofs > maxofs)
1157 ofs = maxofs;
1158 /* Translate back to positive offsets relative to &a[0]. */
1159 k = lastofs;
1160 lastofs = hint - ofs;
1161 ofs = hint - k;
1162 }
1163 else {
1164 /* a[hint] <= key -- gallop right, until
1165 * a[hint + lastofs] <= key < a[hint + ofs]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001166 */
Tim Petersa64dc242002-08-01 02:13:36 +00001167 const int maxofs = n - hint; /* &a[n-1] is highest */
1168 while (ofs < maxofs) {
1169 IFLT(key, a[ofs])
1170 break;
1171 /* a[hint + ofs] <= key */
1172 lastofs = ofs;
1173 ofs = (ofs << 1) + 1;
1174 if (ofs <= 0) /* int overflow */
1175 ofs = maxofs;
1176 }
1177 if (ofs > maxofs)
1178 ofs = maxofs;
1179 /* Translate back to offsets relative to &a[0]. */
1180 lastofs += hint;
1181 ofs += hint;
1182 }
1183 a -= hint;
1184
1185 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1186 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1187 * right of lastofs but no farther right than ofs. Do a binary
1188 * search, with invariant a[lastofs-1] <= key < a[ofs].
1189 */
1190 ++lastofs;
1191 while (lastofs < ofs) {
1192 int m = lastofs + ((ofs - lastofs) >> 1);
1193
1194 IFLT(key, a[m])
1195 ofs = m; /* key < a[m] */
1196 else
1197 lastofs = m+1; /* a[m] <= key */
1198 }
1199 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1200 return ofs;
1201
1202fail:
1203 return -1;
1204}
1205
1206/* The maximum number of entries in a MergeState's pending-runs stack.
1207 * This is enough to sort arrays of size up to about
1208 * 32 * phi ** MAX_MERGE_PENDING
1209 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1210 * with 2**64 elements.
1211 */
1212#define MAX_MERGE_PENDING 85
1213
Tim Peterse05f65a2002-08-10 05:21:15 +00001214/* When we get into galloping mode, we stay there until both runs win less
1215 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001216 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001217#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001218
1219/* Avoid malloc for small temp arrays. */
1220#define MERGESTATE_TEMP_SIZE 256
1221
1222/* One MergeState exists on the stack per invocation of mergesort. It's just
1223 * a convenient way to pass state around among the helper functions.
1224 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001225struct s_slice {
1226 PyObject **base;
1227 int len;
1228};
1229
Tim Petersa64dc242002-08-01 02:13:36 +00001230typedef struct s_MergeState {
1231 /* The user-supplied comparison function. or NULL if none given. */
1232 PyObject *compare;
1233
Tim Peterse05f65a2002-08-10 05:21:15 +00001234 /* This controls when we get *into* galloping mode. It's initialized
1235 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1236 * random data, and lower for highly structured data.
1237 */
1238 int min_gallop;
1239
Tim Petersa64dc242002-08-01 02:13:36 +00001240 /* 'a' is temp storage to help with merges. It contains room for
1241 * alloced entries.
1242 */
1243 PyObject **a; /* may point to temparray below */
1244 int alloced;
1245
1246 /* A stack of n pending runs yet to be merged. Run #i starts at
1247 * address base[i] and extends for len[i] elements. It's always
1248 * true (so long as the indices are in bounds) that
1249 *
Tim Peterse05f65a2002-08-10 05:21:15 +00001250 * pending[i].base + pending[i].len == pending[i+1].base
Tim Petersa64dc242002-08-01 02:13:36 +00001251 *
1252 * so we could cut the storage for this, but it's a minor amount,
1253 * and keeping all the info explicit simplifies the code.
1254 */
1255 int n;
Tim Peterse05f65a2002-08-10 05:21:15 +00001256 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001257
1258 /* 'a' points to this when possible, rather than muck with malloc. */
1259 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1260} MergeState;
1261
1262/* Conceptually a MergeState's constructor. */
1263static void
1264merge_init(MergeState *ms, PyObject *compare)
1265{
1266 assert(ms != NULL);
1267 ms->compare = compare;
1268 ms->a = ms->temparray;
1269 ms->alloced = MERGESTATE_TEMP_SIZE;
1270 ms->n = 0;
Tim Peterse05f65a2002-08-10 05:21:15 +00001271 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001272}
1273
1274/* Free all the temp memory owned by the MergeState. This must be called
1275 * when you're done with a MergeState, and may be called before then if
1276 * you want to free the temp memory early.
1277 */
1278static void
1279merge_freemem(MergeState *ms)
1280{
1281 assert(ms != NULL);
1282 if (ms->a != ms->temparray)
1283 PyMem_Free(ms->a);
1284 ms->a = ms->temparray;
1285 ms->alloced = MERGESTATE_TEMP_SIZE;
1286}
1287
1288/* Ensure enough temp memory for 'need' array slots is available.
1289 * Returns 0 on success and -1 if the memory can't be gotten.
1290 */
1291static int
1292merge_getmem(MergeState *ms, int need)
1293{
1294 assert(ms != NULL);
1295 if (need <= ms->alloced)
1296 return 0;
1297 /* Don't realloc! That can cost cycles to copy the old data, but
1298 * we don't care what's in the block.
1299 */
1300 merge_freemem(ms);
1301 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1302 if (ms->a) {
1303 ms->alloced = need;
1304 return 0;
1305 }
1306 PyErr_NoMemory();
1307 merge_freemem(ms); /* reset to sane state */
1308 return -1;
1309}
1310#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1311 merge_getmem(MS, NEED))
1312
1313/* Merge the na elements starting at pa with the nb elements starting at pb
1314 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1315 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1316 * merge, and should have na <= nb. See listsort.txt for more info.
1317 * Return 0 if successful, -1 if error.
1318 */
1319static int
1320merge_lo(MergeState *ms, PyObject **pa, int na, PyObject **pb, int nb)
1321{
1322 int k;
1323 PyObject *compare;
1324 PyObject **dest;
1325 int result = -1; /* guilty until proved innocent */
Tim Peterse05f65a2002-08-10 05:21:15 +00001326 int min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001327
1328 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1329 if (MERGE_GETMEM(ms, na) < 0)
1330 return -1;
1331 memcpy(ms->a, pa, na * sizeof(PyObject*));
1332 dest = pa;
1333 pa = ms->a;
1334
1335 *dest++ = *pb++;
1336 --nb;
1337 if (nb == 0)
1338 goto Succeed;
1339 if (na == 1)
1340 goto CopyB;
1341
1342 compare = ms->compare;
1343 for (;;) {
1344 int acount = 0; /* # of times A won in a row */
1345 int bcount = 0; /* # of times B won in a row */
1346
1347 /* Do the straightforward thing until (if ever) one run
1348 * appears to win consistently.
1349 */
1350 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001351 assert(na > 1 && nb > 0);
Tim Peters66860f62002-08-04 17:47:26 +00001352 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001353 if (k) {
1354 if (k < 0)
1355 goto Fail;
1356 *dest++ = *pb++;
1357 ++bcount;
1358 acount = 0;
1359 --nb;
1360 if (nb == 0)
1361 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001362 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001363 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001364 }
1365 else {
Tim Petersa64dc242002-08-01 02:13:36 +00001366 *dest++ = *pa++;
1367 ++acount;
1368 bcount = 0;
1369 --na;
1370 if (na == 1)
1371 goto CopyB;
Tim Peterse05f65a2002-08-10 05:21:15 +00001372 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001373 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001374 }
Tim Petersa64dc242002-08-01 02:13:36 +00001375 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001376
Tim Petersa64dc242002-08-01 02:13:36 +00001377 /* One run is winning so consistently that galloping may
1378 * be a huge win. So try that, and continue galloping until
1379 * (if ever) neither run appears to be winning consistently
1380 * anymore.
1381 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001382 ++min_gallop;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001383 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001384 assert(na > 1 && nb > 0);
1385 min_gallop -= min_gallop > 1;
1386 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001387 k = gallop_right(*pb, pa, na, 0, compare);
1388 acount = k;
1389 if (k) {
1390 if (k < 0)
1391 goto Fail;
1392 memcpy(dest, pa, k * sizeof(PyObject *));
1393 dest += k;
1394 pa += k;
1395 na -= k;
1396 if (na == 1)
1397 goto CopyB;
1398 /* na==0 is impossible now if the comparison
1399 * function is consistent, but we can't assume
1400 * that it is.
1401 */
1402 if (na == 0)
1403 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001404 }
Tim Petersa64dc242002-08-01 02:13:36 +00001405 *dest++ = *pb++;
1406 --nb;
1407 if (nb == 0)
1408 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001409
Tim Petersa64dc242002-08-01 02:13:36 +00001410 k = gallop_left(*pa, pb, nb, 0, compare);
1411 bcount = k;
1412 if (k) {
1413 if (k < 0)
1414 goto Fail;
1415 memmove(dest, pb, k * sizeof(PyObject *));
1416 dest += k;
1417 pb += k;
1418 nb -= k;
1419 if (nb == 0)
1420 goto Succeed;
1421 }
1422 *dest++ = *pa++;
1423 --na;
1424 if (na == 1)
1425 goto CopyB;
1426 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001427 ++min_gallop; /* penalize it for leaving galloping mode */
1428 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001429 }
1430Succeed:
1431 result = 0;
1432Fail:
1433 if (na)
1434 memcpy(dest, pa, na * sizeof(PyObject*));
1435 return result;
1436CopyB:
1437 assert(na == 1 && nb > 0);
1438 /* The last element of pa belongs at the end of the merge. */
1439 memmove(dest, pb, nb * sizeof(PyObject *));
1440 dest[nb] = *pa;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001441 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001442}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001443
Tim Petersa64dc242002-08-01 02:13:36 +00001444/* Merge the na elements starting at pa with the nb elements starting at pb
1445 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1446 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1447 * merge, and should have na >= nb. See listsort.txt for more info.
1448 * Return 0 if successful, -1 if error.
1449 */
1450static int
1451merge_hi(MergeState *ms, PyObject **pa, int na, PyObject **pb, int nb)
1452{
1453 int k;
1454 PyObject *compare;
1455 PyObject **dest;
1456 int result = -1; /* guilty until proved innocent */
1457 PyObject **basea;
1458 PyObject **baseb;
Tim Peterse05f65a2002-08-10 05:21:15 +00001459 int min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001460
1461 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1462 if (MERGE_GETMEM(ms, nb) < 0)
1463 return -1;
1464 dest = pb + nb - 1;
1465 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1466 basea = pa;
1467 baseb = ms->a;
1468 pb = ms->a + nb - 1;
1469 pa += na - 1;
1470
1471 *dest-- = *pa--;
1472 --na;
1473 if (na == 0)
1474 goto Succeed;
1475 if (nb == 1)
1476 goto CopyA;
1477
1478 compare = ms->compare;
1479 for (;;) {
1480 int acount = 0; /* # of times A won in a row */
1481 int bcount = 0; /* # of times B won in a row */
1482
1483 /* Do the straightforward thing until (if ever) one run
1484 * appears to win consistently.
1485 */
1486 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001487 assert(na > 0 && nb > 1);
Tim Peters66860f62002-08-04 17:47:26 +00001488 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001489 if (k) {
1490 if (k < 0)
1491 goto Fail;
1492 *dest-- = *pa--;
1493 ++acount;
1494 bcount = 0;
1495 --na;
1496 if (na == 0)
1497 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001498 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001499 break;
1500 }
1501 else {
1502 *dest-- = *pb--;
1503 ++bcount;
1504 acount = 0;
1505 --nb;
1506 if (nb == 1)
1507 goto CopyA;
Tim Peterse05f65a2002-08-10 05:21:15 +00001508 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001509 break;
1510 }
1511 }
1512
1513 /* One run is winning so consistently that galloping may
1514 * be a huge win. So try that, and continue galloping until
1515 * (if ever) neither run appears to be winning consistently
1516 * anymore.
1517 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001518 ++min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001519 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001520 assert(na > 0 && nb > 1);
1521 min_gallop -= min_gallop > 1;
1522 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001523 k = gallop_right(*pb, basea, na, na-1, compare);
1524 if (k < 0)
1525 goto Fail;
1526 k = na - k;
1527 acount = k;
1528 if (k) {
1529 dest -= k;
1530 pa -= k;
1531 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1532 na -= k;
1533 if (na == 0)
1534 goto Succeed;
1535 }
1536 *dest-- = *pb--;
1537 --nb;
1538 if (nb == 1)
1539 goto CopyA;
1540
1541 k = gallop_left(*pa, baseb, nb, nb-1, compare);
1542 if (k < 0)
1543 goto Fail;
1544 k = nb - k;
1545 bcount = k;
1546 if (k) {
1547 dest -= k;
1548 pb -= k;
1549 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1550 nb -= k;
1551 if (nb == 1)
1552 goto CopyA;
1553 /* nb==0 is impossible now if the comparison
1554 * function is consistent, but we can't assume
1555 * that it is.
1556 */
1557 if (nb == 0)
1558 goto Succeed;
1559 }
1560 *dest-- = *pa--;
1561 --na;
1562 if (na == 0)
1563 goto Succeed;
1564 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001565 ++min_gallop; /* penalize it for leaving galloping mode */
1566 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001567 }
1568Succeed:
1569 result = 0;
1570Fail:
1571 if (nb)
1572 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1573 return result;
1574CopyA:
1575 assert(nb == 1 && na > 0);
1576 /* The first element of pb belongs at the front of the merge. */
1577 dest -= na;
1578 pa -= na;
1579 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1580 *dest = *pb;
1581 return 0;
1582}
1583
1584/* Merge the two runs at stack indices i and i+1.
1585 * Returns 0 on success, -1 on error.
1586 */
1587static int
1588merge_at(MergeState *ms, int i)
1589{
1590 PyObject **pa, **pb;
1591 int na, nb;
1592 int k;
1593 PyObject *compare;
1594
1595 assert(ms != NULL);
1596 assert(ms->n >= 2);
1597 assert(i >= 0);
1598 assert(i == ms->n - 2 || i == ms->n - 3);
1599
Tim Peterse05f65a2002-08-10 05:21:15 +00001600 pa = ms->pending[i].base;
1601 na = ms->pending[i].len;
1602 pb = ms->pending[i+1].base;
1603 nb = ms->pending[i+1].len;
Tim Petersa64dc242002-08-01 02:13:36 +00001604 assert(na > 0 && nb > 0);
1605 assert(pa + na == pb);
1606
1607 /* Record the length of the combined runs; if i is the 3rd-last
1608 * run now, also slide over the last run (which isn't involved
1609 * in this merge). The current run i+1 goes away in any case.
1610 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001611 ms->pending[i].len = na + nb;
1612 if (i == ms->n - 3)
1613 ms->pending[i+1] = ms->pending[i+2];
Tim Petersa64dc242002-08-01 02:13:36 +00001614 --ms->n;
1615
1616 /* Where does b start in a? Elements in a before that can be
1617 * ignored (already in place).
1618 */
1619 compare = ms->compare;
1620 k = gallop_right(*pb, pa, na, 0, compare);
1621 if (k < 0)
1622 return -1;
1623 pa += k;
1624 na -= k;
1625 if (na == 0)
1626 return 0;
1627
1628 /* Where does a end in b? Elements in b after that can be
1629 * ignored (already in place).
1630 */
1631 nb = gallop_left(pa[na-1], pb, nb, nb-1, compare);
1632 if (nb <= 0)
1633 return nb;
1634
1635 /* Merge what remains of the runs, using a temp array with
1636 * min(na, nb) elements.
1637 */
1638 if (na <= nb)
1639 return merge_lo(ms, pa, na, pb, nb);
1640 else
1641 return merge_hi(ms, pa, na, pb, nb);
1642}
1643
1644/* Examine the stack of runs waiting to be merged, merging adjacent runs
1645 * until the stack invariants are re-established:
1646 *
1647 * 1. len[-3] > len[-2] + len[-1]
1648 * 2. len[-2] > len[-1]
1649 *
1650 * See listsort.txt for more info.
1651 *
1652 * Returns 0 on success, -1 on error.
1653 */
1654static int
1655merge_collapse(MergeState *ms)
1656{
Tim Peterse05f65a2002-08-10 05:21:15 +00001657 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001658
1659 assert(ms);
1660 while (ms->n > 1) {
1661 int n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001662 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1663 if (p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001664 --n;
1665 if (merge_at(ms, n) < 0)
1666 return -1;
1667 }
Tim Peterse05f65a2002-08-10 05:21:15 +00001668 else if (p[n].len <= p[n+1].len) {
Tim Petersa64dc242002-08-01 02:13:36 +00001669 if (merge_at(ms, n) < 0)
1670 return -1;
1671 }
1672 else
1673 break;
1674 }
1675 return 0;
1676}
1677
1678/* Regardless of invariants, merge all runs on the stack until only one
1679 * remains. This is used at the end of the mergesort.
1680 *
1681 * Returns 0 on success, -1 on error.
1682 */
1683static int
1684merge_force_collapse(MergeState *ms)
1685{
Tim Peterse05f65a2002-08-10 05:21:15 +00001686 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001687
1688 assert(ms);
1689 while (ms->n > 1) {
1690 int n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001691 if (n > 0 && p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001692 --n;
1693 if (merge_at(ms, n) < 0)
1694 return -1;
1695 }
1696 return 0;
1697}
1698
1699/* Compute a good value for the minimum run length; natural runs shorter
1700 * than this are boosted artificially via binary insertion.
1701 *
1702 * If n < 64, return n (it's too small to bother with fancy stuff).
1703 * Else if n is an exact power of 2, return 32.
1704 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1705 * strictly less than, an exact power of 2.
1706 *
1707 * See listsort.txt for more info.
1708 */
1709static int
1710merge_compute_minrun(int n)
1711{
1712 int r = 0; /* becomes 1 if any 1 bits are shifted off */
1713
1714 assert(n >= 0);
1715 while (n >= 64) {
1716 r |= n & 1;
1717 n >>= 1;
1718 }
1719 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001720}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001721
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001722/* Special wrapper to support stable sorting using the decorate-sort-undecorate
1723 pattern. Holds a key which is used for comparisions and the original record
1724 which is returned during the undecorate phase. By exposing only the key
1725 during comparisons, the underlying sort stability characteristics are left
1726 unchanged. Also, if a custom comparison function is used, it will only see
1727 the key instead of a full record. */
1728
1729typedef struct {
1730 PyObject_HEAD
1731 PyObject *key;
1732 PyObject *value;
1733} sortwrapperobject;
1734
1735static PyTypeObject sortwrapper_type;
1736
1737static PyObject *
1738sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
1739{
1740 if (!PyObject_TypeCheck(b, &sortwrapper_type)) {
1741 PyErr_SetString(PyExc_TypeError,
1742 "expected a sortwrapperobject");
1743 return NULL;
1744 }
1745 return PyObject_RichCompare(a->key, b->key, op);
1746}
1747
1748static void
1749sortwrapper_dealloc(sortwrapperobject *so)
1750{
1751 Py_XDECREF(so->key);
1752 Py_XDECREF(so->value);
1753 PyObject_Del(so);
1754}
1755
1756PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
1757
1758static PyTypeObject sortwrapper_type = {
1759 PyObject_HEAD_INIT(&PyType_Type)
1760 0, /* ob_size */
1761 "sortwrapper", /* tp_name */
1762 sizeof(sortwrapperobject), /* tp_basicsize */
1763 0, /* tp_itemsize */
1764 /* methods */
1765 (destructor)sortwrapper_dealloc, /* tp_dealloc */
1766 0, /* tp_print */
1767 0, /* tp_getattr */
1768 0, /* tp_setattr */
1769 0, /* tp_compare */
1770 0, /* tp_repr */
1771 0, /* tp_as_number */
1772 0, /* tp_as_sequence */
1773 0, /* tp_as_mapping */
1774 0, /* tp_hash */
1775 0, /* tp_call */
1776 0, /* tp_str */
1777 PyObject_GenericGetAttr, /* tp_getattro */
1778 0, /* tp_setattro */
1779 0, /* tp_as_buffer */
1780 Py_TPFLAGS_DEFAULT |
1781 Py_TPFLAGS_HAVE_RICHCOMPARE, /* tp_flags */
1782 sortwrapper_doc, /* tp_doc */
1783 0, /* tp_traverse */
1784 0, /* tp_clear */
1785 (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
1786};
1787
1788/* Returns a new reference to a sortwrapper.
1789 Consumes the references to the two underlying objects. */
1790
1791static PyObject *
1792build_sortwrapper(PyObject *key, PyObject *value)
1793{
1794 sortwrapperobject *so;
1795
1796 so = PyObject_New(sortwrapperobject, &sortwrapper_type);
1797 if (so == NULL)
1798 return NULL;
1799 so->key = key;
1800 so->value = value;
1801 return (PyObject *)so;
1802}
1803
1804/* Returns a new reference to the value underlying the wrapper. */
1805static PyObject *
1806sortwrapper_getvalue(PyObject *so)
1807{
1808 PyObject *value;
1809
1810 if (!PyObject_TypeCheck(so, &sortwrapper_type)) {
1811 PyErr_SetString(PyExc_TypeError,
1812 "expected a sortwrapperobject");
1813 return NULL;
1814 }
1815 value = ((sortwrapperobject *)so)->value;
1816 Py_INCREF(value);
1817 return value;
1818}
1819
1820/* Wrapper for user specified cmp functions in combination with a
1821 specified key function. Makes sure the cmp function is presented
1822 with the actual key instead of the sortwrapper */
1823
1824typedef struct {
1825 PyObject_HEAD
1826 PyObject *func;
1827} cmpwrapperobject;
1828
1829static void
1830cmpwrapper_dealloc(cmpwrapperobject *co)
1831{
1832 Py_XDECREF(co->func);
1833 PyObject_Del(co);
1834}
1835
1836static PyObject *
1837cmpwrapper_call(cmpwrapperobject *co, PyObject *args, PyObject *kwds)
1838{
1839 PyObject *x, *y, *xx, *yy;
1840
1841 if (!PyArg_UnpackTuple(args, "", 2, 2, &x, &y))
1842 return NULL;
1843 if (!PyObject_TypeCheck(x, &sortwrapper_type) ||
Raymond Hettingerae4a2992003-10-16 17:16:30 +00001844 !PyObject_TypeCheck(y, &sortwrapper_type)) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001845 PyErr_SetString(PyExc_TypeError,
1846 "expected a sortwrapperobject");
1847 return NULL;
1848 }
1849 xx = ((sortwrapperobject *)x)->key;
1850 yy = ((sortwrapperobject *)y)->key;
1851 return PyObject_CallFunctionObjArgs(co->func, xx, yy, NULL);
1852}
1853
1854PyDoc_STRVAR(cmpwrapper_doc, "cmp() wrapper for sort with custom keys.");
1855
1856static PyTypeObject cmpwrapper_type = {
1857 PyObject_HEAD_INIT(&PyType_Type)
1858 0, /* ob_size */
1859 "cmpwrapper", /* tp_name */
1860 sizeof(cmpwrapperobject), /* tp_basicsize */
1861 0, /* tp_itemsize */
1862 /* methods */
1863 (destructor)cmpwrapper_dealloc, /* tp_dealloc */
1864 0, /* tp_print */
1865 0, /* tp_getattr */
1866 0, /* tp_setattr */
1867 0, /* tp_compare */
1868 0, /* tp_repr */
1869 0, /* tp_as_number */
1870 0, /* tp_as_sequence */
1871 0, /* tp_as_mapping */
1872 0, /* tp_hash */
1873 (ternaryfunc)cmpwrapper_call, /* tp_call */
1874 0, /* tp_str */
1875 PyObject_GenericGetAttr, /* tp_getattro */
1876 0, /* tp_setattro */
1877 0, /* tp_as_buffer */
1878 Py_TPFLAGS_DEFAULT, /* tp_flags */
1879 cmpwrapper_doc, /* tp_doc */
1880};
1881
1882static PyObject *
1883build_cmpwrapper(PyObject *cmpfunc)
1884{
1885 cmpwrapperobject *co;
1886
1887 co = PyObject_New(cmpwrapperobject, &cmpwrapper_type);
1888 if (co == NULL)
1889 return NULL;
1890 Py_INCREF(cmpfunc);
1891 co->func = cmpfunc;
1892 return (PyObject *)co;
1893}
1894
Tim Petersa64dc242002-08-01 02:13:36 +00001895/* An adaptive, stable, natural mergesort. See listsort.txt.
1896 * Returns Py_None on success, NULL on error. Even in case of error, the
1897 * list will be some permutation of its input state (nothing is lost or
1898 * duplicated).
1899 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001900static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001901listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001902{
Tim Petersa64dc242002-08-01 02:13:36 +00001903 MergeState ms;
1904 PyObject **lo, **hi;
1905 int nremaining;
1906 int minrun;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001907 int saved_ob_size, saved_allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00001908 PyObject **saved_ob_item;
1909 PyObject **empty_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001910 PyObject *compare = NULL;
1911 PyObject *result = NULL; /* guilty until proved innocent */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001912 int reverse = 0;
1913 PyObject *keyfunc = NULL;
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001914 int i;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001915 PyObject *key, *value, *kvpair;
1916 static char *kwlist[] = {"cmp", "key", "reverse", 0};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001917
Tim Petersa64dc242002-08-01 02:13:36 +00001918 assert(self != NULL);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001919 assert (PyList_Check(self));
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001920 if (args != NULL) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001921 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:sort",
1922 kwlist, &compare, &keyfunc, &reverse))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001923 return NULL;
1924 }
Skip Montanaro4abd5f02003-01-02 20:51:08 +00001925 if (compare == Py_None)
1926 compare = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001927 if (keyfunc == Py_None)
1928 keyfunc = NULL;
1929 if (compare != NULL && keyfunc != NULL) {
1930 compare = build_cmpwrapper(compare);
1931 if (compare == NULL)
Hye-Shik Chang19cb1932003-12-10 07:31:08 +00001932 return NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001933 } else
1934 Py_XINCREF(compare);
1935
Tim Petersb9099c32002-11-12 22:08:10 +00001936 /* The list is temporarily made empty, so that mutations performed
1937 * by comparison functions can't affect the slice of memory we're
1938 * sorting (allowing mutations during sorting is a core-dump
1939 * factory, since ob_item may change).
1940 */
1941 saved_ob_size = self->ob_size;
1942 saved_ob_item = self->ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001943 saved_allocated = self->allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00001944 self->ob_size = 0;
Tim Peters7049d812004-01-18 20:31:02 +00001945 self->ob_item = empty_ob_item = PyMem_NEW(PyObject *, 0);
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001946 self->allocated = 0;
Tim Peters330f9e92002-07-19 07:05:44 +00001947
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001948 if (keyfunc != NULL) {
1949 for (i=0 ; i < saved_ob_size ; i++) {
1950 value = saved_ob_item[i];
1951 key = PyObject_CallFunctionObjArgs(keyfunc, value,
1952 NULL);
1953 if (key == NULL) {
1954 for (i=i-1 ; i>=0 ; i--) {
1955 kvpair = saved_ob_item[i];
1956 value = sortwrapper_getvalue(kvpair);
1957 saved_ob_item[i] = value;
1958 Py_DECREF(kvpair);
1959 }
1960 if (self->ob_item != empty_ob_item
1961 || self->ob_size) {
1962 /* If the list changed *as well* we
1963 have two errors. We let the first
1964 one "win", but we shouldn't let
1965 what's in the list currently
1966 leak. */
1967 (void)list_ass_slice(
1968 self, 0, self->ob_size,
1969 (PyObject *)NULL);
1970 }
1971
1972 goto dsu_fail;
1973 }
1974 kvpair = build_sortwrapper(key, value);
1975 if (kvpair == NULL)
1976 goto dsu_fail;
1977 saved_ob_item[i] = kvpair;
1978 }
1979 }
1980
1981 /* Reverse sort stability achieved by initially reversing the list,
1982 applying a stable forward sort, then reversing the final result. */
1983 if (reverse && saved_ob_size > 1)
1984 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
1985
1986 merge_init(&ms, compare);
1987
Tim Petersb9099c32002-11-12 22:08:10 +00001988 nremaining = saved_ob_size;
Tim Petersa64dc242002-08-01 02:13:36 +00001989 if (nremaining < 2)
1990 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00001991
Tim Petersa64dc242002-08-01 02:13:36 +00001992 /* March over the array once, left to right, finding natural runs,
1993 * and extending short natural runs to minrun elements.
1994 */
Tim Petersb9099c32002-11-12 22:08:10 +00001995 lo = saved_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001996 hi = lo + nremaining;
1997 minrun = merge_compute_minrun(nremaining);
1998 do {
1999 int descending;
2000 int n;
Tim Peters330f9e92002-07-19 07:05:44 +00002001
Tim Petersa64dc242002-08-01 02:13:36 +00002002 /* Identify next run. */
2003 n = count_run(lo, hi, compare, &descending);
2004 if (n < 0)
2005 goto fail;
2006 if (descending)
2007 reverse_slice(lo, lo + n);
2008 /* If short, extend to min(minrun, nremaining). */
2009 if (n < minrun) {
2010 const int force = nremaining <= minrun ?
2011 nremaining : minrun;
2012 if (binarysort(lo, lo + force, lo + n, compare) < 0)
2013 goto fail;
2014 n = force;
2015 }
2016 /* Push run onto pending-runs stack, and maybe merge. */
2017 assert(ms.n < MAX_MERGE_PENDING);
Tim Peterse05f65a2002-08-10 05:21:15 +00002018 ms.pending[ms.n].base = lo;
2019 ms.pending[ms.n].len = n;
Tim Petersa64dc242002-08-01 02:13:36 +00002020 ++ms.n;
2021 if (merge_collapse(&ms) < 0)
2022 goto fail;
2023 /* Advance to find next run. */
2024 lo += n;
2025 nremaining -= n;
2026 } while (nremaining);
2027 assert(lo == hi);
Tim Peters330f9e92002-07-19 07:05:44 +00002028
Tim Petersa64dc242002-08-01 02:13:36 +00002029 if (merge_force_collapse(&ms) < 0)
2030 goto fail;
2031 assert(ms.n == 1);
Tim Petersb9099c32002-11-12 22:08:10 +00002032 assert(ms.pending[0].base == saved_ob_item);
2033 assert(ms.pending[0].len == saved_ob_size);
Tim Petersa64dc242002-08-01 02:13:36 +00002034
2035succeed:
2036 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002037fail:
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002038 if (keyfunc != NULL) {
2039 for (i=0 ; i < saved_ob_size ; i++) {
2040 kvpair = saved_ob_item[i];
2041 value = sortwrapper_getvalue(kvpair);
2042 saved_ob_item[i] = value;
2043 Py_DECREF(kvpair);
2044 }
2045 }
2046
Tim Petersb9099c32002-11-12 22:08:10 +00002047 if (self->ob_item != empty_ob_item || self->ob_size) {
2048 /* The user mucked with the list during the sort. */
2049 (void)list_ass_slice(self, 0, self->ob_size, (PyObject *)NULL);
2050 if (result != NULL) {
2051 PyErr_SetString(PyExc_ValueError,
2052 "list modified during sort");
2053 result = NULL;
2054 }
2055 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002056
2057 if (reverse && saved_ob_size > 1)
2058 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2059
2060 merge_freemem(&ms);
2061
2062dsu_fail:
Tim Petersb9099c32002-11-12 22:08:10 +00002063 if (self->ob_item == empty_ob_item)
2064 PyMem_FREE(empty_ob_item);
2065 self->ob_size = saved_ob_size;
2066 self->ob_item = saved_ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002067 self->allocated = saved_allocated;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002068 Py_XDECREF(compare);
Tim Petersa64dc242002-08-01 02:13:36 +00002069 Py_XINCREF(result);
2070 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002071}
Tim Peters330f9e92002-07-19 07:05:44 +00002072#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002073#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002074
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002075int
Fred Drakea2f55112000-07-09 15:16:51 +00002076PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002077{
2078 if (v == NULL || !PyList_Check(v)) {
2079 PyErr_BadInternalCall();
2080 return -1;
2081 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002082 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002083 if (v == NULL)
2084 return -1;
2085 Py_DECREF(v);
2086 return 0;
2087}
2088
Guido van Rossumb86c5492001-02-12 22:06:02 +00002089static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002090listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002091{
Tim Peters326b4482002-07-19 04:04:16 +00002092 if (self->ob_size > 1)
2093 reverse_slice(self->ob_item, self->ob_item + self->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002094 Py_INCREF(Py_None);
2095 return Py_None;
Guido van Rossumed98d481991-03-06 13:07:53 +00002096}
2097
Guido van Rossum84c76f51990-10-30 13:32:20 +00002098int
Fred Drakea2f55112000-07-09 15:16:51 +00002099PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002100{
Tim Peters6063e262002-08-08 01:06:39 +00002101 PyListObject *self = (PyListObject *)v;
2102
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002103 if (v == NULL || !PyList_Check(v)) {
2104 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002105 return -1;
2106 }
Tim Peters6063e262002-08-08 01:06:39 +00002107 if (self->ob_size > 1)
2108 reverse_slice(self->ob_item, self->ob_item + self->ob_size);
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002109 return 0;
2110}
2111
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002112PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002113PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002114{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002115 PyObject *w;
2116 PyObject **p;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002117 int n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002118 if (v == NULL || !PyList_Check(v)) {
2119 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002120 return NULL;
2121 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002122 n = ((PyListObject *)v)->ob_size;
2123 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002124 if (w == NULL)
2125 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002126 p = ((PyTupleObject *)w)->ob_item;
Thomas Wouters334fb892000-07-25 12:56:38 +00002127 memcpy((void *)p,
2128 (void *)((PyListObject *)v)->ob_item,
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002129 n*sizeof(PyObject *));
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002130 while (--n >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002131 Py_INCREF(*p);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002132 p++;
2133 }
2134 return w;
2135}
2136
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002137static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002138listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002139{
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002140 int i, start=0, stop=self->ob_size;
2141 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002142
Walter Dörwalde8049bef2003-06-17 19:27:39 +00002143 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2144 _PyEval_SliceIndex, &start,
2145 _PyEval_SliceIndex, &stop))
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002146 return NULL;
Guido van Rossum2743d872003-06-17 14:25:14 +00002147 if (start < 0) {
2148 start += self->ob_size;
2149 if (start < 0)
2150 start = 0;
2151 }
2152 if (stop < 0) {
2153 stop += self->ob_size;
2154 if (stop < 0)
2155 stop = 0;
2156 }
2157 else if (stop > self->ob_size)
2158 stop = self->ob_size;
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002159 for (i = start; i < stop; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002160 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2161 if (cmp > 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002162 return PyInt_FromLong((long)i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002163 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002164 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002165 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002166 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002167 return NULL;
2168}
2169
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002170static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002171listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002172{
2173 int count = 0;
2174 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002175
Guido van Rossume6f7d181991-10-20 20:20:40 +00002176 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002177 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2178 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002179 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002180 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002181 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00002182 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002183 return PyInt_FromLong((long)count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002184}
2185
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002186static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002187listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002188{
2189 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002190
Guido van Rossumed98d481991-03-06 13:07:53 +00002191 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002192 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2193 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002194 if (list_ass_slice(self, i, i+1,
2195 (PyObject *)NULL) != 0)
Guido van Rossumed98d481991-03-06 13:07:53 +00002196 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002197 Py_INCREF(Py_None);
2198 return Py_None;
Guido van Rossumed98d481991-03-06 13:07:53 +00002199 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002200 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002201 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002202 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002203 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002204 return NULL;
2205}
2206
Jeremy Hylton8caad492000-06-23 14:18:11 +00002207static int
2208list_traverse(PyListObject *o, visitproc visit, void *arg)
2209{
2210 int i, err;
2211 PyObject *x;
2212
2213 for (i = o->ob_size; --i >= 0; ) {
2214 x = o->ob_item[i];
2215 if (x != NULL) {
2216 err = visit(x, arg);
2217 if (err)
2218 return err;
2219 }
2220 }
2221 return 0;
2222}
2223
2224static int
2225list_clear(PyListObject *lp)
2226{
2227 (void) PyList_SetSlice((PyObject *)lp, 0, lp->ob_size, 0);
2228 return 0;
2229}
2230
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002231static PyObject *
2232list_richcompare(PyObject *v, PyObject *w, int op)
2233{
2234 PyListObject *vl, *wl;
2235 int i;
2236
2237 if (!PyList_Check(v) || !PyList_Check(w)) {
2238 Py_INCREF(Py_NotImplemented);
2239 return Py_NotImplemented;
2240 }
2241
2242 vl = (PyListObject *)v;
2243 wl = (PyListObject *)w;
2244
2245 if (vl->ob_size != wl->ob_size && (op == Py_EQ || op == Py_NE)) {
2246 /* Shortcut: if the lengths differ, the lists differ */
2247 PyObject *res;
2248 if (op == Py_EQ)
2249 res = Py_False;
2250 else
2251 res = Py_True;
2252 Py_INCREF(res);
2253 return res;
2254 }
2255
2256 /* Search for the first index where items are different */
2257 for (i = 0; i < vl->ob_size && i < wl->ob_size; i++) {
2258 int k = PyObject_RichCompareBool(vl->ob_item[i],
2259 wl->ob_item[i], Py_EQ);
2260 if (k < 0)
2261 return NULL;
2262 if (!k)
2263 break;
2264 }
2265
2266 if (i >= vl->ob_size || i >= wl->ob_size) {
2267 /* No more items to compare -- compare sizes */
2268 int vs = vl->ob_size;
2269 int ws = wl->ob_size;
2270 int cmp;
2271 PyObject *res;
2272 switch (op) {
2273 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00002274 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002275 case Py_EQ: cmp = vs == ws; break;
2276 case Py_NE: cmp = vs != ws; break;
2277 case Py_GT: cmp = vs > ws; break;
2278 case Py_GE: cmp = vs >= ws; break;
2279 default: return NULL; /* cannot happen */
2280 }
2281 if (cmp)
2282 res = Py_True;
2283 else
2284 res = Py_False;
2285 Py_INCREF(res);
2286 return res;
2287 }
2288
2289 /* We have an item that differs -- shortcuts for EQ/NE */
2290 if (op == Py_EQ) {
2291 Py_INCREF(Py_False);
2292 return Py_False;
2293 }
2294 if (op == Py_NE) {
2295 Py_INCREF(Py_True);
2296 return Py_True;
2297 }
2298
2299 /* Compare the final item again using the proper operator */
2300 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
2301}
2302
Tim Peters6d6c1a32001-08-02 04:15:00 +00002303static int
2304list_init(PyListObject *self, PyObject *args, PyObject *kw)
2305{
2306 PyObject *arg = NULL;
2307 static char *kwlist[] = {"sequence", 0};
2308
2309 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2310 return -1;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002311 /* Empty previous contents */
2312 if (self->ob_size != 0) {
2313 if (list_ass_slice(self, 0, self->ob_size, (PyObject *)NULL) != 0)
2314 return -1;
2315 }
2316 if (arg != NULL) {
2317 PyObject *rv = listextend(self, arg);
2318 if (rv == NULL)
2319 return -1;
2320 Py_DECREF(rv);
2321 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002322 return 0;
2323}
2324
Guido van Rossumdbb53d92001-12-03 16:32:18 +00002325static long
2326list_nohash(PyObject *self)
2327{
2328 PyErr_SetString(PyExc_TypeError, "list objects are unhashable");
2329 return -1;
2330}
2331
Raymond Hettinger1021c442003-11-07 15:38:09 +00002332static PyObject *list_iter(PyObject *seq);
2333static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2334
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002335PyDoc_STRVAR(getitem_doc,
2336"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002337PyDoc_STRVAR(reversed_doc,
2338"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002339PyDoc_STRVAR(append_doc,
2340"L.append(object) -- append object to end");
2341PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002342"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002343PyDoc_STRVAR(insert_doc,
2344"L.insert(index, object) -- insert object before index");
2345PyDoc_STRVAR(pop_doc,
2346"L.pop([index]) -> item -- remove and return item at index (default last)");
2347PyDoc_STRVAR(remove_doc,
2348"L.remove(value) -- remove first occurrence of value");
2349PyDoc_STRVAR(index_doc,
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002350"L.index(value, [start, [stop]]) -> integer -- return first index of value");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002351PyDoc_STRVAR(count_doc,
2352"L.count(value) -> integer -- return number of occurrences of value");
2353PyDoc_STRVAR(reverse_doc,
2354"L.reverse() -- reverse *IN PLACE*");
2355PyDoc_STRVAR(sort_doc,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002356"L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n\
2357cmp(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002358
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002359static PyObject *list_subscript(PyListObject*, PyObject*);
2360
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002361static PyMethodDef list_methods[] = {
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002362 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
Raymond Hettinger1021c442003-11-07 15:38:09 +00002363 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002364 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002365 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002366 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002367 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002368 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002369 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002370 {"count", (PyCFunction)listcount, METH_O, count_doc},
2371 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002372 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
Tim Petersa64dc242002-08-01 02:13:36 +00002373 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002374};
2375
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002376static PySequenceMethods list_as_sequence = {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002377 (inquiry)list_length, /* sq_length */
2378 (binaryfunc)list_concat, /* sq_concat */
2379 (intargfunc)list_repeat, /* sq_repeat */
2380 (intargfunc)list_item, /* sq_item */
2381 (intintargfunc)list_slice, /* sq_slice */
2382 (intobjargproc)list_ass_item, /* sq_ass_item */
2383 (intintobjargproc)list_ass_slice, /* sq_ass_slice */
2384 (objobjproc)list_contains, /* sq_contains */
2385 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2386 (intargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002387};
2388
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002389PyDoc_STRVAR(list_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002390"list() -> new list\n"
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002391"list(sequence) -> new list initialized from sequence's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002392
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002393static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002394list_subscript(PyListObject* self, PyObject* item)
2395{
2396 if (PyInt_Check(item)) {
2397 long i = PyInt_AS_LONG(item);
2398 if (i < 0)
2399 i += PyList_GET_SIZE(self);
2400 return list_item(self, i);
2401 }
2402 else if (PyLong_Check(item)) {
2403 long i = PyLong_AsLong(item);
2404 if (i == -1 && PyErr_Occurred())
2405 return NULL;
2406 if (i < 0)
2407 i += PyList_GET_SIZE(self);
2408 return list_item(self, i);
2409 }
2410 else if (PySlice_Check(item)) {
2411 int start, stop, step, slicelength, cur, i;
2412 PyObject* result;
2413 PyObject* it;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002414 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002415
2416 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
2417 &start, &stop, &step, &slicelength) < 0) {
2418 return NULL;
2419 }
2420
2421 if (slicelength <= 0) {
2422 return PyList_New(0);
2423 }
2424 else {
2425 result = PyList_New(slicelength);
2426 if (!result) return NULL;
2427
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002428 src = self->ob_item;
2429 dest = ((PyListObject *)result)->ob_item;
Tim Peters3b01a122002-07-19 02:35:45 +00002430 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002431 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002432 it = src[cur];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002433 Py_INCREF(it);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002434 dest[i] = it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002435 }
Tim Peters3b01a122002-07-19 02:35:45 +00002436
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002437 return result;
2438 }
2439 }
2440 else {
2441 PyErr_SetString(PyExc_TypeError,
2442 "list indices must be integers");
2443 return NULL;
2444 }
2445}
2446
Tim Peters3b01a122002-07-19 02:35:45 +00002447static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002448list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2449{
2450 if (PyInt_Check(item)) {
2451 long i = PyInt_AS_LONG(item);
2452 if (i < 0)
2453 i += PyList_GET_SIZE(self);
2454 return list_ass_item(self, i, value);
2455 }
2456 else if (PyLong_Check(item)) {
2457 long i = PyLong_AsLong(item);
2458 if (i == -1 && PyErr_Occurred())
2459 return -1;
2460 if (i < 0)
2461 i += PyList_GET_SIZE(self);
2462 return list_ass_item(self, i, value);
2463 }
2464 else if (PySlice_Check(item)) {
2465 int start, stop, step, slicelength;
2466
2467 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
2468 &start, &stop, &step, &slicelength) < 0) {
2469 return -1;
2470 }
2471
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002472 /* treat L[slice(a,b)] = v _exactly_ like L[a:b] = v */
2473 if (step == 1 && ((PySliceObject*)item)->step == Py_None)
2474 return list_ass_slice(self, start, stop, value);
2475
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002476 if (value == NULL) {
2477 /* delete slice */
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002478 PyObject **garbage;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002479 int cur, i;
Tim Peters3b01a122002-07-19 02:35:45 +00002480
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002481 if (slicelength <= 0)
2482 return 0;
2483
2484 if (step < 0) {
2485 stop = start + 1;
2486 start = stop + step*(slicelength - 1) - 1;
2487 step = -step;
2488 }
2489
2490 garbage = (PyObject**)
2491 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Tim Peters3b01a122002-07-19 02:35:45 +00002492
2493 /* drawing pictures might help
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002494 understand these for loops */
Guido van Rossum75a20b12002-06-11 12:22:28 +00002495 for (cur = start, i = 0;
2496 cur < stop;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002497 cur += step, i++) {
2498 int lim = step;
2499
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002500 garbage[i] = PyList_GET_ITEM(self, cur);
2501
Michael W. Hudson56796f62002-07-29 14:35:04 +00002502 if (cur + step >= self->ob_size) {
2503 lim = self->ob_size - cur - 1;
2504 }
2505
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002506 memmove(self->ob_item + cur - i,
2507 self->ob_item + cur + 1,
2508 lim * sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002509 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002510
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002511 for (cur = start + slicelength*step + 1;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002512 cur < self->ob_size; cur++) {
2513 PyList_SET_ITEM(self, cur - slicelength,
2514 PyList_GET_ITEM(self, cur));
2515 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002516
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002517 self->ob_size -= slicelength;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002518 list_resize(self, self->ob_size);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002519
2520 for (i = 0; i < slicelength; i++) {
2521 Py_DECREF(garbage[i]);
2522 }
2523 PyMem_FREE(garbage);
2524
2525 return 0;
2526 }
2527 else {
2528 /* assign slice */
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002529 PyObject **garbage, *ins, *seq, **seqitems, **selfitems;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002530 int cur, i;
2531
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002532 /* protect against a[::-1] = a */
Tim Peters3b01a122002-07-19 02:35:45 +00002533 if (self == (PyListObject*)value) {
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002534 seq = list_slice((PyListObject*)value, 0,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002535 PyList_GET_SIZE(value));
Tim Peters3b01a122002-07-19 02:35:45 +00002536 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002537 else {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002538 seq = PySequence_Fast(value,
2539 "must assign iterable to extended slice");
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002540 if (!seq)
2541 return -1;
2542 }
2543
2544 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2545 PyErr_Format(PyExc_ValueError,
2546 "attempt to assign sequence of size %d to extended slice of size %d",
2547 PySequence_Fast_GET_SIZE(seq),
2548 slicelength);
2549 Py_DECREF(seq);
2550 return -1;
2551 }
2552
2553 if (!slicelength) {
2554 Py_DECREF(seq);
2555 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002556 }
2557
2558 garbage = (PyObject**)
2559 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Tim Peters3b01a122002-07-19 02:35:45 +00002560
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002561 selfitems = self->ob_item;
2562 if (PyList_Check(seq))
2563 seqitems = ((PyListObject *)seq)->ob_item;
2564 else
2565 seqitems = ((PyTupleObject *)seq)->ob_item;
Tim Peters3b01a122002-07-19 02:35:45 +00002566 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002567 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002568 garbage[i] = selfitems[cur];
2569 ins = seqitems[i];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002570 Py_INCREF(ins);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002571 selfitems[cur] = ins;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002572 }
2573
2574 for (i = 0; i < slicelength; i++) {
2575 Py_DECREF(garbage[i]);
2576 }
Tim Peters3b01a122002-07-19 02:35:45 +00002577
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002578 PyMem_FREE(garbage);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002579 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002580
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002581 return 0;
2582 }
Tim Peters3b01a122002-07-19 02:35:45 +00002583 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002584 else {
Tim Peters3b01a122002-07-19 02:35:45 +00002585 PyErr_SetString(PyExc_TypeError,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002586 "list indices must be integers");
2587 return -1;
2588 }
2589}
2590
2591static PyMappingMethods list_as_mapping = {
2592 (inquiry)list_length,
2593 (binaryfunc)list_subscript,
2594 (objobjargproc)list_ass_subscript
2595};
2596
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002597PyTypeObject PyList_Type = {
2598 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002599 0,
2600 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002601 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002602 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002603 (destructor)list_dealloc, /* tp_dealloc */
2604 (printfunc)list_print, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002605 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002606 0, /* tp_setattr */
2607 0, /* tp_compare */
2608 (reprfunc)list_repr, /* tp_repr */
2609 0, /* tp_as_number */
2610 &list_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002611 &list_as_mapping, /* tp_as_mapping */
Guido van Rossumdbb53d92001-12-03 16:32:18 +00002612 list_nohash, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002613 0, /* tp_call */
2614 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002615 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002616 0, /* tp_setattro */
2617 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002618 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Tim Peters6d6c1a32001-08-02 04:15:00 +00002619 Py_TPFLAGS_BASETYPE, /* tp_flags */
2620 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002621 (traverseproc)list_traverse, /* tp_traverse */
2622 (inquiry)list_clear, /* tp_clear */
2623 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002624 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002625 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002626 0, /* tp_iternext */
2627 list_methods, /* tp_methods */
2628 0, /* tp_members */
2629 0, /* tp_getset */
2630 0, /* tp_base */
2631 0, /* tp_dict */
2632 0, /* tp_descr_get */
2633 0, /* tp_descr_set */
2634 0, /* tp_dictoffset */
2635 (initproc)list_init, /* tp_init */
2636 PyType_GenericAlloc, /* tp_alloc */
2637 PyType_GenericNew, /* tp_new */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002638 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002639};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002640
2641
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002642/*********************** List Iterator **************************/
2643
2644typedef struct {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002645 PyObject_HEAD
2646 long it_index;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002647 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002648} listiterobject;
2649
2650PyTypeObject PyListIter_Type;
2651
Guido van Rossum5086e492002-07-16 15:56:52 +00002652static PyObject *
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002653list_iter(PyObject *seq)
2654{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002655 listiterobject *it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002656
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002657 if (!PyList_Check(seq)) {
2658 PyErr_BadInternalCall();
2659 return NULL;
2660 }
2661 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2662 if (it == NULL)
2663 return NULL;
2664 it->it_index = 0;
2665 Py_INCREF(seq);
2666 it->it_seq = (PyListObject *)seq;
2667 _PyObject_GC_TRACK(it);
2668 return (PyObject *)it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002669}
2670
2671static void
2672listiter_dealloc(listiterobject *it)
2673{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002674 _PyObject_GC_UNTRACK(it);
Guido van Rossum86103ae2002-07-16 20:07:32 +00002675 Py_XDECREF(it->it_seq);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002676 PyObject_GC_Del(it);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002677}
2678
2679static int
2680listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2681{
Guido van Rossum86103ae2002-07-16 20:07:32 +00002682 if (it->it_seq == NULL)
2683 return 0;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002684 return visit((PyObject *)it->it_seq, arg);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002685}
2686
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002687static PyObject *
Tim Peters93b2cc42002-06-01 05:22:55 +00002688listiter_next(listiterobject *it)
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002689{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002690 PyListObject *seq;
2691 PyObject *item;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002692
Tim Peters93b2cc42002-06-01 05:22:55 +00002693 assert(it != NULL);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002694 seq = it->it_seq;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002695 if (seq == NULL)
2696 return NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002697 assert(PyList_Check(seq));
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002698
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002699 if (it->it_index < PyList_GET_SIZE(seq)) {
Tim Peters93b2cc42002-06-01 05:22:55 +00002700 item = PyList_GET_ITEM(seq, it->it_index);
2701 ++it->it_index;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002702 Py_INCREF(item);
2703 return item;
2704 }
Guido van Rossum86103ae2002-07-16 20:07:32 +00002705
2706 Py_DECREF(seq);
2707 it->it_seq = NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002708 return NULL;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002709}
2710
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002711PyTypeObject PyListIter_Type = {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002712 PyObject_HEAD_INIT(&PyType_Type)
2713 0, /* ob_size */
2714 "listiterator", /* tp_name */
2715 sizeof(listiterobject), /* tp_basicsize */
2716 0, /* tp_itemsize */
2717 /* methods */
2718 (destructor)listiter_dealloc, /* tp_dealloc */
2719 0, /* tp_print */
2720 0, /* tp_getattr */
2721 0, /* tp_setattr */
2722 0, /* tp_compare */
2723 0, /* tp_repr */
2724 0, /* tp_as_number */
2725 0, /* tp_as_sequence */
2726 0, /* tp_as_mapping */
2727 0, /* tp_hash */
2728 0, /* tp_call */
2729 0, /* tp_str */
2730 PyObject_GenericGetAttr, /* tp_getattro */
2731 0, /* tp_setattro */
2732 0, /* tp_as_buffer */
2733 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2734 0, /* tp_doc */
2735 (traverseproc)listiter_traverse, /* tp_traverse */
2736 0, /* tp_clear */
2737 0, /* tp_richcompare */
2738 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00002739 PyObject_SelfIter, /* tp_iter */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002740 (iternextfunc)listiter_next, /* tp_iternext */
Guido van Rossum86103ae2002-07-16 20:07:32 +00002741 0, /* tp_methods */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002742 0, /* tp_members */
2743 0, /* tp_getset */
2744 0, /* tp_base */
2745 0, /* tp_dict */
2746 0, /* tp_descr_get */
2747 0, /* tp_descr_set */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002748};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002749
2750/*********************** List Reverse Iterator **************************/
2751
2752typedef struct {
2753 PyObject_HEAD
2754 long it_index;
Raymond Hettinger001f2282003-11-08 11:58:44 +00002755 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002756} listreviterobject;
2757
2758PyTypeObject PyListRevIter_Type;
2759
2760static PyObject *
2761list_reversed(PyListObject *seq, PyObject *unused)
2762{
2763 listreviterobject *it;
2764
2765 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2766 if (it == NULL)
2767 return NULL;
2768 assert(PyList_Check(seq));
2769 it->it_index = PyList_GET_SIZE(seq) - 1;
2770 Py_INCREF(seq);
2771 it->it_seq = seq;
2772 PyObject_GC_Track(it);
2773 return (PyObject *)it;
2774}
2775
2776static void
2777listreviter_dealloc(listreviterobject *it)
2778{
2779 PyObject_GC_UnTrack(it);
2780 Py_XDECREF(it->it_seq);
2781 PyObject_GC_Del(it);
2782}
2783
2784static int
2785listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2786{
2787 if (it->it_seq == NULL)
2788 return 0;
2789 return visit((PyObject *)it->it_seq, arg);
2790}
2791
2792static PyObject *
2793listreviter_next(listreviterobject *it)
2794{
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002795 PyObject *item;
2796 long index = it->it_index;
2797 PyListObject *seq = it->it_seq;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002798
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002799 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2800 item = PyList_GET_ITEM(seq, index);
Raymond Hettinger1021c442003-11-07 15:38:09 +00002801 it->it_index--;
2802 Py_INCREF(item);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002803 return item;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002804 }
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002805 it->it_index = -1;
2806 if (seq != NULL) {
2807 it->it_seq = NULL;
2808 Py_DECREF(seq);
2809 }
2810 return NULL;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002811}
2812
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002813static int
2814listreviter_len(listreviterobject *it)
2815{
2816 return it->it_index + 1;
2817}
2818
2819static PySequenceMethods listreviter_as_sequence = {
2820 (inquiry)listreviter_len, /* sq_length */
2821 0, /* sq_concat */
2822};
2823
Raymond Hettinger1021c442003-11-07 15:38:09 +00002824PyTypeObject PyListRevIter_Type = {
2825 PyObject_HEAD_INIT(&PyType_Type)
2826 0, /* ob_size */
2827 "listreverseiterator", /* tp_name */
2828 sizeof(listreviterobject), /* tp_basicsize */
2829 0, /* tp_itemsize */
2830 /* methods */
2831 (destructor)listreviter_dealloc, /* tp_dealloc */
2832 0, /* tp_print */
2833 0, /* tp_getattr */
2834 0, /* tp_setattr */
2835 0, /* tp_compare */
2836 0, /* tp_repr */
2837 0, /* tp_as_number */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002838 &listreviter_as_sequence, /* tp_as_sequence */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002839 0, /* tp_as_mapping */
2840 0, /* tp_hash */
2841 0, /* tp_call */
2842 0, /* tp_str */
2843 PyObject_GenericGetAttr, /* tp_getattro */
2844 0, /* tp_setattro */
2845 0, /* tp_as_buffer */
2846 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2847 0, /* tp_doc */
2848 (traverseproc)listreviter_traverse, /* tp_traverse */
2849 0, /* tp_clear */
2850 0, /* tp_richcompare */
2851 0, /* tp_weaklistoffset */
2852 PyObject_SelfIter, /* tp_iter */
2853 (iternextfunc)listreviter_next, /* tp_iternext */
2854 0,
2855};