blob: c8a819018718354f93530be890d1e6b731b5a552 [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 Hettinger0e916432004-03-14 06:42:23 +000012list_resize(PyListObject *self, int newsize, int exact)
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 Hettinger0e916432004-03-14 06:42:23 +000036 if (exact)
37 _new_size = newsize;
38 else
39 _new_size = (newsize>>3) + (self->ob_size < 8 ? 3 : 6) + newsize;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000040 items = self->ob_item;
41 if (_new_size <= ((~(size_t)0) / sizeof(PyObject *)))
42 PyMem_RESIZE(items, PyObject *, _new_size);
43 else
44 items = NULL;
45 if (items == NULL) {
46 PyErr_NoMemory();
47 return -1;
48 }
49 self->ob_item = items;
50 self->ob_size = newsize;
51 self->allocated = _new_size;
52 return 0;
53}
Guido van Rossuma46d51d1995-01-26 22:59:43 +000054
Guido van Rossumc0b618a1997-05-02 03:12:38 +000055PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +000056PyList_New(int size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000057{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000058 PyListObject *op;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +000059 size_t nbytes;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000060 if (size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000061 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000062 return NULL;
63 }
Tim Peters7049d812004-01-18 20:31:02 +000064 nbytes = size * sizeof(PyObject *);
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000065 /* Check for overflow */
Tim Peters7049d812004-01-18 20:31:02 +000066 if (nbytes / sizeof(PyObject *) != (size_t)size) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000067 return PyErr_NoMemory();
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000068 }
Neil Schemenauere83c00e2001-08-29 23:54:21 +000069 op = PyObject_GC_New(PyListObject, &PyList_Type);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000070 if (op == NULL) {
Neil Schemenauere83c00e2001-08-29 23:54:21 +000071 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000072 }
73 if (size <= 0) {
74 op->ob_item = NULL;
75 }
76 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +000077 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000078 if (op->ob_item == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000079 return PyErr_NoMemory();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000080 }
Tim Peters7049d812004-01-18 20:31:02 +000081 memset(op->ob_item, 0, sizeof(*op->ob_item) * size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000082 }
Neil Schemenauere83c00e2001-08-29 23:54:21 +000083 op->ob_size = size;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000084 op->allocated = size;
Neil Schemenauere83c00e2001-08-29 23:54:21 +000085 _PyObject_GC_TRACK(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +000086 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000087}
88
89int
Fred Drakea2f55112000-07-09 15:16:51 +000090PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000091{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000092 if (!PyList_Check(op)) {
93 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000094 return -1;
95 }
96 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +000097 return ((PyListObject *)op) -> ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000098}
99
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000100static PyObject *indexerr;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000101
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000102PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000103PyList_GetItem(PyObject *op, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000104{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000105 if (!PyList_Check(op)) {
106 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000107 return NULL;
108 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000109 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000110 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000111 indexerr = PyString_FromString(
112 "list index out of range");
113 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000114 return NULL;
115 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000116 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000117}
118
119int
Fred Drakea2f55112000-07-09 15:16:51 +0000120PyList_SetItem(register PyObject *op, register int i,
121 register PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000122{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000123 register PyObject *olditem;
124 register PyObject **p;
125 if (!PyList_Check(op)) {
126 Py_XDECREF(newitem);
127 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000128 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000129 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000130 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
131 Py_XDECREF(newitem);
132 PyErr_SetString(PyExc_IndexError,
133 "list assignment index out of range");
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000134 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000135 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000136 p = ((PyListObject *)op) -> ob_item + i;
Guido van Rossum5fe60581995-03-09 12:12:50 +0000137 olditem = *p;
138 *p = newitem;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000139 Py_XDECREF(olditem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000140 return 0;
141}
142
143static int
Fred Drakea2f55112000-07-09 15:16:51 +0000144ins1(PyListObject *self, int where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000145{
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000146 int i, n = self->ob_size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000147 PyObject **items;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000148 if (v == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000149 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000150 return -1;
151 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000152 if (n == INT_MAX) {
Trent Micka5846642000-08-13 22:47:45 +0000153 PyErr_SetString(PyExc_OverflowError,
154 "cannot add more objects to list");
155 return -1;
156 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000157
Raymond Hettinger0e916432004-03-14 06:42:23 +0000158 if (list_resize(self, n+1, 0) == -1)
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000159 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000160
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000161 if (where < 0) {
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000162 where += n;
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000163 if (where < 0)
164 where = 0;
165 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000166 if (where > n)
167 where = n;
168 items = self->ob_item;
169 for (i = n; --i >= where; )
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000170 items[i+1] = items[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000171 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000172 items[where] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000173 return 0;
174}
175
176int
Fred Drakea2f55112000-07-09 15:16:51 +0000177PyList_Insert(PyObject *op, int where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000178{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000179 if (!PyList_Check(op)) {
180 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000181 return -1;
182 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000183 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000184}
185
186int
Fred Drakea2f55112000-07-09 15:16:51 +0000187PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000188{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000189 if (!PyList_Check(op)) {
190 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000191 return -1;
192 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000193 return ins1((PyListObject *)op,
194 (int) ((PyListObject *)op)->ob_size, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000195}
196
197/* Methods */
198
199static void
Fred Drakea2f55112000-07-09 15:16:51 +0000200list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000201{
202 int i;
Guido van Rossumff413af2002-03-28 20:34:59 +0000203 PyObject_GC_UnTrack(op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000204 Py_TRASHCAN_SAFE_BEGIN(op)
Jack Jansen7874d1f1995-01-19 12:09:27 +0000205 if (op->ob_item != NULL) {
Guido van Rossumfa717011999-06-09 15:19:34 +0000206 /* Do it backwards, for Christian Tismer.
207 There's a simple test case where somehow this reduces
208 thrashing when a *very* large list is created and
209 immediately deleted. */
210 i = op->ob_size;
211 while (--i >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000212 Py_XDECREF(op->ob_item[i]);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000213 }
Guido van Rossumb18618d2000-05-03 23:44:39 +0000214 PyMem_FREE(op->ob_item);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000215 }
Guido van Rossum9475a232001-10-05 20:51:39 +0000216 op->ob_type->tp_free((PyObject *)op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000217 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000218}
219
Guido van Rossum90933611991-06-07 16:10:43 +0000220static int
Fred Drakea2f55112000-07-09 15:16:51 +0000221list_print(PyListObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000222{
223 int i;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000224
225 i = Py_ReprEnter((PyObject*)op);
226 if (i != 0) {
227 if (i < 0)
228 return i;
229 fprintf(fp, "[...]");
230 return 0;
231 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000232 fprintf(fp, "[");
Guido van Rossum90933611991-06-07 16:10:43 +0000233 for (i = 0; i < op->ob_size; i++) {
234 if (i > 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000235 fprintf(fp, ", ");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000236 if (PyObject_Print(op->ob_item[i], fp, 0) != 0) {
237 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000238 return -1;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000239 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000240 }
241 fprintf(fp, "]");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000242 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000243 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000244}
245
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000246static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000247list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000248{
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000249 int i;
Tim Petersa7259592001-06-16 05:11:17 +0000250 PyObject *s, *temp;
251 PyObject *pieces = NULL, *result = NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000252
253 i = Py_ReprEnter((PyObject*)v);
254 if (i != 0) {
Tim Petersa7259592001-06-16 05:11:17 +0000255 return i > 0 ? PyString_FromString("[...]") : NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000256 }
Tim Petersa7259592001-06-16 05:11:17 +0000257
258 if (v->ob_size == 0) {
259 result = PyString_FromString("[]");
260 goto Done;
261 }
262
263 pieces = PyList_New(0);
264 if (pieces == NULL)
265 goto Done;
266
267 /* Do repr() on each element. Note that this may mutate the list,
268 so must refetch the list size on each iteration. */
269 for (i = 0; i < v->ob_size; ++i) {
270 int status;
271 s = PyObject_Repr(v->ob_item[i]);
272 if (s == NULL)
273 goto Done;
274 status = PyList_Append(pieces, s);
275 Py_DECREF(s); /* append created a new ref */
276 if (status < 0)
277 goto Done;
278 }
279
280 /* Add "[]" decorations to the first and last items. */
281 assert(PyList_GET_SIZE(pieces) > 0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000282 s = PyString_FromString("[");
Tim Petersa7259592001-06-16 05:11:17 +0000283 if (s == NULL)
284 goto Done;
285 temp = PyList_GET_ITEM(pieces, 0);
286 PyString_ConcatAndDel(&s, temp);
287 PyList_SET_ITEM(pieces, 0, s);
288 if (s == NULL)
289 goto Done;
290
291 s = PyString_FromString("]");
292 if (s == NULL)
293 goto Done;
294 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
295 PyString_ConcatAndDel(&temp, s);
296 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
297 if (temp == NULL)
298 goto Done;
299
300 /* Paste them all together with ", " between. */
301 s = PyString_FromString(", ");
302 if (s == NULL)
303 goto Done;
304 result = _PyString_Join(s, pieces);
Tim Peters3b01a122002-07-19 02:35:45 +0000305 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +0000306
307Done:
308 Py_XDECREF(pieces);
Guido van Rossumfb376de1998-04-10 22:47:27 +0000309 Py_ReprLeave((PyObject *)v);
Tim Petersa7259592001-06-16 05:11:17 +0000310 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000311}
312
313static int
Fred Drakea2f55112000-07-09 15:16:51 +0000314list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000315{
316 return a->ob_size;
317}
318
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000319static int
Fred Drakea2f55112000-07-09 15:16:51 +0000320list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000321{
Raymond Hettingeraae59992002-09-05 14:23:49 +0000322 int i, cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000323
Raymond Hettingeraae59992002-09-05 14:23:49 +0000324 for (i = 0, cmp = 0 ; cmp == 0 && i < a->ob_size; ++i)
325 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000326 Py_EQ);
Neal Norwitzbb9c5f52002-09-05 21:32:55 +0000327 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000328}
329
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000330static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000331list_item(PyListObject *a, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000332{
333 if (i < 0 || i >= a->ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000334 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000335 indexerr = PyString_FromString(
336 "list index out of range");
337 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000338 return NULL;
339 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000340 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000341 return a->ob_item[i];
342}
343
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000344static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000345list_slice(PyListObject *a, int ilow, int ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000346{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000347 PyListObject *np;
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000348 PyObject **src, **dest;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000349 int i, len;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000350 if (ilow < 0)
351 ilow = 0;
352 else if (ilow > a->ob_size)
353 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000354 if (ihigh < ilow)
355 ihigh = ilow;
356 else if (ihigh > a->ob_size)
357 ihigh = a->ob_size;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000358 len = ihigh - ilow;
359 np = (PyListObject *) PyList_New(len);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000360 if (np == NULL)
361 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000362
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000363 src = a->ob_item + ilow;
364 dest = np->ob_item;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000365 for (i = 0; i < len; i++) {
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000366 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000367 Py_INCREF(v);
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000368 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000369 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000370 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000371}
372
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000373PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000374PyList_GetSlice(PyObject *a, int ilow, int ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000375{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000376 if (!PyList_Check(a)) {
377 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000378 return NULL;
379 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000380 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000381}
382
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000383static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000384list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000385{
386 int size;
387 int i;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000388 PyObject **src, **dest;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000389 PyListObject *np;
390 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000391 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000392 "can only concatenate list (not \"%.200s\") to list",
393 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000394 return NULL;
395 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000396#define b ((PyListObject *)bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000397 size = a->ob_size + b->ob_size;
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000398 if (size < 0)
399 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000400 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000401 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000402 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000403 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000404 src = a->ob_item;
405 dest = np->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000406 for (i = 0; i < a->ob_size; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000407 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000408 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000409 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000410 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000411 src = b->ob_item;
412 dest = np->ob_item + a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000413 for (i = 0; i < b->ob_size; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000414 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000415 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000416 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000417 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000418 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000419#undef b
420}
421
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000422static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000423list_repeat(PyListObject *a, int n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000424{
425 int i, j;
426 int size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000427 PyListObject *np;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000428 PyObject **p, **items;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000429 PyObject *elem;
Guido van Rossumed98d481991-03-06 13:07:53 +0000430 if (n < 0)
431 n = 0;
432 size = a->ob_size * n;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000433 if (size == 0)
434 return PyList_New(0);
Guido van Rossumbfa5a142002-10-11 23:39:35 +0000435 if (n && size/n != a->ob_size)
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000436 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000437 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000438 if (np == NULL)
439 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000440
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000441 items = np->ob_item;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000442 if (a->ob_size == 1) {
443 elem = a->ob_item[0];
444 for (i = 0; i < n; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000445 items[i] = elem;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000446 Py_INCREF(elem);
447 }
448 return (PyObject *) np;
449 }
Guido van Rossumed98d481991-03-06 13:07:53 +0000450 p = np->ob_item;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000451 items = a->ob_item;
Guido van Rossumed98d481991-03-06 13:07:53 +0000452 for (i = 0; i < n; i++) {
453 for (j = 0; j < a->ob_size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000454 *p = items[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000455 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000456 p++;
457 }
458 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000459 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000460}
461
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000462static int
Fred Drakea2f55112000-07-09 15:16:51 +0000463list_ass_slice(PyListObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000464{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000465 /* Because [X]DECREF can recursively invoke list operations on
466 this list, we must postpone all [X]DECREF activity until
467 after the list is back in its canonical shape. Therefore
468 we must allocate an additional array, 'recycle', into which
469 we temporarily copy the items that are deleted from the
470 list. :-( */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000471 PyObject **recycle, **p;
472 PyObject **item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000473 PyObject **vitem = NULL;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000474 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000475 int n; /* Size of replacement list */
476 int d; /* Change in size */
477 int k; /* Loop index */
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000478 int s;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000479#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000480 if (v == NULL)
481 n = 0;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000482 else {
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000483 if (a == b) {
484 /* Special case "a[i:j] = a" -- copy b first */
485 int ret;
Michael W. Hudsonda0a0672003-08-15 12:06:41 +0000486 v = list_slice(b, 0, b->ob_size);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000487 if (v == NULL)
488 return -1;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000489 ret = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000490 Py_DECREF(v);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000491 return ret;
492 }
Raymond Hettingerf889e102004-03-09 08:04:33 +0000493 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000494 if(v_as_SF == NULL)
495 return -1;
496 n = PySequence_Fast_GET_SIZE(v_as_SF);
Raymond Hettinger42bec932004-03-12 16:38:17 +0000497 vitem = PySequence_Fast_ITEMS(v_as_SF);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000498 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000499 if (ilow < 0)
500 ilow = 0;
501 else if (ilow > a->ob_size)
502 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000503 if (ihigh < ilow)
504 ihigh = ilow;
505 else if (ihigh > a->ob_size)
506 ihigh = a->ob_size;
507 item = a->ob_item;
508 d = n - (ihigh-ilow);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000509 if (ihigh > ilow) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000510 p = recycle = PyMem_NEW(PyObject *, (ihigh-ilow));
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000511 if (recycle == NULL) {
512 PyErr_NoMemory();
513 return -1;
514 }
515 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000516 else
517 p = recycle = NULL;
518 if (d <= 0) { /* Delete -d items; recycle ihigh-ilow items */
Raymond Hettinger66d31f82004-03-10 11:44:04 +0000519 memcpy(p, &item[ilow], (ihigh - ilow)*sizeof(PyObject *));
Raymond Hettingerf889e102004-03-09 08:04:33 +0000520 p += ihigh - ilow;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000521 if (d < 0) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000522 memmove(&item[ihigh+d], &item[ihigh],
523 (a->ob_size - ihigh)*sizeof(PyObject *));
Raymond Hettinger0e916432004-03-14 06:42:23 +0000524 list_resize(a, a->ob_size + d, 1);
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000525 item = a->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000526 }
527 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000528 else { /* Insert d items; recycle ihigh-ilow items */
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000529 s = a->ob_size;
Raymond Hettinger0e916432004-03-14 06:42:23 +0000530 if (list_resize(a, s+d, 1) == -1) {
Guido van Rossumb18618d2000-05-03 23:44:39 +0000531 if (recycle != NULL)
532 PyMem_DEL(recycle);
Raymond Hettinger2731ae42004-02-14 03:07:21 +0000533 return -1;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000534 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000535 item = a->ob_item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000536 memmove(&item[ihigh+d], &item[ihigh],
537 (s - ihigh)*sizeof(PyObject *));
Raymond Hettinger66d31f82004-03-10 11:44:04 +0000538 memcpy(p, &item[ilow], (ihigh - ilow)*sizeof(PyObject *));
Raymond Hettingerf889e102004-03-09 08:04:33 +0000539 p += ihigh - ilow;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000540 }
541 for (k = 0; k < n; k++, ilow++) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000542 PyObject *w = vitem[k];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000543 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000544 item[ilow] = w;
545 }
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000546 if (recycle) {
547 while (--p >= recycle)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000548 Py_XDECREF(*p);
549 PyMem_DEL(recycle);
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000550 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000551 if (a->ob_size == 0 && a->ob_item != NULL) {
552 PyMem_FREE(a->ob_item);
553 a->ob_item = NULL;
554 }
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000555 Py_XDECREF(v_as_SF);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000556 return 0;
557#undef b
558}
559
Guido van Rossum234f9421993-06-17 12:35:49 +0000560int
Fred Drakea2f55112000-07-09 15:16:51 +0000561PyList_SetSlice(PyObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000562{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000563 if (!PyList_Check(a)) {
564 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000565 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000566 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000567 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000568}
569
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000570static PyObject *
571list_inplace_repeat(PyListObject *self, int n)
572{
573 PyObject **items;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000574 int size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000575
576
577 size = PyList_GET_SIZE(self);
578 if (size == 0) {
579 Py_INCREF(self);
580 return (PyObject *)self;
581 }
582
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000583 if (n < 1) {
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000584 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000585 self->ob_item = NULL;
586 self->ob_size = 0;
587 for (i = 0; i < size; i++)
588 Py_XDECREF(items[i]);
589 PyMem_DEL(items);
590 Py_INCREF(self);
591 return (PyObject *)self;
592 }
593
Raymond Hettinger0e916432004-03-14 06:42:23 +0000594 if (list_resize(self, size*n, 1) == -1)
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000595 return NULL;
596
597 p = size;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000598 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000599 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
600 for (j = 0; j < size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000601 PyObject *o = items[j];
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000602 Py_INCREF(o);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000603 items[p++] = o;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000604 }
605 }
606 Py_INCREF(self);
607 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000608}
609
Guido van Rossum4a450d01991-04-03 19:05:18 +0000610static int
Fred Drakea2f55112000-07-09 15:16:51 +0000611list_ass_item(PyListObject *a, int i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000612{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000613 PyObject *old_value;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000614 if (i < 0 || i >= a->ob_size) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000615 PyErr_SetString(PyExc_IndexError,
616 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000617 return -1;
618 }
619 if (v == NULL)
620 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000621 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000622 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000623 a->ob_item[i] = v;
Tim Peters3b01a122002-07-19 02:35:45 +0000624 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000625 return 0;
626}
627
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000628static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000629ins(PyListObject *self, int where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000630{
631 if (ins1(self, where, v) != 0)
632 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000633 Py_INCREF(Py_None);
634 return Py_None;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000635}
636
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000637static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000638listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000639{
640 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000641 PyObject *v;
Guido van Rossumc00a9382000-02-24 21:48:29 +0000642 if (!PyArg_ParseTuple(args, "iO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000643 return NULL;
Guido van Rossumbf80e541993-02-08 15:49:17 +0000644 return ins(self, i, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000645}
646
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000647static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000648listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000649{
Guido van Rossumbf80e541993-02-08 15:49:17 +0000650 return ins(self, (int) self->ob_size, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000651}
652
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000653static int
654listextend_internal(PyListObject *self, PyObject *b)
Barry Warsawdedf6d61998-10-09 16:37:25 +0000655{
Raymond Hettinger6e058d72004-03-12 15:30:38 +0000656 int selflen = PyList_GET_SIZE(self);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000657 int blen;
658 register int i;
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000659 PyObject **src, **dest;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000660
Raymond Hettinger6e058d72004-03-12 15:30:38 +0000661 blen = PyObject_Size(b);
662 if (blen == 0) {
Barry Warsawdedf6d61998-10-09 16:37:25 +0000663 /* short circuit when b is empty */
Jeremy Hyltondb60bb52001-01-03 22:32:16 +0000664 Py_DECREF(b);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000665 return 0;
Jeremy Hyltondb60bb52001-01-03 22:32:16 +0000666 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000667
Barry Warsawdedf6d61998-10-09 16:37:25 +0000668 if (self == (PyListObject*)b) {
669 /* as in list_ass_slice() we must special case the
670 * situation: a.extend(a)
671 *
672 * XXX: I think this way ought to be faster than using
673 * list_slice() the way list_ass_slice() does.
674 */
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000675 Py_DECREF(b);
Barry Warsawdedf6d61998-10-09 16:37:25 +0000676 b = PyList_New(selflen);
677 if (!b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000678 return -1;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000679 for (i = 0; i < selflen; i++) {
680 PyObject *o = PyList_GET_ITEM(self, i);
681 Py_INCREF(o);
682 PyList_SET_ITEM(b, i, o);
683 }
684 }
Barry Warsawdedf6d61998-10-09 16:37:25 +0000685
Raymond Hettinger0e916432004-03-14 06:42:23 +0000686 if (list_resize(self, selflen + blen, 0) == -1) {
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000687 Py_DECREF(b);
688 return -1;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000689 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000690
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000691 /* populate the end of self with b's items */
Raymond Hettinger42bec932004-03-12 16:38:17 +0000692 src = PySequence_Fast_ITEMS(b);
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000693 dest = self->ob_item + selflen;
694 for (i = 0; i < blen; i++) {
695 PyObject *o = src[i];
696 Py_INCREF(o);
697 dest[i] = o;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000698 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +0000699 Py_DECREF(b);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000700 return 0;
Barry Warsawdedf6d61998-10-09 16:37:25 +0000701}
702
Barry Warsawdedf6d61998-10-09 16:37:25 +0000703static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000704listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000705{
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000706 PyObject *it; /* iter(v) */
707 int m; /* size of self */
708 int n; /* guess for size of b */
709 int mn; /* m + n */
710 int i;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000711 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000712
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000713 /* Special cases:
714 1) lists and tuples which can use PySequence_Fast ops
715 2) extending self to self requires making a copy first
716 */
717 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
718 b = PySequence_Fast(b, "argument must be iterable");
719 if (!b)
720 return NULL;
721 if (listextend_internal(self, b) < 0)
722 return NULL;
723 Py_RETURN_NONE;
724 }
725
726 it = PyObject_GetIter(b);
727 if (it == NULL)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000728 return NULL;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000729 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000730
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000731 /* Guess a result list size. */
732 n = PyObject_Size(b);
733 if (n < 0) {
734 PyErr_Clear();
735 n = 8; /* arbitrary */
736 }
737 m = self->ob_size;
738 mn = m + n;
Raymond Hettinger0e916432004-03-14 06:42:23 +0000739 if (list_resize(self, mn, 0) == -1)
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000740 goto error;
741 memset(&(self->ob_item[m]), 0, sizeof(*self->ob_item) * n);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000742
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000743 /* Run iterator to exhaustion. */
744 for (i = m; ; i++) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000745 PyObject *item = iternext(it);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000746 if (item == NULL) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000747 if (PyErr_Occurred()) {
748 if (PyErr_ExceptionMatches(PyExc_StopIteration))
749 PyErr_Clear();
750 else
751 goto error;
752 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000753 break;
754 }
755 if (i < mn)
756 PyList_SET_ITEM(self, i, item); /* steals ref */
757 else {
758 int status = ins1(self, self->ob_size, item);
759 Py_DECREF(item); /* append creates a new ref */
760 if (status < 0)
761 goto error;
762 }
763 }
764
765 /* Cut back result list if initial guess was too large. */
766 if (i < mn && self != NULL) {
767 if (list_ass_slice(self, i, mn, (PyObject *)NULL) != 0)
768 goto error;
769 }
770 Py_DECREF(it);
771 Py_RETURN_NONE;
772
773 error:
774 Py_DECREF(it);
775 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000776}
777
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000778PyObject *
779_PyList_Extend(PyListObject *self, PyObject *b)
780{
781 return listextend(self, b);
782}
783
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000784static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000785list_inplace_concat(PyListObject *self, PyObject *other)
786{
787 PyObject *result;
788
789 result = listextend(self, other);
790 if (result == NULL)
791 return result;
792 Py_DECREF(result);
793 Py_INCREF(self);
794 return (PyObject *)self;
795}
796
797static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000798listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000799{
800 int i = -1;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000801 PyObject *v, *arg = NULL;
802
803 if (!PyArg_UnpackTuple(args, "pop", 0, 1, &arg))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000804 return NULL;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000805 if (arg != NULL) {
806 if (PyInt_Check(arg))
807 i = (int)(PyInt_AS_LONG((PyIntObject*) arg));
Raymond Hettingerfa6c6f82004-02-19 06:12:06 +0000808 else if (!PyArg_ParseTuple(args, "|i:pop", &i))
809 return NULL;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000810 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000811 if (self->ob_size == 0) {
812 /* Special-case most common failure cause */
813 PyErr_SetString(PyExc_IndexError, "pop from empty list");
814 return NULL;
815 }
816 if (i < 0)
817 i += self->ob_size;
818 if (i < 0 || i >= self->ob_size) {
819 PyErr_SetString(PyExc_IndexError, "pop index out of range");
820 return NULL;
821 }
822 v = self->ob_item[i];
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000823 if (i == self->ob_size - 1) {
Raymond Hettinger0e916432004-03-14 06:42:23 +0000824 if (list_resize(self, self->ob_size - 1, 0) == -1)
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000825 return NULL;
826 return v;
827 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000828 Py_INCREF(v);
829 if (list_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) {
830 Py_DECREF(v);
831 return NULL;
832 }
833 return v;
834}
835
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000836/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
837static void
838reverse_slice(PyObject **lo, PyObject **hi)
839{
840 assert(lo && hi);
841
842 --hi;
843 while (lo < hi) {
844 PyObject *t = *lo;
845 *lo = *hi;
846 *hi = t;
847 ++lo;
848 --hi;
849 }
850}
851
Tim Petersa64dc242002-08-01 02:13:36 +0000852/* Lots of code for an adaptive, stable, natural mergesort. There are many
853 * pieces to this algorithm; read listsort.txt for overviews and details.
854 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000855
Guido van Rossum3f236de1996-12-10 23:55:39 +0000856/* Comparison function. Takes care of calling a user-supplied
Tim Peters66860f62002-08-04 17:47:26 +0000857 * comparison function (any callable Python object), which must not be
858 * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool
859 * with Py_LT if you know it's NULL).
Tim Petersa64dc242002-08-01 02:13:36 +0000860 * Returns -1 on error, 1 if x < y, 0 if x >= y.
861 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000862static int
Tim Petersa8c974c2002-07-19 03:30:57 +0000863islt(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000864{
Tim Petersf2a04732002-07-11 21:46:16 +0000865 PyObject *res;
866 PyObject *args;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000867 int i;
868
Tim Peters66860f62002-08-04 17:47:26 +0000869 assert(compare != NULL);
Tim Petersa8c974c2002-07-19 03:30:57 +0000870 /* Call the user's comparison function and translate the 3-way
871 * result into true or false (or error).
872 */
Tim Petersf2a04732002-07-11 21:46:16 +0000873 args = PyTuple_New(2);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000874 if (args == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000875 return -1;
Tim Petersf2a04732002-07-11 21:46:16 +0000876 Py_INCREF(x);
877 Py_INCREF(y);
878 PyTuple_SET_ITEM(args, 0, x);
879 PyTuple_SET_ITEM(args, 1, y);
Tim Peters58cf3612002-07-15 05:16:13 +0000880 res = PyObject_Call(compare, args, NULL);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000881 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000882 if (res == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000883 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000884 if (!PyInt_Check(res)) {
885 Py_DECREF(res);
886 PyErr_SetString(PyExc_TypeError,
Guido van Rossum9bcd1d71999-04-19 17:44:39 +0000887 "comparison function must return int");
Tim Petersa8c974c2002-07-19 03:30:57 +0000888 return -1;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000889 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000890 i = PyInt_AsLong(res);
891 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +0000892 return i < 0;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000893}
894
Tim Peters66860f62002-08-04 17:47:26 +0000895/* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
896 * islt. This avoids a layer of function call in the usual case, and
897 * sorting does many comparisons.
898 * Returns -1 on error, 1 if x < y, 0 if x >= y.
899 */
900#define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
901 PyObject_RichCompareBool(X, Y, Py_LT) : \
902 islt(X, Y, COMPARE))
903
904/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +0000905 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
906 started. It makes more sense in context <wink>. X and Y are PyObject*s.
907*/
Tim Peters66860f62002-08-04 17:47:26 +0000908#define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
Tim Petersa8c974c2002-07-19 03:30:57 +0000909 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000910
911/* binarysort is the best method for sorting small arrays: it does
912 few compares, but can do data movement quadratic in the number of
913 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000914 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +0000915 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000916 On entry, must have lo <= start <= hi, and that [lo, start) is already
917 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +0000918 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000919 Even in case of error, the output slice will be some permutation of
920 the input (nothing is lost or duplicated).
921*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000922static int
Fred Drakea2f55112000-07-09 15:16:51 +0000923binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
924 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000925{
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000926 register int k;
927 register PyObject **l, **p, **r;
928 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000929
Tim Petersa8c974c2002-07-19 03:30:57 +0000930 assert(lo <= start && start <= hi);
931 /* assert [lo, start) is sorted */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000932 if (lo == start)
933 ++start;
934 for (; start < hi; ++start) {
935 /* set l to where *start belongs */
936 l = lo;
937 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000938 pivot = *r;
Tim Peters0fe977c2002-07-19 06:12:32 +0000939 /* Invariants:
940 * pivot >= all in [lo, l).
941 * pivot < all in [r, start).
942 * The second is vacuously true at the start.
943 */
944 assert(l < r);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000945 do {
946 p = l + ((r - l) >> 1);
Tim Petersa8c974c2002-07-19 03:30:57 +0000947 IFLT(pivot, *p)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000948 r = p;
949 else
Tim Peters0fe977c2002-07-19 06:12:32 +0000950 l = p+1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000951 } while (l < r);
Tim Peters0fe977c2002-07-19 06:12:32 +0000952 assert(l == r);
953 /* The invariants still hold, so pivot >= all in [lo, l) and
954 pivot < all in [l, start), so pivot belongs at l. Note
955 that if there are elements equal to pivot, l points to the
956 first slot after them -- that's why this sort is stable.
957 Slide over to make room.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000958 Caution: using memmove is much slower under MSVC 5;
959 we're not usually moving many slots. */
960 for (p = start; p > l; --p)
961 *p = *(p-1);
962 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000963 }
Guido van Rossum3f236de1996-12-10 23:55:39 +0000964 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000965
966 fail:
967 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000968}
969
Tim Petersa64dc242002-08-01 02:13:36 +0000970/*
971Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
972is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000973
Tim Petersa64dc242002-08-01 02:13:36 +0000974 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000975
Tim Petersa64dc242002-08-01 02:13:36 +0000976or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000977
Tim Petersa64dc242002-08-01 02:13:36 +0000978 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +0000979
Tim Petersa64dc242002-08-01 02:13:36 +0000980Boolean *descending is set to 0 in the former case, or to 1 in the latter.
981For its intended use in a stable mergesort, the strictness of the defn of
982"descending" is needed so that the caller can safely reverse a descending
983sequence without violating stability (strict > ensures there are no equal
984elements to get out of order).
985
986Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000987*/
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000988static int
Tim Petersa64dc242002-08-01 02:13:36 +0000989count_run(PyObject **lo, PyObject **hi, PyObject *compare, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000990{
Tim Petersa64dc242002-08-01 02:13:36 +0000991 int k;
992 int n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000993
Tim Petersa64dc242002-08-01 02:13:36 +0000994 assert(lo < hi);
995 *descending = 0;
996 ++lo;
997 if (lo == hi)
998 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000999
Tim Petersa64dc242002-08-01 02:13:36 +00001000 n = 2;
1001 IFLT(*lo, *(lo-1)) {
1002 *descending = 1;
1003 for (lo = lo+1; lo < hi; ++lo, ++n) {
1004 IFLT(*lo, *(lo-1))
1005 ;
1006 else
1007 break;
1008 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001009 }
Tim Petersa64dc242002-08-01 02:13:36 +00001010 else {
1011 for (lo = lo+1; lo < hi; ++lo, ++n) {
1012 IFLT(*lo, *(lo-1))
1013 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001014 }
1015 }
1016
Tim Petersa64dc242002-08-01 02:13:36 +00001017 return n;
1018fail:
1019 return -1;
1020}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001021
Tim Petersa64dc242002-08-01 02:13:36 +00001022/*
1023Locate the proper position of key in a sorted vector; if the vector contains
1024an element equal to key, return the position immediately to the left of
1025the leftmost equal element. [gallop_right() does the same except returns
1026the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001027
Tim Petersa64dc242002-08-01 02:13:36 +00001028"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001029
Tim Petersa64dc242002-08-01 02:13:36 +00001030"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1031hint is to the final result, the faster this runs.
1032
1033The return value is the int k in 0..n such that
1034
1035 a[k-1] < key <= a[k]
1036
1037pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1038key belongs at index k; or, IOW, the first k elements of a should precede
1039key, and the last n-k should follow key.
1040
1041Returns -1 on error. See listsort.txt for info on the method.
1042*/
1043static int
1044gallop_left(PyObject *key, PyObject **a, int n, int hint, PyObject *compare)
1045{
1046 int ofs;
1047 int lastofs;
1048 int k;
1049
1050 assert(key && a && n > 0 && hint >= 0 && hint < n);
1051
1052 a += hint;
1053 lastofs = 0;
1054 ofs = 1;
1055 IFLT(*a, key) {
1056 /* a[hint] < key -- gallop right, until
1057 * a[hint + lastofs] < key <= a[hint + ofs]
1058 */
1059 const int maxofs = n - hint; /* &a[n-1] is highest */
1060 while (ofs < maxofs) {
1061 IFLT(a[ofs], key) {
1062 lastofs = ofs;
1063 ofs = (ofs << 1) + 1;
1064 if (ofs <= 0) /* int overflow */
1065 ofs = maxofs;
1066 }
1067 else /* key <= a[hint + ofs] */
1068 break;
1069 }
1070 if (ofs > maxofs)
1071 ofs = maxofs;
1072 /* Translate back to offsets relative to &a[0]. */
1073 lastofs += hint;
1074 ofs += hint;
1075 }
1076 else {
1077 /* key <= a[hint] -- gallop left, until
1078 * a[hint - ofs] < key <= a[hint - lastofs]
1079 */
1080 const int maxofs = hint + 1; /* &a[0] is lowest */
1081 while (ofs < maxofs) {
1082 IFLT(*(a-ofs), key)
1083 break;
1084 /* key <= a[hint - ofs] */
1085 lastofs = ofs;
1086 ofs = (ofs << 1) + 1;
1087 if (ofs <= 0) /* int overflow */
1088 ofs = maxofs;
1089 }
1090 if (ofs > maxofs)
1091 ofs = maxofs;
1092 /* Translate back to positive offsets relative to &a[0]. */
1093 k = lastofs;
1094 lastofs = hint - ofs;
1095 ofs = hint - k;
1096 }
1097 a -= hint;
1098
1099 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1100 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1101 * right of lastofs but no farther right than ofs. Do a binary
1102 * search, with invariant a[lastofs-1] < key <= a[ofs].
1103 */
1104 ++lastofs;
1105 while (lastofs < ofs) {
1106 int m = lastofs + ((ofs - lastofs) >> 1);
1107
1108 IFLT(a[m], key)
1109 lastofs = m+1; /* a[m] < key */
1110 else
1111 ofs = m; /* key <= a[m] */
1112 }
1113 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1114 return ofs;
1115
1116fail:
1117 return -1;
1118}
1119
1120/*
1121Exactly like gallop_left(), except that if key already exists in a[0:n],
1122finds the position immediately to the right of the rightmost equal value.
1123
1124The return value is the int k in 0..n such that
1125
1126 a[k-1] <= key < a[k]
1127
1128or -1 if error.
1129
1130The code duplication is massive, but this is enough different given that
1131we're sticking to "<" comparisons that it's much harder to follow if
1132written as one routine with yet another "left or right?" flag.
1133*/
1134static int
1135gallop_right(PyObject *key, PyObject **a, int n, int hint, PyObject *compare)
1136{
1137 int ofs;
1138 int lastofs;
1139 int k;
1140
1141 assert(key && a && n > 0 && hint >= 0 && hint < n);
1142
1143 a += hint;
1144 lastofs = 0;
1145 ofs = 1;
1146 IFLT(key, *a) {
1147 /* key < a[hint] -- gallop left, until
1148 * a[hint - ofs] <= key < a[hint - lastofs]
1149 */
1150 const int maxofs = hint + 1; /* &a[0] is lowest */
1151 while (ofs < maxofs) {
1152 IFLT(key, *(a-ofs)) {
1153 lastofs = ofs;
1154 ofs = (ofs << 1) + 1;
1155 if (ofs <= 0) /* int overflow */
1156 ofs = maxofs;
1157 }
1158 else /* a[hint - ofs] <= key */
1159 break;
1160 }
1161 if (ofs > maxofs)
1162 ofs = maxofs;
1163 /* Translate back to positive offsets relative to &a[0]. */
1164 k = lastofs;
1165 lastofs = hint - ofs;
1166 ofs = hint - k;
1167 }
1168 else {
1169 /* a[hint] <= key -- gallop right, until
1170 * a[hint + lastofs] <= key < a[hint + ofs]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001171 */
Tim Petersa64dc242002-08-01 02:13:36 +00001172 const int maxofs = n - hint; /* &a[n-1] is highest */
1173 while (ofs < maxofs) {
1174 IFLT(key, a[ofs])
1175 break;
1176 /* a[hint + ofs] <= key */
1177 lastofs = ofs;
1178 ofs = (ofs << 1) + 1;
1179 if (ofs <= 0) /* int overflow */
1180 ofs = maxofs;
1181 }
1182 if (ofs > maxofs)
1183 ofs = maxofs;
1184 /* Translate back to offsets relative to &a[0]. */
1185 lastofs += hint;
1186 ofs += hint;
1187 }
1188 a -= hint;
1189
1190 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1191 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1192 * right of lastofs but no farther right than ofs. Do a binary
1193 * search, with invariant a[lastofs-1] <= key < a[ofs].
1194 */
1195 ++lastofs;
1196 while (lastofs < ofs) {
1197 int m = lastofs + ((ofs - lastofs) >> 1);
1198
1199 IFLT(key, a[m])
1200 ofs = m; /* key < a[m] */
1201 else
1202 lastofs = m+1; /* a[m] <= key */
1203 }
1204 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1205 return ofs;
1206
1207fail:
1208 return -1;
1209}
1210
1211/* The maximum number of entries in a MergeState's pending-runs stack.
1212 * This is enough to sort arrays of size up to about
1213 * 32 * phi ** MAX_MERGE_PENDING
1214 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1215 * with 2**64 elements.
1216 */
1217#define MAX_MERGE_PENDING 85
1218
Tim Peterse05f65a2002-08-10 05:21:15 +00001219/* When we get into galloping mode, we stay there until both runs win less
1220 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001221 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001222#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001223
1224/* Avoid malloc for small temp arrays. */
1225#define MERGESTATE_TEMP_SIZE 256
1226
1227/* One MergeState exists on the stack per invocation of mergesort. It's just
1228 * a convenient way to pass state around among the helper functions.
1229 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001230struct s_slice {
1231 PyObject **base;
1232 int len;
1233};
1234
Tim Petersa64dc242002-08-01 02:13:36 +00001235typedef struct s_MergeState {
1236 /* The user-supplied comparison function. or NULL if none given. */
1237 PyObject *compare;
1238
Tim Peterse05f65a2002-08-10 05:21:15 +00001239 /* This controls when we get *into* galloping mode. It's initialized
1240 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1241 * random data, and lower for highly structured data.
1242 */
1243 int min_gallop;
1244
Tim Petersa64dc242002-08-01 02:13:36 +00001245 /* 'a' is temp storage to help with merges. It contains room for
1246 * alloced entries.
1247 */
1248 PyObject **a; /* may point to temparray below */
1249 int alloced;
1250
1251 /* A stack of n pending runs yet to be merged. Run #i starts at
1252 * address base[i] and extends for len[i] elements. It's always
1253 * true (so long as the indices are in bounds) that
1254 *
Tim Peterse05f65a2002-08-10 05:21:15 +00001255 * pending[i].base + pending[i].len == pending[i+1].base
Tim Petersa64dc242002-08-01 02:13:36 +00001256 *
1257 * so we could cut the storage for this, but it's a minor amount,
1258 * and keeping all the info explicit simplifies the code.
1259 */
1260 int n;
Tim Peterse05f65a2002-08-10 05:21:15 +00001261 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001262
1263 /* 'a' points to this when possible, rather than muck with malloc. */
1264 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1265} MergeState;
1266
1267/* Conceptually a MergeState's constructor. */
1268static void
1269merge_init(MergeState *ms, PyObject *compare)
1270{
1271 assert(ms != NULL);
1272 ms->compare = compare;
1273 ms->a = ms->temparray;
1274 ms->alloced = MERGESTATE_TEMP_SIZE;
1275 ms->n = 0;
Tim Peterse05f65a2002-08-10 05:21:15 +00001276 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001277}
1278
1279/* Free all the temp memory owned by the MergeState. This must be called
1280 * when you're done with a MergeState, and may be called before then if
1281 * you want to free the temp memory early.
1282 */
1283static void
1284merge_freemem(MergeState *ms)
1285{
1286 assert(ms != NULL);
1287 if (ms->a != ms->temparray)
1288 PyMem_Free(ms->a);
1289 ms->a = ms->temparray;
1290 ms->alloced = MERGESTATE_TEMP_SIZE;
1291}
1292
1293/* Ensure enough temp memory for 'need' array slots is available.
1294 * Returns 0 on success and -1 if the memory can't be gotten.
1295 */
1296static int
1297merge_getmem(MergeState *ms, int need)
1298{
1299 assert(ms != NULL);
1300 if (need <= ms->alloced)
1301 return 0;
1302 /* Don't realloc! That can cost cycles to copy the old data, but
1303 * we don't care what's in the block.
1304 */
1305 merge_freemem(ms);
1306 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1307 if (ms->a) {
1308 ms->alloced = need;
1309 return 0;
1310 }
1311 PyErr_NoMemory();
1312 merge_freemem(ms); /* reset to sane state */
1313 return -1;
1314}
1315#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1316 merge_getmem(MS, NEED))
1317
1318/* Merge the na elements starting at pa with the nb elements starting at pb
1319 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1320 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1321 * merge, and should have na <= nb. See listsort.txt for more info.
1322 * Return 0 if successful, -1 if error.
1323 */
1324static int
1325merge_lo(MergeState *ms, PyObject **pa, int na, PyObject **pb, int nb)
1326{
1327 int k;
1328 PyObject *compare;
1329 PyObject **dest;
1330 int result = -1; /* guilty until proved innocent */
Tim Peterse05f65a2002-08-10 05:21:15 +00001331 int min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001332
1333 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1334 if (MERGE_GETMEM(ms, na) < 0)
1335 return -1;
1336 memcpy(ms->a, pa, na * sizeof(PyObject*));
1337 dest = pa;
1338 pa = ms->a;
1339
1340 *dest++ = *pb++;
1341 --nb;
1342 if (nb == 0)
1343 goto Succeed;
1344 if (na == 1)
1345 goto CopyB;
1346
1347 compare = ms->compare;
1348 for (;;) {
1349 int acount = 0; /* # of times A won in a row */
1350 int bcount = 0; /* # of times B won in a row */
1351
1352 /* Do the straightforward thing until (if ever) one run
1353 * appears to win consistently.
1354 */
1355 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001356 assert(na > 1 && nb > 0);
Tim Peters66860f62002-08-04 17:47:26 +00001357 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001358 if (k) {
1359 if (k < 0)
1360 goto Fail;
1361 *dest++ = *pb++;
1362 ++bcount;
1363 acount = 0;
1364 --nb;
1365 if (nb == 0)
1366 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001367 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001368 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001369 }
1370 else {
Tim Petersa64dc242002-08-01 02:13:36 +00001371 *dest++ = *pa++;
1372 ++acount;
1373 bcount = 0;
1374 --na;
1375 if (na == 1)
1376 goto CopyB;
Tim Peterse05f65a2002-08-10 05:21:15 +00001377 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001378 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001379 }
Tim Petersa64dc242002-08-01 02:13:36 +00001380 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001381
Tim Petersa64dc242002-08-01 02:13:36 +00001382 /* One run is winning so consistently that galloping may
1383 * be a huge win. So try that, and continue galloping until
1384 * (if ever) neither run appears to be winning consistently
1385 * anymore.
1386 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001387 ++min_gallop;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001388 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001389 assert(na > 1 && nb > 0);
1390 min_gallop -= min_gallop > 1;
1391 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001392 k = gallop_right(*pb, pa, na, 0, compare);
1393 acount = k;
1394 if (k) {
1395 if (k < 0)
1396 goto Fail;
1397 memcpy(dest, pa, k * sizeof(PyObject *));
1398 dest += k;
1399 pa += k;
1400 na -= k;
1401 if (na == 1)
1402 goto CopyB;
1403 /* na==0 is impossible now if the comparison
1404 * function is consistent, but we can't assume
1405 * that it is.
1406 */
1407 if (na == 0)
1408 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001409 }
Tim Petersa64dc242002-08-01 02:13:36 +00001410 *dest++ = *pb++;
1411 --nb;
1412 if (nb == 0)
1413 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001414
Tim Petersa64dc242002-08-01 02:13:36 +00001415 k = gallop_left(*pa, pb, nb, 0, compare);
1416 bcount = k;
1417 if (k) {
1418 if (k < 0)
1419 goto Fail;
1420 memmove(dest, pb, k * sizeof(PyObject *));
1421 dest += k;
1422 pb += k;
1423 nb -= k;
1424 if (nb == 0)
1425 goto Succeed;
1426 }
1427 *dest++ = *pa++;
1428 --na;
1429 if (na == 1)
1430 goto CopyB;
1431 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001432 ++min_gallop; /* penalize it for leaving galloping mode */
1433 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001434 }
1435Succeed:
1436 result = 0;
1437Fail:
1438 if (na)
1439 memcpy(dest, pa, na * sizeof(PyObject*));
1440 return result;
1441CopyB:
1442 assert(na == 1 && nb > 0);
1443 /* The last element of pa belongs at the end of the merge. */
1444 memmove(dest, pb, nb * sizeof(PyObject *));
1445 dest[nb] = *pa;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001446 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001447}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001448
Tim Petersa64dc242002-08-01 02:13:36 +00001449/* Merge the na elements starting at pa with the nb elements starting at pb
1450 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1451 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1452 * merge, and should have na >= nb. See listsort.txt for more info.
1453 * Return 0 if successful, -1 if error.
1454 */
1455static int
1456merge_hi(MergeState *ms, PyObject **pa, int na, PyObject **pb, int nb)
1457{
1458 int k;
1459 PyObject *compare;
1460 PyObject **dest;
1461 int result = -1; /* guilty until proved innocent */
1462 PyObject **basea;
1463 PyObject **baseb;
Tim Peterse05f65a2002-08-10 05:21:15 +00001464 int min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001465
1466 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1467 if (MERGE_GETMEM(ms, nb) < 0)
1468 return -1;
1469 dest = pb + nb - 1;
1470 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1471 basea = pa;
1472 baseb = ms->a;
1473 pb = ms->a + nb - 1;
1474 pa += na - 1;
1475
1476 *dest-- = *pa--;
1477 --na;
1478 if (na == 0)
1479 goto Succeed;
1480 if (nb == 1)
1481 goto CopyA;
1482
1483 compare = ms->compare;
1484 for (;;) {
1485 int acount = 0; /* # of times A won in a row */
1486 int bcount = 0; /* # of times B won in a row */
1487
1488 /* Do the straightforward thing until (if ever) one run
1489 * appears to win consistently.
1490 */
1491 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001492 assert(na > 0 && nb > 1);
Tim Peters66860f62002-08-04 17:47:26 +00001493 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001494 if (k) {
1495 if (k < 0)
1496 goto Fail;
1497 *dest-- = *pa--;
1498 ++acount;
1499 bcount = 0;
1500 --na;
1501 if (na == 0)
1502 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001503 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001504 break;
1505 }
1506 else {
1507 *dest-- = *pb--;
1508 ++bcount;
1509 acount = 0;
1510 --nb;
1511 if (nb == 1)
1512 goto CopyA;
Tim Peterse05f65a2002-08-10 05:21:15 +00001513 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001514 break;
1515 }
1516 }
1517
1518 /* One run is winning so consistently that galloping may
1519 * be a huge win. So try that, and continue galloping until
1520 * (if ever) neither run appears to be winning consistently
1521 * anymore.
1522 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001523 ++min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001524 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001525 assert(na > 0 && nb > 1);
1526 min_gallop -= min_gallop > 1;
1527 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001528 k = gallop_right(*pb, basea, na, na-1, compare);
1529 if (k < 0)
1530 goto Fail;
1531 k = na - k;
1532 acount = k;
1533 if (k) {
1534 dest -= k;
1535 pa -= k;
1536 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1537 na -= k;
1538 if (na == 0)
1539 goto Succeed;
1540 }
1541 *dest-- = *pb--;
1542 --nb;
1543 if (nb == 1)
1544 goto CopyA;
1545
1546 k = gallop_left(*pa, baseb, nb, nb-1, compare);
1547 if (k < 0)
1548 goto Fail;
1549 k = nb - k;
1550 bcount = k;
1551 if (k) {
1552 dest -= k;
1553 pb -= k;
1554 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1555 nb -= k;
1556 if (nb == 1)
1557 goto CopyA;
1558 /* nb==0 is impossible now if the comparison
1559 * function is consistent, but we can't assume
1560 * that it is.
1561 */
1562 if (nb == 0)
1563 goto Succeed;
1564 }
1565 *dest-- = *pa--;
1566 --na;
1567 if (na == 0)
1568 goto Succeed;
1569 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001570 ++min_gallop; /* penalize it for leaving galloping mode */
1571 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001572 }
1573Succeed:
1574 result = 0;
1575Fail:
1576 if (nb)
1577 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1578 return result;
1579CopyA:
1580 assert(nb == 1 && na > 0);
1581 /* The first element of pb belongs at the front of the merge. */
1582 dest -= na;
1583 pa -= na;
1584 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1585 *dest = *pb;
1586 return 0;
1587}
1588
1589/* Merge the two runs at stack indices i and i+1.
1590 * Returns 0 on success, -1 on error.
1591 */
1592static int
1593merge_at(MergeState *ms, int i)
1594{
1595 PyObject **pa, **pb;
1596 int na, nb;
1597 int k;
1598 PyObject *compare;
1599
1600 assert(ms != NULL);
1601 assert(ms->n >= 2);
1602 assert(i >= 0);
1603 assert(i == ms->n - 2 || i == ms->n - 3);
1604
Tim Peterse05f65a2002-08-10 05:21:15 +00001605 pa = ms->pending[i].base;
1606 na = ms->pending[i].len;
1607 pb = ms->pending[i+1].base;
1608 nb = ms->pending[i+1].len;
Tim Petersa64dc242002-08-01 02:13:36 +00001609 assert(na > 0 && nb > 0);
1610 assert(pa + na == pb);
1611
1612 /* Record the length of the combined runs; if i is the 3rd-last
1613 * run now, also slide over the last run (which isn't involved
1614 * in this merge). The current run i+1 goes away in any case.
1615 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001616 ms->pending[i].len = na + nb;
1617 if (i == ms->n - 3)
1618 ms->pending[i+1] = ms->pending[i+2];
Tim Petersa64dc242002-08-01 02:13:36 +00001619 --ms->n;
1620
1621 /* Where does b start in a? Elements in a before that can be
1622 * ignored (already in place).
1623 */
1624 compare = ms->compare;
1625 k = gallop_right(*pb, pa, na, 0, compare);
1626 if (k < 0)
1627 return -1;
1628 pa += k;
1629 na -= k;
1630 if (na == 0)
1631 return 0;
1632
1633 /* Where does a end in b? Elements in b after that can be
1634 * ignored (already in place).
1635 */
1636 nb = gallop_left(pa[na-1], pb, nb, nb-1, compare);
1637 if (nb <= 0)
1638 return nb;
1639
1640 /* Merge what remains of the runs, using a temp array with
1641 * min(na, nb) elements.
1642 */
1643 if (na <= nb)
1644 return merge_lo(ms, pa, na, pb, nb);
1645 else
1646 return merge_hi(ms, pa, na, pb, nb);
1647}
1648
1649/* Examine the stack of runs waiting to be merged, merging adjacent runs
1650 * until the stack invariants are re-established:
1651 *
1652 * 1. len[-3] > len[-2] + len[-1]
1653 * 2. len[-2] > len[-1]
1654 *
1655 * See listsort.txt for more info.
1656 *
1657 * Returns 0 on success, -1 on error.
1658 */
1659static int
1660merge_collapse(MergeState *ms)
1661{
Tim Peterse05f65a2002-08-10 05:21:15 +00001662 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001663
1664 assert(ms);
1665 while (ms->n > 1) {
1666 int n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001667 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1668 if (p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001669 --n;
1670 if (merge_at(ms, n) < 0)
1671 return -1;
1672 }
Tim Peterse05f65a2002-08-10 05:21:15 +00001673 else if (p[n].len <= p[n+1].len) {
Tim Petersa64dc242002-08-01 02:13:36 +00001674 if (merge_at(ms, n) < 0)
1675 return -1;
1676 }
1677 else
1678 break;
1679 }
1680 return 0;
1681}
1682
1683/* Regardless of invariants, merge all runs on the stack until only one
1684 * remains. This is used at the end of the mergesort.
1685 *
1686 * Returns 0 on success, -1 on error.
1687 */
1688static int
1689merge_force_collapse(MergeState *ms)
1690{
Tim Peterse05f65a2002-08-10 05:21:15 +00001691 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001692
1693 assert(ms);
1694 while (ms->n > 1) {
1695 int n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001696 if (n > 0 && p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001697 --n;
1698 if (merge_at(ms, n) < 0)
1699 return -1;
1700 }
1701 return 0;
1702}
1703
1704/* Compute a good value for the minimum run length; natural runs shorter
1705 * than this are boosted artificially via binary insertion.
1706 *
1707 * If n < 64, return n (it's too small to bother with fancy stuff).
1708 * Else if n is an exact power of 2, return 32.
1709 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1710 * strictly less than, an exact power of 2.
1711 *
1712 * See listsort.txt for more info.
1713 */
1714static int
1715merge_compute_minrun(int n)
1716{
1717 int r = 0; /* becomes 1 if any 1 bits are shifted off */
1718
1719 assert(n >= 0);
1720 while (n >= 64) {
1721 r |= n & 1;
1722 n >>= 1;
1723 }
1724 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001725}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001726
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001727/* Special wrapper to support stable sorting using the decorate-sort-undecorate
1728 pattern. Holds a key which is used for comparisions and the original record
1729 which is returned during the undecorate phase. By exposing only the key
1730 during comparisons, the underlying sort stability characteristics are left
1731 unchanged. Also, if a custom comparison function is used, it will only see
1732 the key instead of a full record. */
1733
1734typedef struct {
1735 PyObject_HEAD
1736 PyObject *key;
1737 PyObject *value;
1738} sortwrapperobject;
1739
1740static PyTypeObject sortwrapper_type;
1741
1742static PyObject *
1743sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
1744{
1745 if (!PyObject_TypeCheck(b, &sortwrapper_type)) {
1746 PyErr_SetString(PyExc_TypeError,
1747 "expected a sortwrapperobject");
1748 return NULL;
1749 }
1750 return PyObject_RichCompare(a->key, b->key, op);
1751}
1752
1753static void
1754sortwrapper_dealloc(sortwrapperobject *so)
1755{
1756 Py_XDECREF(so->key);
1757 Py_XDECREF(so->value);
1758 PyObject_Del(so);
1759}
1760
1761PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
1762
1763static PyTypeObject sortwrapper_type = {
1764 PyObject_HEAD_INIT(&PyType_Type)
1765 0, /* ob_size */
1766 "sortwrapper", /* tp_name */
1767 sizeof(sortwrapperobject), /* tp_basicsize */
1768 0, /* tp_itemsize */
1769 /* methods */
1770 (destructor)sortwrapper_dealloc, /* tp_dealloc */
1771 0, /* tp_print */
1772 0, /* tp_getattr */
1773 0, /* tp_setattr */
1774 0, /* tp_compare */
1775 0, /* tp_repr */
1776 0, /* tp_as_number */
1777 0, /* tp_as_sequence */
1778 0, /* tp_as_mapping */
1779 0, /* tp_hash */
1780 0, /* tp_call */
1781 0, /* tp_str */
1782 PyObject_GenericGetAttr, /* tp_getattro */
1783 0, /* tp_setattro */
1784 0, /* tp_as_buffer */
1785 Py_TPFLAGS_DEFAULT |
1786 Py_TPFLAGS_HAVE_RICHCOMPARE, /* tp_flags */
1787 sortwrapper_doc, /* tp_doc */
1788 0, /* tp_traverse */
1789 0, /* tp_clear */
1790 (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
1791};
1792
1793/* Returns a new reference to a sortwrapper.
1794 Consumes the references to the two underlying objects. */
1795
1796static PyObject *
1797build_sortwrapper(PyObject *key, PyObject *value)
1798{
1799 sortwrapperobject *so;
1800
1801 so = PyObject_New(sortwrapperobject, &sortwrapper_type);
1802 if (so == NULL)
1803 return NULL;
1804 so->key = key;
1805 so->value = value;
1806 return (PyObject *)so;
1807}
1808
1809/* Returns a new reference to the value underlying the wrapper. */
1810static PyObject *
1811sortwrapper_getvalue(PyObject *so)
1812{
1813 PyObject *value;
1814
1815 if (!PyObject_TypeCheck(so, &sortwrapper_type)) {
1816 PyErr_SetString(PyExc_TypeError,
1817 "expected a sortwrapperobject");
1818 return NULL;
1819 }
1820 value = ((sortwrapperobject *)so)->value;
1821 Py_INCREF(value);
1822 return value;
1823}
1824
1825/* Wrapper for user specified cmp functions in combination with a
1826 specified key function. Makes sure the cmp function is presented
1827 with the actual key instead of the sortwrapper */
1828
1829typedef struct {
1830 PyObject_HEAD
1831 PyObject *func;
1832} cmpwrapperobject;
1833
1834static void
1835cmpwrapper_dealloc(cmpwrapperobject *co)
1836{
1837 Py_XDECREF(co->func);
1838 PyObject_Del(co);
1839}
1840
1841static PyObject *
1842cmpwrapper_call(cmpwrapperobject *co, PyObject *args, PyObject *kwds)
1843{
1844 PyObject *x, *y, *xx, *yy;
1845
1846 if (!PyArg_UnpackTuple(args, "", 2, 2, &x, &y))
1847 return NULL;
1848 if (!PyObject_TypeCheck(x, &sortwrapper_type) ||
Raymond Hettingerae4a2992003-10-16 17:16:30 +00001849 !PyObject_TypeCheck(y, &sortwrapper_type)) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001850 PyErr_SetString(PyExc_TypeError,
1851 "expected a sortwrapperobject");
1852 return NULL;
1853 }
1854 xx = ((sortwrapperobject *)x)->key;
1855 yy = ((sortwrapperobject *)y)->key;
1856 return PyObject_CallFunctionObjArgs(co->func, xx, yy, NULL);
1857}
1858
1859PyDoc_STRVAR(cmpwrapper_doc, "cmp() wrapper for sort with custom keys.");
1860
1861static PyTypeObject cmpwrapper_type = {
1862 PyObject_HEAD_INIT(&PyType_Type)
1863 0, /* ob_size */
1864 "cmpwrapper", /* tp_name */
1865 sizeof(cmpwrapperobject), /* tp_basicsize */
1866 0, /* tp_itemsize */
1867 /* methods */
1868 (destructor)cmpwrapper_dealloc, /* tp_dealloc */
1869 0, /* tp_print */
1870 0, /* tp_getattr */
1871 0, /* tp_setattr */
1872 0, /* tp_compare */
1873 0, /* tp_repr */
1874 0, /* tp_as_number */
1875 0, /* tp_as_sequence */
1876 0, /* tp_as_mapping */
1877 0, /* tp_hash */
1878 (ternaryfunc)cmpwrapper_call, /* tp_call */
1879 0, /* tp_str */
1880 PyObject_GenericGetAttr, /* tp_getattro */
1881 0, /* tp_setattro */
1882 0, /* tp_as_buffer */
1883 Py_TPFLAGS_DEFAULT, /* tp_flags */
1884 cmpwrapper_doc, /* tp_doc */
1885};
1886
1887static PyObject *
1888build_cmpwrapper(PyObject *cmpfunc)
1889{
1890 cmpwrapperobject *co;
1891
1892 co = PyObject_New(cmpwrapperobject, &cmpwrapper_type);
1893 if (co == NULL)
1894 return NULL;
1895 Py_INCREF(cmpfunc);
1896 co->func = cmpfunc;
1897 return (PyObject *)co;
1898}
1899
Tim Petersa64dc242002-08-01 02:13:36 +00001900/* An adaptive, stable, natural mergesort. See listsort.txt.
1901 * Returns Py_None on success, NULL on error. Even in case of error, the
1902 * list will be some permutation of its input state (nothing is lost or
1903 * duplicated).
1904 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001905static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001906listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001907{
Tim Petersa64dc242002-08-01 02:13:36 +00001908 MergeState ms;
1909 PyObject **lo, **hi;
1910 int nremaining;
1911 int minrun;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001912 int saved_ob_size, saved_allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00001913 PyObject **saved_ob_item;
1914 PyObject **empty_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001915 PyObject *compare = NULL;
1916 PyObject *result = NULL; /* guilty until proved innocent */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001917 int reverse = 0;
1918 PyObject *keyfunc = NULL;
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001919 int i;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001920 PyObject *key, *value, *kvpair;
1921 static char *kwlist[] = {"cmp", "key", "reverse", 0};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001922
Tim Petersa64dc242002-08-01 02:13:36 +00001923 assert(self != NULL);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001924 assert (PyList_Check(self));
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001925 if (args != NULL) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001926 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:sort",
1927 kwlist, &compare, &keyfunc, &reverse))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001928 return NULL;
1929 }
Skip Montanaro4abd5f02003-01-02 20:51:08 +00001930 if (compare == Py_None)
1931 compare = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001932 if (keyfunc == Py_None)
1933 keyfunc = NULL;
1934 if (compare != NULL && keyfunc != NULL) {
1935 compare = build_cmpwrapper(compare);
1936 if (compare == NULL)
Hye-Shik Chang19cb1932003-12-10 07:31:08 +00001937 return NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001938 } else
1939 Py_XINCREF(compare);
1940
Tim Petersb9099c32002-11-12 22:08:10 +00001941 /* The list is temporarily made empty, so that mutations performed
1942 * by comparison functions can't affect the slice of memory we're
1943 * sorting (allowing mutations during sorting is a core-dump
1944 * factory, since ob_item may change).
1945 */
1946 saved_ob_size = self->ob_size;
1947 saved_ob_item = self->ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001948 saved_allocated = self->allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00001949 self->ob_size = 0;
Tim Peters7049d812004-01-18 20:31:02 +00001950 self->ob_item = empty_ob_item = PyMem_NEW(PyObject *, 0);
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001951 self->allocated = 0;
Tim Peters330f9e92002-07-19 07:05:44 +00001952
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001953 if (keyfunc != NULL) {
1954 for (i=0 ; i < saved_ob_size ; i++) {
1955 value = saved_ob_item[i];
1956 key = PyObject_CallFunctionObjArgs(keyfunc, value,
1957 NULL);
1958 if (key == NULL) {
1959 for (i=i-1 ; i>=0 ; i--) {
1960 kvpair = saved_ob_item[i];
1961 value = sortwrapper_getvalue(kvpair);
1962 saved_ob_item[i] = value;
1963 Py_DECREF(kvpair);
1964 }
1965 if (self->ob_item != empty_ob_item
1966 || self->ob_size) {
1967 /* If the list changed *as well* we
1968 have two errors. We let the first
1969 one "win", but we shouldn't let
1970 what's in the list currently
1971 leak. */
1972 (void)list_ass_slice(
1973 self, 0, self->ob_size,
1974 (PyObject *)NULL);
1975 }
1976
1977 goto dsu_fail;
1978 }
1979 kvpair = build_sortwrapper(key, value);
1980 if (kvpair == NULL)
1981 goto dsu_fail;
1982 saved_ob_item[i] = kvpair;
1983 }
1984 }
1985
1986 /* Reverse sort stability achieved by initially reversing the list,
1987 applying a stable forward sort, then reversing the final result. */
1988 if (reverse && saved_ob_size > 1)
1989 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
1990
1991 merge_init(&ms, compare);
1992
Tim Petersb9099c32002-11-12 22:08:10 +00001993 nremaining = saved_ob_size;
Tim Petersa64dc242002-08-01 02:13:36 +00001994 if (nremaining < 2)
1995 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00001996
Tim Petersa64dc242002-08-01 02:13:36 +00001997 /* March over the array once, left to right, finding natural runs,
1998 * and extending short natural runs to minrun elements.
1999 */
Tim Petersb9099c32002-11-12 22:08:10 +00002000 lo = saved_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00002001 hi = lo + nremaining;
2002 minrun = merge_compute_minrun(nremaining);
2003 do {
2004 int descending;
2005 int n;
Tim Peters330f9e92002-07-19 07:05:44 +00002006
Tim Petersa64dc242002-08-01 02:13:36 +00002007 /* Identify next run. */
2008 n = count_run(lo, hi, compare, &descending);
2009 if (n < 0)
2010 goto fail;
2011 if (descending)
2012 reverse_slice(lo, lo + n);
2013 /* If short, extend to min(minrun, nremaining). */
2014 if (n < minrun) {
2015 const int force = nremaining <= minrun ?
2016 nremaining : minrun;
2017 if (binarysort(lo, lo + force, lo + n, compare) < 0)
2018 goto fail;
2019 n = force;
2020 }
2021 /* Push run onto pending-runs stack, and maybe merge. */
2022 assert(ms.n < MAX_MERGE_PENDING);
Tim Peterse05f65a2002-08-10 05:21:15 +00002023 ms.pending[ms.n].base = lo;
2024 ms.pending[ms.n].len = n;
Tim Petersa64dc242002-08-01 02:13:36 +00002025 ++ms.n;
2026 if (merge_collapse(&ms) < 0)
2027 goto fail;
2028 /* Advance to find next run. */
2029 lo += n;
2030 nremaining -= n;
2031 } while (nremaining);
2032 assert(lo == hi);
Tim Peters330f9e92002-07-19 07:05:44 +00002033
Tim Petersa64dc242002-08-01 02:13:36 +00002034 if (merge_force_collapse(&ms) < 0)
2035 goto fail;
2036 assert(ms.n == 1);
Tim Petersb9099c32002-11-12 22:08:10 +00002037 assert(ms.pending[0].base == saved_ob_item);
2038 assert(ms.pending[0].len == saved_ob_size);
Tim Petersa64dc242002-08-01 02:13:36 +00002039
2040succeed:
2041 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002042fail:
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002043 if (keyfunc != NULL) {
2044 for (i=0 ; i < saved_ob_size ; i++) {
2045 kvpair = saved_ob_item[i];
2046 value = sortwrapper_getvalue(kvpair);
2047 saved_ob_item[i] = value;
2048 Py_DECREF(kvpair);
2049 }
2050 }
2051
Tim Petersb9099c32002-11-12 22:08:10 +00002052 if (self->ob_item != empty_ob_item || self->ob_size) {
2053 /* The user mucked with the list during the sort. */
2054 (void)list_ass_slice(self, 0, self->ob_size, (PyObject *)NULL);
2055 if (result != NULL) {
2056 PyErr_SetString(PyExc_ValueError,
2057 "list modified during sort");
2058 result = NULL;
2059 }
2060 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002061
2062 if (reverse && saved_ob_size > 1)
2063 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2064
2065 merge_freemem(&ms);
2066
2067dsu_fail:
Tim Petersb9099c32002-11-12 22:08:10 +00002068 if (self->ob_item == empty_ob_item)
2069 PyMem_FREE(empty_ob_item);
2070 self->ob_size = saved_ob_size;
2071 self->ob_item = saved_ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002072 self->allocated = saved_allocated;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002073 Py_XDECREF(compare);
Tim Petersa64dc242002-08-01 02:13:36 +00002074 Py_XINCREF(result);
2075 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002076}
Tim Peters330f9e92002-07-19 07:05:44 +00002077#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002078#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002079
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002080int
Fred Drakea2f55112000-07-09 15:16:51 +00002081PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002082{
2083 if (v == NULL || !PyList_Check(v)) {
2084 PyErr_BadInternalCall();
2085 return -1;
2086 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002087 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002088 if (v == NULL)
2089 return -1;
2090 Py_DECREF(v);
2091 return 0;
2092}
2093
Guido van Rossumb86c5492001-02-12 22:06:02 +00002094static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002095listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002096{
Tim Peters326b4482002-07-19 04:04:16 +00002097 if (self->ob_size > 1)
2098 reverse_slice(self->ob_item, self->ob_item + self->ob_size);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002099 Py_INCREF(Py_None);
2100 return Py_None;
Guido van Rossumed98d481991-03-06 13:07:53 +00002101}
2102
Guido van Rossum84c76f51990-10-30 13:32:20 +00002103int
Fred Drakea2f55112000-07-09 15:16:51 +00002104PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002105{
Tim Peters6063e262002-08-08 01:06:39 +00002106 PyListObject *self = (PyListObject *)v;
2107
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002108 if (v == NULL || !PyList_Check(v)) {
2109 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002110 return -1;
2111 }
Tim Peters6063e262002-08-08 01:06:39 +00002112 if (self->ob_size > 1)
2113 reverse_slice(self->ob_item, self->ob_item + self->ob_size);
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002114 return 0;
2115}
2116
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002117PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002118PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002119{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002120 PyObject *w;
2121 PyObject **p;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002122 int n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002123 if (v == NULL || !PyList_Check(v)) {
2124 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002125 return NULL;
2126 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002127 n = ((PyListObject *)v)->ob_size;
2128 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002129 if (w == NULL)
2130 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002131 p = ((PyTupleObject *)w)->ob_item;
Thomas Wouters334fb892000-07-25 12:56:38 +00002132 memcpy((void *)p,
2133 (void *)((PyListObject *)v)->ob_item,
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002134 n*sizeof(PyObject *));
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002135 while (--n >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002136 Py_INCREF(*p);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002137 p++;
2138 }
2139 return w;
2140}
2141
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002142static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002143listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002144{
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002145 int i, start=0, stop=self->ob_size;
2146 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002147
Walter Dörwalde8049bef2003-06-17 19:27:39 +00002148 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2149 _PyEval_SliceIndex, &start,
2150 _PyEval_SliceIndex, &stop))
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002151 return NULL;
Guido van Rossum2743d872003-06-17 14:25:14 +00002152 if (start < 0) {
2153 start += self->ob_size;
2154 if (start < 0)
2155 start = 0;
2156 }
2157 if (stop < 0) {
2158 stop += self->ob_size;
2159 if (stop < 0)
2160 stop = 0;
2161 }
2162 else if (stop > self->ob_size)
2163 stop = self->ob_size;
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002164 for (i = start; i < stop; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002165 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2166 if (cmp > 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002167 return PyInt_FromLong((long)i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002168 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002169 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002170 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002171 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002172 return NULL;
2173}
2174
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002175static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002176listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002177{
2178 int count = 0;
2179 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002180
Guido van Rossume6f7d181991-10-20 20:20:40 +00002181 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002182 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2183 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002184 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002185 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002186 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00002187 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002188 return PyInt_FromLong((long)count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002189}
2190
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002191static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002192listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002193{
2194 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002195
Guido van Rossumed98d481991-03-06 13:07:53 +00002196 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002197 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2198 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002199 if (list_ass_slice(self, i, i+1,
2200 (PyObject *)NULL) != 0)
Guido van Rossumed98d481991-03-06 13:07:53 +00002201 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002202 Py_INCREF(Py_None);
2203 return Py_None;
Guido van Rossumed98d481991-03-06 13:07:53 +00002204 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002205 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002206 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002207 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002208 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002209 return NULL;
2210}
2211
Jeremy Hylton8caad492000-06-23 14:18:11 +00002212static int
2213list_traverse(PyListObject *o, visitproc visit, void *arg)
2214{
2215 int i, err;
2216 PyObject *x;
2217
2218 for (i = o->ob_size; --i >= 0; ) {
2219 x = o->ob_item[i];
2220 if (x != NULL) {
2221 err = visit(x, arg);
2222 if (err)
2223 return err;
2224 }
2225 }
2226 return 0;
2227}
2228
2229static int
2230list_clear(PyListObject *lp)
2231{
2232 (void) PyList_SetSlice((PyObject *)lp, 0, lp->ob_size, 0);
2233 return 0;
2234}
2235
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002236static PyObject *
2237list_richcompare(PyObject *v, PyObject *w, int op)
2238{
2239 PyListObject *vl, *wl;
2240 int i;
2241
2242 if (!PyList_Check(v) || !PyList_Check(w)) {
2243 Py_INCREF(Py_NotImplemented);
2244 return Py_NotImplemented;
2245 }
2246
2247 vl = (PyListObject *)v;
2248 wl = (PyListObject *)w;
2249
2250 if (vl->ob_size != wl->ob_size && (op == Py_EQ || op == Py_NE)) {
2251 /* Shortcut: if the lengths differ, the lists differ */
2252 PyObject *res;
2253 if (op == Py_EQ)
2254 res = Py_False;
2255 else
2256 res = Py_True;
2257 Py_INCREF(res);
2258 return res;
2259 }
2260
2261 /* Search for the first index where items are different */
2262 for (i = 0; i < vl->ob_size && i < wl->ob_size; i++) {
2263 int k = PyObject_RichCompareBool(vl->ob_item[i],
2264 wl->ob_item[i], Py_EQ);
2265 if (k < 0)
2266 return NULL;
2267 if (!k)
2268 break;
2269 }
2270
2271 if (i >= vl->ob_size || i >= wl->ob_size) {
2272 /* No more items to compare -- compare sizes */
2273 int vs = vl->ob_size;
2274 int ws = wl->ob_size;
2275 int cmp;
2276 PyObject *res;
2277 switch (op) {
2278 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00002279 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002280 case Py_EQ: cmp = vs == ws; break;
2281 case Py_NE: cmp = vs != ws; break;
2282 case Py_GT: cmp = vs > ws; break;
2283 case Py_GE: cmp = vs >= ws; break;
2284 default: return NULL; /* cannot happen */
2285 }
2286 if (cmp)
2287 res = Py_True;
2288 else
2289 res = Py_False;
2290 Py_INCREF(res);
2291 return res;
2292 }
2293
2294 /* We have an item that differs -- shortcuts for EQ/NE */
2295 if (op == Py_EQ) {
2296 Py_INCREF(Py_False);
2297 return Py_False;
2298 }
2299 if (op == Py_NE) {
2300 Py_INCREF(Py_True);
2301 return Py_True;
2302 }
2303
2304 /* Compare the final item again using the proper operator */
2305 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
2306}
2307
Tim Peters6d6c1a32001-08-02 04:15:00 +00002308static int
2309list_init(PyListObject *self, PyObject *args, PyObject *kw)
2310{
2311 PyObject *arg = NULL;
2312 static char *kwlist[] = {"sequence", 0};
2313
2314 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2315 return -1;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002316 /* Empty previous contents */
2317 if (self->ob_size != 0) {
2318 if (list_ass_slice(self, 0, self->ob_size, (PyObject *)NULL) != 0)
2319 return -1;
2320 }
2321 if (arg != NULL) {
2322 PyObject *rv = listextend(self, arg);
2323 if (rv == NULL)
2324 return -1;
2325 Py_DECREF(rv);
2326 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002327 return 0;
2328}
2329
Guido van Rossumdbb53d92001-12-03 16:32:18 +00002330static long
2331list_nohash(PyObject *self)
2332{
2333 PyErr_SetString(PyExc_TypeError, "list objects are unhashable");
2334 return -1;
2335}
2336
Raymond Hettinger1021c442003-11-07 15:38:09 +00002337static PyObject *list_iter(PyObject *seq);
2338static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2339
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002340PyDoc_STRVAR(getitem_doc,
2341"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002342PyDoc_STRVAR(reversed_doc,
2343"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002344PyDoc_STRVAR(append_doc,
2345"L.append(object) -- append object to end");
2346PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002347"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002348PyDoc_STRVAR(insert_doc,
2349"L.insert(index, object) -- insert object before index");
2350PyDoc_STRVAR(pop_doc,
2351"L.pop([index]) -> item -- remove and return item at index (default last)");
2352PyDoc_STRVAR(remove_doc,
2353"L.remove(value) -- remove first occurrence of value");
2354PyDoc_STRVAR(index_doc,
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002355"L.index(value, [start, [stop]]) -> integer -- return first index of value");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002356PyDoc_STRVAR(count_doc,
2357"L.count(value) -> integer -- return number of occurrences of value");
2358PyDoc_STRVAR(reverse_doc,
2359"L.reverse() -- reverse *IN PLACE*");
2360PyDoc_STRVAR(sort_doc,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002361"L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n\
2362cmp(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002363
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002364static PyObject *list_subscript(PyListObject*, PyObject*);
2365
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002366static PyMethodDef list_methods[] = {
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002367 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
Raymond Hettinger1021c442003-11-07 15:38:09 +00002368 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002369 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002370 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002371 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002372 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002373 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002374 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002375 {"count", (PyCFunction)listcount, METH_O, count_doc},
2376 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002377 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
Tim Petersa64dc242002-08-01 02:13:36 +00002378 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002379};
2380
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002381static PySequenceMethods list_as_sequence = {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002382 (inquiry)list_length, /* sq_length */
2383 (binaryfunc)list_concat, /* sq_concat */
2384 (intargfunc)list_repeat, /* sq_repeat */
2385 (intargfunc)list_item, /* sq_item */
2386 (intintargfunc)list_slice, /* sq_slice */
2387 (intobjargproc)list_ass_item, /* sq_ass_item */
2388 (intintobjargproc)list_ass_slice, /* sq_ass_slice */
2389 (objobjproc)list_contains, /* sq_contains */
2390 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2391 (intargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002392};
2393
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002394PyDoc_STRVAR(list_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002395"list() -> new list\n"
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002396"list(sequence) -> new list initialized from sequence's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002397
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002398static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002399list_subscript(PyListObject* self, PyObject* item)
2400{
2401 if (PyInt_Check(item)) {
2402 long i = PyInt_AS_LONG(item);
2403 if (i < 0)
2404 i += PyList_GET_SIZE(self);
2405 return list_item(self, i);
2406 }
2407 else if (PyLong_Check(item)) {
2408 long i = PyLong_AsLong(item);
2409 if (i == -1 && PyErr_Occurred())
2410 return NULL;
2411 if (i < 0)
2412 i += PyList_GET_SIZE(self);
2413 return list_item(self, i);
2414 }
2415 else if (PySlice_Check(item)) {
2416 int start, stop, step, slicelength, cur, i;
2417 PyObject* result;
2418 PyObject* it;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002419 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002420
2421 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
2422 &start, &stop, &step, &slicelength) < 0) {
2423 return NULL;
2424 }
2425
2426 if (slicelength <= 0) {
2427 return PyList_New(0);
2428 }
2429 else {
2430 result = PyList_New(slicelength);
2431 if (!result) return NULL;
2432
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002433 src = self->ob_item;
2434 dest = ((PyListObject *)result)->ob_item;
Tim Peters3b01a122002-07-19 02:35:45 +00002435 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002436 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002437 it = src[cur];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002438 Py_INCREF(it);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002439 dest[i] = it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002440 }
Tim Peters3b01a122002-07-19 02:35:45 +00002441
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002442 return result;
2443 }
2444 }
2445 else {
2446 PyErr_SetString(PyExc_TypeError,
2447 "list indices must be integers");
2448 return NULL;
2449 }
2450}
2451
Tim Peters3b01a122002-07-19 02:35:45 +00002452static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002453list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2454{
2455 if (PyInt_Check(item)) {
2456 long i = PyInt_AS_LONG(item);
2457 if (i < 0)
2458 i += PyList_GET_SIZE(self);
2459 return list_ass_item(self, i, value);
2460 }
2461 else if (PyLong_Check(item)) {
2462 long i = PyLong_AsLong(item);
2463 if (i == -1 && PyErr_Occurred())
2464 return -1;
2465 if (i < 0)
2466 i += PyList_GET_SIZE(self);
2467 return list_ass_item(self, i, value);
2468 }
2469 else if (PySlice_Check(item)) {
2470 int start, stop, step, slicelength;
2471
2472 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
2473 &start, &stop, &step, &slicelength) < 0) {
2474 return -1;
2475 }
2476
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002477 /* treat L[slice(a,b)] = v _exactly_ like L[a:b] = v */
2478 if (step == 1 && ((PySliceObject*)item)->step == Py_None)
2479 return list_ass_slice(self, start, stop, value);
2480
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002481 if (value == NULL) {
2482 /* delete slice */
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002483 PyObject **garbage;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002484 int cur, i;
Tim Peters3b01a122002-07-19 02:35:45 +00002485
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002486 if (slicelength <= 0)
2487 return 0;
2488
2489 if (step < 0) {
2490 stop = start + 1;
2491 start = stop + step*(slicelength - 1) - 1;
2492 step = -step;
2493 }
2494
2495 garbage = (PyObject**)
2496 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Tim Peters3b01a122002-07-19 02:35:45 +00002497
2498 /* drawing pictures might help
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002499 understand these for loops */
Guido van Rossum75a20b12002-06-11 12:22:28 +00002500 for (cur = start, i = 0;
2501 cur < stop;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002502 cur += step, i++) {
2503 int lim = step;
2504
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002505 garbage[i] = PyList_GET_ITEM(self, cur);
2506
Michael W. Hudson56796f62002-07-29 14:35:04 +00002507 if (cur + step >= self->ob_size) {
2508 lim = self->ob_size - cur - 1;
2509 }
2510
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002511 memmove(self->ob_item + cur - i,
2512 self->ob_item + cur + 1,
2513 lim * sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002514 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002515
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002516 for (cur = start + slicelength*step + 1;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002517 cur < self->ob_size; cur++) {
2518 PyList_SET_ITEM(self, cur - slicelength,
2519 PyList_GET_ITEM(self, cur));
2520 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002521
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002522 self->ob_size -= slicelength;
Raymond Hettinger0e916432004-03-14 06:42:23 +00002523 list_resize(self, self->ob_size, 1);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002524
2525 for (i = 0; i < slicelength; i++) {
2526 Py_DECREF(garbage[i]);
2527 }
2528 PyMem_FREE(garbage);
2529
2530 return 0;
2531 }
2532 else {
2533 /* assign slice */
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002534 PyObject **garbage, *ins, *seq, **seqitems, **selfitems;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002535 int cur, i;
2536
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002537 /* protect against a[::-1] = a */
Tim Peters3b01a122002-07-19 02:35:45 +00002538 if (self == (PyListObject*)value) {
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002539 seq = list_slice((PyListObject*)value, 0,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002540 PyList_GET_SIZE(value));
Tim Peters3b01a122002-07-19 02:35:45 +00002541 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002542 else {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002543 seq = PySequence_Fast(value,
2544 "must assign iterable to extended slice");
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002545 if (!seq)
2546 return -1;
2547 }
2548
2549 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2550 PyErr_Format(PyExc_ValueError,
2551 "attempt to assign sequence of size %d to extended slice of size %d",
2552 PySequence_Fast_GET_SIZE(seq),
2553 slicelength);
2554 Py_DECREF(seq);
2555 return -1;
2556 }
2557
2558 if (!slicelength) {
2559 Py_DECREF(seq);
2560 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002561 }
2562
2563 garbage = (PyObject**)
2564 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Tim Peters3b01a122002-07-19 02:35:45 +00002565
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002566 selfitems = self->ob_item;
Raymond Hettinger42bec932004-03-12 16:38:17 +00002567 seqitems = PySequence_Fast_ITEMS(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002568 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002569 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002570 garbage[i] = selfitems[cur];
2571 ins = seqitems[i];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002572 Py_INCREF(ins);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002573 selfitems[cur] = ins;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002574 }
2575
2576 for (i = 0; i < slicelength; i++) {
2577 Py_DECREF(garbage[i]);
2578 }
Tim Peters3b01a122002-07-19 02:35:45 +00002579
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002580 PyMem_FREE(garbage);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002581 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002582
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002583 return 0;
2584 }
Tim Peters3b01a122002-07-19 02:35:45 +00002585 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002586 else {
Tim Peters3b01a122002-07-19 02:35:45 +00002587 PyErr_SetString(PyExc_TypeError,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002588 "list indices must be integers");
2589 return -1;
2590 }
2591}
2592
2593static PyMappingMethods list_as_mapping = {
2594 (inquiry)list_length,
2595 (binaryfunc)list_subscript,
2596 (objobjargproc)list_ass_subscript
2597};
2598
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002599PyTypeObject PyList_Type = {
2600 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002601 0,
2602 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002603 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002604 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002605 (destructor)list_dealloc, /* tp_dealloc */
2606 (printfunc)list_print, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002607 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002608 0, /* tp_setattr */
2609 0, /* tp_compare */
2610 (reprfunc)list_repr, /* tp_repr */
2611 0, /* tp_as_number */
2612 &list_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002613 &list_as_mapping, /* tp_as_mapping */
Guido van Rossumdbb53d92001-12-03 16:32:18 +00002614 list_nohash, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002615 0, /* tp_call */
2616 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002617 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002618 0, /* tp_setattro */
2619 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002620 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Tim Peters6d6c1a32001-08-02 04:15:00 +00002621 Py_TPFLAGS_BASETYPE, /* tp_flags */
2622 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002623 (traverseproc)list_traverse, /* tp_traverse */
2624 (inquiry)list_clear, /* tp_clear */
2625 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002626 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002627 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002628 0, /* tp_iternext */
2629 list_methods, /* tp_methods */
2630 0, /* tp_members */
2631 0, /* tp_getset */
2632 0, /* tp_base */
2633 0, /* tp_dict */
2634 0, /* tp_descr_get */
2635 0, /* tp_descr_set */
2636 0, /* tp_dictoffset */
2637 (initproc)list_init, /* tp_init */
2638 PyType_GenericAlloc, /* tp_alloc */
2639 PyType_GenericNew, /* tp_new */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002640 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002641};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002642
2643
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002644/*********************** List Iterator **************************/
2645
2646typedef struct {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002647 PyObject_HEAD
2648 long it_index;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002649 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002650} listiterobject;
2651
2652PyTypeObject PyListIter_Type;
2653
Guido van Rossum5086e492002-07-16 15:56:52 +00002654static PyObject *
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002655list_iter(PyObject *seq)
2656{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002657 listiterobject *it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002658
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002659 if (!PyList_Check(seq)) {
2660 PyErr_BadInternalCall();
2661 return NULL;
2662 }
2663 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2664 if (it == NULL)
2665 return NULL;
2666 it->it_index = 0;
2667 Py_INCREF(seq);
2668 it->it_seq = (PyListObject *)seq;
2669 _PyObject_GC_TRACK(it);
2670 return (PyObject *)it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002671}
2672
2673static void
2674listiter_dealloc(listiterobject *it)
2675{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002676 _PyObject_GC_UNTRACK(it);
Guido van Rossum86103ae2002-07-16 20:07:32 +00002677 Py_XDECREF(it->it_seq);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002678 PyObject_GC_Del(it);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002679}
2680
2681static int
2682listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2683{
Guido van Rossum86103ae2002-07-16 20:07:32 +00002684 if (it->it_seq == NULL)
2685 return 0;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002686 return visit((PyObject *)it->it_seq, arg);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002687}
2688
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002689static PyObject *
Tim Peters93b2cc42002-06-01 05:22:55 +00002690listiter_next(listiterobject *it)
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002691{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002692 PyListObject *seq;
2693 PyObject *item;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002694
Tim Peters93b2cc42002-06-01 05:22:55 +00002695 assert(it != NULL);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002696 seq = it->it_seq;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002697 if (seq == NULL)
2698 return NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002699 assert(PyList_Check(seq));
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002700
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002701 if (it->it_index < PyList_GET_SIZE(seq)) {
Tim Peters93b2cc42002-06-01 05:22:55 +00002702 item = PyList_GET_ITEM(seq, it->it_index);
2703 ++it->it_index;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002704 Py_INCREF(item);
2705 return item;
2706 }
Guido van Rossum86103ae2002-07-16 20:07:32 +00002707
2708 Py_DECREF(seq);
2709 it->it_seq = NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002710 return NULL;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002711}
2712
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002713PyTypeObject PyListIter_Type = {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002714 PyObject_HEAD_INIT(&PyType_Type)
2715 0, /* ob_size */
2716 "listiterator", /* tp_name */
2717 sizeof(listiterobject), /* tp_basicsize */
2718 0, /* tp_itemsize */
2719 /* methods */
2720 (destructor)listiter_dealloc, /* tp_dealloc */
2721 0, /* tp_print */
2722 0, /* tp_getattr */
2723 0, /* tp_setattr */
2724 0, /* tp_compare */
2725 0, /* tp_repr */
2726 0, /* tp_as_number */
2727 0, /* tp_as_sequence */
2728 0, /* tp_as_mapping */
2729 0, /* tp_hash */
2730 0, /* tp_call */
2731 0, /* tp_str */
2732 PyObject_GenericGetAttr, /* tp_getattro */
2733 0, /* tp_setattro */
2734 0, /* tp_as_buffer */
2735 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2736 0, /* tp_doc */
2737 (traverseproc)listiter_traverse, /* tp_traverse */
2738 0, /* tp_clear */
2739 0, /* tp_richcompare */
2740 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00002741 PyObject_SelfIter, /* tp_iter */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002742 (iternextfunc)listiter_next, /* tp_iternext */
Guido van Rossum86103ae2002-07-16 20:07:32 +00002743 0, /* tp_methods */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002744 0, /* tp_members */
2745 0, /* tp_getset */
2746 0, /* tp_base */
2747 0, /* tp_dict */
2748 0, /* tp_descr_get */
2749 0, /* tp_descr_set */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002750};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002751
2752/*********************** List Reverse Iterator **************************/
2753
2754typedef struct {
2755 PyObject_HEAD
2756 long it_index;
Raymond Hettinger001f2282003-11-08 11:58:44 +00002757 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002758} listreviterobject;
2759
2760PyTypeObject PyListRevIter_Type;
2761
2762static PyObject *
2763list_reversed(PyListObject *seq, PyObject *unused)
2764{
2765 listreviterobject *it;
2766
2767 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2768 if (it == NULL)
2769 return NULL;
2770 assert(PyList_Check(seq));
2771 it->it_index = PyList_GET_SIZE(seq) - 1;
2772 Py_INCREF(seq);
2773 it->it_seq = seq;
2774 PyObject_GC_Track(it);
2775 return (PyObject *)it;
2776}
2777
2778static void
2779listreviter_dealloc(listreviterobject *it)
2780{
2781 PyObject_GC_UnTrack(it);
2782 Py_XDECREF(it->it_seq);
2783 PyObject_GC_Del(it);
2784}
2785
2786static int
2787listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2788{
2789 if (it->it_seq == NULL)
2790 return 0;
2791 return visit((PyObject *)it->it_seq, arg);
2792}
2793
2794static PyObject *
2795listreviter_next(listreviterobject *it)
2796{
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002797 PyObject *item;
2798 long index = it->it_index;
2799 PyListObject *seq = it->it_seq;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002800
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002801 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2802 item = PyList_GET_ITEM(seq, index);
Raymond Hettinger1021c442003-11-07 15:38:09 +00002803 it->it_index--;
2804 Py_INCREF(item);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002805 return item;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002806 }
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002807 it->it_index = -1;
2808 if (seq != NULL) {
2809 it->it_seq = NULL;
2810 Py_DECREF(seq);
2811 }
2812 return NULL;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002813}
2814
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002815static int
2816listreviter_len(listreviterobject *it)
2817{
2818 return it->it_index + 1;
2819}
2820
2821static PySequenceMethods listreviter_as_sequence = {
2822 (inquiry)listreviter_len, /* sq_length */
2823 0, /* sq_concat */
2824};
2825
Raymond Hettinger1021c442003-11-07 15:38:09 +00002826PyTypeObject PyListRevIter_Type = {
2827 PyObject_HEAD_INIT(&PyType_Type)
2828 0, /* ob_size */
2829 "listreverseiterator", /* tp_name */
2830 sizeof(listreviterobject), /* tp_basicsize */
2831 0, /* tp_itemsize */
2832 /* methods */
2833 (destructor)listreviter_dealloc, /* tp_dealloc */
2834 0, /* tp_print */
2835 0, /* tp_getattr */
2836 0, /* tp_setattr */
2837 0, /* tp_compare */
2838 0, /* tp_repr */
2839 0, /* tp_as_number */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002840 &listreviter_as_sequence, /* tp_as_sequence */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002841 0, /* tp_as_mapping */
2842 0, /* tp_hash */
2843 0, /* tp_call */
2844 0, /* tp_str */
2845 PyObject_GenericGetAttr, /* tp_getattro */
2846 0, /* tp_setattro */
2847 0, /* tp_as_buffer */
2848 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2849 0, /* tp_doc */
2850 (traverseproc)listreviter_traverse, /* tp_traverse */
2851 0, /* tp_clear */
2852 0, /* tp_richcompare */
2853 0, /* tp_weaklistoffset */
2854 PyObject_SelfIter, /* tp_iter */
2855 (iternextfunc)listreviter_next, /* tp_iternext */
2856 0,
2857};