blob: 72b235629c6e9e580e8e7d211ba680718e7d2b3d [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
Tim Peters8d9eb102004-07-31 02:24:20 +000011/* Ensure ob_item has room for at least newsize elements, and set
12 * ob_size to newsize. If newsize > ob_size on entry, the content
13 * of the new slots at exit is undefined heap trash; it's the caller's
14 * responsiblity to overwrite them with sane values.
15 * The number of allocated elements may grow, shrink, or stay the same.
16 * Failure is impossible if newsize <= self.allocated on entry, although
17 * that partly relies on an assumption that the system realloc() never
18 * fails when passed a number of bytes <= the number of bytes last
19 * allocated (the C standard doesn't guarantee this, but it's hard to
20 * imagine a realloc implementation where it wouldn't be true).
21 * Note that self->ob_item may change, and even if newsize is less
22 * than ob_size on entry.
23 */
Guido van Rossuma46d51d1995-01-26 22:59:43 +000024static int
Raymond Hettingerd4ff7412004-03-15 09:01:31 +000025list_resize(PyListObject *self, int newsize)
Guido van Rossuma46d51d1995-01-26 22:59:43 +000026{
Raymond Hettinger4bb95402004-02-13 11:36:39 +000027 PyObject **items;
28 size_t _new_size;
Tim Peters65b8b842001-05-26 05:28:40 +000029
Raymond Hettinger4bb95402004-02-13 11:36:39 +000030 /* Bypass realloc() when a previous overallocation is large enough
31 to accommodate the newsize. If the newsize is 16 smaller than the
32 current size, then proceed with the realloc() to shrink the list.
33 */
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +000034 if (self->allocated >= newsize && self->ob_size < newsize + 16) {
35 assert(self->ob_item != NULL || newsize == 0);
Raymond Hettinger4bb95402004-02-13 11:36:39 +000036 self->ob_size = newsize;
37 return 0;
38 }
39
40 /* This over-allocates proportional to the list size, making room
Tim Peters65b8b842001-05-26 05:28:40 +000041 * for additional growth. The over-allocation is mild, but is
42 * enough to give linear-time amortized behavior over a long
43 * sequence of appends() in the presence of a poorly-performing
Raymond Hettingerab517d22004-02-14 18:34:46 +000044 * system realloc().
45 * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
Tim Peters65b8b842001-05-26 05:28:40 +000046 */
Raymond Hettingerd4ff7412004-03-15 09:01:31 +000047 _new_size = (newsize >> 3) + (self->ob_size < 8 ? 3 : 6) + newsize;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000048 items = self->ob_item;
49 if (_new_size <= ((~(size_t)0) / sizeof(PyObject *)))
50 PyMem_RESIZE(items, PyObject *, _new_size);
51 else
52 items = NULL;
53 if (items == NULL) {
54 PyErr_NoMemory();
55 return -1;
56 }
57 self->ob_item = items;
58 self->ob_size = newsize;
59 self->allocated = _new_size;
60 return 0;
61}
Guido van Rossuma46d51d1995-01-26 22:59:43 +000062
Raymond Hettinger0468e412004-05-05 05:37:53 +000063/* Empty list reuse scheme to save calls to malloc and free */
64#define MAXFREELISTS 80
65static PyListObject *free_lists[MAXFREELISTS];
66static int num_free_lists = 0;
67
Guido van Rossumc0b618a1997-05-02 03:12:38 +000068PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +000069PyList_New(int size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000070{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000071 PyListObject *op;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +000072 size_t nbytes;
Tim Peters3986d4e2004-07-29 02:28:42 +000073
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000074 if (size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000075 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000076 return NULL;
77 }
Tim Peters7049d812004-01-18 20:31:02 +000078 nbytes = size * sizeof(PyObject *);
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000079 /* Check for overflow */
Raymond Hettingerfdfe6182004-05-05 06:28:16 +000080 if (nbytes / sizeof(PyObject *) != (size_t)size)
Guido van Rossumc0b618a1997-05-02 03:12:38 +000081 return PyErr_NoMemory();
Raymond Hettinger0468e412004-05-05 05:37:53 +000082 if (num_free_lists) {
83 num_free_lists--;
84 op = free_lists[num_free_lists];
85 _Py_NewReference((PyObject *)op);
86 } else {
87 op = PyObject_GC_New(PyListObject, &PyList_Type);
88 if (op == NULL)
89 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000090 }
Raymond Hettingerfdfe6182004-05-05 06:28:16 +000091 if (size <= 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000092 op->ob_item = NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000093 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +000094 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
Raymond Hettingerfdfe6182004-05-05 06:28:16 +000095 if (op->ob_item == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +000096 return PyErr_NoMemory();
Tim Peters3986d4e2004-07-29 02:28:42 +000097 memset(op->ob_item, 0, nbytes);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000098 }
Neil Schemenauere83c00e2001-08-29 23:54:21 +000099 op->ob_size = size;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000100 op->allocated = size;
Neil Schemenauere83c00e2001-08-29 23:54:21 +0000101 _PyObject_GC_TRACK(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000102 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000103}
104
105int
Fred Drakea2f55112000-07-09 15:16:51 +0000106PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000107{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000108 if (!PyList_Check(op)) {
109 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000110 return -1;
111 }
112 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000113 return ((PyListObject *)op) -> ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000114}
115
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000116static PyObject *indexerr = NULL;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000117
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000118PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000119PyList_GetItem(PyObject *op, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000120{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000121 if (!PyList_Check(op)) {
122 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000123 return NULL;
124 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000125 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000126 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000127 indexerr = PyString_FromString(
128 "list index out of range");
129 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000130 return NULL;
131 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000132 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000133}
134
135int
Fred Drakea2f55112000-07-09 15:16:51 +0000136PyList_SetItem(register PyObject *op, register int i,
137 register PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000138{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000139 register PyObject *olditem;
140 register PyObject **p;
141 if (!PyList_Check(op)) {
142 Py_XDECREF(newitem);
143 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000144 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000145 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000146 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
147 Py_XDECREF(newitem);
148 PyErr_SetString(PyExc_IndexError,
149 "list assignment index out of range");
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000150 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000151 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000152 p = ((PyListObject *)op) -> ob_item + i;
Guido van Rossum5fe60581995-03-09 12:12:50 +0000153 olditem = *p;
154 *p = newitem;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000155 Py_XDECREF(olditem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000156 return 0;
157}
158
159static int
Fred Drakea2f55112000-07-09 15:16:51 +0000160ins1(PyListObject *self, int where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000161{
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000162 int i, n = self->ob_size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000163 PyObject **items;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000164 if (v == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000165 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000166 return -1;
167 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000168 if (n == INT_MAX) {
Trent Micka5846642000-08-13 22:47:45 +0000169 PyErr_SetString(PyExc_OverflowError,
170 "cannot add more objects to list");
171 return -1;
172 }
Tim Petersb38e2b62004-07-29 02:29:26 +0000173
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000174 if (list_resize(self, n+1) == -1)
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000175 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000176
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000177 if (where < 0) {
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000178 where += n;
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000179 if (where < 0)
180 where = 0;
181 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000182 if (where > n)
183 where = n;
184 items = self->ob_item;
185 for (i = n; --i >= where; )
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000186 items[i+1] = items[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000187 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000188 items[where] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000189 return 0;
190}
191
192int
Fred Drakea2f55112000-07-09 15:16:51 +0000193PyList_Insert(PyObject *op, int where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000194{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000195 if (!PyList_Check(op)) {
196 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000197 return -1;
198 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000199 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000200}
201
Raymond Hettinger40a03822004-04-12 13:05:09 +0000202static int
203app1(PyListObject *self, PyObject *v)
204{
205 int n = PyList_GET_SIZE(self);
206
207 assert (v != NULL);
208 if (n == INT_MAX) {
209 PyErr_SetString(PyExc_OverflowError,
210 "cannot add more objects to list");
211 return -1;
212 }
213
214 if (list_resize(self, n+1) == -1)
215 return -1;
216
217 Py_INCREF(v);
218 PyList_SET_ITEM(self, n, v);
219 return 0;
220}
221
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000222int
Fred Drakea2f55112000-07-09 15:16:51 +0000223PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000224{
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000225 if (PyList_Check(op) && (newitem != NULL))
226 return app1((PyListObject *)op, newitem);
227 PyErr_BadInternalCall();
228 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000229}
230
231/* Methods */
232
233static void
Fred Drakea2f55112000-07-09 15:16:51 +0000234list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000235{
236 int i;
Guido van Rossumff413af2002-03-28 20:34:59 +0000237 PyObject_GC_UnTrack(op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000238 Py_TRASHCAN_SAFE_BEGIN(op)
Jack Jansen7874d1f1995-01-19 12:09:27 +0000239 if (op->ob_item != NULL) {
Guido van Rossumfa717011999-06-09 15:19:34 +0000240 /* Do it backwards, for Christian Tismer.
241 There's a simple test case where somehow this reduces
242 thrashing when a *very* large list is created and
243 immediately deleted. */
244 i = op->ob_size;
245 while (--i >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000246 Py_XDECREF(op->ob_item[i]);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000247 }
Guido van Rossumb18618d2000-05-03 23:44:39 +0000248 PyMem_FREE(op->ob_item);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000249 }
Raymond Hettinger0468e412004-05-05 05:37:53 +0000250 if (num_free_lists < MAXFREELISTS && PyList_CheckExact(op))
251 free_lists[num_free_lists++] = op;
Tim Petersb38e2b62004-07-29 02:29:26 +0000252 else
253 op->ob_type->tp_free((PyObject *)op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000254 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000255}
256
Guido van Rossum90933611991-06-07 16:10:43 +0000257static int
Fred Drakea2f55112000-07-09 15:16:51 +0000258list_print(PyListObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000259{
260 int i;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000261
262 i = Py_ReprEnter((PyObject*)op);
263 if (i != 0) {
264 if (i < 0)
265 return i;
266 fprintf(fp, "[...]");
267 return 0;
268 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000269 fprintf(fp, "[");
Guido van Rossum90933611991-06-07 16:10:43 +0000270 for (i = 0; i < op->ob_size; i++) {
271 if (i > 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000272 fprintf(fp, ", ");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000273 if (PyObject_Print(op->ob_item[i], fp, 0) != 0) {
274 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000275 return -1;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000276 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000277 }
278 fprintf(fp, "]");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000279 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000280 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000281}
282
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000283static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000284list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000285{
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000286 int i;
Tim Petersa7259592001-06-16 05:11:17 +0000287 PyObject *s, *temp;
288 PyObject *pieces = NULL, *result = NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000289
290 i = Py_ReprEnter((PyObject*)v);
291 if (i != 0) {
Tim Petersa7259592001-06-16 05:11:17 +0000292 return i > 0 ? PyString_FromString("[...]") : NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000293 }
Tim Petersa7259592001-06-16 05:11:17 +0000294
295 if (v->ob_size == 0) {
296 result = PyString_FromString("[]");
297 goto Done;
298 }
299
300 pieces = PyList_New(0);
301 if (pieces == NULL)
302 goto Done;
303
304 /* Do repr() on each element. Note that this may mutate the list,
305 so must refetch the list size on each iteration. */
306 for (i = 0; i < v->ob_size; ++i) {
307 int status;
308 s = PyObject_Repr(v->ob_item[i]);
309 if (s == NULL)
310 goto Done;
311 status = PyList_Append(pieces, s);
312 Py_DECREF(s); /* append created a new ref */
313 if (status < 0)
314 goto Done;
315 }
316
317 /* Add "[]" decorations to the first and last items. */
318 assert(PyList_GET_SIZE(pieces) > 0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000319 s = PyString_FromString("[");
Tim Petersa7259592001-06-16 05:11:17 +0000320 if (s == NULL)
321 goto Done;
322 temp = PyList_GET_ITEM(pieces, 0);
323 PyString_ConcatAndDel(&s, temp);
324 PyList_SET_ITEM(pieces, 0, s);
325 if (s == NULL)
326 goto Done;
327
328 s = PyString_FromString("]");
329 if (s == NULL)
330 goto Done;
331 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
332 PyString_ConcatAndDel(&temp, s);
333 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
334 if (temp == NULL)
335 goto Done;
336
337 /* Paste them all together with ", " between. */
338 s = PyString_FromString(", ");
339 if (s == NULL)
340 goto Done;
341 result = _PyString_Join(s, pieces);
Tim Peters3b01a122002-07-19 02:35:45 +0000342 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +0000343
344Done:
345 Py_XDECREF(pieces);
Guido van Rossumfb376de1998-04-10 22:47:27 +0000346 Py_ReprLeave((PyObject *)v);
Tim Petersa7259592001-06-16 05:11:17 +0000347 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000348}
349
350static int
Fred Drakea2f55112000-07-09 15:16:51 +0000351list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000352{
353 return a->ob_size;
354}
355
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000356static int
Fred Drakea2f55112000-07-09 15:16:51 +0000357list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000358{
Raymond Hettingeraae59992002-09-05 14:23:49 +0000359 int i, cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000360
Raymond Hettingeraae59992002-09-05 14:23:49 +0000361 for (i = 0, cmp = 0 ; cmp == 0 && i < a->ob_size; ++i)
362 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000363 Py_EQ);
Neal Norwitzbb9c5f52002-09-05 21:32:55 +0000364 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000365}
366
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000367static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000368list_item(PyListObject *a, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000369{
370 if (i < 0 || i >= a->ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000371 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000372 indexerr = PyString_FromString(
373 "list index out of range");
374 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000375 return NULL;
376 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000377 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000378 return a->ob_item[i];
379}
380
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000381static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000382list_slice(PyListObject *a, int ilow, int ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000383{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000384 PyListObject *np;
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000385 PyObject **src, **dest;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000386 int i, len;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000387 if (ilow < 0)
388 ilow = 0;
389 else if (ilow > a->ob_size)
390 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000391 if (ihigh < ilow)
392 ihigh = ilow;
393 else if (ihigh > a->ob_size)
394 ihigh = a->ob_size;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000395 len = ihigh - ilow;
396 np = (PyListObject *) PyList_New(len);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000397 if (np == NULL)
398 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000399
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000400 src = a->ob_item + ilow;
401 dest = np->ob_item;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000402 for (i = 0; i < len; i++) {
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000403 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000404 Py_INCREF(v);
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000405 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000406 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000407 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000408}
409
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000410PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000411PyList_GetSlice(PyObject *a, int ilow, int ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000412{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000413 if (!PyList_Check(a)) {
414 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000415 return NULL;
416 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000417 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000418}
419
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000420static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000421list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000422{
423 int size;
424 int i;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000425 PyObject **src, **dest;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000426 PyListObject *np;
427 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000428 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000429 "can only concatenate list (not \"%.200s\") to list",
430 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000431 return NULL;
432 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000433#define b ((PyListObject *)bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000434 size = a->ob_size + b->ob_size;
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000435 if (size < 0)
436 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000437 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000438 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000439 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000440 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000441 src = a->ob_item;
442 dest = np->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000443 for (i = 0; i < a->ob_size; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000444 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000445 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000446 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000447 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000448 src = b->ob_item;
449 dest = np->ob_item + a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000450 for (i = 0; i < b->ob_size; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000451 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000452 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000453 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000454 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000455 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000456#undef b
457}
458
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000459static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000460list_repeat(PyListObject *a, int n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000461{
462 int i, j;
463 int size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000464 PyListObject *np;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000465 PyObject **p, **items;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000466 PyObject *elem;
Guido van Rossumed98d481991-03-06 13:07:53 +0000467 if (n < 0)
468 n = 0;
469 size = a->ob_size * n;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000470 if (size == 0)
471 return PyList_New(0);
Guido van Rossumbfa5a142002-10-11 23:39:35 +0000472 if (n && size/n != a->ob_size)
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000473 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000474 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000475 if (np == NULL)
476 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000477
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000478 items = np->ob_item;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000479 if (a->ob_size == 1) {
480 elem = a->ob_item[0];
481 for (i = 0; i < n; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000482 items[i] = elem;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000483 Py_INCREF(elem);
484 }
485 return (PyObject *) np;
486 }
Guido van Rossumed98d481991-03-06 13:07:53 +0000487 p = np->ob_item;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000488 items = a->ob_item;
Guido van Rossumed98d481991-03-06 13:07:53 +0000489 for (i = 0; i < n; i++) {
490 for (j = 0; j < a->ob_size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000491 *p = items[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000492 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000493 p++;
494 }
495 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000496 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000497}
498
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000499static int
Armin Rigo93677f02004-07-29 12:40:23 +0000500list_clear(PyListObject *a)
501{
502 int i;
503 PyObject **item = a->ob_item;
504 if (item != NULL) {
505 /* Because XDECREF can recursively invoke operations on
506 this list, we make it empty first. */
507 i = a->ob_size;
508 a->ob_size = 0;
509 a->ob_item = NULL;
510 a->allocated = 0;
511 while (--i >= 0) {
512 Py_XDECREF(item[i]);
513 }
514 PyMem_FREE(item);
515 }
516 /* Never fails; the return value can be ignored.
517 Note that there is no guarantee that the list is actually empty
518 at this point, because XDECREF may have populated it again! */
519 return 0;
520}
521
Tim Peters8fc4a912004-07-31 21:53:19 +0000522/* a[ilow:ihigh] = v if v != NULL.
523 * del a[ilow:ihigh] if v == NULL.
524 *
525 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
526 * guaranteed the call cannot fail.
527 */
Armin Rigo93677f02004-07-29 12:40:23 +0000528static int
Fred Drakea2f55112000-07-09 15:16:51 +0000529list_ass_slice(PyListObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000530{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000531 /* Because [X]DECREF can recursively invoke list operations on
532 this list, we must postpone all [X]DECREF activity until
533 after the list is back in its canonical shape. Therefore
534 we must allocate an additional array, 'recycle', into which
535 we temporarily copy the items that are deleted from the
536 list. :-( */
Tim Peters73572222004-07-31 02:54:42 +0000537 PyObject *recycle_on_stack[8];
538 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000539 PyObject **item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000540 PyObject **vitem = NULL;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000541 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
Tim Peters8d9eb102004-07-31 02:24:20 +0000542 int n; /* # of elements in replacement list */
543 int norig; /* # of elements in list getting replaced */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000544 int d; /* Change in size */
Tim Peters73572222004-07-31 02:54:42 +0000545 int k;
Tim Peters8d9eb102004-07-31 02:24:20 +0000546 size_t s;
547 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000548#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000549 if (v == NULL)
550 n = 0;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000551 else {
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000552 if (a == b) {
553 /* Special case "a[i:j] = a" -- copy b first */
Michael W. Hudsonda0a0672003-08-15 12:06:41 +0000554 v = list_slice(b, 0, b->ob_size);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000555 if (v == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000556 return result;
557 result = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000558 Py_DECREF(v);
Tim Peters8d9eb102004-07-31 02:24:20 +0000559 return result;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000560 }
Raymond Hettingerf889e102004-03-09 08:04:33 +0000561 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000562 if(v_as_SF == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000563 goto Error;
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000564 n = PySequence_Fast_GET_SIZE(v_as_SF);
Raymond Hettinger42bec932004-03-12 16:38:17 +0000565 vitem = PySequence_Fast_ITEMS(v_as_SF);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000566 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000567 if (ilow < 0)
568 ilow = 0;
569 else if (ilow > a->ob_size)
570 ilow = a->ob_size;
Tim Peters8d9eb102004-07-31 02:24:20 +0000571
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000572 if (ihigh < ilow)
573 ihigh = ilow;
574 else if (ihigh > a->ob_size)
575 ihigh = a->ob_size;
Armin Rigo93677f02004-07-29 12:40:23 +0000576
Tim Peters8d9eb102004-07-31 02:24:20 +0000577 norig = ihigh - ilow;
578 assert(norig >= 0);
579 d = n - norig;
Armin Rigo93677f02004-07-29 12:40:23 +0000580 if (a->ob_size + d == 0) {
581 Py_XDECREF(v_as_SF);
582 return list_clear(a);
583 }
584 item = a->ob_item;
Tim Peters8d9eb102004-07-31 02:24:20 +0000585 /* recycle the items that we are about to remove */
586 s = norig * sizeof(PyObject *);
Tim Peters73572222004-07-31 02:54:42 +0000587 if (s > sizeof(recycle_on_stack)) {
Armin Rigo1dd04a02004-07-30 11:38:22 +0000588 recycle = (PyObject **)PyMem_MALLOC(s);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000589 if (recycle == NULL) {
590 PyErr_NoMemory();
Tim Peters8d9eb102004-07-31 02:24:20 +0000591 goto Error;
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000592 }
593 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000594 memcpy(recycle, &item[ilow], s);
Tim Peters8d9eb102004-07-31 02:24:20 +0000595
Armin Rigo1dd04a02004-07-30 11:38:22 +0000596 if (d < 0) { /* Delete -d items */
597 memmove(&item[ihigh+d], &item[ihigh],
598 (a->ob_size - ihigh)*sizeof(PyObject *));
599 list_resize(a, a->ob_size + d);
600 item = a->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000601 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000602 else if (d > 0) { /* Insert d items */
Tim Peters73572222004-07-31 02:54:42 +0000603 k = a->ob_size;
604 if (list_resize(a, k+d) < 0)
Tim Peters8d9eb102004-07-31 02:24:20 +0000605 goto Error;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000606 item = a->ob_item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000607 memmove(&item[ihigh+d], &item[ihigh],
Tim Peters73572222004-07-31 02:54:42 +0000608 (k - ihigh)*sizeof(PyObject *));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000609 }
610 for (k = 0; k < n; k++, ilow++) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000611 PyObject *w = vitem[k];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000612 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000613 item[ilow] = w;
614 }
Tim Peters73572222004-07-31 02:54:42 +0000615 for (k = norig - 1; k >= 0; --k)
616 Py_XDECREF(recycle[k]);
Tim Peters8d9eb102004-07-31 02:24:20 +0000617 result = 0;
618 Error:
Tim Peters73572222004-07-31 02:54:42 +0000619 if (recycle != recycle_on_stack)
Armin Rigo1dd04a02004-07-30 11:38:22 +0000620 PyMem_FREE(recycle);
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000621 Py_XDECREF(v_as_SF);
Tim Peters8d9eb102004-07-31 02:24:20 +0000622 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000623#undef b
624}
625
Guido van Rossum234f9421993-06-17 12:35:49 +0000626int
Fred Drakea2f55112000-07-09 15:16:51 +0000627PyList_SetSlice(PyObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000628{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000629 if (!PyList_Check(a)) {
630 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000631 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000632 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000633 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000634}
635
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000636static PyObject *
637list_inplace_repeat(PyListObject *self, int n)
638{
639 PyObject **items;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000640 int size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000641
642
643 size = PyList_GET_SIZE(self);
644 if (size == 0) {
645 Py_INCREF(self);
646 return (PyObject *)self;
647 }
648
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000649 if (n < 1) {
Armin Rigo93677f02004-07-29 12:40:23 +0000650 (void)list_clear(self);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000651 Py_INCREF(self);
652 return (PyObject *)self;
653 }
654
Tim Petersb38e2b62004-07-29 02:29:26 +0000655 if (list_resize(self, size*n) == -1)
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000656 return NULL;
657
658 p = size;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000659 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000660 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
661 for (j = 0; j < size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000662 PyObject *o = items[j];
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000663 Py_INCREF(o);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000664 items[p++] = o;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000665 }
666 }
667 Py_INCREF(self);
668 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000669}
670
Guido van Rossum4a450d01991-04-03 19:05:18 +0000671static int
Fred Drakea2f55112000-07-09 15:16:51 +0000672list_ass_item(PyListObject *a, int i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000673{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000674 PyObject *old_value;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000675 if (i < 0 || i >= a->ob_size) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000676 PyErr_SetString(PyExc_IndexError,
677 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000678 return -1;
679 }
680 if (v == NULL)
681 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000682 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000683 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000684 a->ob_item[i] = v;
Tim Peters3b01a122002-07-19 02:35:45 +0000685 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000686 return 0;
687}
688
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000689static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000690listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000691{
692 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000693 PyObject *v;
Guido van Rossumc00a9382000-02-24 21:48:29 +0000694 if (!PyArg_ParseTuple(args, "iO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000695 return NULL;
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000696 if (ins1(self, i, v) == 0)
697 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000698 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000699}
700
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000701static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000702listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000703{
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000704 if (app1(self, v) == 0)
705 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000706 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000707}
708
Barry Warsawdedf6d61998-10-09 16:37:25 +0000709static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000710listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000711{
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000712 PyObject *it; /* iter(v) */
713 int m; /* size of self */
714 int n; /* guess for size of b */
715 int mn; /* m + n */
716 int i;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000717 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000718
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000719 /* Special cases:
Tim Petersb38e2b62004-07-29 02:29:26 +0000720 1) lists and tuples which can use PySequence_Fast ops
721 2) extending self to self requires making a copy first
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000722 */
723 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
Armin Rigo70d172d2004-03-20 22:19:23 +0000724 PyObject **src, **dest;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000725 b = PySequence_Fast(b, "argument must be iterable");
726 if (!b)
727 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000728 n = PySequence_Fast_GET_SIZE(b);
729 if (n == 0) {
730 /* short circuit when b is empty */
731 Py_DECREF(b);
732 Py_RETURN_NONE;
733 }
734 m = self->ob_size;
735 if (list_resize(self, m + n) == -1) {
736 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000737 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000738 }
739 /* note that we may still have self == b here for the
740 * situation a.extend(a), but the following code works
741 * in that case too. Just make sure to resize self
742 * before calling PySequence_Fast_ITEMS.
743 */
744 /* populate the end of self with b's items */
745 src = PySequence_Fast_ITEMS(b);
746 dest = self->ob_item + m;
747 for (i = 0; i < n; i++) {
748 PyObject *o = src[i];
749 Py_INCREF(o);
750 dest[i] = o;
751 }
752 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000753 Py_RETURN_NONE;
754 }
755
756 it = PyObject_GetIter(b);
757 if (it == NULL)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000758 return NULL;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000759 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000760
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000761 /* Guess a result list size. */
762 n = PyObject_Size(b);
763 if (n < 0) {
764 PyErr_Clear();
765 n = 8; /* arbitrary */
766 }
767 m = self->ob_size;
768 mn = m + n;
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000769 if (list_resize(self, mn) == -1)
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000770 goto error;
771 memset(&(self->ob_item[m]), 0, sizeof(*self->ob_item) * n);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000772
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000773 /* Run iterator to exhaustion. */
774 for (i = m; ; i++) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000775 PyObject *item = iternext(it);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000776 if (item == NULL) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000777 if (PyErr_Occurred()) {
778 if (PyErr_ExceptionMatches(PyExc_StopIteration))
779 PyErr_Clear();
780 else
781 goto error;
782 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000783 break;
784 }
785 if (i < mn)
786 PyList_SET_ITEM(self, i, item); /* steals ref */
787 else {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000788 int status = app1(self, item);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000789 Py_DECREF(item); /* append creates a new ref */
790 if (status < 0)
791 goto error;
792 }
793 }
794
795 /* Cut back result list if initial guess was too large. */
796 if (i < mn && self != NULL) {
797 if (list_ass_slice(self, i, mn, (PyObject *)NULL) != 0)
798 goto error;
799 }
800 Py_DECREF(it);
801 Py_RETURN_NONE;
802
803 error:
804 Py_DECREF(it);
805 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000806}
807
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000808PyObject *
809_PyList_Extend(PyListObject *self, PyObject *b)
810{
811 return listextend(self, b);
812}
813
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000814static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000815list_inplace_concat(PyListObject *self, PyObject *other)
816{
817 PyObject *result;
818
819 result = listextend(self, other);
820 if (result == NULL)
821 return result;
822 Py_DECREF(result);
823 Py_INCREF(self);
824 return (PyObject *)self;
825}
826
827static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000828listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000829{
830 int i = -1;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000831 PyObject *v, *arg = NULL;
Tim Peters8fc4a912004-07-31 21:53:19 +0000832 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000833
834 if (!PyArg_UnpackTuple(args, "pop", 0, 1, &arg))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000835 return NULL;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000836 if (arg != NULL) {
837 if (PyInt_Check(arg))
838 i = (int)(PyInt_AS_LONG((PyIntObject*) arg));
Raymond Hettingerfa6c6f82004-02-19 06:12:06 +0000839 else if (!PyArg_ParseTuple(args, "|i:pop", &i))
840 return NULL;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000841 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000842 if (self->ob_size == 0) {
843 /* Special-case most common failure cause */
844 PyErr_SetString(PyExc_IndexError, "pop from empty list");
845 return NULL;
846 }
847 if (i < 0)
848 i += self->ob_size;
849 if (i < 0 || i >= self->ob_size) {
850 PyErr_SetString(PyExc_IndexError, "pop index out of range");
851 return NULL;
852 }
853 v = self->ob_item[i];
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000854 if (i == self->ob_size - 1) {
Tim Peters8fc4a912004-07-31 21:53:19 +0000855 status = list_resize(self, self->ob_size - 1);
856 assert(status >= 0);
857 return v; /* and v now owns the reference the list had */
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000858 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000859 Py_INCREF(v);
Tim Peters8fc4a912004-07-31 21:53:19 +0000860 status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
861 assert(status >= 0);
862 /* Use status, so that in a release build compilers don't
863 * complain about the unused name.
864 */
865 return status, v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000866}
867
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000868/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
869static void
870reverse_slice(PyObject **lo, PyObject **hi)
871{
872 assert(lo && hi);
873
874 --hi;
875 while (lo < hi) {
876 PyObject *t = *lo;
877 *lo = *hi;
878 *hi = t;
879 ++lo;
880 --hi;
881 }
882}
883
Tim Petersa64dc242002-08-01 02:13:36 +0000884/* Lots of code for an adaptive, stable, natural mergesort. There are many
885 * pieces to this algorithm; read listsort.txt for overviews and details.
886 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000887
Guido van Rossum3f236de1996-12-10 23:55:39 +0000888/* Comparison function. Takes care of calling a user-supplied
Tim Peters66860f62002-08-04 17:47:26 +0000889 * comparison function (any callable Python object), which must not be
890 * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool
891 * with Py_LT if you know it's NULL).
Tim Petersa64dc242002-08-01 02:13:36 +0000892 * Returns -1 on error, 1 if x < y, 0 if x >= y.
893 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000894static int
Tim Petersa8c974c2002-07-19 03:30:57 +0000895islt(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000896{
Tim Petersf2a04732002-07-11 21:46:16 +0000897 PyObject *res;
898 PyObject *args;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000899 int i;
900
Tim Peters66860f62002-08-04 17:47:26 +0000901 assert(compare != NULL);
Tim Petersa8c974c2002-07-19 03:30:57 +0000902 /* Call the user's comparison function and translate the 3-way
903 * result into true or false (or error).
904 */
Tim Petersf2a04732002-07-11 21:46:16 +0000905 args = PyTuple_New(2);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000906 if (args == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000907 return -1;
Tim Petersf2a04732002-07-11 21:46:16 +0000908 Py_INCREF(x);
909 Py_INCREF(y);
910 PyTuple_SET_ITEM(args, 0, x);
911 PyTuple_SET_ITEM(args, 1, y);
Tim Peters58cf3612002-07-15 05:16:13 +0000912 res = PyObject_Call(compare, args, NULL);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000913 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000914 if (res == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000915 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000916 if (!PyInt_Check(res)) {
917 Py_DECREF(res);
918 PyErr_SetString(PyExc_TypeError,
Guido van Rossum9bcd1d71999-04-19 17:44:39 +0000919 "comparison function must return int");
Tim Petersa8c974c2002-07-19 03:30:57 +0000920 return -1;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000921 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000922 i = PyInt_AsLong(res);
923 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +0000924 return i < 0;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000925}
926
Tim Peters66860f62002-08-04 17:47:26 +0000927/* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
928 * islt. This avoids a layer of function call in the usual case, and
929 * sorting does many comparisons.
930 * Returns -1 on error, 1 if x < y, 0 if x >= y.
931 */
932#define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
933 PyObject_RichCompareBool(X, Y, Py_LT) : \
934 islt(X, Y, COMPARE))
935
936/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +0000937 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
938 started. It makes more sense in context <wink>. X and Y are PyObject*s.
939*/
Tim Peters66860f62002-08-04 17:47:26 +0000940#define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
Tim Petersa8c974c2002-07-19 03:30:57 +0000941 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000942
943/* binarysort is the best method for sorting small arrays: it does
944 few compares, but can do data movement quadratic in the number of
945 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000946 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +0000947 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000948 On entry, must have lo <= start <= hi, and that [lo, start) is already
949 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +0000950 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000951 Even in case of error, the output slice will be some permutation of
952 the input (nothing is lost or duplicated).
953*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000954static int
Fred Drakea2f55112000-07-09 15:16:51 +0000955binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
956 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000957{
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000958 register int k;
959 register PyObject **l, **p, **r;
960 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000961
Tim Petersa8c974c2002-07-19 03:30:57 +0000962 assert(lo <= start && start <= hi);
963 /* assert [lo, start) is sorted */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000964 if (lo == start)
965 ++start;
966 for (; start < hi; ++start) {
967 /* set l to where *start belongs */
968 l = lo;
969 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000970 pivot = *r;
Tim Peters0fe977c2002-07-19 06:12:32 +0000971 /* Invariants:
972 * pivot >= all in [lo, l).
973 * pivot < all in [r, start).
974 * The second is vacuously true at the start.
975 */
976 assert(l < r);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000977 do {
978 p = l + ((r - l) >> 1);
Tim Petersa8c974c2002-07-19 03:30:57 +0000979 IFLT(pivot, *p)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000980 r = p;
981 else
Tim Peters0fe977c2002-07-19 06:12:32 +0000982 l = p+1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000983 } while (l < r);
Tim Peters0fe977c2002-07-19 06:12:32 +0000984 assert(l == r);
985 /* The invariants still hold, so pivot >= all in [lo, l) and
986 pivot < all in [l, start), so pivot belongs at l. Note
987 that if there are elements equal to pivot, l points to the
988 first slot after them -- that's why this sort is stable.
989 Slide over to make room.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000990 Caution: using memmove is much slower under MSVC 5;
991 we're not usually moving many slots. */
992 for (p = start; p > l; --p)
993 *p = *(p-1);
994 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000995 }
Guido van Rossum3f236de1996-12-10 23:55:39 +0000996 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000997
998 fail:
999 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001000}
1001
Tim Petersa64dc242002-08-01 02:13:36 +00001002/*
1003Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1004is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001005
Tim Petersa64dc242002-08-01 02:13:36 +00001006 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001007
Tim Petersa64dc242002-08-01 02:13:36 +00001008or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001009
Tim Petersa64dc242002-08-01 02:13:36 +00001010 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001011
Tim Petersa64dc242002-08-01 02:13:36 +00001012Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1013For its intended use in a stable mergesort, the strictness of the defn of
1014"descending" is needed so that the caller can safely reverse a descending
1015sequence without violating stability (strict > ensures there are no equal
1016elements to get out of order).
1017
1018Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001019*/
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001020static int
Tim Petersa64dc242002-08-01 02:13:36 +00001021count_run(PyObject **lo, PyObject **hi, PyObject *compare, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001022{
Tim Petersa64dc242002-08-01 02:13:36 +00001023 int k;
1024 int n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001025
Tim Petersa64dc242002-08-01 02:13:36 +00001026 assert(lo < hi);
1027 *descending = 0;
1028 ++lo;
1029 if (lo == hi)
1030 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001031
Tim Petersa64dc242002-08-01 02:13:36 +00001032 n = 2;
1033 IFLT(*lo, *(lo-1)) {
1034 *descending = 1;
1035 for (lo = lo+1; lo < hi; ++lo, ++n) {
1036 IFLT(*lo, *(lo-1))
1037 ;
1038 else
1039 break;
1040 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001041 }
Tim Petersa64dc242002-08-01 02:13:36 +00001042 else {
1043 for (lo = lo+1; lo < hi; ++lo, ++n) {
1044 IFLT(*lo, *(lo-1))
1045 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001046 }
1047 }
1048
Tim Petersa64dc242002-08-01 02:13:36 +00001049 return n;
1050fail:
1051 return -1;
1052}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001053
Tim Petersa64dc242002-08-01 02:13:36 +00001054/*
1055Locate the proper position of key in a sorted vector; if the vector contains
1056an element equal to key, return the position immediately to the left of
1057the leftmost equal element. [gallop_right() does the same except returns
1058the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001059
Tim Petersa64dc242002-08-01 02:13:36 +00001060"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001061
Tim Petersa64dc242002-08-01 02:13:36 +00001062"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1063hint is to the final result, the faster this runs.
1064
1065The return value is the int k in 0..n such that
1066
1067 a[k-1] < key <= a[k]
1068
1069pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1070key belongs at index k; or, IOW, the first k elements of a should precede
1071key, and the last n-k should follow key.
1072
1073Returns -1 on error. See listsort.txt for info on the method.
1074*/
1075static int
1076gallop_left(PyObject *key, PyObject **a, int n, int hint, PyObject *compare)
1077{
1078 int ofs;
1079 int lastofs;
1080 int k;
1081
1082 assert(key && a && n > 0 && hint >= 0 && hint < n);
1083
1084 a += hint;
1085 lastofs = 0;
1086 ofs = 1;
1087 IFLT(*a, key) {
1088 /* a[hint] < key -- gallop right, until
1089 * a[hint + lastofs] < key <= a[hint + ofs]
1090 */
1091 const int maxofs = n - hint; /* &a[n-1] is highest */
1092 while (ofs < maxofs) {
1093 IFLT(a[ofs], key) {
1094 lastofs = ofs;
1095 ofs = (ofs << 1) + 1;
1096 if (ofs <= 0) /* int overflow */
1097 ofs = maxofs;
1098 }
1099 else /* key <= a[hint + ofs] */
1100 break;
1101 }
1102 if (ofs > maxofs)
1103 ofs = maxofs;
1104 /* Translate back to offsets relative to &a[0]. */
1105 lastofs += hint;
1106 ofs += hint;
1107 }
1108 else {
1109 /* key <= a[hint] -- gallop left, until
1110 * a[hint - ofs] < key <= a[hint - lastofs]
1111 */
1112 const int maxofs = hint + 1; /* &a[0] is lowest */
1113 while (ofs < maxofs) {
1114 IFLT(*(a-ofs), key)
1115 break;
1116 /* key <= a[hint - ofs] */
1117 lastofs = ofs;
1118 ofs = (ofs << 1) + 1;
1119 if (ofs <= 0) /* int overflow */
1120 ofs = maxofs;
1121 }
1122 if (ofs > maxofs)
1123 ofs = maxofs;
1124 /* Translate back to positive offsets relative to &a[0]. */
1125 k = lastofs;
1126 lastofs = hint - ofs;
1127 ofs = hint - k;
1128 }
1129 a -= hint;
1130
1131 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1132 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1133 * right of lastofs but no farther right than ofs. Do a binary
1134 * search, with invariant a[lastofs-1] < key <= a[ofs].
1135 */
1136 ++lastofs;
1137 while (lastofs < ofs) {
1138 int m = lastofs + ((ofs - lastofs) >> 1);
1139
1140 IFLT(a[m], key)
1141 lastofs = m+1; /* a[m] < key */
1142 else
1143 ofs = m; /* key <= a[m] */
1144 }
1145 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1146 return ofs;
1147
1148fail:
1149 return -1;
1150}
1151
1152/*
1153Exactly like gallop_left(), except that if key already exists in a[0:n],
1154finds the position immediately to the right of the rightmost equal value.
1155
1156The return value is the int k in 0..n such that
1157
1158 a[k-1] <= key < a[k]
1159
1160or -1 if error.
1161
1162The code duplication is massive, but this is enough different given that
1163we're sticking to "<" comparisons that it's much harder to follow if
1164written as one routine with yet another "left or right?" flag.
1165*/
1166static int
1167gallop_right(PyObject *key, PyObject **a, int n, int hint, PyObject *compare)
1168{
1169 int ofs;
1170 int lastofs;
1171 int k;
1172
1173 assert(key && a && n > 0 && hint >= 0 && hint < n);
1174
1175 a += hint;
1176 lastofs = 0;
1177 ofs = 1;
1178 IFLT(key, *a) {
1179 /* key < a[hint] -- gallop left, until
1180 * a[hint - ofs] <= key < a[hint - lastofs]
1181 */
1182 const int maxofs = hint + 1; /* &a[0] is lowest */
1183 while (ofs < maxofs) {
1184 IFLT(key, *(a-ofs)) {
1185 lastofs = ofs;
1186 ofs = (ofs << 1) + 1;
1187 if (ofs <= 0) /* int overflow */
1188 ofs = maxofs;
1189 }
1190 else /* a[hint - ofs] <= key */
1191 break;
1192 }
1193 if (ofs > maxofs)
1194 ofs = maxofs;
1195 /* Translate back to positive offsets relative to &a[0]. */
1196 k = lastofs;
1197 lastofs = hint - ofs;
1198 ofs = hint - k;
1199 }
1200 else {
1201 /* a[hint] <= key -- gallop right, until
1202 * a[hint + lastofs] <= key < a[hint + ofs]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001203 */
Tim Petersa64dc242002-08-01 02:13:36 +00001204 const int maxofs = n - hint; /* &a[n-1] is highest */
1205 while (ofs < maxofs) {
1206 IFLT(key, a[ofs])
1207 break;
1208 /* a[hint + ofs] <= key */
1209 lastofs = ofs;
1210 ofs = (ofs << 1) + 1;
1211 if (ofs <= 0) /* int overflow */
1212 ofs = maxofs;
1213 }
1214 if (ofs > maxofs)
1215 ofs = maxofs;
1216 /* Translate back to offsets relative to &a[0]. */
1217 lastofs += hint;
1218 ofs += hint;
1219 }
1220 a -= hint;
1221
1222 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1223 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1224 * right of lastofs but no farther right than ofs. Do a binary
1225 * search, with invariant a[lastofs-1] <= key < a[ofs].
1226 */
1227 ++lastofs;
1228 while (lastofs < ofs) {
1229 int m = lastofs + ((ofs - lastofs) >> 1);
1230
1231 IFLT(key, a[m])
1232 ofs = m; /* key < a[m] */
1233 else
1234 lastofs = m+1; /* a[m] <= key */
1235 }
1236 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1237 return ofs;
1238
1239fail:
1240 return -1;
1241}
1242
1243/* The maximum number of entries in a MergeState's pending-runs stack.
1244 * This is enough to sort arrays of size up to about
1245 * 32 * phi ** MAX_MERGE_PENDING
1246 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1247 * with 2**64 elements.
1248 */
1249#define MAX_MERGE_PENDING 85
1250
Tim Peterse05f65a2002-08-10 05:21:15 +00001251/* When we get into galloping mode, we stay there until both runs win less
1252 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001253 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001254#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001255
1256/* Avoid malloc for small temp arrays. */
1257#define MERGESTATE_TEMP_SIZE 256
1258
1259/* One MergeState exists on the stack per invocation of mergesort. It's just
1260 * a convenient way to pass state around among the helper functions.
1261 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001262struct s_slice {
1263 PyObject **base;
1264 int len;
1265};
1266
Tim Petersa64dc242002-08-01 02:13:36 +00001267typedef struct s_MergeState {
1268 /* The user-supplied comparison function. or NULL if none given. */
1269 PyObject *compare;
1270
Tim Peterse05f65a2002-08-10 05:21:15 +00001271 /* This controls when we get *into* galloping mode. It's initialized
1272 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1273 * random data, and lower for highly structured data.
1274 */
1275 int min_gallop;
1276
Tim Petersa64dc242002-08-01 02:13:36 +00001277 /* 'a' is temp storage to help with merges. It contains room for
1278 * alloced entries.
1279 */
1280 PyObject **a; /* may point to temparray below */
1281 int alloced;
1282
1283 /* A stack of n pending runs yet to be merged. Run #i starts at
1284 * address base[i] and extends for len[i] elements. It's always
1285 * true (so long as the indices are in bounds) that
1286 *
Tim Peterse05f65a2002-08-10 05:21:15 +00001287 * pending[i].base + pending[i].len == pending[i+1].base
Tim Petersa64dc242002-08-01 02:13:36 +00001288 *
1289 * so we could cut the storage for this, but it's a minor amount,
1290 * and keeping all the info explicit simplifies the code.
1291 */
1292 int n;
Tim Peterse05f65a2002-08-10 05:21:15 +00001293 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001294
1295 /* 'a' points to this when possible, rather than muck with malloc. */
1296 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1297} MergeState;
1298
1299/* Conceptually a MergeState's constructor. */
1300static void
1301merge_init(MergeState *ms, PyObject *compare)
1302{
1303 assert(ms != NULL);
1304 ms->compare = compare;
1305 ms->a = ms->temparray;
1306 ms->alloced = MERGESTATE_TEMP_SIZE;
1307 ms->n = 0;
Tim Peterse05f65a2002-08-10 05:21:15 +00001308 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001309}
1310
1311/* Free all the temp memory owned by the MergeState. This must be called
1312 * when you're done with a MergeState, and may be called before then if
1313 * you want to free the temp memory early.
1314 */
1315static void
1316merge_freemem(MergeState *ms)
1317{
1318 assert(ms != NULL);
1319 if (ms->a != ms->temparray)
1320 PyMem_Free(ms->a);
1321 ms->a = ms->temparray;
1322 ms->alloced = MERGESTATE_TEMP_SIZE;
1323}
1324
1325/* Ensure enough temp memory for 'need' array slots is available.
1326 * Returns 0 on success and -1 if the memory can't be gotten.
1327 */
1328static int
1329merge_getmem(MergeState *ms, int need)
1330{
1331 assert(ms != NULL);
1332 if (need <= ms->alloced)
1333 return 0;
1334 /* Don't realloc! That can cost cycles to copy the old data, but
1335 * we don't care what's in the block.
1336 */
1337 merge_freemem(ms);
1338 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1339 if (ms->a) {
1340 ms->alloced = need;
1341 return 0;
1342 }
1343 PyErr_NoMemory();
1344 merge_freemem(ms); /* reset to sane state */
1345 return -1;
1346}
1347#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1348 merge_getmem(MS, NEED))
1349
1350/* Merge the na elements starting at pa with the nb elements starting at pb
1351 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1352 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1353 * merge, and should have na <= nb. See listsort.txt for more info.
1354 * Return 0 if successful, -1 if error.
1355 */
1356static int
1357merge_lo(MergeState *ms, PyObject **pa, int na, PyObject **pb, int nb)
1358{
1359 int k;
1360 PyObject *compare;
1361 PyObject **dest;
1362 int result = -1; /* guilty until proved innocent */
Tim Peterse05f65a2002-08-10 05:21:15 +00001363 int min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001364
1365 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1366 if (MERGE_GETMEM(ms, na) < 0)
1367 return -1;
1368 memcpy(ms->a, pa, na * sizeof(PyObject*));
1369 dest = pa;
1370 pa = ms->a;
1371
1372 *dest++ = *pb++;
1373 --nb;
1374 if (nb == 0)
1375 goto Succeed;
1376 if (na == 1)
1377 goto CopyB;
1378
1379 compare = ms->compare;
1380 for (;;) {
1381 int acount = 0; /* # of times A won in a row */
1382 int bcount = 0; /* # of times B won in a row */
1383
1384 /* Do the straightforward thing until (if ever) one run
1385 * appears to win consistently.
1386 */
1387 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001388 assert(na > 1 && nb > 0);
Tim Peters66860f62002-08-04 17:47:26 +00001389 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001390 if (k) {
1391 if (k < 0)
1392 goto Fail;
1393 *dest++ = *pb++;
1394 ++bcount;
1395 acount = 0;
1396 --nb;
1397 if (nb == 0)
1398 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001399 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001400 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001401 }
1402 else {
Tim Petersa64dc242002-08-01 02:13:36 +00001403 *dest++ = *pa++;
1404 ++acount;
1405 bcount = 0;
1406 --na;
1407 if (na == 1)
1408 goto CopyB;
Tim Peterse05f65a2002-08-10 05:21:15 +00001409 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001410 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001411 }
Tim Petersa64dc242002-08-01 02:13:36 +00001412 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001413
Tim Petersa64dc242002-08-01 02:13:36 +00001414 /* One run is winning so consistently that galloping may
1415 * be a huge win. So try that, and continue galloping until
1416 * (if ever) neither run appears to be winning consistently
1417 * anymore.
1418 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001419 ++min_gallop;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001420 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001421 assert(na > 1 && nb > 0);
1422 min_gallop -= min_gallop > 1;
1423 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001424 k = gallop_right(*pb, pa, na, 0, compare);
1425 acount = k;
1426 if (k) {
1427 if (k < 0)
1428 goto Fail;
1429 memcpy(dest, pa, k * sizeof(PyObject *));
1430 dest += k;
1431 pa += k;
1432 na -= k;
1433 if (na == 1)
1434 goto CopyB;
1435 /* na==0 is impossible now if the comparison
1436 * function is consistent, but we can't assume
1437 * that it is.
1438 */
1439 if (na == 0)
1440 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001441 }
Tim Petersa64dc242002-08-01 02:13:36 +00001442 *dest++ = *pb++;
1443 --nb;
1444 if (nb == 0)
1445 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001446
Tim Petersa64dc242002-08-01 02:13:36 +00001447 k = gallop_left(*pa, pb, nb, 0, compare);
1448 bcount = k;
1449 if (k) {
1450 if (k < 0)
1451 goto Fail;
1452 memmove(dest, pb, k * sizeof(PyObject *));
1453 dest += k;
1454 pb += k;
1455 nb -= k;
1456 if (nb == 0)
1457 goto Succeed;
1458 }
1459 *dest++ = *pa++;
1460 --na;
1461 if (na == 1)
1462 goto CopyB;
1463 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001464 ++min_gallop; /* penalize it for leaving galloping mode */
1465 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001466 }
1467Succeed:
1468 result = 0;
1469Fail:
1470 if (na)
1471 memcpy(dest, pa, na * sizeof(PyObject*));
1472 return result;
1473CopyB:
1474 assert(na == 1 && nb > 0);
1475 /* The last element of pa belongs at the end of the merge. */
1476 memmove(dest, pb, nb * sizeof(PyObject *));
1477 dest[nb] = *pa;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001478 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001479}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001480
Tim Petersa64dc242002-08-01 02:13:36 +00001481/* Merge the na elements starting at pa with the nb elements starting at pb
1482 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1483 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1484 * merge, and should have na >= nb. See listsort.txt for more info.
1485 * Return 0 if successful, -1 if error.
1486 */
1487static int
1488merge_hi(MergeState *ms, PyObject **pa, int na, PyObject **pb, int nb)
1489{
1490 int k;
1491 PyObject *compare;
1492 PyObject **dest;
1493 int result = -1; /* guilty until proved innocent */
1494 PyObject **basea;
1495 PyObject **baseb;
Tim Peterse05f65a2002-08-10 05:21:15 +00001496 int min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001497
1498 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1499 if (MERGE_GETMEM(ms, nb) < 0)
1500 return -1;
1501 dest = pb + nb - 1;
1502 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1503 basea = pa;
1504 baseb = ms->a;
1505 pb = ms->a + nb - 1;
1506 pa += na - 1;
1507
1508 *dest-- = *pa--;
1509 --na;
1510 if (na == 0)
1511 goto Succeed;
1512 if (nb == 1)
1513 goto CopyA;
1514
1515 compare = ms->compare;
1516 for (;;) {
1517 int acount = 0; /* # of times A won in a row */
1518 int bcount = 0; /* # of times B won in a row */
1519
1520 /* Do the straightforward thing until (if ever) one run
1521 * appears to win consistently.
1522 */
1523 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001524 assert(na > 0 && nb > 1);
Tim Peters66860f62002-08-04 17:47:26 +00001525 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001526 if (k) {
1527 if (k < 0)
1528 goto Fail;
1529 *dest-- = *pa--;
1530 ++acount;
1531 bcount = 0;
1532 --na;
1533 if (na == 0)
1534 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001535 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001536 break;
1537 }
1538 else {
1539 *dest-- = *pb--;
1540 ++bcount;
1541 acount = 0;
1542 --nb;
1543 if (nb == 1)
1544 goto CopyA;
Tim Peterse05f65a2002-08-10 05:21:15 +00001545 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001546 break;
1547 }
1548 }
1549
1550 /* One run is winning so consistently that galloping may
1551 * be a huge win. So try that, and continue galloping until
1552 * (if ever) neither run appears to be winning consistently
1553 * anymore.
1554 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001555 ++min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001556 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001557 assert(na > 0 && nb > 1);
1558 min_gallop -= min_gallop > 1;
1559 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001560 k = gallop_right(*pb, basea, na, na-1, compare);
1561 if (k < 0)
1562 goto Fail;
1563 k = na - k;
1564 acount = k;
1565 if (k) {
1566 dest -= k;
1567 pa -= k;
1568 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1569 na -= k;
1570 if (na == 0)
1571 goto Succeed;
1572 }
1573 *dest-- = *pb--;
1574 --nb;
1575 if (nb == 1)
1576 goto CopyA;
1577
1578 k = gallop_left(*pa, baseb, nb, nb-1, compare);
1579 if (k < 0)
1580 goto Fail;
1581 k = nb - k;
1582 bcount = k;
1583 if (k) {
1584 dest -= k;
1585 pb -= k;
1586 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1587 nb -= k;
1588 if (nb == 1)
1589 goto CopyA;
1590 /* nb==0 is impossible now if the comparison
1591 * function is consistent, but we can't assume
1592 * that it is.
1593 */
1594 if (nb == 0)
1595 goto Succeed;
1596 }
1597 *dest-- = *pa--;
1598 --na;
1599 if (na == 0)
1600 goto Succeed;
1601 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001602 ++min_gallop; /* penalize it for leaving galloping mode */
1603 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001604 }
1605Succeed:
1606 result = 0;
1607Fail:
1608 if (nb)
1609 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1610 return result;
1611CopyA:
1612 assert(nb == 1 && na > 0);
1613 /* The first element of pb belongs at the front of the merge. */
1614 dest -= na;
1615 pa -= na;
1616 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1617 *dest = *pb;
1618 return 0;
1619}
1620
1621/* Merge the two runs at stack indices i and i+1.
1622 * Returns 0 on success, -1 on error.
1623 */
1624static int
1625merge_at(MergeState *ms, int i)
1626{
1627 PyObject **pa, **pb;
1628 int na, nb;
1629 int k;
1630 PyObject *compare;
1631
1632 assert(ms != NULL);
1633 assert(ms->n >= 2);
1634 assert(i >= 0);
1635 assert(i == ms->n - 2 || i == ms->n - 3);
1636
Tim Peterse05f65a2002-08-10 05:21:15 +00001637 pa = ms->pending[i].base;
1638 na = ms->pending[i].len;
1639 pb = ms->pending[i+1].base;
1640 nb = ms->pending[i+1].len;
Tim Petersa64dc242002-08-01 02:13:36 +00001641 assert(na > 0 && nb > 0);
1642 assert(pa + na == pb);
1643
1644 /* Record the length of the combined runs; if i is the 3rd-last
1645 * run now, also slide over the last run (which isn't involved
1646 * in this merge). The current run i+1 goes away in any case.
1647 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001648 ms->pending[i].len = na + nb;
1649 if (i == ms->n - 3)
1650 ms->pending[i+1] = ms->pending[i+2];
Tim Petersa64dc242002-08-01 02:13:36 +00001651 --ms->n;
1652
1653 /* Where does b start in a? Elements in a before that can be
1654 * ignored (already in place).
1655 */
1656 compare = ms->compare;
1657 k = gallop_right(*pb, pa, na, 0, compare);
1658 if (k < 0)
1659 return -1;
1660 pa += k;
1661 na -= k;
1662 if (na == 0)
1663 return 0;
1664
1665 /* Where does a end in b? Elements in b after that can be
1666 * ignored (already in place).
1667 */
1668 nb = gallop_left(pa[na-1], pb, nb, nb-1, compare);
1669 if (nb <= 0)
1670 return nb;
1671
1672 /* Merge what remains of the runs, using a temp array with
1673 * min(na, nb) elements.
1674 */
1675 if (na <= nb)
1676 return merge_lo(ms, pa, na, pb, nb);
1677 else
1678 return merge_hi(ms, pa, na, pb, nb);
1679}
1680
1681/* Examine the stack of runs waiting to be merged, merging adjacent runs
1682 * until the stack invariants are re-established:
1683 *
1684 * 1. len[-3] > len[-2] + len[-1]
1685 * 2. len[-2] > len[-1]
1686 *
1687 * See listsort.txt for more info.
1688 *
1689 * Returns 0 on success, -1 on error.
1690 */
1691static int
1692merge_collapse(MergeState *ms)
1693{
Tim Peterse05f65a2002-08-10 05:21:15 +00001694 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001695
1696 assert(ms);
1697 while (ms->n > 1) {
1698 int n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001699 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1700 if (p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001701 --n;
1702 if (merge_at(ms, n) < 0)
1703 return -1;
1704 }
Tim Peterse05f65a2002-08-10 05:21:15 +00001705 else if (p[n].len <= p[n+1].len) {
Tim Petersa64dc242002-08-01 02:13:36 +00001706 if (merge_at(ms, n) < 0)
1707 return -1;
1708 }
1709 else
1710 break;
1711 }
1712 return 0;
1713}
1714
1715/* Regardless of invariants, merge all runs on the stack until only one
1716 * remains. This is used at the end of the mergesort.
1717 *
1718 * Returns 0 on success, -1 on error.
1719 */
1720static int
1721merge_force_collapse(MergeState *ms)
1722{
Tim Peterse05f65a2002-08-10 05:21:15 +00001723 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001724
1725 assert(ms);
1726 while (ms->n > 1) {
1727 int n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001728 if (n > 0 && p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001729 --n;
1730 if (merge_at(ms, n) < 0)
1731 return -1;
1732 }
1733 return 0;
1734}
1735
1736/* Compute a good value for the minimum run length; natural runs shorter
1737 * than this are boosted artificially via binary insertion.
1738 *
1739 * If n < 64, return n (it's too small to bother with fancy stuff).
1740 * Else if n is an exact power of 2, return 32.
1741 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1742 * strictly less than, an exact power of 2.
1743 *
1744 * See listsort.txt for more info.
1745 */
1746static int
1747merge_compute_minrun(int n)
1748{
1749 int r = 0; /* becomes 1 if any 1 bits are shifted off */
1750
1751 assert(n >= 0);
1752 while (n >= 64) {
1753 r |= n & 1;
1754 n >>= 1;
1755 }
1756 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001757}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001758
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001759/* Special wrapper to support stable sorting using the decorate-sort-undecorate
1760 pattern. Holds a key which is used for comparisions and the original record
Tim Petersb38e2b62004-07-29 02:29:26 +00001761 which is returned during the undecorate phase. By exposing only the key
1762 during comparisons, the underlying sort stability characteristics are left
1763 unchanged. Also, if a custom comparison function is used, it will only see
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001764 the key instead of a full record. */
1765
1766typedef struct {
1767 PyObject_HEAD
1768 PyObject *key;
1769 PyObject *value;
1770} sortwrapperobject;
1771
1772static PyTypeObject sortwrapper_type;
1773
1774static PyObject *
1775sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
1776{
1777 if (!PyObject_TypeCheck(b, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001778 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001779 "expected a sortwrapperobject");
1780 return NULL;
1781 }
1782 return PyObject_RichCompare(a->key, b->key, op);
1783}
1784
1785static void
1786sortwrapper_dealloc(sortwrapperobject *so)
1787{
1788 Py_XDECREF(so->key);
1789 Py_XDECREF(so->value);
1790 PyObject_Del(so);
1791}
1792
1793PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
1794
1795static PyTypeObject sortwrapper_type = {
1796 PyObject_HEAD_INIT(&PyType_Type)
1797 0, /* ob_size */
1798 "sortwrapper", /* tp_name */
1799 sizeof(sortwrapperobject), /* tp_basicsize */
1800 0, /* tp_itemsize */
1801 /* methods */
1802 (destructor)sortwrapper_dealloc, /* tp_dealloc */
1803 0, /* tp_print */
1804 0, /* tp_getattr */
1805 0, /* tp_setattr */
1806 0, /* tp_compare */
1807 0, /* tp_repr */
1808 0, /* tp_as_number */
1809 0, /* tp_as_sequence */
1810 0, /* tp_as_mapping */
1811 0, /* tp_hash */
1812 0, /* tp_call */
1813 0, /* tp_str */
1814 PyObject_GenericGetAttr, /* tp_getattro */
1815 0, /* tp_setattro */
1816 0, /* tp_as_buffer */
Tim Petersb38e2b62004-07-29 02:29:26 +00001817 Py_TPFLAGS_DEFAULT |
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001818 Py_TPFLAGS_HAVE_RICHCOMPARE, /* tp_flags */
1819 sortwrapper_doc, /* tp_doc */
1820 0, /* tp_traverse */
1821 0, /* tp_clear */
1822 (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
1823};
1824
1825/* Returns a new reference to a sortwrapper.
1826 Consumes the references to the two underlying objects. */
1827
1828static PyObject *
1829build_sortwrapper(PyObject *key, PyObject *value)
1830{
1831 sortwrapperobject *so;
Tim Petersb38e2b62004-07-29 02:29:26 +00001832
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001833 so = PyObject_New(sortwrapperobject, &sortwrapper_type);
1834 if (so == NULL)
1835 return NULL;
1836 so->key = key;
1837 so->value = value;
1838 return (PyObject *)so;
1839}
1840
1841/* Returns a new reference to the value underlying the wrapper. */
1842static PyObject *
1843sortwrapper_getvalue(PyObject *so)
1844{
1845 PyObject *value;
1846
1847 if (!PyObject_TypeCheck(so, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001848 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001849 "expected a sortwrapperobject");
1850 return NULL;
1851 }
1852 value = ((sortwrapperobject *)so)->value;
1853 Py_INCREF(value);
1854 return value;
1855}
1856
1857/* Wrapper for user specified cmp functions in combination with a
1858 specified key function. Makes sure the cmp function is presented
1859 with the actual key instead of the sortwrapper */
1860
1861typedef struct {
1862 PyObject_HEAD
1863 PyObject *func;
1864} cmpwrapperobject;
1865
1866static void
1867cmpwrapper_dealloc(cmpwrapperobject *co)
1868{
1869 Py_XDECREF(co->func);
1870 PyObject_Del(co);
1871}
1872
1873static PyObject *
1874cmpwrapper_call(cmpwrapperobject *co, PyObject *args, PyObject *kwds)
1875{
1876 PyObject *x, *y, *xx, *yy;
1877
1878 if (!PyArg_UnpackTuple(args, "", 2, 2, &x, &y))
1879 return NULL;
1880 if (!PyObject_TypeCheck(x, &sortwrapper_type) ||
Raymond Hettingerae4a2992003-10-16 17:16:30 +00001881 !PyObject_TypeCheck(y, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001882 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001883 "expected a sortwrapperobject");
1884 return NULL;
1885 }
1886 xx = ((sortwrapperobject *)x)->key;
1887 yy = ((sortwrapperobject *)y)->key;
1888 return PyObject_CallFunctionObjArgs(co->func, xx, yy, NULL);
1889}
1890
1891PyDoc_STRVAR(cmpwrapper_doc, "cmp() wrapper for sort with custom keys.");
1892
1893static PyTypeObject cmpwrapper_type = {
1894 PyObject_HEAD_INIT(&PyType_Type)
1895 0, /* ob_size */
1896 "cmpwrapper", /* tp_name */
1897 sizeof(cmpwrapperobject), /* tp_basicsize */
1898 0, /* tp_itemsize */
1899 /* methods */
1900 (destructor)cmpwrapper_dealloc, /* tp_dealloc */
1901 0, /* tp_print */
1902 0, /* tp_getattr */
1903 0, /* tp_setattr */
1904 0, /* tp_compare */
1905 0, /* tp_repr */
1906 0, /* tp_as_number */
1907 0, /* tp_as_sequence */
1908 0, /* tp_as_mapping */
1909 0, /* tp_hash */
1910 (ternaryfunc)cmpwrapper_call, /* tp_call */
1911 0, /* tp_str */
1912 PyObject_GenericGetAttr, /* tp_getattro */
1913 0, /* tp_setattro */
1914 0, /* tp_as_buffer */
1915 Py_TPFLAGS_DEFAULT, /* tp_flags */
1916 cmpwrapper_doc, /* tp_doc */
1917};
1918
1919static PyObject *
1920build_cmpwrapper(PyObject *cmpfunc)
1921{
1922 cmpwrapperobject *co;
Tim Petersb38e2b62004-07-29 02:29:26 +00001923
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001924 co = PyObject_New(cmpwrapperobject, &cmpwrapper_type);
1925 if (co == NULL)
1926 return NULL;
1927 Py_INCREF(cmpfunc);
1928 co->func = cmpfunc;
1929 return (PyObject *)co;
1930}
1931
Tim Petersa64dc242002-08-01 02:13:36 +00001932/* An adaptive, stable, natural mergesort. See listsort.txt.
1933 * Returns Py_None on success, NULL on error. Even in case of error, the
1934 * list will be some permutation of its input state (nothing is lost or
1935 * duplicated).
1936 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001937static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001938listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001939{
Tim Petersa64dc242002-08-01 02:13:36 +00001940 MergeState ms;
1941 PyObject **lo, **hi;
1942 int nremaining;
1943 int minrun;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001944 int saved_ob_size, saved_allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00001945 PyObject **saved_ob_item;
Armin Rigo93677f02004-07-29 12:40:23 +00001946 PyObject **final_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001947 PyObject *compare = NULL;
1948 PyObject *result = NULL; /* guilty until proved innocent */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001949 int reverse = 0;
1950 PyObject *keyfunc = NULL;
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001951 int i;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001952 PyObject *key, *value, *kvpair;
1953 static char *kwlist[] = {"cmp", "key", "reverse", 0};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001954
Tim Petersa64dc242002-08-01 02:13:36 +00001955 assert(self != NULL);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001956 assert (PyList_Check(self));
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001957 if (args != NULL) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001958 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:sort",
1959 kwlist, &compare, &keyfunc, &reverse))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001960 return NULL;
1961 }
Skip Montanaro4abd5f02003-01-02 20:51:08 +00001962 if (compare == Py_None)
1963 compare = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001964 if (keyfunc == Py_None)
1965 keyfunc = NULL;
1966 if (compare != NULL && keyfunc != NULL) {
1967 compare = build_cmpwrapper(compare);
1968 if (compare == NULL)
Hye-Shik Chang19cb1932003-12-10 07:31:08 +00001969 return NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001970 } else
1971 Py_XINCREF(compare);
1972
Tim Petersb9099c32002-11-12 22:08:10 +00001973 /* The list is temporarily made empty, so that mutations performed
1974 * by comparison functions can't affect the slice of memory we're
1975 * sorting (allowing mutations during sorting is a core-dump
1976 * factory, since ob_item may change).
1977 */
1978 saved_ob_size = self->ob_size;
1979 saved_ob_item = self->ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001980 saved_allocated = self->allocated;
Armin Rigo93677f02004-07-29 12:40:23 +00001981 self->ob_size = 0;
Tim Peters51b4ade2004-07-29 04:07:15 +00001982 self->ob_item = NULL;
Armin Rigo93677f02004-07-29 12:40:23 +00001983 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00001984
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001985 if (keyfunc != NULL) {
1986 for (i=0 ; i < saved_ob_size ; i++) {
1987 value = saved_ob_item[i];
Tim Petersb38e2b62004-07-29 02:29:26 +00001988 key = PyObject_CallFunctionObjArgs(keyfunc, value,
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001989 NULL);
1990 if (key == NULL) {
1991 for (i=i-1 ; i>=0 ; i--) {
1992 kvpair = saved_ob_item[i];
1993 value = sortwrapper_getvalue(kvpair);
1994 saved_ob_item[i] = value;
1995 Py_DECREF(kvpair);
1996 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001997 goto dsu_fail;
1998 }
1999 kvpair = build_sortwrapper(key, value);
2000 if (kvpair == NULL)
2001 goto dsu_fail;
2002 saved_ob_item[i] = kvpair;
2003 }
2004 }
2005
2006 /* Reverse sort stability achieved by initially reversing the list,
2007 applying a stable forward sort, then reversing the final result. */
2008 if (reverse && saved_ob_size > 1)
2009 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2010
2011 merge_init(&ms, compare);
2012
Tim Petersb9099c32002-11-12 22:08:10 +00002013 nremaining = saved_ob_size;
Tim Petersa64dc242002-08-01 02:13:36 +00002014 if (nremaining < 2)
2015 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00002016
Tim Petersa64dc242002-08-01 02:13:36 +00002017 /* March over the array once, left to right, finding natural runs,
2018 * and extending short natural runs to minrun elements.
2019 */
Tim Petersb9099c32002-11-12 22:08:10 +00002020 lo = saved_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00002021 hi = lo + nremaining;
2022 minrun = merge_compute_minrun(nremaining);
2023 do {
2024 int descending;
2025 int n;
Tim Peters330f9e92002-07-19 07:05:44 +00002026
Tim Petersa64dc242002-08-01 02:13:36 +00002027 /* Identify next run. */
2028 n = count_run(lo, hi, compare, &descending);
2029 if (n < 0)
2030 goto fail;
2031 if (descending)
2032 reverse_slice(lo, lo + n);
2033 /* If short, extend to min(minrun, nremaining). */
2034 if (n < minrun) {
2035 const int force = nremaining <= minrun ?
2036 nremaining : minrun;
2037 if (binarysort(lo, lo + force, lo + n, compare) < 0)
2038 goto fail;
2039 n = force;
2040 }
2041 /* Push run onto pending-runs stack, and maybe merge. */
2042 assert(ms.n < MAX_MERGE_PENDING);
Tim Peterse05f65a2002-08-10 05:21:15 +00002043 ms.pending[ms.n].base = lo;
2044 ms.pending[ms.n].len = n;
Tim Petersa64dc242002-08-01 02:13:36 +00002045 ++ms.n;
2046 if (merge_collapse(&ms) < 0)
2047 goto fail;
2048 /* Advance to find next run. */
2049 lo += n;
2050 nremaining -= n;
2051 } while (nremaining);
2052 assert(lo == hi);
Tim Peters330f9e92002-07-19 07:05:44 +00002053
Tim Petersa64dc242002-08-01 02:13:36 +00002054 if (merge_force_collapse(&ms) < 0)
2055 goto fail;
2056 assert(ms.n == 1);
Tim Petersb9099c32002-11-12 22:08:10 +00002057 assert(ms.pending[0].base == saved_ob_item);
2058 assert(ms.pending[0].len == saved_ob_size);
Tim Petersa64dc242002-08-01 02:13:36 +00002059
2060succeed:
2061 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002062fail:
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002063 if (keyfunc != NULL) {
2064 for (i=0 ; i < saved_ob_size ; i++) {
2065 kvpair = saved_ob_item[i];
2066 value = sortwrapper_getvalue(kvpair);
2067 saved_ob_item[i] = value;
2068 Py_DECREF(kvpair);
2069 }
2070 }
2071
Armin Rigo93677f02004-07-29 12:40:23 +00002072 if (self->allocated != -1 && result != NULL) {
Tim Peters51b4ade2004-07-29 04:07:15 +00002073 /* The user mucked with the list during the sort,
2074 * and we don't already have another error to report.
2075 */
2076 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2077 result = NULL;
Tim Petersb9099c32002-11-12 22:08:10 +00002078 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002079
2080 if (reverse && saved_ob_size > 1)
2081 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2082
2083 merge_freemem(&ms);
2084
2085dsu_fail:
Armin Rigo93677f02004-07-29 12:40:23 +00002086 final_ob_item = self->ob_item;
2087 i = self->ob_size;
Tim Petersb9099c32002-11-12 22:08:10 +00002088 self->ob_size = saved_ob_size;
2089 self->ob_item = saved_ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002090 self->allocated = saved_allocated;
Armin Rigo93677f02004-07-29 12:40:23 +00002091 if (final_ob_item != NULL) {
2092 /* we cannot use list_clear() for this because it does not
2093 guarantee that the list is really empty when it returns */
2094 while (--i >= 0) {
2095 Py_XDECREF(final_ob_item[i]);
2096 }
2097 PyMem_FREE(final_ob_item);
2098 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002099 Py_XDECREF(compare);
Tim Petersa64dc242002-08-01 02:13:36 +00002100 Py_XINCREF(result);
2101 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002102}
Tim Peters330f9e92002-07-19 07:05:44 +00002103#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002104#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002105
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002106int
Fred Drakea2f55112000-07-09 15:16:51 +00002107PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002108{
2109 if (v == NULL || !PyList_Check(v)) {
2110 PyErr_BadInternalCall();
2111 return -1;
2112 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002113 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002114 if (v == NULL)
2115 return -1;
2116 Py_DECREF(v);
2117 return 0;
2118}
2119
Guido van Rossumb86c5492001-02-12 22:06:02 +00002120static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002121listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002122{
Tim Peters326b4482002-07-19 04:04:16 +00002123 if (self->ob_size > 1)
2124 reverse_slice(self->ob_item, self->ob_item + self->ob_size);
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002125 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002126}
2127
Guido van Rossum84c76f51990-10-30 13:32:20 +00002128int
Fred Drakea2f55112000-07-09 15:16:51 +00002129PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002130{
Tim Peters6063e262002-08-08 01:06:39 +00002131 PyListObject *self = (PyListObject *)v;
2132
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002133 if (v == NULL || !PyList_Check(v)) {
2134 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002135 return -1;
2136 }
Tim Peters6063e262002-08-08 01:06:39 +00002137 if (self->ob_size > 1)
2138 reverse_slice(self->ob_item, self->ob_item + self->ob_size);
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002139 return 0;
2140}
2141
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002142PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002143PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002144{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002145 PyObject *w;
2146 PyObject **p;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002147 int n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002148 if (v == NULL || !PyList_Check(v)) {
2149 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002150 return NULL;
2151 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002152 n = ((PyListObject *)v)->ob_size;
2153 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002154 if (w == NULL)
2155 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002156 p = ((PyTupleObject *)w)->ob_item;
Thomas Wouters334fb892000-07-25 12:56:38 +00002157 memcpy((void *)p,
2158 (void *)((PyListObject *)v)->ob_item,
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002159 n*sizeof(PyObject *));
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002160 while (--n >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002161 Py_INCREF(*p);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002162 p++;
2163 }
2164 return w;
2165}
2166
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002167static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002168listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002169{
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002170 int i, start=0, stop=self->ob_size;
2171 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002172
Walter Dörwalde8049bef2003-06-17 19:27:39 +00002173 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2174 _PyEval_SliceIndex, &start,
2175 _PyEval_SliceIndex, &stop))
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002176 return NULL;
Guido van Rossum2743d872003-06-17 14:25:14 +00002177 if (start < 0) {
2178 start += self->ob_size;
2179 if (start < 0)
2180 start = 0;
2181 }
2182 if (stop < 0) {
2183 stop += self->ob_size;
2184 if (stop < 0)
2185 stop = 0;
2186 }
2187 else if (stop > self->ob_size)
2188 stop = self->ob_size;
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002189 for (i = start; i < stop; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002190 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2191 if (cmp > 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002192 return PyInt_FromLong((long)i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002193 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002194 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002195 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002196 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002197 return NULL;
2198}
2199
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002200static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002201listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002202{
2203 int count = 0;
2204 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002205
Guido van Rossume6f7d181991-10-20 20:20:40 +00002206 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002207 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2208 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002209 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002210 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002211 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00002212 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002213 return PyInt_FromLong((long)count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002214}
2215
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002216static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002217listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002218{
2219 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002220
Guido van Rossumed98d481991-03-06 13:07:53 +00002221 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002222 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2223 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002224 if (list_ass_slice(self, i, i+1,
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002225 (PyObject *)NULL) == 0)
2226 Py_RETURN_NONE;
2227 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002228 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002229 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002230 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002231 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002232 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002233 return NULL;
2234}
2235
Jeremy Hylton8caad492000-06-23 14:18:11 +00002236static int
2237list_traverse(PyListObject *o, visitproc visit, void *arg)
2238{
2239 int i, err;
2240 PyObject *x;
2241
2242 for (i = o->ob_size; --i >= 0; ) {
2243 x = o->ob_item[i];
2244 if (x != NULL) {
2245 err = visit(x, arg);
2246 if (err)
2247 return err;
2248 }
2249 }
2250 return 0;
2251}
2252
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002253static PyObject *
2254list_richcompare(PyObject *v, PyObject *w, int op)
2255{
2256 PyListObject *vl, *wl;
2257 int i;
2258
2259 if (!PyList_Check(v) || !PyList_Check(w)) {
2260 Py_INCREF(Py_NotImplemented);
2261 return Py_NotImplemented;
2262 }
2263
2264 vl = (PyListObject *)v;
2265 wl = (PyListObject *)w;
2266
2267 if (vl->ob_size != wl->ob_size && (op == Py_EQ || op == Py_NE)) {
2268 /* Shortcut: if the lengths differ, the lists differ */
2269 PyObject *res;
2270 if (op == Py_EQ)
2271 res = Py_False;
2272 else
2273 res = Py_True;
2274 Py_INCREF(res);
2275 return res;
2276 }
2277
2278 /* Search for the first index where items are different */
2279 for (i = 0; i < vl->ob_size && i < wl->ob_size; i++) {
2280 int k = PyObject_RichCompareBool(vl->ob_item[i],
2281 wl->ob_item[i], Py_EQ);
2282 if (k < 0)
2283 return NULL;
2284 if (!k)
2285 break;
2286 }
2287
2288 if (i >= vl->ob_size || i >= wl->ob_size) {
2289 /* No more items to compare -- compare sizes */
2290 int vs = vl->ob_size;
2291 int ws = wl->ob_size;
2292 int cmp;
2293 PyObject *res;
2294 switch (op) {
2295 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00002296 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002297 case Py_EQ: cmp = vs == ws; break;
2298 case Py_NE: cmp = vs != ws; break;
2299 case Py_GT: cmp = vs > ws; break;
2300 case Py_GE: cmp = vs >= ws; break;
2301 default: return NULL; /* cannot happen */
2302 }
2303 if (cmp)
2304 res = Py_True;
2305 else
2306 res = Py_False;
2307 Py_INCREF(res);
2308 return res;
2309 }
2310
2311 /* We have an item that differs -- shortcuts for EQ/NE */
2312 if (op == Py_EQ) {
2313 Py_INCREF(Py_False);
2314 return Py_False;
2315 }
2316 if (op == Py_NE) {
2317 Py_INCREF(Py_True);
2318 return Py_True;
2319 }
2320
2321 /* Compare the final item again using the proper operator */
2322 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
2323}
2324
Tim Peters6d6c1a32001-08-02 04:15:00 +00002325static int
2326list_init(PyListObject *self, PyObject *args, PyObject *kw)
2327{
2328 PyObject *arg = NULL;
2329 static char *kwlist[] = {"sequence", 0};
2330
2331 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2332 return -1;
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002333
2334 /* Verify list invariants established by PyType_GenericAlloc() */
Armin Rigoa37bbf22004-07-30 11:20:18 +00002335 assert(0 <= self->ob_size);
2336 assert(self->ob_size <= self->allocated || self->allocated == -1);
2337 assert(self->ob_item != NULL ||
2338 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002339
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002340 /* Empty previous contents */
Armin Rigo93677f02004-07-29 12:40:23 +00002341 if (self->ob_item != NULL) {
2342 (void)list_clear(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002343 }
2344 if (arg != NULL) {
2345 PyObject *rv = listextend(self, arg);
2346 if (rv == NULL)
2347 return -1;
2348 Py_DECREF(rv);
2349 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002350 return 0;
2351}
2352
Guido van Rossumdbb53d92001-12-03 16:32:18 +00002353static long
2354list_nohash(PyObject *self)
2355{
2356 PyErr_SetString(PyExc_TypeError, "list objects are unhashable");
2357 return -1;
2358}
2359
Raymond Hettinger1021c442003-11-07 15:38:09 +00002360static PyObject *list_iter(PyObject *seq);
2361static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2362
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002363PyDoc_STRVAR(getitem_doc,
2364"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002365PyDoc_STRVAR(reversed_doc,
2366"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002367PyDoc_STRVAR(append_doc,
2368"L.append(object) -- append object to end");
2369PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002370"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002371PyDoc_STRVAR(insert_doc,
2372"L.insert(index, object) -- insert object before index");
2373PyDoc_STRVAR(pop_doc,
2374"L.pop([index]) -> item -- remove and return item at index (default last)");
2375PyDoc_STRVAR(remove_doc,
2376"L.remove(value) -- remove first occurrence of value");
2377PyDoc_STRVAR(index_doc,
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002378"L.index(value, [start, [stop]]) -> integer -- return first index of value");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002379PyDoc_STRVAR(count_doc,
2380"L.count(value) -> integer -- return number of occurrences of value");
2381PyDoc_STRVAR(reverse_doc,
2382"L.reverse() -- reverse *IN PLACE*");
2383PyDoc_STRVAR(sort_doc,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002384"L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n\
2385cmp(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002386
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002387static PyObject *list_subscript(PyListObject*, PyObject*);
2388
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002389static PyMethodDef list_methods[] = {
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002390 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
Raymond Hettinger1021c442003-11-07 15:38:09 +00002391 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002392 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002393 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002394 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002395 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002396 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002397 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002398 {"count", (PyCFunction)listcount, METH_O, count_doc},
2399 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002400 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
Tim Petersa64dc242002-08-01 02:13:36 +00002401 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002402};
2403
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002404static PySequenceMethods list_as_sequence = {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002405 (inquiry)list_length, /* sq_length */
2406 (binaryfunc)list_concat, /* sq_concat */
2407 (intargfunc)list_repeat, /* sq_repeat */
2408 (intargfunc)list_item, /* sq_item */
2409 (intintargfunc)list_slice, /* sq_slice */
2410 (intobjargproc)list_ass_item, /* sq_ass_item */
2411 (intintobjargproc)list_ass_slice, /* sq_ass_slice */
2412 (objobjproc)list_contains, /* sq_contains */
2413 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2414 (intargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002415};
2416
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002417PyDoc_STRVAR(list_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002418"list() -> new list\n"
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002419"list(sequence) -> new list initialized from sequence's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002420
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002421static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002422list_subscript(PyListObject* self, PyObject* item)
2423{
2424 if (PyInt_Check(item)) {
2425 long i = PyInt_AS_LONG(item);
2426 if (i < 0)
2427 i += PyList_GET_SIZE(self);
2428 return list_item(self, i);
2429 }
2430 else if (PyLong_Check(item)) {
2431 long i = PyLong_AsLong(item);
2432 if (i == -1 && PyErr_Occurred())
2433 return NULL;
2434 if (i < 0)
2435 i += PyList_GET_SIZE(self);
2436 return list_item(self, i);
2437 }
2438 else if (PySlice_Check(item)) {
2439 int start, stop, step, slicelength, cur, i;
2440 PyObject* result;
2441 PyObject* it;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002442 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002443
2444 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
2445 &start, &stop, &step, &slicelength) < 0) {
2446 return NULL;
2447 }
2448
2449 if (slicelength <= 0) {
2450 return PyList_New(0);
2451 }
2452 else {
2453 result = PyList_New(slicelength);
2454 if (!result) return NULL;
2455
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002456 src = self->ob_item;
2457 dest = ((PyListObject *)result)->ob_item;
Tim Peters3b01a122002-07-19 02:35:45 +00002458 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002459 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002460 it = src[cur];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002461 Py_INCREF(it);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002462 dest[i] = it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002463 }
Tim Peters3b01a122002-07-19 02:35:45 +00002464
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002465 return result;
2466 }
2467 }
2468 else {
2469 PyErr_SetString(PyExc_TypeError,
2470 "list indices must be integers");
2471 return NULL;
2472 }
2473}
2474
Tim Peters3b01a122002-07-19 02:35:45 +00002475static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002476list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2477{
2478 if (PyInt_Check(item)) {
2479 long i = PyInt_AS_LONG(item);
2480 if (i < 0)
2481 i += PyList_GET_SIZE(self);
2482 return list_ass_item(self, i, value);
2483 }
2484 else if (PyLong_Check(item)) {
2485 long i = PyLong_AsLong(item);
2486 if (i == -1 && PyErr_Occurred())
2487 return -1;
2488 if (i < 0)
2489 i += PyList_GET_SIZE(self);
2490 return list_ass_item(self, i, value);
2491 }
2492 else if (PySlice_Check(item)) {
2493 int start, stop, step, slicelength;
2494
2495 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
2496 &start, &stop, &step, &slicelength) < 0) {
2497 return -1;
2498 }
2499
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002500 /* treat L[slice(a,b)] = v _exactly_ like L[a:b] = v */
2501 if (step == 1 && ((PySliceObject*)item)->step == Py_None)
2502 return list_ass_slice(self, start, stop, value);
2503
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002504 if (value == NULL) {
2505 /* delete slice */
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002506 PyObject **garbage;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002507 int cur, i;
Tim Peters3b01a122002-07-19 02:35:45 +00002508
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002509 if (slicelength <= 0)
2510 return 0;
2511
2512 if (step < 0) {
2513 stop = start + 1;
2514 start = stop + step*(slicelength - 1) - 1;
2515 step = -step;
2516 }
2517
2518 garbage = (PyObject**)
2519 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Tim Peters3b01a122002-07-19 02:35:45 +00002520
2521 /* drawing pictures might help
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002522 understand these for loops */
Guido van Rossum75a20b12002-06-11 12:22:28 +00002523 for (cur = start, i = 0;
2524 cur < stop;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002525 cur += step, i++) {
2526 int lim = step;
2527
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002528 garbage[i] = PyList_GET_ITEM(self, cur);
2529
Michael W. Hudson56796f62002-07-29 14:35:04 +00002530 if (cur + step >= self->ob_size) {
2531 lim = self->ob_size - cur - 1;
2532 }
2533
Tim Petersb38e2b62004-07-29 02:29:26 +00002534 memmove(self->ob_item + cur - i,
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002535 self->ob_item + cur + 1,
2536 lim * sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002537 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002538
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002539 for (cur = start + slicelength*step + 1;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002540 cur < self->ob_size; cur++) {
2541 PyList_SET_ITEM(self, cur - slicelength,
2542 PyList_GET_ITEM(self, cur));
2543 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002544
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002545 self->ob_size -= slicelength;
Raymond Hettingerd4ff7412004-03-15 09:01:31 +00002546 list_resize(self, self->ob_size);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002547
2548 for (i = 0; i < slicelength; i++) {
2549 Py_DECREF(garbage[i]);
2550 }
2551 PyMem_FREE(garbage);
2552
2553 return 0;
2554 }
2555 else {
2556 /* assign slice */
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002557 PyObject **garbage, *ins, *seq, **seqitems, **selfitems;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002558 int cur, i;
2559
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002560 /* protect against a[::-1] = a */
Tim Peters3b01a122002-07-19 02:35:45 +00002561 if (self == (PyListObject*)value) {
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002562 seq = list_slice((PyListObject*)value, 0,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002563 PyList_GET_SIZE(value));
Tim Peters3b01a122002-07-19 02:35:45 +00002564 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002565 else {
Tim Petersb38e2b62004-07-29 02:29:26 +00002566 seq = PySequence_Fast(value,
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002567 "must assign iterable to extended slice");
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002568 if (!seq)
2569 return -1;
2570 }
2571
2572 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2573 PyErr_Format(PyExc_ValueError,
2574 "attempt to assign sequence of size %d to extended slice of size %d",
2575 PySequence_Fast_GET_SIZE(seq),
2576 slicelength);
2577 Py_DECREF(seq);
2578 return -1;
2579 }
2580
2581 if (!slicelength) {
2582 Py_DECREF(seq);
2583 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002584 }
2585
2586 garbage = (PyObject**)
2587 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Tim Peters3b01a122002-07-19 02:35:45 +00002588
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002589 selfitems = self->ob_item;
Raymond Hettinger42bec932004-03-12 16:38:17 +00002590 seqitems = PySequence_Fast_ITEMS(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002591 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002592 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002593 garbage[i] = selfitems[cur];
2594 ins = seqitems[i];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002595 Py_INCREF(ins);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002596 selfitems[cur] = ins;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002597 }
2598
2599 for (i = 0; i < slicelength; i++) {
2600 Py_DECREF(garbage[i]);
2601 }
Tim Peters3b01a122002-07-19 02:35:45 +00002602
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002603 PyMem_FREE(garbage);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002604 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002605
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002606 return 0;
2607 }
Tim Peters3b01a122002-07-19 02:35:45 +00002608 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002609 else {
Tim Peters3b01a122002-07-19 02:35:45 +00002610 PyErr_SetString(PyExc_TypeError,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002611 "list indices must be integers");
2612 return -1;
2613 }
2614}
2615
2616static PyMappingMethods list_as_mapping = {
2617 (inquiry)list_length,
2618 (binaryfunc)list_subscript,
2619 (objobjargproc)list_ass_subscript
2620};
2621
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002622PyTypeObject PyList_Type = {
2623 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002624 0,
2625 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002626 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002627 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002628 (destructor)list_dealloc, /* tp_dealloc */
2629 (printfunc)list_print, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002630 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002631 0, /* tp_setattr */
2632 0, /* tp_compare */
2633 (reprfunc)list_repr, /* tp_repr */
2634 0, /* tp_as_number */
2635 &list_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002636 &list_as_mapping, /* tp_as_mapping */
Guido van Rossumdbb53d92001-12-03 16:32:18 +00002637 list_nohash, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002638 0, /* tp_call */
2639 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002640 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002641 0, /* tp_setattro */
2642 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002643 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Tim Peters6d6c1a32001-08-02 04:15:00 +00002644 Py_TPFLAGS_BASETYPE, /* tp_flags */
2645 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002646 (traverseproc)list_traverse, /* tp_traverse */
2647 (inquiry)list_clear, /* tp_clear */
2648 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002649 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002650 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002651 0, /* tp_iternext */
2652 list_methods, /* tp_methods */
2653 0, /* tp_members */
2654 0, /* tp_getset */
2655 0, /* tp_base */
2656 0, /* tp_dict */
2657 0, /* tp_descr_get */
2658 0, /* tp_descr_set */
2659 0, /* tp_dictoffset */
2660 (initproc)list_init, /* tp_init */
2661 PyType_GenericAlloc, /* tp_alloc */
2662 PyType_GenericNew, /* tp_new */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002663 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002664};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002665
2666
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002667/*********************** List Iterator **************************/
2668
2669typedef struct {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002670 PyObject_HEAD
2671 long it_index;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002672 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002673} listiterobject;
2674
2675PyTypeObject PyListIter_Type;
2676
Guido van Rossum5086e492002-07-16 15:56:52 +00002677static PyObject *
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002678list_iter(PyObject *seq)
2679{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002680 listiterobject *it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002681
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002682 if (!PyList_Check(seq)) {
2683 PyErr_BadInternalCall();
2684 return NULL;
2685 }
2686 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2687 if (it == NULL)
2688 return NULL;
2689 it->it_index = 0;
2690 Py_INCREF(seq);
2691 it->it_seq = (PyListObject *)seq;
2692 _PyObject_GC_TRACK(it);
2693 return (PyObject *)it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002694}
2695
2696static void
2697listiter_dealloc(listiterobject *it)
2698{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002699 _PyObject_GC_UNTRACK(it);
Guido van Rossum86103ae2002-07-16 20:07:32 +00002700 Py_XDECREF(it->it_seq);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002701 PyObject_GC_Del(it);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002702}
2703
2704static int
2705listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2706{
Guido van Rossum86103ae2002-07-16 20:07:32 +00002707 if (it->it_seq == NULL)
2708 return 0;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002709 return visit((PyObject *)it->it_seq, arg);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002710}
2711
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002712static PyObject *
Tim Peters93b2cc42002-06-01 05:22:55 +00002713listiter_next(listiterobject *it)
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002714{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002715 PyListObject *seq;
2716 PyObject *item;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002717
Tim Peters93b2cc42002-06-01 05:22:55 +00002718 assert(it != NULL);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002719 seq = it->it_seq;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002720 if (seq == NULL)
2721 return NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002722 assert(PyList_Check(seq));
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002723
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002724 if (it->it_index < PyList_GET_SIZE(seq)) {
Tim Peters93b2cc42002-06-01 05:22:55 +00002725 item = PyList_GET_ITEM(seq, it->it_index);
2726 ++it->it_index;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002727 Py_INCREF(item);
2728 return item;
2729 }
Guido van Rossum86103ae2002-07-16 20:07:32 +00002730
2731 Py_DECREF(seq);
2732 it->it_seq = NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002733 return NULL;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002734}
2735
Raymond Hettinger435bf582004-03-18 22:43:10 +00002736static int
2737listiter_len(listiterobject *it)
2738{
Raymond Hettinger40a03822004-04-12 13:05:09 +00002739 int len;
2740 if (it->it_seq) {
2741 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2742 if (len >= 0)
2743 return len;
2744 }
Raymond Hettinger435bf582004-03-18 22:43:10 +00002745 return 0;
2746}
2747
2748static PySequenceMethods listiter_as_sequence = {
2749 (inquiry)listiter_len, /* sq_length */
2750 0, /* sq_concat */
2751};
2752
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002753PyTypeObject PyListIter_Type = {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002754 PyObject_HEAD_INIT(&PyType_Type)
2755 0, /* ob_size */
2756 "listiterator", /* tp_name */
2757 sizeof(listiterobject), /* tp_basicsize */
2758 0, /* tp_itemsize */
2759 /* methods */
2760 (destructor)listiter_dealloc, /* tp_dealloc */
2761 0, /* tp_print */
2762 0, /* tp_getattr */
2763 0, /* tp_setattr */
2764 0, /* tp_compare */
2765 0, /* tp_repr */
2766 0, /* tp_as_number */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002767 &listiter_as_sequence, /* tp_as_sequence */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002768 0, /* tp_as_mapping */
2769 0, /* tp_hash */
2770 0, /* tp_call */
2771 0, /* tp_str */
2772 PyObject_GenericGetAttr, /* tp_getattro */
2773 0, /* tp_setattro */
2774 0, /* tp_as_buffer */
2775 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2776 0, /* tp_doc */
2777 (traverseproc)listiter_traverse, /* tp_traverse */
2778 0, /* tp_clear */
2779 0, /* tp_richcompare */
2780 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00002781 PyObject_SelfIter, /* tp_iter */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002782 (iternextfunc)listiter_next, /* tp_iternext */
Guido van Rossum86103ae2002-07-16 20:07:32 +00002783 0, /* tp_methods */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002784 0, /* tp_members */
2785 0, /* tp_getset */
2786 0, /* tp_base */
2787 0, /* tp_dict */
2788 0, /* tp_descr_get */
2789 0, /* tp_descr_set */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002790};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002791
2792/*********************** List Reverse Iterator **************************/
2793
2794typedef struct {
2795 PyObject_HEAD
2796 long it_index;
Raymond Hettinger001f2282003-11-08 11:58:44 +00002797 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002798} listreviterobject;
2799
2800PyTypeObject PyListRevIter_Type;
2801
2802static PyObject *
2803list_reversed(PyListObject *seq, PyObject *unused)
2804{
2805 listreviterobject *it;
2806
2807 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2808 if (it == NULL)
2809 return NULL;
2810 assert(PyList_Check(seq));
2811 it->it_index = PyList_GET_SIZE(seq) - 1;
2812 Py_INCREF(seq);
2813 it->it_seq = seq;
2814 PyObject_GC_Track(it);
2815 return (PyObject *)it;
2816}
2817
2818static void
2819listreviter_dealloc(listreviterobject *it)
2820{
2821 PyObject_GC_UnTrack(it);
2822 Py_XDECREF(it->it_seq);
2823 PyObject_GC_Del(it);
2824}
2825
2826static int
2827listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2828{
2829 if (it->it_seq == NULL)
2830 return 0;
2831 return visit((PyObject *)it->it_seq, arg);
2832}
2833
2834static PyObject *
2835listreviter_next(listreviterobject *it)
2836{
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002837 PyObject *item;
2838 long index = it->it_index;
2839 PyListObject *seq = it->it_seq;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002840
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002841 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2842 item = PyList_GET_ITEM(seq, index);
Raymond Hettinger1021c442003-11-07 15:38:09 +00002843 it->it_index--;
2844 Py_INCREF(item);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002845 return item;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002846 }
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002847 it->it_index = -1;
2848 if (seq != NULL) {
2849 it->it_seq = NULL;
2850 Py_DECREF(seq);
2851 }
2852 return NULL;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002853}
2854
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002855static int
2856listreviter_len(listreviterobject *it)
2857{
Raymond Hettinger40a03822004-04-12 13:05:09 +00002858 int len = it->it_index + 1;
2859 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
2860 return 0;
2861 return len;
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002862}
2863
2864static PySequenceMethods listreviter_as_sequence = {
2865 (inquiry)listreviter_len, /* sq_length */
2866 0, /* sq_concat */
2867};
2868
Raymond Hettinger1021c442003-11-07 15:38:09 +00002869PyTypeObject PyListRevIter_Type = {
2870 PyObject_HEAD_INIT(&PyType_Type)
2871 0, /* ob_size */
2872 "listreverseiterator", /* tp_name */
2873 sizeof(listreviterobject), /* tp_basicsize */
2874 0, /* tp_itemsize */
2875 /* methods */
2876 (destructor)listreviter_dealloc, /* tp_dealloc */
2877 0, /* tp_print */
2878 0, /* tp_getattr */
2879 0, /* tp_setattr */
2880 0, /* tp_compare */
2881 0, /* tp_repr */
2882 0, /* tp_as_number */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002883 &listreviter_as_sequence, /* tp_as_sequence */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002884 0, /* tp_as_mapping */
2885 0, /* tp_hash */
2886 0, /* tp_call */
2887 0, /* tp_str */
2888 PyObject_GenericGetAttr, /* tp_getattro */
2889 0, /* tp_setattro */
2890 0, /* tp_as_buffer */
2891 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2892 0, /* tp_doc */
2893 (traverseproc)listreviter_traverse, /* tp_traverse */
2894 0, /* tp_clear */
2895 0, /* tp_richcompare */
2896 0, /* tp_weaklistoffset */
2897 PyObject_SelfIter, /* tp_iter */
2898 (iternextfunc)listreviter_next, /* tp_iternext */
2899 0,
2900};