blob: 1fb77b9760c3762ec23f075d61950a48cf3f76f5 [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;
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000028 size_t new_allocated;
29 int allocated = self->allocated;
Tim Peters65b8b842001-05-26 05:28:40 +000030
Raymond Hettinger4bb95402004-02-13 11:36:39 +000031 /* Bypass realloc() when a previous overallocation is large enough
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000032 to accommodate the newsize. If the newsize falls lower than half
33 the allocated size, then proceed with the realloc() to shrink the list.
Raymond Hettinger4bb95402004-02-13 11:36:39 +000034 */
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000035 if (allocated >= newsize && newsize >= (allocated >> 1)) {
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +000036 assert(self->ob_item != NULL || newsize == 0);
Raymond Hettinger4bb95402004-02-13 11:36:39 +000037 self->ob_size = newsize;
38 return 0;
39 }
40
41 /* This over-allocates proportional to the list size, making room
Tim Peters65b8b842001-05-26 05:28:40 +000042 * for additional growth. The over-allocation is mild, but is
43 * enough to give linear-time amortized behavior over a long
44 * sequence of appends() in the presence of a poorly-performing
Raymond Hettingerab517d22004-02-14 18:34:46 +000045 * system realloc().
46 * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
Tim Peters65b8b842001-05-26 05:28:40 +000047 */
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000048 new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6) + newsize;
49 if (newsize == 0)
50 new_allocated = 0;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000051 items = self->ob_item;
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000052 if (new_allocated <= ((~(size_t)0) / sizeof(PyObject *)))
53 PyMem_RESIZE(items, PyObject *, new_allocated);
Raymond Hettinger4bb95402004-02-13 11:36:39 +000054 else
55 items = NULL;
56 if (items == NULL) {
57 PyErr_NoMemory();
58 return -1;
59 }
60 self->ob_item = items;
61 self->ob_size = newsize;
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000062 self->allocated = new_allocated;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000063 return 0;
64}
Guido van Rossuma46d51d1995-01-26 22:59:43 +000065
Raymond Hettinger0468e412004-05-05 05:37:53 +000066/* Empty list reuse scheme to save calls to malloc and free */
67#define MAXFREELISTS 80
68static PyListObject *free_lists[MAXFREELISTS];
69static int num_free_lists = 0;
70
Guido van Rossumc0b618a1997-05-02 03:12:38 +000071PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +000072PyList_New(int size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000073{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000074 PyListObject *op;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +000075 size_t nbytes;
Tim Peters3986d4e2004-07-29 02:28:42 +000076
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000077 if (size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000078 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000079 return NULL;
80 }
Tim Peters7049d812004-01-18 20:31:02 +000081 nbytes = size * sizeof(PyObject *);
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000082 /* Check for overflow */
Raymond Hettingerfdfe6182004-05-05 06:28:16 +000083 if (nbytes / sizeof(PyObject *) != (size_t)size)
Guido van Rossumc0b618a1997-05-02 03:12:38 +000084 return PyErr_NoMemory();
Raymond Hettinger0468e412004-05-05 05:37:53 +000085 if (num_free_lists) {
86 num_free_lists--;
87 op = free_lists[num_free_lists];
88 _Py_NewReference((PyObject *)op);
89 } else {
90 op = PyObject_GC_New(PyListObject, &PyList_Type);
91 if (op == NULL)
92 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000093 }
Raymond Hettingerfdfe6182004-05-05 06:28:16 +000094 if (size <= 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000095 op->ob_item = NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000096 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +000097 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
Raymond Hettingerfdfe6182004-05-05 06:28:16 +000098 if (op->ob_item == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +000099 return PyErr_NoMemory();
Tim Peters3986d4e2004-07-29 02:28:42 +0000100 memset(op->ob_item, 0, nbytes);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000101 }
Neil Schemenauere83c00e2001-08-29 23:54:21 +0000102 op->ob_size = size;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000103 op->allocated = size;
Neil Schemenauere83c00e2001-08-29 23:54:21 +0000104 _PyObject_GC_TRACK(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000105 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000106}
107
108int
Fred Drakea2f55112000-07-09 15:16:51 +0000109PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000110{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000111 if (!PyList_Check(op)) {
112 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000113 return -1;
114 }
115 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000116 return ((PyListObject *)op) -> ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000117}
118
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000119static PyObject *indexerr = NULL;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000120
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000121PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000122PyList_GetItem(PyObject *op, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000123{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000124 if (!PyList_Check(op)) {
125 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000126 return NULL;
127 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000128 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000129 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000130 indexerr = PyString_FromString(
131 "list index out of range");
132 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000133 return NULL;
134 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000135 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000136}
137
138int
Fred Drakea2f55112000-07-09 15:16:51 +0000139PyList_SetItem(register PyObject *op, register int i,
140 register PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000141{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000142 register PyObject *olditem;
143 register PyObject **p;
144 if (!PyList_Check(op)) {
145 Py_XDECREF(newitem);
146 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000147 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000148 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000149 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
150 Py_XDECREF(newitem);
151 PyErr_SetString(PyExc_IndexError,
152 "list assignment index out of range");
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000153 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000154 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000155 p = ((PyListObject *)op) -> ob_item + i;
Guido van Rossum5fe60581995-03-09 12:12:50 +0000156 olditem = *p;
157 *p = newitem;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000158 Py_XDECREF(olditem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000159 return 0;
160}
161
162static int
Fred Drakea2f55112000-07-09 15:16:51 +0000163ins1(PyListObject *self, int where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000164{
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000165 int i, n = self->ob_size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000166 PyObject **items;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000167 if (v == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000168 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000169 return -1;
170 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000171 if (n == INT_MAX) {
Trent Micka5846642000-08-13 22:47:45 +0000172 PyErr_SetString(PyExc_OverflowError,
173 "cannot add more objects to list");
174 return -1;
175 }
Tim Petersb38e2b62004-07-29 02:29:26 +0000176
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000177 if (list_resize(self, n+1) == -1)
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000178 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000179
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000180 if (where < 0) {
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000181 where += n;
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000182 if (where < 0)
183 where = 0;
184 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000185 if (where > n)
186 where = n;
187 items = self->ob_item;
188 for (i = n; --i >= where; )
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000189 items[i+1] = items[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000190 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000191 items[where] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000192 return 0;
193}
194
195int
Fred Drakea2f55112000-07-09 15:16:51 +0000196PyList_Insert(PyObject *op, int where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000197{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000198 if (!PyList_Check(op)) {
199 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000200 return -1;
201 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000202 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000203}
204
Raymond Hettinger40a03822004-04-12 13:05:09 +0000205static int
206app1(PyListObject *self, PyObject *v)
207{
208 int n = PyList_GET_SIZE(self);
209
210 assert (v != NULL);
211 if (n == INT_MAX) {
212 PyErr_SetString(PyExc_OverflowError,
213 "cannot add more objects to list");
214 return -1;
215 }
216
217 if (list_resize(self, n+1) == -1)
218 return -1;
219
220 Py_INCREF(v);
221 PyList_SET_ITEM(self, n, v);
222 return 0;
223}
224
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000225int
Fred Drakea2f55112000-07-09 15:16:51 +0000226PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000227{
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000228 if (PyList_Check(op) && (newitem != NULL))
229 return app1((PyListObject *)op, newitem);
230 PyErr_BadInternalCall();
231 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000232}
233
234/* Methods */
235
236static void
Fred Drakea2f55112000-07-09 15:16:51 +0000237list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000238{
239 int i;
Guido van Rossumff413af2002-03-28 20:34:59 +0000240 PyObject_GC_UnTrack(op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000241 Py_TRASHCAN_SAFE_BEGIN(op)
Jack Jansen7874d1f1995-01-19 12:09:27 +0000242 if (op->ob_item != NULL) {
Guido van Rossumfa717011999-06-09 15:19:34 +0000243 /* Do it backwards, for Christian Tismer.
244 There's a simple test case where somehow this reduces
245 thrashing when a *very* large list is created and
246 immediately deleted. */
247 i = op->ob_size;
248 while (--i >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000249 Py_XDECREF(op->ob_item[i]);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000250 }
Guido van Rossumb18618d2000-05-03 23:44:39 +0000251 PyMem_FREE(op->ob_item);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000252 }
Raymond Hettinger0468e412004-05-05 05:37:53 +0000253 if (num_free_lists < MAXFREELISTS && PyList_CheckExact(op))
254 free_lists[num_free_lists++] = op;
Tim Petersb38e2b62004-07-29 02:29:26 +0000255 else
256 op->ob_type->tp_free((PyObject *)op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000257 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000258}
259
Guido van Rossum90933611991-06-07 16:10:43 +0000260static int
Fred Drakea2f55112000-07-09 15:16:51 +0000261list_print(PyListObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000262{
263 int i;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000264
265 i = Py_ReprEnter((PyObject*)op);
266 if (i != 0) {
267 if (i < 0)
268 return i;
269 fprintf(fp, "[...]");
270 return 0;
271 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000272 fprintf(fp, "[");
Guido van Rossum90933611991-06-07 16:10:43 +0000273 for (i = 0; i < op->ob_size; i++) {
274 if (i > 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000275 fprintf(fp, ", ");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000276 if (PyObject_Print(op->ob_item[i], fp, 0) != 0) {
277 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000278 return -1;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000279 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000280 }
281 fprintf(fp, "]");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000282 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000283 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000284}
285
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000286static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000287list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000288{
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000289 int i;
Tim Petersa7259592001-06-16 05:11:17 +0000290 PyObject *s, *temp;
291 PyObject *pieces = NULL, *result = NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000292
293 i = Py_ReprEnter((PyObject*)v);
294 if (i != 0) {
Tim Petersa7259592001-06-16 05:11:17 +0000295 return i > 0 ? PyString_FromString("[...]") : NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000296 }
Tim Petersa7259592001-06-16 05:11:17 +0000297
298 if (v->ob_size == 0) {
299 result = PyString_FromString("[]");
300 goto Done;
301 }
302
303 pieces = PyList_New(0);
304 if (pieces == NULL)
305 goto Done;
306
307 /* Do repr() on each element. Note that this may mutate the list,
308 so must refetch the list size on each iteration. */
309 for (i = 0; i < v->ob_size; ++i) {
310 int status;
311 s = PyObject_Repr(v->ob_item[i]);
312 if (s == NULL)
313 goto Done;
314 status = PyList_Append(pieces, s);
315 Py_DECREF(s); /* append created a new ref */
316 if (status < 0)
317 goto Done;
318 }
319
320 /* Add "[]" decorations to the first and last items. */
321 assert(PyList_GET_SIZE(pieces) > 0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000322 s = PyString_FromString("[");
Tim Petersa7259592001-06-16 05:11:17 +0000323 if (s == NULL)
324 goto Done;
325 temp = PyList_GET_ITEM(pieces, 0);
326 PyString_ConcatAndDel(&s, temp);
327 PyList_SET_ITEM(pieces, 0, s);
328 if (s == NULL)
329 goto Done;
330
331 s = PyString_FromString("]");
332 if (s == NULL)
333 goto Done;
334 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
335 PyString_ConcatAndDel(&temp, s);
336 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
337 if (temp == NULL)
338 goto Done;
339
340 /* Paste them all together with ", " between. */
341 s = PyString_FromString(", ");
342 if (s == NULL)
343 goto Done;
344 result = _PyString_Join(s, pieces);
Tim Peters3b01a122002-07-19 02:35:45 +0000345 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +0000346
347Done:
348 Py_XDECREF(pieces);
Guido van Rossumfb376de1998-04-10 22:47:27 +0000349 Py_ReprLeave((PyObject *)v);
Tim Petersa7259592001-06-16 05:11:17 +0000350 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000351}
352
353static int
Fred Drakea2f55112000-07-09 15:16:51 +0000354list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000355{
356 return a->ob_size;
357}
358
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000359static int
Fred Drakea2f55112000-07-09 15:16:51 +0000360list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000361{
Raymond Hettingeraae59992002-09-05 14:23:49 +0000362 int i, cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000363
Raymond Hettingeraae59992002-09-05 14:23:49 +0000364 for (i = 0, cmp = 0 ; cmp == 0 && i < a->ob_size; ++i)
365 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000366 Py_EQ);
Neal Norwitzbb9c5f52002-09-05 21:32:55 +0000367 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000368}
369
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000370static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000371list_item(PyListObject *a, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000372{
373 if (i < 0 || i >= a->ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000374 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000375 indexerr = PyString_FromString(
376 "list index out of range");
377 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000378 return NULL;
379 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000380 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000381 return a->ob_item[i];
382}
383
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000384static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000385list_slice(PyListObject *a, int ilow, int ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000386{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000387 PyListObject *np;
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000388 PyObject **src, **dest;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000389 int i, len;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000390 if (ilow < 0)
391 ilow = 0;
392 else if (ilow > a->ob_size)
393 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000394 if (ihigh < ilow)
395 ihigh = ilow;
396 else if (ihigh > a->ob_size)
397 ihigh = a->ob_size;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000398 len = ihigh - ilow;
399 np = (PyListObject *) PyList_New(len);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000400 if (np == NULL)
401 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000402
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000403 src = a->ob_item + ilow;
404 dest = np->ob_item;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000405 for (i = 0; i < len; i++) {
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000406 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000407 Py_INCREF(v);
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000408 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000409 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000410 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000411}
412
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000413PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000414PyList_GetSlice(PyObject *a, int ilow, int ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000415{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000416 if (!PyList_Check(a)) {
417 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000418 return NULL;
419 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000420 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000421}
422
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000423static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000424list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000425{
426 int size;
427 int i;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000428 PyObject **src, **dest;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000429 PyListObject *np;
430 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000431 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000432 "can only concatenate list (not \"%.200s\") to list",
433 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000434 return NULL;
435 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000436#define b ((PyListObject *)bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000437 size = a->ob_size + b->ob_size;
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000438 if (size < 0)
439 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000440 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000441 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000442 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000443 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000444 src = a->ob_item;
445 dest = np->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000446 for (i = 0; i < a->ob_size; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000447 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000448 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000449 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000450 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000451 src = b->ob_item;
452 dest = np->ob_item + a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000453 for (i = 0; i < b->ob_size; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000454 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000455 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000456 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000457 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000458 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000459#undef b
460}
461
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000462static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000463list_repeat(PyListObject *a, int n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000464{
465 int i, j;
466 int size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000467 PyListObject *np;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000468 PyObject **p, **items;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000469 PyObject *elem;
Guido van Rossumed98d481991-03-06 13:07:53 +0000470 if (n < 0)
471 n = 0;
472 size = a->ob_size * n;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000473 if (size == 0)
474 return PyList_New(0);
Guido van Rossumbfa5a142002-10-11 23:39:35 +0000475 if (n && size/n != a->ob_size)
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000476 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000477 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000478 if (np == NULL)
479 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000480
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000481 items = np->ob_item;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000482 if (a->ob_size == 1) {
483 elem = a->ob_item[0];
484 for (i = 0; i < n; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000485 items[i] = elem;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000486 Py_INCREF(elem);
487 }
488 return (PyObject *) np;
489 }
Guido van Rossumed98d481991-03-06 13:07:53 +0000490 p = np->ob_item;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000491 items = a->ob_item;
Guido van Rossumed98d481991-03-06 13:07:53 +0000492 for (i = 0; i < n; i++) {
493 for (j = 0; j < a->ob_size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000494 *p = items[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000495 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000496 p++;
497 }
498 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000499 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000500}
501
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000502static int
Armin Rigo93677f02004-07-29 12:40:23 +0000503list_clear(PyListObject *a)
504{
505 int i;
506 PyObject **item = a->ob_item;
507 if (item != NULL) {
508 /* Because XDECREF can recursively invoke operations on
509 this list, we make it empty first. */
510 i = a->ob_size;
511 a->ob_size = 0;
512 a->ob_item = NULL;
513 a->allocated = 0;
514 while (--i >= 0) {
515 Py_XDECREF(item[i]);
516 }
517 PyMem_FREE(item);
518 }
519 /* Never fails; the return value can be ignored.
520 Note that there is no guarantee that the list is actually empty
521 at this point, because XDECREF may have populated it again! */
522 return 0;
523}
524
Tim Peters8fc4a912004-07-31 21:53:19 +0000525/* a[ilow:ihigh] = v if v != NULL.
526 * del a[ilow:ihigh] if v == NULL.
527 *
528 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
529 * guaranteed the call cannot fail.
530 */
Armin Rigo93677f02004-07-29 12:40:23 +0000531static int
Fred Drakea2f55112000-07-09 15:16:51 +0000532list_ass_slice(PyListObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000533{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000534 /* Because [X]DECREF can recursively invoke list operations on
535 this list, we must postpone all [X]DECREF activity until
536 after the list is back in its canonical shape. Therefore
537 we must allocate an additional array, 'recycle', into which
538 we temporarily copy the items that are deleted from the
539 list. :-( */
Tim Peters73572222004-07-31 02:54:42 +0000540 PyObject *recycle_on_stack[8];
541 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000542 PyObject **item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000543 PyObject **vitem = NULL;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000544 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
Tim Peters8d9eb102004-07-31 02:24:20 +0000545 int n; /* # of elements in replacement list */
546 int norig; /* # of elements in list getting replaced */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000547 int d; /* Change in size */
Tim Peters73572222004-07-31 02:54:42 +0000548 int k;
Tim Peters8d9eb102004-07-31 02:24:20 +0000549 size_t s;
550 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000551#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000552 if (v == NULL)
553 n = 0;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000554 else {
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000555 if (a == b) {
556 /* Special case "a[i:j] = a" -- copy b first */
Michael W. Hudsonda0a0672003-08-15 12:06:41 +0000557 v = list_slice(b, 0, b->ob_size);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000558 if (v == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000559 return result;
560 result = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000561 Py_DECREF(v);
Tim Peters8d9eb102004-07-31 02:24:20 +0000562 return result;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000563 }
Raymond Hettingerf889e102004-03-09 08:04:33 +0000564 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000565 if(v_as_SF == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000566 goto Error;
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000567 n = PySequence_Fast_GET_SIZE(v_as_SF);
Raymond Hettinger42bec932004-03-12 16:38:17 +0000568 vitem = PySequence_Fast_ITEMS(v_as_SF);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000569 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000570 if (ilow < 0)
571 ilow = 0;
572 else if (ilow > a->ob_size)
573 ilow = a->ob_size;
Tim Peters8d9eb102004-07-31 02:24:20 +0000574
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000575 if (ihigh < ilow)
576 ihigh = ilow;
577 else if (ihigh > a->ob_size)
578 ihigh = a->ob_size;
Armin Rigo93677f02004-07-29 12:40:23 +0000579
Tim Peters8d9eb102004-07-31 02:24:20 +0000580 norig = ihigh - ilow;
581 assert(norig >= 0);
582 d = n - norig;
Armin Rigo93677f02004-07-29 12:40:23 +0000583 if (a->ob_size + d == 0) {
584 Py_XDECREF(v_as_SF);
585 return list_clear(a);
586 }
587 item = a->ob_item;
Tim Peters8d9eb102004-07-31 02:24:20 +0000588 /* recycle the items that we are about to remove */
589 s = norig * sizeof(PyObject *);
Tim Peters73572222004-07-31 02:54:42 +0000590 if (s > sizeof(recycle_on_stack)) {
Armin Rigo1dd04a02004-07-30 11:38:22 +0000591 recycle = (PyObject **)PyMem_MALLOC(s);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000592 if (recycle == NULL) {
593 PyErr_NoMemory();
Tim Peters8d9eb102004-07-31 02:24:20 +0000594 goto Error;
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000595 }
596 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000597 memcpy(recycle, &item[ilow], s);
Tim Peters8d9eb102004-07-31 02:24:20 +0000598
Armin Rigo1dd04a02004-07-30 11:38:22 +0000599 if (d < 0) { /* Delete -d items */
600 memmove(&item[ihigh+d], &item[ihigh],
601 (a->ob_size - ihigh)*sizeof(PyObject *));
602 list_resize(a, a->ob_size + d);
603 item = a->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000604 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000605 else if (d > 0) { /* Insert d items */
Tim Peters73572222004-07-31 02:54:42 +0000606 k = a->ob_size;
607 if (list_resize(a, k+d) < 0)
Tim Peters8d9eb102004-07-31 02:24:20 +0000608 goto Error;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000609 item = a->ob_item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000610 memmove(&item[ihigh+d], &item[ihigh],
Tim Peters73572222004-07-31 02:54:42 +0000611 (k - ihigh)*sizeof(PyObject *));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000612 }
613 for (k = 0; k < n; k++, ilow++) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000614 PyObject *w = vitem[k];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000615 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000616 item[ilow] = w;
617 }
Tim Peters73572222004-07-31 02:54:42 +0000618 for (k = norig - 1; k >= 0; --k)
619 Py_XDECREF(recycle[k]);
Tim Peters8d9eb102004-07-31 02:24:20 +0000620 result = 0;
621 Error:
Tim Peters73572222004-07-31 02:54:42 +0000622 if (recycle != recycle_on_stack)
Armin Rigo1dd04a02004-07-30 11:38:22 +0000623 PyMem_FREE(recycle);
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000624 Py_XDECREF(v_as_SF);
Tim Peters8d9eb102004-07-31 02:24:20 +0000625 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000626#undef b
627}
628
Guido van Rossum234f9421993-06-17 12:35:49 +0000629int
Fred Drakea2f55112000-07-09 15:16:51 +0000630PyList_SetSlice(PyObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000631{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000632 if (!PyList_Check(a)) {
633 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000634 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000635 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000636 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000637}
638
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000639static PyObject *
640list_inplace_repeat(PyListObject *self, int n)
641{
642 PyObject **items;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000643 int size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000644
645
646 size = PyList_GET_SIZE(self);
647 if (size == 0) {
648 Py_INCREF(self);
649 return (PyObject *)self;
650 }
651
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000652 if (n < 1) {
Armin Rigo93677f02004-07-29 12:40:23 +0000653 (void)list_clear(self);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000654 Py_INCREF(self);
655 return (PyObject *)self;
656 }
657
Tim Petersb38e2b62004-07-29 02:29:26 +0000658 if (list_resize(self, size*n) == -1)
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000659 return NULL;
660
661 p = size;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000662 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000663 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
664 for (j = 0; j < size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000665 PyObject *o = items[j];
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000666 Py_INCREF(o);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000667 items[p++] = o;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000668 }
669 }
670 Py_INCREF(self);
671 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000672}
673
Guido van Rossum4a450d01991-04-03 19:05:18 +0000674static int
Fred Drakea2f55112000-07-09 15:16:51 +0000675list_ass_item(PyListObject *a, int i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000676{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000677 PyObject *old_value;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000678 if (i < 0 || i >= a->ob_size) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000679 PyErr_SetString(PyExc_IndexError,
680 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000681 return -1;
682 }
683 if (v == NULL)
684 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000685 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000686 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000687 a->ob_item[i] = v;
Tim Peters3b01a122002-07-19 02:35:45 +0000688 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000689 return 0;
690}
691
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000692static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000693listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000694{
695 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000696 PyObject *v;
Guido van Rossumc00a9382000-02-24 21:48:29 +0000697 if (!PyArg_ParseTuple(args, "iO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000698 return NULL;
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000699 if (ins1(self, i, v) == 0)
700 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000701 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000702}
703
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000704static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000705listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000706{
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000707 if (app1(self, v) == 0)
708 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000709 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000710}
711
Barry Warsawdedf6d61998-10-09 16:37:25 +0000712static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000713listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000714{
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000715 PyObject *it; /* iter(v) */
716 int m; /* size of self */
717 int n; /* guess for size of b */
718 int mn; /* m + n */
719 int i;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000720 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000721
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000722 /* Special cases:
Tim Petersb38e2b62004-07-29 02:29:26 +0000723 1) lists and tuples which can use PySequence_Fast ops
724 2) extending self to self requires making a copy first
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000725 */
726 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
Armin Rigo70d172d2004-03-20 22:19:23 +0000727 PyObject **src, **dest;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000728 b = PySequence_Fast(b, "argument must be iterable");
729 if (!b)
730 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000731 n = PySequence_Fast_GET_SIZE(b);
732 if (n == 0) {
733 /* short circuit when b is empty */
734 Py_DECREF(b);
735 Py_RETURN_NONE;
736 }
737 m = self->ob_size;
738 if (list_resize(self, m + n) == -1) {
739 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000740 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000741 }
742 /* note that we may still have self == b here for the
743 * situation a.extend(a), but the following code works
744 * in that case too. Just make sure to resize self
745 * before calling PySequence_Fast_ITEMS.
746 */
747 /* populate the end of self with b's items */
748 src = PySequence_Fast_ITEMS(b);
749 dest = self->ob_item + m;
750 for (i = 0; i < n; i++) {
751 PyObject *o = src[i];
752 Py_INCREF(o);
753 dest[i] = o;
754 }
755 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000756 Py_RETURN_NONE;
757 }
758
759 it = PyObject_GetIter(b);
760 if (it == NULL)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000761 return NULL;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000762 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000763
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000764 /* Guess a result list size. */
765 n = PyObject_Size(b);
766 if (n < 0) {
767 PyErr_Clear();
768 n = 8; /* arbitrary */
769 }
770 m = self->ob_size;
771 mn = m + n;
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000772 if (list_resize(self, mn) == -1)
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000773 goto error;
774 memset(&(self->ob_item[m]), 0, sizeof(*self->ob_item) * n);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000775
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000776 /* Run iterator to exhaustion. */
777 for (i = m; ; i++) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000778 PyObject *item = iternext(it);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000779 if (item == NULL) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000780 if (PyErr_Occurred()) {
781 if (PyErr_ExceptionMatches(PyExc_StopIteration))
782 PyErr_Clear();
783 else
784 goto error;
785 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000786 break;
787 }
788 if (i < mn)
789 PyList_SET_ITEM(self, i, item); /* steals ref */
790 else {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000791 int status = app1(self, item);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000792 Py_DECREF(item); /* append creates a new ref */
793 if (status < 0)
794 goto error;
795 }
796 }
797
798 /* Cut back result list if initial guess was too large. */
799 if (i < mn && self != NULL) {
800 if (list_ass_slice(self, i, mn, (PyObject *)NULL) != 0)
801 goto error;
802 }
803 Py_DECREF(it);
804 Py_RETURN_NONE;
805
806 error:
807 Py_DECREF(it);
808 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000809}
810
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000811PyObject *
812_PyList_Extend(PyListObject *self, PyObject *b)
813{
814 return listextend(self, b);
815}
816
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000817static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000818list_inplace_concat(PyListObject *self, PyObject *other)
819{
820 PyObject *result;
821
822 result = listextend(self, other);
823 if (result == NULL)
824 return result;
825 Py_DECREF(result);
826 Py_INCREF(self);
827 return (PyObject *)self;
828}
829
830static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000831listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000832{
833 int i = -1;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000834 PyObject *v, *arg = NULL;
Tim Peters8fc4a912004-07-31 21:53:19 +0000835 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000836
837 if (!PyArg_UnpackTuple(args, "pop", 0, 1, &arg))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000838 return NULL;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000839 if (arg != NULL) {
840 if (PyInt_Check(arg))
841 i = (int)(PyInt_AS_LONG((PyIntObject*) arg));
Raymond Hettingerfa6c6f82004-02-19 06:12:06 +0000842 else if (!PyArg_ParseTuple(args, "|i:pop", &i))
843 return NULL;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000844 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000845 if (self->ob_size == 0) {
846 /* Special-case most common failure cause */
847 PyErr_SetString(PyExc_IndexError, "pop from empty list");
848 return NULL;
849 }
850 if (i < 0)
851 i += self->ob_size;
852 if (i < 0 || i >= self->ob_size) {
853 PyErr_SetString(PyExc_IndexError, "pop index out of range");
854 return NULL;
855 }
856 v = self->ob_item[i];
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000857 if (i == self->ob_size - 1) {
Tim Peters8fc4a912004-07-31 21:53:19 +0000858 status = list_resize(self, self->ob_size - 1);
859 assert(status >= 0);
860 return v; /* and v now owns the reference the list had */
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000861 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000862 Py_INCREF(v);
Tim Peters8fc4a912004-07-31 21:53:19 +0000863 status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
864 assert(status >= 0);
865 /* Use status, so that in a release build compilers don't
866 * complain about the unused name.
867 */
Brett Cannon651dd522004-08-08 21:21:18 +0000868 (void) status;
869
870 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000871}
872
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000873/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
874static void
875reverse_slice(PyObject **lo, PyObject **hi)
876{
877 assert(lo && hi);
878
879 --hi;
880 while (lo < hi) {
881 PyObject *t = *lo;
882 *lo = *hi;
883 *hi = t;
884 ++lo;
885 --hi;
886 }
887}
888
Tim Petersa64dc242002-08-01 02:13:36 +0000889/* Lots of code for an adaptive, stable, natural mergesort. There are many
890 * pieces to this algorithm; read listsort.txt for overviews and details.
891 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000892
Guido van Rossum3f236de1996-12-10 23:55:39 +0000893/* Comparison function. Takes care of calling a user-supplied
Tim Peters66860f62002-08-04 17:47:26 +0000894 * comparison function (any callable Python object), which must not be
895 * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool
896 * with Py_LT if you know it's NULL).
Tim Petersa64dc242002-08-01 02:13:36 +0000897 * Returns -1 on error, 1 if x < y, 0 if x >= y.
898 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000899static int
Tim Petersa8c974c2002-07-19 03:30:57 +0000900islt(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000901{
Tim Petersf2a04732002-07-11 21:46:16 +0000902 PyObject *res;
903 PyObject *args;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000904 int i;
905
Tim Peters66860f62002-08-04 17:47:26 +0000906 assert(compare != NULL);
Tim Petersa8c974c2002-07-19 03:30:57 +0000907 /* Call the user's comparison function and translate the 3-way
908 * result into true or false (or error).
909 */
Tim Petersf2a04732002-07-11 21:46:16 +0000910 args = PyTuple_New(2);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000911 if (args == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000912 return -1;
Tim Petersf2a04732002-07-11 21:46:16 +0000913 Py_INCREF(x);
914 Py_INCREF(y);
915 PyTuple_SET_ITEM(args, 0, x);
916 PyTuple_SET_ITEM(args, 1, y);
Tim Peters58cf3612002-07-15 05:16:13 +0000917 res = PyObject_Call(compare, args, NULL);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000918 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000919 if (res == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000920 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000921 if (!PyInt_Check(res)) {
922 Py_DECREF(res);
923 PyErr_SetString(PyExc_TypeError,
Guido van Rossum9bcd1d71999-04-19 17:44:39 +0000924 "comparison function must return int");
Tim Petersa8c974c2002-07-19 03:30:57 +0000925 return -1;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000926 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000927 i = PyInt_AsLong(res);
928 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +0000929 return i < 0;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000930}
931
Tim Peters66860f62002-08-04 17:47:26 +0000932/* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
933 * islt. This avoids a layer of function call in the usual case, and
934 * sorting does many comparisons.
935 * Returns -1 on error, 1 if x < y, 0 if x >= y.
936 */
937#define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
938 PyObject_RichCompareBool(X, Y, Py_LT) : \
939 islt(X, Y, COMPARE))
940
941/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +0000942 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
943 started. It makes more sense in context <wink>. X and Y are PyObject*s.
944*/
Tim Peters66860f62002-08-04 17:47:26 +0000945#define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
Tim Petersa8c974c2002-07-19 03:30:57 +0000946 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000947
948/* binarysort is the best method for sorting small arrays: it does
949 few compares, but can do data movement quadratic in the number of
950 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000951 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +0000952 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000953 On entry, must have lo <= start <= hi, and that [lo, start) is already
954 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +0000955 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000956 Even in case of error, the output slice will be some permutation of
957 the input (nothing is lost or duplicated).
958*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000959static int
Fred Drakea2f55112000-07-09 15:16:51 +0000960binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
961 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000962{
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000963 register int k;
964 register PyObject **l, **p, **r;
965 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000966
Tim Petersa8c974c2002-07-19 03:30:57 +0000967 assert(lo <= start && start <= hi);
968 /* assert [lo, start) is sorted */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000969 if (lo == start)
970 ++start;
971 for (; start < hi; ++start) {
972 /* set l to where *start belongs */
973 l = lo;
974 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000975 pivot = *r;
Tim Peters0fe977c2002-07-19 06:12:32 +0000976 /* Invariants:
977 * pivot >= all in [lo, l).
978 * pivot < all in [r, start).
979 * The second is vacuously true at the start.
980 */
981 assert(l < r);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000982 do {
983 p = l + ((r - l) >> 1);
Tim Petersa8c974c2002-07-19 03:30:57 +0000984 IFLT(pivot, *p)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000985 r = p;
986 else
Tim Peters0fe977c2002-07-19 06:12:32 +0000987 l = p+1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000988 } while (l < r);
Tim Peters0fe977c2002-07-19 06:12:32 +0000989 assert(l == r);
990 /* The invariants still hold, so pivot >= all in [lo, l) and
991 pivot < all in [l, start), so pivot belongs at l. Note
992 that if there are elements equal to pivot, l points to the
993 first slot after them -- that's why this sort is stable.
994 Slide over to make room.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000995 Caution: using memmove is much slower under MSVC 5;
996 we're not usually moving many slots. */
997 for (p = start; p > l; --p)
998 *p = *(p-1);
999 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001000 }
Guido van Rossum3f236de1996-12-10 23:55:39 +00001001 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001002
1003 fail:
1004 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001005}
1006
Tim Petersa64dc242002-08-01 02:13:36 +00001007/*
1008Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1009is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001010
Tim Petersa64dc242002-08-01 02:13:36 +00001011 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001012
Tim Petersa64dc242002-08-01 02:13:36 +00001013or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001014
Tim Petersa64dc242002-08-01 02:13:36 +00001015 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001016
Tim Petersa64dc242002-08-01 02:13:36 +00001017Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1018For its intended use in a stable mergesort, the strictness of the defn of
1019"descending" is needed so that the caller can safely reverse a descending
1020sequence without violating stability (strict > ensures there are no equal
1021elements to get out of order).
1022
1023Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001024*/
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001025static int
Tim Petersa64dc242002-08-01 02:13:36 +00001026count_run(PyObject **lo, PyObject **hi, PyObject *compare, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001027{
Tim Petersa64dc242002-08-01 02:13:36 +00001028 int k;
1029 int n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001030
Tim Petersa64dc242002-08-01 02:13:36 +00001031 assert(lo < hi);
1032 *descending = 0;
1033 ++lo;
1034 if (lo == hi)
1035 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001036
Tim Petersa64dc242002-08-01 02:13:36 +00001037 n = 2;
1038 IFLT(*lo, *(lo-1)) {
1039 *descending = 1;
1040 for (lo = lo+1; lo < hi; ++lo, ++n) {
1041 IFLT(*lo, *(lo-1))
1042 ;
1043 else
1044 break;
1045 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001046 }
Tim Petersa64dc242002-08-01 02:13:36 +00001047 else {
1048 for (lo = lo+1; lo < hi; ++lo, ++n) {
1049 IFLT(*lo, *(lo-1))
1050 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001051 }
1052 }
1053
Tim Petersa64dc242002-08-01 02:13:36 +00001054 return n;
1055fail:
1056 return -1;
1057}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001058
Tim Petersa64dc242002-08-01 02:13:36 +00001059/*
1060Locate the proper position of key in a sorted vector; if the vector contains
1061an element equal to key, return the position immediately to the left of
1062the leftmost equal element. [gallop_right() does the same except returns
1063the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001064
Tim Petersa64dc242002-08-01 02:13:36 +00001065"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001066
Tim Petersa64dc242002-08-01 02:13:36 +00001067"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1068hint is to the final result, the faster this runs.
1069
1070The return value is the int k in 0..n such that
1071
1072 a[k-1] < key <= a[k]
1073
1074pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1075key belongs at index k; or, IOW, the first k elements of a should precede
1076key, and the last n-k should follow key.
1077
1078Returns -1 on error. See listsort.txt for info on the method.
1079*/
1080static int
1081gallop_left(PyObject *key, PyObject **a, int n, int hint, PyObject *compare)
1082{
1083 int ofs;
1084 int lastofs;
1085 int k;
1086
1087 assert(key && a && n > 0 && hint >= 0 && hint < n);
1088
1089 a += hint;
1090 lastofs = 0;
1091 ofs = 1;
1092 IFLT(*a, key) {
1093 /* a[hint] < key -- gallop right, until
1094 * a[hint + lastofs] < key <= a[hint + ofs]
1095 */
1096 const int maxofs = n - hint; /* &a[n-1] is highest */
1097 while (ofs < maxofs) {
1098 IFLT(a[ofs], key) {
1099 lastofs = ofs;
1100 ofs = (ofs << 1) + 1;
1101 if (ofs <= 0) /* int overflow */
1102 ofs = maxofs;
1103 }
1104 else /* key <= a[hint + ofs] */
1105 break;
1106 }
1107 if (ofs > maxofs)
1108 ofs = maxofs;
1109 /* Translate back to offsets relative to &a[0]. */
1110 lastofs += hint;
1111 ofs += hint;
1112 }
1113 else {
1114 /* key <= a[hint] -- gallop left, until
1115 * a[hint - ofs] < key <= a[hint - lastofs]
1116 */
1117 const int maxofs = hint + 1; /* &a[0] is lowest */
1118 while (ofs < maxofs) {
1119 IFLT(*(a-ofs), key)
1120 break;
1121 /* key <= a[hint - ofs] */
1122 lastofs = ofs;
1123 ofs = (ofs << 1) + 1;
1124 if (ofs <= 0) /* int overflow */
1125 ofs = maxofs;
1126 }
1127 if (ofs > maxofs)
1128 ofs = maxofs;
1129 /* Translate back to positive offsets relative to &a[0]. */
1130 k = lastofs;
1131 lastofs = hint - ofs;
1132 ofs = hint - k;
1133 }
1134 a -= hint;
1135
1136 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1137 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1138 * right of lastofs but no farther right than ofs. Do a binary
1139 * search, with invariant a[lastofs-1] < key <= a[ofs].
1140 */
1141 ++lastofs;
1142 while (lastofs < ofs) {
1143 int m = lastofs + ((ofs - lastofs) >> 1);
1144
1145 IFLT(a[m], key)
1146 lastofs = m+1; /* a[m] < key */
1147 else
1148 ofs = m; /* key <= a[m] */
1149 }
1150 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1151 return ofs;
1152
1153fail:
1154 return -1;
1155}
1156
1157/*
1158Exactly like gallop_left(), except that if key already exists in a[0:n],
1159finds the position immediately to the right of the rightmost equal value.
1160
1161The return value is the int k in 0..n such that
1162
1163 a[k-1] <= key < a[k]
1164
1165or -1 if error.
1166
1167The code duplication is massive, but this is enough different given that
1168we're sticking to "<" comparisons that it's much harder to follow if
1169written as one routine with yet another "left or right?" flag.
1170*/
1171static int
1172gallop_right(PyObject *key, PyObject **a, int n, int hint, PyObject *compare)
1173{
1174 int ofs;
1175 int lastofs;
1176 int k;
1177
1178 assert(key && a && n > 0 && hint >= 0 && hint < n);
1179
1180 a += hint;
1181 lastofs = 0;
1182 ofs = 1;
1183 IFLT(key, *a) {
1184 /* key < a[hint] -- gallop left, until
1185 * a[hint - ofs] <= key < a[hint - lastofs]
1186 */
1187 const int maxofs = hint + 1; /* &a[0] is lowest */
1188 while (ofs < maxofs) {
1189 IFLT(key, *(a-ofs)) {
1190 lastofs = ofs;
1191 ofs = (ofs << 1) + 1;
1192 if (ofs <= 0) /* int overflow */
1193 ofs = maxofs;
1194 }
1195 else /* a[hint - ofs] <= key */
1196 break;
1197 }
1198 if (ofs > maxofs)
1199 ofs = maxofs;
1200 /* Translate back to positive offsets relative to &a[0]. */
1201 k = lastofs;
1202 lastofs = hint - ofs;
1203 ofs = hint - k;
1204 }
1205 else {
1206 /* a[hint] <= key -- gallop right, until
1207 * a[hint + lastofs] <= key < a[hint + ofs]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001208 */
Tim Petersa64dc242002-08-01 02:13:36 +00001209 const int maxofs = n - hint; /* &a[n-1] is highest */
1210 while (ofs < maxofs) {
1211 IFLT(key, a[ofs])
1212 break;
1213 /* a[hint + ofs] <= key */
1214 lastofs = ofs;
1215 ofs = (ofs << 1) + 1;
1216 if (ofs <= 0) /* int overflow */
1217 ofs = maxofs;
1218 }
1219 if (ofs > maxofs)
1220 ofs = maxofs;
1221 /* Translate back to offsets relative to &a[0]. */
1222 lastofs += hint;
1223 ofs += hint;
1224 }
1225 a -= hint;
1226
1227 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1228 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1229 * right of lastofs but no farther right than ofs. Do a binary
1230 * search, with invariant a[lastofs-1] <= key < a[ofs].
1231 */
1232 ++lastofs;
1233 while (lastofs < ofs) {
1234 int m = lastofs + ((ofs - lastofs) >> 1);
1235
1236 IFLT(key, a[m])
1237 ofs = m; /* key < a[m] */
1238 else
1239 lastofs = m+1; /* a[m] <= key */
1240 }
1241 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1242 return ofs;
1243
1244fail:
1245 return -1;
1246}
1247
1248/* The maximum number of entries in a MergeState's pending-runs stack.
1249 * This is enough to sort arrays of size up to about
1250 * 32 * phi ** MAX_MERGE_PENDING
1251 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1252 * with 2**64 elements.
1253 */
1254#define MAX_MERGE_PENDING 85
1255
Tim Peterse05f65a2002-08-10 05:21:15 +00001256/* When we get into galloping mode, we stay there until both runs win less
1257 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001258 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001259#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001260
1261/* Avoid malloc for small temp arrays. */
1262#define MERGESTATE_TEMP_SIZE 256
1263
1264/* One MergeState exists on the stack per invocation of mergesort. It's just
1265 * a convenient way to pass state around among the helper functions.
1266 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001267struct s_slice {
1268 PyObject **base;
1269 int len;
1270};
1271
Tim Petersa64dc242002-08-01 02:13:36 +00001272typedef struct s_MergeState {
1273 /* The user-supplied comparison function. or NULL if none given. */
1274 PyObject *compare;
1275
Tim Peterse05f65a2002-08-10 05:21:15 +00001276 /* This controls when we get *into* galloping mode. It's initialized
1277 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1278 * random data, and lower for highly structured data.
1279 */
1280 int min_gallop;
1281
Tim Petersa64dc242002-08-01 02:13:36 +00001282 /* 'a' is temp storage to help with merges. It contains room for
1283 * alloced entries.
1284 */
1285 PyObject **a; /* may point to temparray below */
1286 int alloced;
1287
1288 /* A stack of n pending runs yet to be merged. Run #i starts at
1289 * address base[i] and extends for len[i] elements. It's always
1290 * true (so long as the indices are in bounds) that
1291 *
Tim Peterse05f65a2002-08-10 05:21:15 +00001292 * pending[i].base + pending[i].len == pending[i+1].base
Tim Petersa64dc242002-08-01 02:13:36 +00001293 *
1294 * so we could cut the storage for this, but it's a minor amount,
1295 * and keeping all the info explicit simplifies the code.
1296 */
1297 int n;
Tim Peterse05f65a2002-08-10 05:21:15 +00001298 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001299
1300 /* 'a' points to this when possible, rather than muck with malloc. */
1301 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1302} MergeState;
1303
1304/* Conceptually a MergeState's constructor. */
1305static void
1306merge_init(MergeState *ms, PyObject *compare)
1307{
1308 assert(ms != NULL);
1309 ms->compare = compare;
1310 ms->a = ms->temparray;
1311 ms->alloced = MERGESTATE_TEMP_SIZE;
1312 ms->n = 0;
Tim Peterse05f65a2002-08-10 05:21:15 +00001313 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001314}
1315
1316/* Free all the temp memory owned by the MergeState. This must be called
1317 * when you're done with a MergeState, and may be called before then if
1318 * you want to free the temp memory early.
1319 */
1320static void
1321merge_freemem(MergeState *ms)
1322{
1323 assert(ms != NULL);
1324 if (ms->a != ms->temparray)
1325 PyMem_Free(ms->a);
1326 ms->a = ms->temparray;
1327 ms->alloced = MERGESTATE_TEMP_SIZE;
1328}
1329
1330/* Ensure enough temp memory for 'need' array slots is available.
1331 * Returns 0 on success and -1 if the memory can't be gotten.
1332 */
1333static int
1334merge_getmem(MergeState *ms, int need)
1335{
1336 assert(ms != NULL);
1337 if (need <= ms->alloced)
1338 return 0;
1339 /* Don't realloc! That can cost cycles to copy the old data, but
1340 * we don't care what's in the block.
1341 */
1342 merge_freemem(ms);
1343 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1344 if (ms->a) {
1345 ms->alloced = need;
1346 return 0;
1347 }
1348 PyErr_NoMemory();
1349 merge_freemem(ms); /* reset to sane state */
1350 return -1;
1351}
1352#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1353 merge_getmem(MS, NEED))
1354
1355/* Merge the na elements starting at pa with the nb elements starting at pb
1356 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1357 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1358 * merge, and should have na <= nb. See listsort.txt for more info.
1359 * Return 0 if successful, -1 if error.
1360 */
1361static int
1362merge_lo(MergeState *ms, PyObject **pa, int na, PyObject **pb, int nb)
1363{
1364 int k;
1365 PyObject *compare;
1366 PyObject **dest;
1367 int result = -1; /* guilty until proved innocent */
Tim Peterse05f65a2002-08-10 05:21:15 +00001368 int min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001369
1370 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1371 if (MERGE_GETMEM(ms, na) < 0)
1372 return -1;
1373 memcpy(ms->a, pa, na * sizeof(PyObject*));
1374 dest = pa;
1375 pa = ms->a;
1376
1377 *dest++ = *pb++;
1378 --nb;
1379 if (nb == 0)
1380 goto Succeed;
1381 if (na == 1)
1382 goto CopyB;
1383
1384 compare = ms->compare;
1385 for (;;) {
1386 int acount = 0; /* # of times A won in a row */
1387 int bcount = 0; /* # of times B won in a row */
1388
1389 /* Do the straightforward thing until (if ever) one run
1390 * appears to win consistently.
1391 */
1392 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001393 assert(na > 1 && nb > 0);
Tim Peters66860f62002-08-04 17:47:26 +00001394 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001395 if (k) {
1396 if (k < 0)
1397 goto Fail;
1398 *dest++ = *pb++;
1399 ++bcount;
1400 acount = 0;
1401 --nb;
1402 if (nb == 0)
1403 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001404 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001405 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001406 }
1407 else {
Tim Petersa64dc242002-08-01 02:13:36 +00001408 *dest++ = *pa++;
1409 ++acount;
1410 bcount = 0;
1411 --na;
1412 if (na == 1)
1413 goto CopyB;
Tim Peterse05f65a2002-08-10 05:21:15 +00001414 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001415 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001416 }
Tim Petersa64dc242002-08-01 02:13:36 +00001417 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001418
Tim Petersa64dc242002-08-01 02:13:36 +00001419 /* One run is winning so consistently that galloping may
1420 * be a huge win. So try that, and continue galloping until
1421 * (if ever) neither run appears to be winning consistently
1422 * anymore.
1423 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001424 ++min_gallop;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001425 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001426 assert(na > 1 && nb > 0);
1427 min_gallop -= min_gallop > 1;
1428 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001429 k = gallop_right(*pb, pa, na, 0, compare);
1430 acount = k;
1431 if (k) {
1432 if (k < 0)
1433 goto Fail;
1434 memcpy(dest, pa, k * sizeof(PyObject *));
1435 dest += k;
1436 pa += k;
1437 na -= k;
1438 if (na == 1)
1439 goto CopyB;
1440 /* na==0 is impossible now if the comparison
1441 * function is consistent, but we can't assume
1442 * that it is.
1443 */
1444 if (na == 0)
1445 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001446 }
Tim Petersa64dc242002-08-01 02:13:36 +00001447 *dest++ = *pb++;
1448 --nb;
1449 if (nb == 0)
1450 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001451
Tim Petersa64dc242002-08-01 02:13:36 +00001452 k = gallop_left(*pa, pb, nb, 0, compare);
1453 bcount = k;
1454 if (k) {
1455 if (k < 0)
1456 goto Fail;
1457 memmove(dest, pb, k * sizeof(PyObject *));
1458 dest += k;
1459 pb += k;
1460 nb -= k;
1461 if (nb == 0)
1462 goto Succeed;
1463 }
1464 *dest++ = *pa++;
1465 --na;
1466 if (na == 1)
1467 goto CopyB;
1468 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001469 ++min_gallop; /* penalize it for leaving galloping mode */
1470 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001471 }
1472Succeed:
1473 result = 0;
1474Fail:
1475 if (na)
1476 memcpy(dest, pa, na * sizeof(PyObject*));
1477 return result;
1478CopyB:
1479 assert(na == 1 && nb > 0);
1480 /* The last element of pa belongs at the end of the merge. */
1481 memmove(dest, pb, nb * sizeof(PyObject *));
1482 dest[nb] = *pa;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001483 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001484}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001485
Tim Petersa64dc242002-08-01 02:13:36 +00001486/* Merge the na elements starting at pa with the nb elements starting at pb
1487 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1488 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1489 * merge, and should have na >= nb. See listsort.txt for more info.
1490 * Return 0 if successful, -1 if error.
1491 */
1492static int
1493merge_hi(MergeState *ms, PyObject **pa, int na, PyObject **pb, int nb)
1494{
1495 int k;
1496 PyObject *compare;
1497 PyObject **dest;
1498 int result = -1; /* guilty until proved innocent */
1499 PyObject **basea;
1500 PyObject **baseb;
Tim Peterse05f65a2002-08-10 05:21:15 +00001501 int min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001502
1503 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1504 if (MERGE_GETMEM(ms, nb) < 0)
1505 return -1;
1506 dest = pb + nb - 1;
1507 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1508 basea = pa;
1509 baseb = ms->a;
1510 pb = ms->a + nb - 1;
1511 pa += na - 1;
1512
1513 *dest-- = *pa--;
1514 --na;
1515 if (na == 0)
1516 goto Succeed;
1517 if (nb == 1)
1518 goto CopyA;
1519
1520 compare = ms->compare;
1521 for (;;) {
1522 int acount = 0; /* # of times A won in a row */
1523 int bcount = 0; /* # of times B won in a row */
1524
1525 /* Do the straightforward thing until (if ever) one run
1526 * appears to win consistently.
1527 */
1528 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001529 assert(na > 0 && nb > 1);
Tim Peters66860f62002-08-04 17:47:26 +00001530 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001531 if (k) {
1532 if (k < 0)
1533 goto Fail;
1534 *dest-- = *pa--;
1535 ++acount;
1536 bcount = 0;
1537 --na;
1538 if (na == 0)
1539 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001540 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001541 break;
1542 }
1543 else {
1544 *dest-- = *pb--;
1545 ++bcount;
1546 acount = 0;
1547 --nb;
1548 if (nb == 1)
1549 goto CopyA;
Tim Peterse05f65a2002-08-10 05:21:15 +00001550 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001551 break;
1552 }
1553 }
1554
1555 /* One run is winning so consistently that galloping may
1556 * be a huge win. So try that, and continue galloping until
1557 * (if ever) neither run appears to be winning consistently
1558 * anymore.
1559 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001560 ++min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001561 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001562 assert(na > 0 && nb > 1);
1563 min_gallop -= min_gallop > 1;
1564 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001565 k = gallop_right(*pb, basea, na, na-1, compare);
1566 if (k < 0)
1567 goto Fail;
1568 k = na - k;
1569 acount = k;
1570 if (k) {
1571 dest -= k;
1572 pa -= k;
1573 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1574 na -= k;
1575 if (na == 0)
1576 goto Succeed;
1577 }
1578 *dest-- = *pb--;
1579 --nb;
1580 if (nb == 1)
1581 goto CopyA;
1582
1583 k = gallop_left(*pa, baseb, nb, nb-1, compare);
1584 if (k < 0)
1585 goto Fail;
1586 k = nb - k;
1587 bcount = k;
1588 if (k) {
1589 dest -= k;
1590 pb -= k;
1591 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1592 nb -= k;
1593 if (nb == 1)
1594 goto CopyA;
1595 /* nb==0 is impossible now if the comparison
1596 * function is consistent, but we can't assume
1597 * that it is.
1598 */
1599 if (nb == 0)
1600 goto Succeed;
1601 }
1602 *dest-- = *pa--;
1603 --na;
1604 if (na == 0)
1605 goto Succeed;
1606 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001607 ++min_gallop; /* penalize it for leaving galloping mode */
1608 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001609 }
1610Succeed:
1611 result = 0;
1612Fail:
1613 if (nb)
1614 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1615 return result;
1616CopyA:
1617 assert(nb == 1 && na > 0);
1618 /* The first element of pb belongs at the front of the merge. */
1619 dest -= na;
1620 pa -= na;
1621 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1622 *dest = *pb;
1623 return 0;
1624}
1625
1626/* Merge the two runs at stack indices i and i+1.
1627 * Returns 0 on success, -1 on error.
1628 */
1629static int
1630merge_at(MergeState *ms, int i)
1631{
1632 PyObject **pa, **pb;
1633 int na, nb;
1634 int k;
1635 PyObject *compare;
1636
1637 assert(ms != NULL);
1638 assert(ms->n >= 2);
1639 assert(i >= 0);
1640 assert(i == ms->n - 2 || i == ms->n - 3);
1641
Tim Peterse05f65a2002-08-10 05:21:15 +00001642 pa = ms->pending[i].base;
1643 na = ms->pending[i].len;
1644 pb = ms->pending[i+1].base;
1645 nb = ms->pending[i+1].len;
Tim Petersa64dc242002-08-01 02:13:36 +00001646 assert(na > 0 && nb > 0);
1647 assert(pa + na == pb);
1648
1649 /* Record the length of the combined runs; if i is the 3rd-last
1650 * run now, also slide over the last run (which isn't involved
1651 * in this merge). The current run i+1 goes away in any case.
1652 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001653 ms->pending[i].len = na + nb;
1654 if (i == ms->n - 3)
1655 ms->pending[i+1] = ms->pending[i+2];
Tim Petersa64dc242002-08-01 02:13:36 +00001656 --ms->n;
1657
1658 /* Where does b start in a? Elements in a before that can be
1659 * ignored (already in place).
1660 */
1661 compare = ms->compare;
1662 k = gallop_right(*pb, pa, na, 0, compare);
1663 if (k < 0)
1664 return -1;
1665 pa += k;
1666 na -= k;
1667 if (na == 0)
1668 return 0;
1669
1670 /* Where does a end in b? Elements in b after that can be
1671 * ignored (already in place).
1672 */
1673 nb = gallop_left(pa[na-1], pb, nb, nb-1, compare);
1674 if (nb <= 0)
1675 return nb;
1676
1677 /* Merge what remains of the runs, using a temp array with
1678 * min(na, nb) elements.
1679 */
1680 if (na <= nb)
1681 return merge_lo(ms, pa, na, pb, nb);
1682 else
1683 return merge_hi(ms, pa, na, pb, nb);
1684}
1685
1686/* Examine the stack of runs waiting to be merged, merging adjacent runs
1687 * until the stack invariants are re-established:
1688 *
1689 * 1. len[-3] > len[-2] + len[-1]
1690 * 2. len[-2] > len[-1]
1691 *
1692 * See listsort.txt for more info.
1693 *
1694 * Returns 0 on success, -1 on error.
1695 */
1696static int
1697merge_collapse(MergeState *ms)
1698{
Tim Peterse05f65a2002-08-10 05:21:15 +00001699 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001700
1701 assert(ms);
1702 while (ms->n > 1) {
1703 int n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001704 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1705 if (p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001706 --n;
1707 if (merge_at(ms, n) < 0)
1708 return -1;
1709 }
Tim Peterse05f65a2002-08-10 05:21:15 +00001710 else if (p[n].len <= p[n+1].len) {
Tim Petersa64dc242002-08-01 02:13:36 +00001711 if (merge_at(ms, n) < 0)
1712 return -1;
1713 }
1714 else
1715 break;
1716 }
1717 return 0;
1718}
1719
1720/* Regardless of invariants, merge all runs on the stack until only one
1721 * remains. This is used at the end of the mergesort.
1722 *
1723 * Returns 0 on success, -1 on error.
1724 */
1725static int
1726merge_force_collapse(MergeState *ms)
1727{
Tim Peterse05f65a2002-08-10 05:21:15 +00001728 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001729
1730 assert(ms);
1731 while (ms->n > 1) {
1732 int n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001733 if (n > 0 && p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001734 --n;
1735 if (merge_at(ms, n) < 0)
1736 return -1;
1737 }
1738 return 0;
1739}
1740
1741/* Compute a good value for the minimum run length; natural runs shorter
1742 * than this are boosted artificially via binary insertion.
1743 *
1744 * If n < 64, return n (it's too small to bother with fancy stuff).
1745 * Else if n is an exact power of 2, return 32.
1746 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1747 * strictly less than, an exact power of 2.
1748 *
1749 * See listsort.txt for more info.
1750 */
1751static int
1752merge_compute_minrun(int n)
1753{
1754 int r = 0; /* becomes 1 if any 1 bits are shifted off */
1755
1756 assert(n >= 0);
1757 while (n >= 64) {
1758 r |= n & 1;
1759 n >>= 1;
1760 }
1761 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001762}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001763
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001764/* Special wrapper to support stable sorting using the decorate-sort-undecorate
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001765 pattern. Holds a key which is used for comparisons and the original record
Tim Petersb38e2b62004-07-29 02:29:26 +00001766 which is returned during the undecorate phase. By exposing only the key
1767 during comparisons, the underlying sort stability characteristics are left
1768 unchanged. Also, if a custom comparison function is used, it will only see
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001769 the key instead of a full record. */
1770
1771typedef struct {
1772 PyObject_HEAD
1773 PyObject *key;
1774 PyObject *value;
1775} sortwrapperobject;
1776
1777static PyTypeObject sortwrapper_type;
1778
1779static PyObject *
1780sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
1781{
1782 if (!PyObject_TypeCheck(b, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001783 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001784 "expected a sortwrapperobject");
1785 return NULL;
1786 }
1787 return PyObject_RichCompare(a->key, b->key, op);
1788}
1789
1790static void
1791sortwrapper_dealloc(sortwrapperobject *so)
1792{
1793 Py_XDECREF(so->key);
1794 Py_XDECREF(so->value);
1795 PyObject_Del(so);
1796}
1797
1798PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
1799
1800static PyTypeObject sortwrapper_type = {
1801 PyObject_HEAD_INIT(&PyType_Type)
1802 0, /* ob_size */
1803 "sortwrapper", /* tp_name */
1804 sizeof(sortwrapperobject), /* tp_basicsize */
1805 0, /* tp_itemsize */
1806 /* methods */
1807 (destructor)sortwrapper_dealloc, /* tp_dealloc */
1808 0, /* tp_print */
1809 0, /* tp_getattr */
1810 0, /* tp_setattr */
1811 0, /* tp_compare */
1812 0, /* tp_repr */
1813 0, /* tp_as_number */
1814 0, /* tp_as_sequence */
1815 0, /* tp_as_mapping */
1816 0, /* tp_hash */
1817 0, /* tp_call */
1818 0, /* tp_str */
1819 PyObject_GenericGetAttr, /* tp_getattro */
1820 0, /* tp_setattro */
1821 0, /* tp_as_buffer */
Tim Petersb38e2b62004-07-29 02:29:26 +00001822 Py_TPFLAGS_DEFAULT |
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001823 Py_TPFLAGS_HAVE_RICHCOMPARE, /* tp_flags */
1824 sortwrapper_doc, /* tp_doc */
1825 0, /* tp_traverse */
1826 0, /* tp_clear */
1827 (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
1828};
1829
1830/* Returns a new reference to a sortwrapper.
1831 Consumes the references to the two underlying objects. */
1832
1833static PyObject *
1834build_sortwrapper(PyObject *key, PyObject *value)
1835{
1836 sortwrapperobject *so;
Tim Petersb38e2b62004-07-29 02:29:26 +00001837
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001838 so = PyObject_New(sortwrapperobject, &sortwrapper_type);
1839 if (so == NULL)
1840 return NULL;
1841 so->key = key;
1842 so->value = value;
1843 return (PyObject *)so;
1844}
1845
1846/* Returns a new reference to the value underlying the wrapper. */
1847static PyObject *
1848sortwrapper_getvalue(PyObject *so)
1849{
1850 PyObject *value;
1851
1852 if (!PyObject_TypeCheck(so, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001853 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001854 "expected a sortwrapperobject");
1855 return NULL;
1856 }
1857 value = ((sortwrapperobject *)so)->value;
1858 Py_INCREF(value);
1859 return value;
1860}
1861
1862/* Wrapper for user specified cmp functions in combination with a
1863 specified key function. Makes sure the cmp function is presented
1864 with the actual key instead of the sortwrapper */
1865
1866typedef struct {
1867 PyObject_HEAD
1868 PyObject *func;
1869} cmpwrapperobject;
1870
1871static void
1872cmpwrapper_dealloc(cmpwrapperobject *co)
1873{
1874 Py_XDECREF(co->func);
1875 PyObject_Del(co);
1876}
1877
1878static PyObject *
1879cmpwrapper_call(cmpwrapperobject *co, PyObject *args, PyObject *kwds)
1880{
1881 PyObject *x, *y, *xx, *yy;
1882
1883 if (!PyArg_UnpackTuple(args, "", 2, 2, &x, &y))
1884 return NULL;
1885 if (!PyObject_TypeCheck(x, &sortwrapper_type) ||
Raymond Hettingerae4a2992003-10-16 17:16:30 +00001886 !PyObject_TypeCheck(y, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001887 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001888 "expected a sortwrapperobject");
1889 return NULL;
1890 }
1891 xx = ((sortwrapperobject *)x)->key;
1892 yy = ((sortwrapperobject *)y)->key;
1893 return PyObject_CallFunctionObjArgs(co->func, xx, yy, NULL);
1894}
1895
1896PyDoc_STRVAR(cmpwrapper_doc, "cmp() wrapper for sort with custom keys.");
1897
1898static PyTypeObject cmpwrapper_type = {
1899 PyObject_HEAD_INIT(&PyType_Type)
1900 0, /* ob_size */
1901 "cmpwrapper", /* tp_name */
1902 sizeof(cmpwrapperobject), /* tp_basicsize */
1903 0, /* tp_itemsize */
1904 /* methods */
1905 (destructor)cmpwrapper_dealloc, /* tp_dealloc */
1906 0, /* tp_print */
1907 0, /* tp_getattr */
1908 0, /* tp_setattr */
1909 0, /* tp_compare */
1910 0, /* tp_repr */
1911 0, /* tp_as_number */
1912 0, /* tp_as_sequence */
1913 0, /* tp_as_mapping */
1914 0, /* tp_hash */
1915 (ternaryfunc)cmpwrapper_call, /* tp_call */
1916 0, /* tp_str */
1917 PyObject_GenericGetAttr, /* tp_getattro */
1918 0, /* tp_setattro */
1919 0, /* tp_as_buffer */
1920 Py_TPFLAGS_DEFAULT, /* tp_flags */
1921 cmpwrapper_doc, /* tp_doc */
1922};
1923
1924static PyObject *
1925build_cmpwrapper(PyObject *cmpfunc)
1926{
1927 cmpwrapperobject *co;
Tim Petersb38e2b62004-07-29 02:29:26 +00001928
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001929 co = PyObject_New(cmpwrapperobject, &cmpwrapper_type);
1930 if (co == NULL)
1931 return NULL;
1932 Py_INCREF(cmpfunc);
1933 co->func = cmpfunc;
1934 return (PyObject *)co;
1935}
1936
Tim Petersa64dc242002-08-01 02:13:36 +00001937/* An adaptive, stable, natural mergesort. See listsort.txt.
1938 * Returns Py_None on success, NULL on error. Even in case of error, the
1939 * list will be some permutation of its input state (nothing is lost or
1940 * duplicated).
1941 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001942static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001943listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001944{
Tim Petersa64dc242002-08-01 02:13:36 +00001945 MergeState ms;
1946 PyObject **lo, **hi;
1947 int nremaining;
1948 int minrun;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001949 int saved_ob_size, saved_allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00001950 PyObject **saved_ob_item;
Armin Rigo93677f02004-07-29 12:40:23 +00001951 PyObject **final_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001952 PyObject *compare = NULL;
1953 PyObject *result = NULL; /* guilty until proved innocent */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001954 int reverse = 0;
1955 PyObject *keyfunc = NULL;
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001956 int i;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001957 PyObject *key, *value, *kvpair;
1958 static char *kwlist[] = {"cmp", "key", "reverse", 0};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001959
Tim Petersa64dc242002-08-01 02:13:36 +00001960 assert(self != NULL);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001961 assert (PyList_Check(self));
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001962 if (args != NULL) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001963 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:sort",
1964 kwlist, &compare, &keyfunc, &reverse))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001965 return NULL;
1966 }
Skip Montanaro4abd5f02003-01-02 20:51:08 +00001967 if (compare == Py_None)
1968 compare = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001969 if (keyfunc == Py_None)
1970 keyfunc = NULL;
1971 if (compare != NULL && keyfunc != NULL) {
1972 compare = build_cmpwrapper(compare);
1973 if (compare == NULL)
Hye-Shik Chang19cb1932003-12-10 07:31:08 +00001974 return NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001975 } else
1976 Py_XINCREF(compare);
1977
Tim Petersb9099c32002-11-12 22:08:10 +00001978 /* The list is temporarily made empty, so that mutations performed
1979 * by comparison functions can't affect the slice of memory we're
1980 * sorting (allowing mutations during sorting is a core-dump
1981 * factory, since ob_item may change).
1982 */
1983 saved_ob_size = self->ob_size;
1984 saved_ob_item = self->ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001985 saved_allocated = self->allocated;
Armin Rigo93677f02004-07-29 12:40:23 +00001986 self->ob_size = 0;
Tim Peters51b4ade2004-07-29 04:07:15 +00001987 self->ob_item = NULL;
Armin Rigo93677f02004-07-29 12:40:23 +00001988 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00001989
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001990 if (keyfunc != NULL) {
1991 for (i=0 ; i < saved_ob_size ; i++) {
1992 value = saved_ob_item[i];
Tim Petersb38e2b62004-07-29 02:29:26 +00001993 key = PyObject_CallFunctionObjArgs(keyfunc, value,
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001994 NULL);
1995 if (key == NULL) {
1996 for (i=i-1 ; i>=0 ; i--) {
1997 kvpair = saved_ob_item[i];
1998 value = sortwrapper_getvalue(kvpair);
1999 saved_ob_item[i] = value;
2000 Py_DECREF(kvpair);
2001 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002002 goto dsu_fail;
2003 }
2004 kvpair = build_sortwrapper(key, value);
2005 if (kvpair == NULL)
2006 goto dsu_fail;
2007 saved_ob_item[i] = kvpair;
2008 }
2009 }
2010
2011 /* Reverse sort stability achieved by initially reversing the list,
2012 applying a stable forward sort, then reversing the final result. */
2013 if (reverse && saved_ob_size > 1)
2014 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2015
2016 merge_init(&ms, compare);
2017
Tim Petersb9099c32002-11-12 22:08:10 +00002018 nremaining = saved_ob_size;
Tim Petersa64dc242002-08-01 02:13:36 +00002019 if (nremaining < 2)
2020 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00002021
Tim Petersa64dc242002-08-01 02:13:36 +00002022 /* March over the array once, left to right, finding natural runs,
2023 * and extending short natural runs to minrun elements.
2024 */
Tim Petersb9099c32002-11-12 22:08:10 +00002025 lo = saved_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00002026 hi = lo + nremaining;
2027 minrun = merge_compute_minrun(nremaining);
2028 do {
2029 int descending;
2030 int n;
Tim Peters330f9e92002-07-19 07:05:44 +00002031
Tim Petersa64dc242002-08-01 02:13:36 +00002032 /* Identify next run. */
2033 n = count_run(lo, hi, compare, &descending);
2034 if (n < 0)
2035 goto fail;
2036 if (descending)
2037 reverse_slice(lo, lo + n);
2038 /* If short, extend to min(minrun, nremaining). */
2039 if (n < minrun) {
2040 const int force = nremaining <= minrun ?
2041 nremaining : minrun;
2042 if (binarysort(lo, lo + force, lo + n, compare) < 0)
2043 goto fail;
2044 n = force;
2045 }
2046 /* Push run onto pending-runs stack, and maybe merge. */
2047 assert(ms.n < MAX_MERGE_PENDING);
Tim Peterse05f65a2002-08-10 05:21:15 +00002048 ms.pending[ms.n].base = lo;
2049 ms.pending[ms.n].len = n;
Tim Petersa64dc242002-08-01 02:13:36 +00002050 ++ms.n;
2051 if (merge_collapse(&ms) < 0)
2052 goto fail;
2053 /* Advance to find next run. */
2054 lo += n;
2055 nremaining -= n;
2056 } while (nremaining);
2057 assert(lo == hi);
Tim Peters330f9e92002-07-19 07:05:44 +00002058
Tim Petersa64dc242002-08-01 02:13:36 +00002059 if (merge_force_collapse(&ms) < 0)
2060 goto fail;
2061 assert(ms.n == 1);
Tim Petersb9099c32002-11-12 22:08:10 +00002062 assert(ms.pending[0].base == saved_ob_item);
2063 assert(ms.pending[0].len == saved_ob_size);
Tim Petersa64dc242002-08-01 02:13:36 +00002064
2065succeed:
2066 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002067fail:
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002068 if (keyfunc != NULL) {
2069 for (i=0 ; i < saved_ob_size ; i++) {
2070 kvpair = saved_ob_item[i];
2071 value = sortwrapper_getvalue(kvpair);
2072 saved_ob_item[i] = value;
2073 Py_DECREF(kvpair);
2074 }
2075 }
2076
Armin Rigo93677f02004-07-29 12:40:23 +00002077 if (self->allocated != -1 && result != NULL) {
Tim Peters51b4ade2004-07-29 04:07:15 +00002078 /* The user mucked with the list during the sort,
2079 * and we don't already have another error to report.
2080 */
2081 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2082 result = NULL;
Tim Petersb9099c32002-11-12 22:08:10 +00002083 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002084
2085 if (reverse && saved_ob_size > 1)
2086 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2087
2088 merge_freemem(&ms);
2089
2090dsu_fail:
Armin Rigo93677f02004-07-29 12:40:23 +00002091 final_ob_item = self->ob_item;
2092 i = self->ob_size;
Tim Petersb9099c32002-11-12 22:08:10 +00002093 self->ob_size = saved_ob_size;
2094 self->ob_item = saved_ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002095 self->allocated = saved_allocated;
Armin Rigo93677f02004-07-29 12:40:23 +00002096 if (final_ob_item != NULL) {
2097 /* we cannot use list_clear() for this because it does not
2098 guarantee that the list is really empty when it returns */
2099 while (--i >= 0) {
2100 Py_XDECREF(final_ob_item[i]);
2101 }
2102 PyMem_FREE(final_ob_item);
2103 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002104 Py_XDECREF(compare);
Tim Petersa64dc242002-08-01 02:13:36 +00002105 Py_XINCREF(result);
2106 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002107}
Tim Peters330f9e92002-07-19 07:05:44 +00002108#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002109#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002110
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002111int
Fred Drakea2f55112000-07-09 15:16:51 +00002112PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002113{
2114 if (v == NULL || !PyList_Check(v)) {
2115 PyErr_BadInternalCall();
2116 return -1;
2117 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002118 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002119 if (v == NULL)
2120 return -1;
2121 Py_DECREF(v);
2122 return 0;
2123}
2124
Guido van Rossumb86c5492001-02-12 22:06:02 +00002125static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002126listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002127{
Tim Peters326b4482002-07-19 04:04:16 +00002128 if (self->ob_size > 1)
2129 reverse_slice(self->ob_item, self->ob_item + self->ob_size);
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002130 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002131}
2132
Guido van Rossum84c76f51990-10-30 13:32:20 +00002133int
Fred Drakea2f55112000-07-09 15:16:51 +00002134PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002135{
Tim Peters6063e262002-08-08 01:06:39 +00002136 PyListObject *self = (PyListObject *)v;
2137
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002138 if (v == NULL || !PyList_Check(v)) {
2139 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002140 return -1;
2141 }
Tim Peters6063e262002-08-08 01:06:39 +00002142 if (self->ob_size > 1)
2143 reverse_slice(self->ob_item, self->ob_item + self->ob_size);
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002144 return 0;
2145}
2146
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002147PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002148PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002149{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002150 PyObject *w;
2151 PyObject **p;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002152 int n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002153 if (v == NULL || !PyList_Check(v)) {
2154 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002155 return NULL;
2156 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002157 n = ((PyListObject *)v)->ob_size;
2158 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002159 if (w == NULL)
2160 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002161 p = ((PyTupleObject *)w)->ob_item;
Thomas Wouters334fb892000-07-25 12:56:38 +00002162 memcpy((void *)p,
2163 (void *)((PyListObject *)v)->ob_item,
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002164 n*sizeof(PyObject *));
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002165 while (--n >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002166 Py_INCREF(*p);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002167 p++;
2168 }
2169 return w;
2170}
2171
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002172static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002173listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002174{
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002175 int i, start=0, stop=self->ob_size;
2176 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002177
Walter Dörwalde8049bef2003-06-17 19:27:39 +00002178 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2179 _PyEval_SliceIndex, &start,
2180 _PyEval_SliceIndex, &stop))
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002181 return NULL;
Guido van Rossum2743d872003-06-17 14:25:14 +00002182 if (start < 0) {
2183 start += self->ob_size;
2184 if (start < 0)
2185 start = 0;
2186 }
2187 if (stop < 0) {
2188 stop += self->ob_size;
2189 if (stop < 0)
2190 stop = 0;
2191 }
Neal Norwitzf0769532004-08-13 03:18:29 +00002192 for (i = start; i < stop && i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002193 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2194 if (cmp > 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002195 return PyInt_FromLong((long)i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002196 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002197 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002198 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002199 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002200 return NULL;
2201}
2202
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002203static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002204listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002205{
2206 int count = 0;
2207 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002208
Guido van Rossume6f7d181991-10-20 20:20:40 +00002209 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002210 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2211 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002212 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002213 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002214 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00002215 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002216 return PyInt_FromLong((long)count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002217}
2218
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002219static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002220listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002221{
2222 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002223
Guido van Rossumed98d481991-03-06 13:07:53 +00002224 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002225 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2226 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002227 if (list_ass_slice(self, i, i+1,
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002228 (PyObject *)NULL) == 0)
2229 Py_RETURN_NONE;
2230 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002231 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002232 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002233 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002234 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002235 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002236 return NULL;
2237}
2238
Jeremy Hylton8caad492000-06-23 14:18:11 +00002239static int
2240list_traverse(PyListObject *o, visitproc visit, void *arg)
2241{
2242 int i, err;
2243 PyObject *x;
2244
2245 for (i = o->ob_size; --i >= 0; ) {
2246 x = o->ob_item[i];
2247 if (x != NULL) {
2248 err = visit(x, arg);
2249 if (err)
2250 return err;
2251 }
2252 }
2253 return 0;
2254}
2255
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002256static PyObject *
2257list_richcompare(PyObject *v, PyObject *w, int op)
2258{
2259 PyListObject *vl, *wl;
2260 int i;
2261
2262 if (!PyList_Check(v) || !PyList_Check(w)) {
2263 Py_INCREF(Py_NotImplemented);
2264 return Py_NotImplemented;
2265 }
2266
2267 vl = (PyListObject *)v;
2268 wl = (PyListObject *)w;
2269
2270 if (vl->ob_size != wl->ob_size && (op == Py_EQ || op == Py_NE)) {
2271 /* Shortcut: if the lengths differ, the lists differ */
2272 PyObject *res;
2273 if (op == Py_EQ)
2274 res = Py_False;
2275 else
2276 res = Py_True;
2277 Py_INCREF(res);
2278 return res;
2279 }
2280
2281 /* Search for the first index where items are different */
2282 for (i = 0; i < vl->ob_size && i < wl->ob_size; i++) {
2283 int k = PyObject_RichCompareBool(vl->ob_item[i],
2284 wl->ob_item[i], Py_EQ);
2285 if (k < 0)
2286 return NULL;
2287 if (!k)
2288 break;
2289 }
2290
2291 if (i >= vl->ob_size || i >= wl->ob_size) {
2292 /* No more items to compare -- compare sizes */
2293 int vs = vl->ob_size;
2294 int ws = wl->ob_size;
2295 int cmp;
2296 PyObject *res;
2297 switch (op) {
2298 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00002299 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002300 case Py_EQ: cmp = vs == ws; break;
2301 case Py_NE: cmp = vs != ws; break;
2302 case Py_GT: cmp = vs > ws; break;
2303 case Py_GE: cmp = vs >= ws; break;
2304 default: return NULL; /* cannot happen */
2305 }
2306 if (cmp)
2307 res = Py_True;
2308 else
2309 res = Py_False;
2310 Py_INCREF(res);
2311 return res;
2312 }
2313
2314 /* We have an item that differs -- shortcuts for EQ/NE */
2315 if (op == Py_EQ) {
2316 Py_INCREF(Py_False);
2317 return Py_False;
2318 }
2319 if (op == Py_NE) {
2320 Py_INCREF(Py_True);
2321 return Py_True;
2322 }
2323
2324 /* Compare the final item again using the proper operator */
2325 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
2326}
2327
Tim Peters6d6c1a32001-08-02 04:15:00 +00002328static int
2329list_init(PyListObject *self, PyObject *args, PyObject *kw)
2330{
2331 PyObject *arg = NULL;
2332 static char *kwlist[] = {"sequence", 0};
2333
2334 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2335 return -1;
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002336
2337 /* Verify list invariants established by PyType_GenericAlloc() */
Armin Rigoa37bbf22004-07-30 11:20:18 +00002338 assert(0 <= self->ob_size);
2339 assert(self->ob_size <= self->allocated || self->allocated == -1);
2340 assert(self->ob_item != NULL ||
2341 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002342
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002343 /* Empty previous contents */
Armin Rigo93677f02004-07-29 12:40:23 +00002344 if (self->ob_item != NULL) {
2345 (void)list_clear(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002346 }
2347 if (arg != NULL) {
2348 PyObject *rv = listextend(self, arg);
2349 if (rv == NULL)
2350 return -1;
2351 Py_DECREF(rv);
2352 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002353 return 0;
2354}
2355
Guido van Rossumdbb53d92001-12-03 16:32:18 +00002356static long
2357list_nohash(PyObject *self)
2358{
2359 PyErr_SetString(PyExc_TypeError, "list objects are unhashable");
2360 return -1;
2361}
2362
Raymond Hettinger1021c442003-11-07 15:38:09 +00002363static PyObject *list_iter(PyObject *seq);
2364static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2365
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002366PyDoc_STRVAR(getitem_doc,
2367"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002368PyDoc_STRVAR(reversed_doc,
2369"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002370PyDoc_STRVAR(append_doc,
2371"L.append(object) -- append object to end");
2372PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002373"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002374PyDoc_STRVAR(insert_doc,
2375"L.insert(index, object) -- insert object before index");
2376PyDoc_STRVAR(pop_doc,
2377"L.pop([index]) -> item -- remove and return item at index (default last)");
2378PyDoc_STRVAR(remove_doc,
2379"L.remove(value) -- remove first occurrence of value");
2380PyDoc_STRVAR(index_doc,
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002381"L.index(value, [start, [stop]]) -> integer -- return first index of value");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002382PyDoc_STRVAR(count_doc,
2383"L.count(value) -> integer -- return number of occurrences of value");
2384PyDoc_STRVAR(reverse_doc,
2385"L.reverse() -- reverse *IN PLACE*");
2386PyDoc_STRVAR(sort_doc,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002387"L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n\
2388cmp(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002389
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002390static PyObject *list_subscript(PyListObject*, PyObject*);
2391
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002392static PyMethodDef list_methods[] = {
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002393 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
Raymond Hettinger1021c442003-11-07 15:38:09 +00002394 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002395 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002396 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002397 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002398 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002399 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002400 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002401 {"count", (PyCFunction)listcount, METH_O, count_doc},
2402 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002403 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
Tim Petersa64dc242002-08-01 02:13:36 +00002404 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002405};
2406
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002407static PySequenceMethods list_as_sequence = {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002408 (inquiry)list_length, /* sq_length */
2409 (binaryfunc)list_concat, /* sq_concat */
2410 (intargfunc)list_repeat, /* sq_repeat */
2411 (intargfunc)list_item, /* sq_item */
2412 (intintargfunc)list_slice, /* sq_slice */
2413 (intobjargproc)list_ass_item, /* sq_ass_item */
2414 (intintobjargproc)list_ass_slice, /* sq_ass_slice */
2415 (objobjproc)list_contains, /* sq_contains */
2416 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2417 (intargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002418};
2419
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002420PyDoc_STRVAR(list_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002421"list() -> new list\n"
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002422"list(sequence) -> new list initialized from sequence's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002423
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002424static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002425list_subscript(PyListObject* self, PyObject* item)
2426{
2427 if (PyInt_Check(item)) {
2428 long i = PyInt_AS_LONG(item);
2429 if (i < 0)
2430 i += PyList_GET_SIZE(self);
2431 return list_item(self, i);
2432 }
2433 else if (PyLong_Check(item)) {
2434 long i = PyLong_AsLong(item);
2435 if (i == -1 && PyErr_Occurred())
2436 return NULL;
2437 if (i < 0)
2438 i += PyList_GET_SIZE(self);
2439 return list_item(self, i);
2440 }
2441 else if (PySlice_Check(item)) {
2442 int start, stop, step, slicelength, cur, i;
2443 PyObject* result;
2444 PyObject* it;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002445 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002446
2447 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
2448 &start, &stop, &step, &slicelength) < 0) {
2449 return NULL;
2450 }
2451
2452 if (slicelength <= 0) {
2453 return PyList_New(0);
2454 }
2455 else {
2456 result = PyList_New(slicelength);
2457 if (!result) return NULL;
2458
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002459 src = self->ob_item;
2460 dest = ((PyListObject *)result)->ob_item;
Tim Peters3b01a122002-07-19 02:35:45 +00002461 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002462 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002463 it = src[cur];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002464 Py_INCREF(it);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002465 dest[i] = it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002466 }
Tim Peters3b01a122002-07-19 02:35:45 +00002467
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002468 return result;
2469 }
2470 }
2471 else {
2472 PyErr_SetString(PyExc_TypeError,
2473 "list indices must be integers");
2474 return NULL;
2475 }
2476}
2477
Tim Peters3b01a122002-07-19 02:35:45 +00002478static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002479list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2480{
2481 if (PyInt_Check(item)) {
2482 long i = PyInt_AS_LONG(item);
2483 if (i < 0)
2484 i += PyList_GET_SIZE(self);
2485 return list_ass_item(self, i, value);
2486 }
2487 else if (PyLong_Check(item)) {
2488 long i = PyLong_AsLong(item);
2489 if (i == -1 && PyErr_Occurred())
2490 return -1;
2491 if (i < 0)
2492 i += PyList_GET_SIZE(self);
2493 return list_ass_item(self, i, value);
2494 }
2495 else if (PySlice_Check(item)) {
2496 int start, stop, step, slicelength;
2497
2498 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
2499 &start, &stop, &step, &slicelength) < 0) {
2500 return -1;
2501 }
2502
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002503 /* treat L[slice(a,b)] = v _exactly_ like L[a:b] = v */
2504 if (step == 1 && ((PySliceObject*)item)->step == Py_None)
2505 return list_ass_slice(self, start, stop, value);
2506
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002507 if (value == NULL) {
2508 /* delete slice */
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002509 PyObject **garbage;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002510 int cur, i;
Tim Peters3b01a122002-07-19 02:35:45 +00002511
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002512 if (slicelength <= 0)
2513 return 0;
2514
2515 if (step < 0) {
2516 stop = start + 1;
2517 start = stop + step*(slicelength - 1) - 1;
2518 step = -step;
2519 }
2520
2521 garbage = (PyObject**)
2522 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Tim Peters3b01a122002-07-19 02:35:45 +00002523
2524 /* drawing pictures might help
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002525 understand these for loops */
Guido van Rossum75a20b12002-06-11 12:22:28 +00002526 for (cur = start, i = 0;
2527 cur < stop;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002528 cur += step, i++) {
2529 int lim = step;
2530
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002531 garbage[i] = PyList_GET_ITEM(self, cur);
2532
Michael W. Hudson56796f62002-07-29 14:35:04 +00002533 if (cur + step >= self->ob_size) {
2534 lim = self->ob_size - cur - 1;
2535 }
2536
Tim Petersb38e2b62004-07-29 02:29:26 +00002537 memmove(self->ob_item + cur - i,
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002538 self->ob_item + cur + 1,
2539 lim * sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002540 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002541
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002542 for (cur = start + slicelength*step + 1;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002543 cur < self->ob_size; cur++) {
2544 PyList_SET_ITEM(self, cur - slicelength,
2545 PyList_GET_ITEM(self, cur));
2546 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002547
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002548 self->ob_size -= slicelength;
Raymond Hettingerd4ff7412004-03-15 09:01:31 +00002549 list_resize(self, self->ob_size);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002550
2551 for (i = 0; i < slicelength; i++) {
2552 Py_DECREF(garbage[i]);
2553 }
2554 PyMem_FREE(garbage);
2555
2556 return 0;
2557 }
2558 else {
2559 /* assign slice */
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002560 PyObject **garbage, *ins, *seq, **seqitems, **selfitems;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002561 int cur, i;
2562
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002563 /* protect against a[::-1] = a */
Tim Peters3b01a122002-07-19 02:35:45 +00002564 if (self == (PyListObject*)value) {
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002565 seq = list_slice((PyListObject*)value, 0,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002566 PyList_GET_SIZE(value));
Tim Peters3b01a122002-07-19 02:35:45 +00002567 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002568 else {
Tim Petersb38e2b62004-07-29 02:29:26 +00002569 seq = PySequence_Fast(value,
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002570 "must assign iterable to extended slice");
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002571 if (!seq)
2572 return -1;
2573 }
2574
2575 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2576 PyErr_Format(PyExc_ValueError,
2577 "attempt to assign sequence of size %d to extended slice of size %d",
2578 PySequence_Fast_GET_SIZE(seq),
2579 slicelength);
2580 Py_DECREF(seq);
2581 return -1;
2582 }
2583
2584 if (!slicelength) {
2585 Py_DECREF(seq);
2586 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002587 }
2588
2589 garbage = (PyObject**)
2590 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Tim Peters3b01a122002-07-19 02:35:45 +00002591
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002592 selfitems = self->ob_item;
Raymond Hettinger42bec932004-03-12 16:38:17 +00002593 seqitems = PySequence_Fast_ITEMS(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002594 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002595 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002596 garbage[i] = selfitems[cur];
2597 ins = seqitems[i];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002598 Py_INCREF(ins);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002599 selfitems[cur] = ins;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002600 }
2601
2602 for (i = 0; i < slicelength; i++) {
2603 Py_DECREF(garbage[i]);
2604 }
Tim Peters3b01a122002-07-19 02:35:45 +00002605
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002606 PyMem_FREE(garbage);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002607 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002608
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002609 return 0;
2610 }
Tim Peters3b01a122002-07-19 02:35:45 +00002611 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002612 else {
Tim Peters3b01a122002-07-19 02:35:45 +00002613 PyErr_SetString(PyExc_TypeError,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002614 "list indices must be integers");
2615 return -1;
2616 }
2617}
2618
2619static PyMappingMethods list_as_mapping = {
2620 (inquiry)list_length,
2621 (binaryfunc)list_subscript,
2622 (objobjargproc)list_ass_subscript
2623};
2624
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002625PyTypeObject PyList_Type = {
2626 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002627 0,
2628 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002629 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002630 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002631 (destructor)list_dealloc, /* tp_dealloc */
2632 (printfunc)list_print, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002633 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002634 0, /* tp_setattr */
2635 0, /* tp_compare */
2636 (reprfunc)list_repr, /* tp_repr */
2637 0, /* tp_as_number */
2638 &list_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002639 &list_as_mapping, /* tp_as_mapping */
Guido van Rossumdbb53d92001-12-03 16:32:18 +00002640 list_nohash, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002641 0, /* tp_call */
2642 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002643 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002644 0, /* tp_setattro */
2645 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002646 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Tim Peters6d6c1a32001-08-02 04:15:00 +00002647 Py_TPFLAGS_BASETYPE, /* tp_flags */
2648 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002649 (traverseproc)list_traverse, /* tp_traverse */
2650 (inquiry)list_clear, /* tp_clear */
2651 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002652 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002653 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002654 0, /* tp_iternext */
2655 list_methods, /* tp_methods */
2656 0, /* tp_members */
2657 0, /* tp_getset */
2658 0, /* tp_base */
2659 0, /* tp_dict */
2660 0, /* tp_descr_get */
2661 0, /* tp_descr_set */
2662 0, /* tp_dictoffset */
2663 (initproc)list_init, /* tp_init */
2664 PyType_GenericAlloc, /* tp_alloc */
2665 PyType_GenericNew, /* tp_new */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002666 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002667};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002668
2669
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002670/*********************** List Iterator **************************/
2671
2672typedef struct {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002673 PyObject_HEAD
2674 long it_index;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002675 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002676} listiterobject;
2677
2678PyTypeObject PyListIter_Type;
2679
Guido van Rossum5086e492002-07-16 15:56:52 +00002680static PyObject *
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002681list_iter(PyObject *seq)
2682{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002683 listiterobject *it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002684
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002685 if (!PyList_Check(seq)) {
2686 PyErr_BadInternalCall();
2687 return NULL;
2688 }
2689 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2690 if (it == NULL)
2691 return NULL;
2692 it->it_index = 0;
2693 Py_INCREF(seq);
2694 it->it_seq = (PyListObject *)seq;
2695 _PyObject_GC_TRACK(it);
2696 return (PyObject *)it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002697}
2698
2699static void
2700listiter_dealloc(listiterobject *it)
2701{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002702 _PyObject_GC_UNTRACK(it);
Guido van Rossum86103ae2002-07-16 20:07:32 +00002703 Py_XDECREF(it->it_seq);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002704 PyObject_GC_Del(it);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002705}
2706
2707static int
2708listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2709{
Guido van Rossum86103ae2002-07-16 20:07:32 +00002710 if (it->it_seq == NULL)
2711 return 0;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002712 return visit((PyObject *)it->it_seq, arg);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002713}
2714
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002715static PyObject *
Tim Peters93b2cc42002-06-01 05:22:55 +00002716listiter_next(listiterobject *it)
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002717{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002718 PyListObject *seq;
2719 PyObject *item;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002720
Tim Peters93b2cc42002-06-01 05:22:55 +00002721 assert(it != NULL);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002722 seq = it->it_seq;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002723 if (seq == NULL)
2724 return NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002725 assert(PyList_Check(seq));
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002726
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002727 if (it->it_index < PyList_GET_SIZE(seq)) {
Tim Peters93b2cc42002-06-01 05:22:55 +00002728 item = PyList_GET_ITEM(seq, it->it_index);
2729 ++it->it_index;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002730 Py_INCREF(item);
2731 return item;
2732 }
Guido van Rossum86103ae2002-07-16 20:07:32 +00002733
2734 Py_DECREF(seq);
2735 it->it_seq = NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002736 return NULL;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002737}
2738
Raymond Hettinger435bf582004-03-18 22:43:10 +00002739static int
2740listiter_len(listiterobject *it)
2741{
Raymond Hettinger40a03822004-04-12 13:05:09 +00002742 int len;
2743 if (it->it_seq) {
2744 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2745 if (len >= 0)
2746 return len;
2747 }
Raymond Hettinger435bf582004-03-18 22:43:10 +00002748 return 0;
2749}
2750
2751static PySequenceMethods listiter_as_sequence = {
2752 (inquiry)listiter_len, /* sq_length */
2753 0, /* sq_concat */
2754};
2755
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002756PyTypeObject PyListIter_Type = {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002757 PyObject_HEAD_INIT(&PyType_Type)
2758 0, /* ob_size */
2759 "listiterator", /* tp_name */
2760 sizeof(listiterobject), /* tp_basicsize */
2761 0, /* tp_itemsize */
2762 /* methods */
2763 (destructor)listiter_dealloc, /* tp_dealloc */
2764 0, /* tp_print */
2765 0, /* tp_getattr */
2766 0, /* tp_setattr */
2767 0, /* tp_compare */
2768 0, /* tp_repr */
2769 0, /* tp_as_number */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002770 &listiter_as_sequence, /* tp_as_sequence */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002771 0, /* tp_as_mapping */
2772 0, /* tp_hash */
2773 0, /* tp_call */
2774 0, /* tp_str */
2775 PyObject_GenericGetAttr, /* tp_getattro */
2776 0, /* tp_setattro */
2777 0, /* tp_as_buffer */
2778 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2779 0, /* tp_doc */
2780 (traverseproc)listiter_traverse, /* tp_traverse */
2781 0, /* tp_clear */
2782 0, /* tp_richcompare */
2783 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00002784 PyObject_SelfIter, /* tp_iter */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002785 (iternextfunc)listiter_next, /* tp_iternext */
Guido van Rossum86103ae2002-07-16 20:07:32 +00002786 0, /* tp_methods */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002787 0, /* tp_members */
2788 0, /* tp_getset */
2789 0, /* tp_base */
2790 0, /* tp_dict */
2791 0, /* tp_descr_get */
2792 0, /* tp_descr_set */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002793};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002794
2795/*********************** List Reverse Iterator **************************/
2796
2797typedef struct {
2798 PyObject_HEAD
2799 long it_index;
Raymond Hettinger001f2282003-11-08 11:58:44 +00002800 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002801} listreviterobject;
2802
2803PyTypeObject PyListRevIter_Type;
2804
2805static PyObject *
2806list_reversed(PyListObject *seq, PyObject *unused)
2807{
2808 listreviterobject *it;
2809
2810 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2811 if (it == NULL)
2812 return NULL;
2813 assert(PyList_Check(seq));
2814 it->it_index = PyList_GET_SIZE(seq) - 1;
2815 Py_INCREF(seq);
2816 it->it_seq = seq;
2817 PyObject_GC_Track(it);
2818 return (PyObject *)it;
2819}
2820
2821static void
2822listreviter_dealloc(listreviterobject *it)
2823{
2824 PyObject_GC_UnTrack(it);
2825 Py_XDECREF(it->it_seq);
2826 PyObject_GC_Del(it);
2827}
2828
2829static int
2830listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2831{
2832 if (it->it_seq == NULL)
2833 return 0;
2834 return visit((PyObject *)it->it_seq, arg);
2835}
2836
2837static PyObject *
2838listreviter_next(listreviterobject *it)
2839{
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002840 PyObject *item;
2841 long index = it->it_index;
2842 PyListObject *seq = it->it_seq;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002843
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002844 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2845 item = PyList_GET_ITEM(seq, index);
Raymond Hettinger1021c442003-11-07 15:38:09 +00002846 it->it_index--;
2847 Py_INCREF(item);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002848 return item;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002849 }
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002850 it->it_index = -1;
2851 if (seq != NULL) {
2852 it->it_seq = NULL;
2853 Py_DECREF(seq);
2854 }
2855 return NULL;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002856}
2857
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002858static int
2859listreviter_len(listreviterobject *it)
2860{
Raymond Hettinger40a03822004-04-12 13:05:09 +00002861 int len = it->it_index + 1;
2862 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
2863 return 0;
2864 return len;
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002865}
2866
2867static PySequenceMethods listreviter_as_sequence = {
2868 (inquiry)listreviter_len, /* sq_length */
2869 0, /* sq_concat */
2870};
2871
Raymond Hettinger1021c442003-11-07 15:38:09 +00002872PyTypeObject PyListRevIter_Type = {
2873 PyObject_HEAD_INIT(&PyType_Type)
2874 0, /* ob_size */
2875 "listreverseiterator", /* tp_name */
2876 sizeof(listreviterobject), /* tp_basicsize */
2877 0, /* tp_itemsize */
2878 /* methods */
2879 (destructor)listreviter_dealloc, /* tp_dealloc */
2880 0, /* tp_print */
2881 0, /* tp_getattr */
2882 0, /* tp_setattr */
2883 0, /* tp_compare */
2884 0, /* tp_repr */
2885 0, /* tp_as_number */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002886 &listreviter_as_sequence, /* tp_as_sequence */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002887 0, /* tp_as_mapping */
2888 0, /* tp_hash */
2889 0, /* tp_call */
2890 0, /* tp_str */
2891 PyObject_GenericGetAttr, /* tp_getattro */
2892 0, /* tp_setattro */
2893 0, /* tp_as_buffer */
2894 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2895 0, /* tp_doc */
2896 (traverseproc)listreviter_traverse, /* tp_traverse */
2897 0, /* tp_clear */
2898 0, /* tp_richcompare */
2899 0, /* tp_weaklistoffset */
2900 PyObject_SelfIter, /* tp_iter */
2901 (iternextfunc)listreviter_next, /* tp_iternext */
2902 0,
2903};