blob: 44616e56a031be77b884cc214d6f2d6153bba3fd [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 Hettingeraa241e02004-09-26 19:24:20 +0000772 if (mn >= m) {
773 /* Make room. */
774 if (list_resize(self, mn) == -1)
775 goto error;
776 /* Make the list sane again. */
777 self->ob_size = m;
778 }
779 /* Else m + n overflowed; on the chance that n lied, and there really
780 * is enough room, ignore it. If n was telling the truth, we'll
781 * eventually run out of memory during the loop.
782 */
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000783
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000784 /* Run iterator to exhaustion. */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000785 for (;;) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000786 PyObject *item = iternext(it);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000787 if (item == NULL) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000788 if (PyErr_Occurred()) {
789 if (PyErr_ExceptionMatches(PyExc_StopIteration))
790 PyErr_Clear();
791 else
792 goto error;
793 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000794 break;
795 }
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000796 if (self->ob_size < self->allocated) {
797 /* steals ref */
798 PyList_SET_ITEM(self, self->ob_size, item);
799 ++self->ob_size;
800 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000801 else {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000802 int status = app1(self, item);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000803 Py_DECREF(item); /* append creates a new ref */
804 if (status < 0)
805 goto error;
806 }
807 }
808
809 /* Cut back result list if initial guess was too large. */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000810 if (self->ob_size < self->allocated)
811 list_resize(self, self->ob_size); /* shrinking can't fail */
812
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000813 Py_DECREF(it);
814 Py_RETURN_NONE;
815
816 error:
817 Py_DECREF(it);
818 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000819}
820
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000821PyObject *
822_PyList_Extend(PyListObject *self, PyObject *b)
823{
824 return listextend(self, b);
825}
826
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000827static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000828list_inplace_concat(PyListObject *self, PyObject *other)
829{
830 PyObject *result;
831
832 result = listextend(self, other);
833 if (result == NULL)
834 return result;
835 Py_DECREF(result);
836 Py_INCREF(self);
837 return (PyObject *)self;
838}
839
840static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000841listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000842{
843 int i = -1;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000844 PyObject *v, *arg = NULL;
Tim Peters8fc4a912004-07-31 21:53:19 +0000845 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000846
847 if (!PyArg_UnpackTuple(args, "pop", 0, 1, &arg))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000848 return NULL;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000849 if (arg != NULL) {
850 if (PyInt_Check(arg))
851 i = (int)(PyInt_AS_LONG((PyIntObject*) arg));
Raymond Hettingerfa6c6f82004-02-19 06:12:06 +0000852 else if (!PyArg_ParseTuple(args, "|i:pop", &i))
853 return NULL;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000854 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000855 if (self->ob_size == 0) {
856 /* Special-case most common failure cause */
857 PyErr_SetString(PyExc_IndexError, "pop from empty list");
858 return NULL;
859 }
860 if (i < 0)
861 i += self->ob_size;
862 if (i < 0 || i >= self->ob_size) {
863 PyErr_SetString(PyExc_IndexError, "pop index out of range");
864 return NULL;
865 }
866 v = self->ob_item[i];
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000867 if (i == self->ob_size - 1) {
Tim Peters8fc4a912004-07-31 21:53:19 +0000868 status = list_resize(self, self->ob_size - 1);
869 assert(status >= 0);
870 return v; /* and v now owns the reference the list had */
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000871 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000872 Py_INCREF(v);
Tim Peters8fc4a912004-07-31 21:53:19 +0000873 status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
874 assert(status >= 0);
875 /* Use status, so that in a release build compilers don't
876 * complain about the unused name.
877 */
Brett Cannon651dd522004-08-08 21:21:18 +0000878 (void) status;
879
880 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000881}
882
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000883/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
884static void
885reverse_slice(PyObject **lo, PyObject **hi)
886{
887 assert(lo && hi);
888
889 --hi;
890 while (lo < hi) {
891 PyObject *t = *lo;
892 *lo = *hi;
893 *hi = t;
894 ++lo;
895 --hi;
896 }
897}
898
Tim Petersa64dc242002-08-01 02:13:36 +0000899/* Lots of code for an adaptive, stable, natural mergesort. There are many
900 * pieces to this algorithm; read listsort.txt for overviews and details.
901 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000902
Guido van Rossum3f236de1996-12-10 23:55:39 +0000903/* Comparison function. Takes care of calling a user-supplied
Tim Peters66860f62002-08-04 17:47:26 +0000904 * comparison function (any callable Python object), which must not be
905 * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool
906 * with Py_LT if you know it's NULL).
Tim Petersa64dc242002-08-01 02:13:36 +0000907 * Returns -1 on error, 1 if x < y, 0 if x >= y.
908 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000909static int
Tim Petersa8c974c2002-07-19 03:30:57 +0000910islt(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000911{
Tim Petersf2a04732002-07-11 21:46:16 +0000912 PyObject *res;
913 PyObject *args;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000914 int i;
915
Tim Peters66860f62002-08-04 17:47:26 +0000916 assert(compare != NULL);
Tim Petersa8c974c2002-07-19 03:30:57 +0000917 /* Call the user's comparison function and translate the 3-way
918 * result into true or false (or error).
919 */
Tim Petersf2a04732002-07-11 21:46:16 +0000920 args = PyTuple_New(2);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000921 if (args == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000922 return -1;
Tim Petersf2a04732002-07-11 21:46:16 +0000923 Py_INCREF(x);
924 Py_INCREF(y);
925 PyTuple_SET_ITEM(args, 0, x);
926 PyTuple_SET_ITEM(args, 1, y);
Tim Peters58cf3612002-07-15 05:16:13 +0000927 res = PyObject_Call(compare, args, NULL);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000928 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000929 if (res == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000930 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000931 if (!PyInt_Check(res)) {
932 Py_DECREF(res);
933 PyErr_SetString(PyExc_TypeError,
Guido van Rossum9bcd1d71999-04-19 17:44:39 +0000934 "comparison function must return int");
Tim Petersa8c974c2002-07-19 03:30:57 +0000935 return -1;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000936 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000937 i = PyInt_AsLong(res);
938 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +0000939 return i < 0;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000940}
941
Tim Peters66860f62002-08-04 17:47:26 +0000942/* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
943 * islt. This avoids a layer of function call in the usual case, and
944 * sorting does many comparisons.
945 * Returns -1 on error, 1 if x < y, 0 if x >= y.
946 */
947#define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
948 PyObject_RichCompareBool(X, Y, Py_LT) : \
949 islt(X, Y, COMPARE))
950
951/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +0000952 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
953 started. It makes more sense in context <wink>. X and Y are PyObject*s.
954*/
Tim Peters66860f62002-08-04 17:47:26 +0000955#define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
Tim Petersa8c974c2002-07-19 03:30:57 +0000956 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000957
958/* binarysort is the best method for sorting small arrays: it does
959 few compares, but can do data movement quadratic in the number of
960 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000961 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +0000962 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000963 On entry, must have lo <= start <= hi, and that [lo, start) is already
964 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +0000965 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000966 Even in case of error, the output slice will be some permutation of
967 the input (nothing is lost or duplicated).
968*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000969static int
Fred Drakea2f55112000-07-09 15:16:51 +0000970binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
971 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000972{
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000973 register int k;
974 register PyObject **l, **p, **r;
975 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000976
Tim Petersa8c974c2002-07-19 03:30:57 +0000977 assert(lo <= start && start <= hi);
978 /* assert [lo, start) is sorted */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000979 if (lo == start)
980 ++start;
981 for (; start < hi; ++start) {
982 /* set l to where *start belongs */
983 l = lo;
984 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000985 pivot = *r;
Tim Peters0fe977c2002-07-19 06:12:32 +0000986 /* Invariants:
987 * pivot >= all in [lo, l).
988 * pivot < all in [r, start).
989 * The second is vacuously true at the start.
990 */
991 assert(l < r);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000992 do {
993 p = l + ((r - l) >> 1);
Tim Petersa8c974c2002-07-19 03:30:57 +0000994 IFLT(pivot, *p)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000995 r = p;
996 else
Tim Peters0fe977c2002-07-19 06:12:32 +0000997 l = p+1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000998 } while (l < r);
Tim Peters0fe977c2002-07-19 06:12:32 +0000999 assert(l == r);
1000 /* The invariants still hold, so pivot >= all in [lo, l) and
1001 pivot < all in [l, start), so pivot belongs at l. Note
1002 that if there are elements equal to pivot, l points to the
1003 first slot after them -- that's why this sort is stable.
1004 Slide over to make room.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001005 Caution: using memmove is much slower under MSVC 5;
1006 we're not usually moving many slots. */
1007 for (p = start; p > l; --p)
1008 *p = *(p-1);
1009 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001010 }
Guido van Rossum3f236de1996-12-10 23:55:39 +00001011 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001012
1013 fail:
1014 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001015}
1016
Tim Petersa64dc242002-08-01 02:13:36 +00001017/*
1018Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1019is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001020
Tim Petersa64dc242002-08-01 02:13:36 +00001021 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001022
Tim Petersa64dc242002-08-01 02:13:36 +00001023or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001024
Tim Petersa64dc242002-08-01 02:13:36 +00001025 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001026
Tim Petersa64dc242002-08-01 02:13:36 +00001027Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1028For its intended use in a stable mergesort, the strictness of the defn of
1029"descending" is needed so that the caller can safely reverse a descending
1030sequence without violating stability (strict > ensures there are no equal
1031elements to get out of order).
1032
1033Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001034*/
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001035static int
Tim Petersa64dc242002-08-01 02:13:36 +00001036count_run(PyObject **lo, PyObject **hi, PyObject *compare, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001037{
Tim Petersa64dc242002-08-01 02:13:36 +00001038 int k;
1039 int n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001040
Tim Petersa64dc242002-08-01 02:13:36 +00001041 assert(lo < hi);
1042 *descending = 0;
1043 ++lo;
1044 if (lo == hi)
1045 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001046
Tim Petersa64dc242002-08-01 02:13:36 +00001047 n = 2;
1048 IFLT(*lo, *(lo-1)) {
1049 *descending = 1;
1050 for (lo = lo+1; lo < hi; ++lo, ++n) {
1051 IFLT(*lo, *(lo-1))
1052 ;
1053 else
1054 break;
1055 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001056 }
Tim Petersa64dc242002-08-01 02:13:36 +00001057 else {
1058 for (lo = lo+1; lo < hi; ++lo, ++n) {
1059 IFLT(*lo, *(lo-1))
1060 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001061 }
1062 }
1063
Tim Petersa64dc242002-08-01 02:13:36 +00001064 return n;
1065fail:
1066 return -1;
1067}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001068
Tim Petersa64dc242002-08-01 02:13:36 +00001069/*
1070Locate the proper position of key in a sorted vector; if the vector contains
1071an element equal to key, return the position immediately to the left of
1072the leftmost equal element. [gallop_right() does the same except returns
1073the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001074
Tim Petersa64dc242002-08-01 02:13:36 +00001075"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001076
Tim Petersa64dc242002-08-01 02:13:36 +00001077"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1078hint is to the final result, the faster this runs.
1079
1080The return value is the int k in 0..n such that
1081
1082 a[k-1] < key <= a[k]
1083
1084pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1085key belongs at index k; or, IOW, the first k elements of a should precede
1086key, and the last n-k should follow key.
1087
1088Returns -1 on error. See listsort.txt for info on the method.
1089*/
1090static int
1091gallop_left(PyObject *key, PyObject **a, int n, int hint, PyObject *compare)
1092{
1093 int ofs;
1094 int lastofs;
1095 int k;
1096
1097 assert(key && a && n > 0 && hint >= 0 && hint < n);
1098
1099 a += hint;
1100 lastofs = 0;
1101 ofs = 1;
1102 IFLT(*a, key) {
1103 /* a[hint] < key -- gallop right, until
1104 * a[hint + lastofs] < key <= a[hint + ofs]
1105 */
1106 const int maxofs = n - hint; /* &a[n-1] is highest */
1107 while (ofs < maxofs) {
1108 IFLT(a[ofs], key) {
1109 lastofs = ofs;
1110 ofs = (ofs << 1) + 1;
1111 if (ofs <= 0) /* int overflow */
1112 ofs = maxofs;
1113 }
1114 else /* key <= a[hint + ofs] */
1115 break;
1116 }
1117 if (ofs > maxofs)
1118 ofs = maxofs;
1119 /* Translate back to offsets relative to &a[0]. */
1120 lastofs += hint;
1121 ofs += hint;
1122 }
1123 else {
1124 /* key <= a[hint] -- gallop left, until
1125 * a[hint - ofs] < key <= a[hint - lastofs]
1126 */
1127 const int maxofs = hint + 1; /* &a[0] is lowest */
1128 while (ofs < maxofs) {
1129 IFLT(*(a-ofs), key)
1130 break;
1131 /* key <= a[hint - ofs] */
1132 lastofs = ofs;
1133 ofs = (ofs << 1) + 1;
1134 if (ofs <= 0) /* int overflow */
1135 ofs = maxofs;
1136 }
1137 if (ofs > maxofs)
1138 ofs = maxofs;
1139 /* Translate back to positive offsets relative to &a[0]. */
1140 k = lastofs;
1141 lastofs = hint - ofs;
1142 ofs = hint - k;
1143 }
1144 a -= hint;
1145
1146 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1147 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1148 * right of lastofs but no farther right than ofs. Do a binary
1149 * search, with invariant a[lastofs-1] < key <= a[ofs].
1150 */
1151 ++lastofs;
1152 while (lastofs < ofs) {
1153 int m = lastofs + ((ofs - lastofs) >> 1);
1154
1155 IFLT(a[m], key)
1156 lastofs = m+1; /* a[m] < key */
1157 else
1158 ofs = m; /* key <= a[m] */
1159 }
1160 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1161 return ofs;
1162
1163fail:
1164 return -1;
1165}
1166
1167/*
1168Exactly like gallop_left(), except that if key already exists in a[0:n],
1169finds the position immediately to the right of the rightmost equal value.
1170
1171The return value is the int k in 0..n such that
1172
1173 a[k-1] <= key < a[k]
1174
1175or -1 if error.
1176
1177The code duplication is massive, but this is enough different given that
1178we're sticking to "<" comparisons that it's much harder to follow if
1179written as one routine with yet another "left or right?" flag.
1180*/
1181static int
1182gallop_right(PyObject *key, PyObject **a, int n, int hint, PyObject *compare)
1183{
1184 int ofs;
1185 int lastofs;
1186 int k;
1187
1188 assert(key && a && n > 0 && hint >= 0 && hint < n);
1189
1190 a += hint;
1191 lastofs = 0;
1192 ofs = 1;
1193 IFLT(key, *a) {
1194 /* key < a[hint] -- gallop left, until
1195 * a[hint - ofs] <= key < a[hint - lastofs]
1196 */
1197 const int maxofs = hint + 1; /* &a[0] is lowest */
1198 while (ofs < maxofs) {
1199 IFLT(key, *(a-ofs)) {
1200 lastofs = ofs;
1201 ofs = (ofs << 1) + 1;
1202 if (ofs <= 0) /* int overflow */
1203 ofs = maxofs;
1204 }
1205 else /* a[hint - ofs] <= key */
1206 break;
1207 }
1208 if (ofs > maxofs)
1209 ofs = maxofs;
1210 /* Translate back to positive offsets relative to &a[0]. */
1211 k = lastofs;
1212 lastofs = hint - ofs;
1213 ofs = hint - k;
1214 }
1215 else {
1216 /* a[hint] <= key -- gallop right, until
1217 * a[hint + lastofs] <= key < a[hint + ofs]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001218 */
Tim Petersa64dc242002-08-01 02:13:36 +00001219 const int maxofs = n - hint; /* &a[n-1] is highest */
1220 while (ofs < maxofs) {
1221 IFLT(key, a[ofs])
1222 break;
1223 /* a[hint + ofs] <= key */
1224 lastofs = ofs;
1225 ofs = (ofs << 1) + 1;
1226 if (ofs <= 0) /* int overflow */
1227 ofs = maxofs;
1228 }
1229 if (ofs > maxofs)
1230 ofs = maxofs;
1231 /* Translate back to offsets relative to &a[0]. */
1232 lastofs += hint;
1233 ofs += hint;
1234 }
1235 a -= hint;
1236
1237 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1238 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1239 * right of lastofs but no farther right than ofs. Do a binary
1240 * search, with invariant a[lastofs-1] <= key < a[ofs].
1241 */
1242 ++lastofs;
1243 while (lastofs < ofs) {
1244 int m = lastofs + ((ofs - lastofs) >> 1);
1245
1246 IFLT(key, a[m])
1247 ofs = m; /* key < a[m] */
1248 else
1249 lastofs = m+1; /* a[m] <= key */
1250 }
1251 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1252 return ofs;
1253
1254fail:
1255 return -1;
1256}
1257
1258/* The maximum number of entries in a MergeState's pending-runs stack.
1259 * This is enough to sort arrays of size up to about
1260 * 32 * phi ** MAX_MERGE_PENDING
1261 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1262 * with 2**64 elements.
1263 */
1264#define MAX_MERGE_PENDING 85
1265
Tim Peterse05f65a2002-08-10 05:21:15 +00001266/* When we get into galloping mode, we stay there until both runs win less
1267 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001268 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001269#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001270
1271/* Avoid malloc for small temp arrays. */
1272#define MERGESTATE_TEMP_SIZE 256
1273
1274/* One MergeState exists on the stack per invocation of mergesort. It's just
1275 * a convenient way to pass state around among the helper functions.
1276 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001277struct s_slice {
1278 PyObject **base;
1279 int len;
1280};
1281
Tim Petersa64dc242002-08-01 02:13:36 +00001282typedef struct s_MergeState {
1283 /* The user-supplied comparison function. or NULL if none given. */
1284 PyObject *compare;
1285
Tim Peterse05f65a2002-08-10 05:21:15 +00001286 /* This controls when we get *into* galloping mode. It's initialized
1287 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1288 * random data, and lower for highly structured data.
1289 */
1290 int min_gallop;
1291
Tim Petersa64dc242002-08-01 02:13:36 +00001292 /* 'a' is temp storage to help with merges. It contains room for
1293 * alloced entries.
1294 */
1295 PyObject **a; /* may point to temparray below */
1296 int alloced;
1297
1298 /* A stack of n pending runs yet to be merged. Run #i starts at
1299 * address base[i] and extends for len[i] elements. It's always
1300 * true (so long as the indices are in bounds) that
1301 *
Tim Peterse05f65a2002-08-10 05:21:15 +00001302 * pending[i].base + pending[i].len == pending[i+1].base
Tim Petersa64dc242002-08-01 02:13:36 +00001303 *
1304 * so we could cut the storage for this, but it's a minor amount,
1305 * and keeping all the info explicit simplifies the code.
1306 */
1307 int n;
Tim Peterse05f65a2002-08-10 05:21:15 +00001308 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001309
1310 /* 'a' points to this when possible, rather than muck with malloc. */
1311 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1312} MergeState;
1313
1314/* Conceptually a MergeState's constructor. */
1315static void
1316merge_init(MergeState *ms, PyObject *compare)
1317{
1318 assert(ms != NULL);
1319 ms->compare = compare;
1320 ms->a = ms->temparray;
1321 ms->alloced = MERGESTATE_TEMP_SIZE;
1322 ms->n = 0;
Tim Peterse05f65a2002-08-10 05:21:15 +00001323 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001324}
1325
1326/* Free all the temp memory owned by the MergeState. This must be called
1327 * when you're done with a MergeState, and may be called before then if
1328 * you want to free the temp memory early.
1329 */
1330static void
1331merge_freemem(MergeState *ms)
1332{
1333 assert(ms != NULL);
1334 if (ms->a != ms->temparray)
1335 PyMem_Free(ms->a);
1336 ms->a = ms->temparray;
1337 ms->alloced = MERGESTATE_TEMP_SIZE;
1338}
1339
1340/* Ensure enough temp memory for 'need' array slots is available.
1341 * Returns 0 on success and -1 if the memory can't be gotten.
1342 */
1343static int
1344merge_getmem(MergeState *ms, int need)
1345{
1346 assert(ms != NULL);
1347 if (need <= ms->alloced)
1348 return 0;
1349 /* Don't realloc! That can cost cycles to copy the old data, but
1350 * we don't care what's in the block.
1351 */
1352 merge_freemem(ms);
1353 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1354 if (ms->a) {
1355 ms->alloced = need;
1356 return 0;
1357 }
1358 PyErr_NoMemory();
1359 merge_freemem(ms); /* reset to sane state */
1360 return -1;
1361}
1362#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1363 merge_getmem(MS, NEED))
1364
1365/* Merge the na elements starting at pa with the nb elements starting at pb
1366 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1367 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1368 * merge, and should have na <= nb. See listsort.txt for more info.
1369 * Return 0 if successful, -1 if error.
1370 */
1371static int
1372merge_lo(MergeState *ms, PyObject **pa, int na, PyObject **pb, int nb)
1373{
1374 int k;
1375 PyObject *compare;
1376 PyObject **dest;
1377 int result = -1; /* guilty until proved innocent */
Tim Peterse05f65a2002-08-10 05:21:15 +00001378 int min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001379
1380 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1381 if (MERGE_GETMEM(ms, na) < 0)
1382 return -1;
1383 memcpy(ms->a, pa, na * sizeof(PyObject*));
1384 dest = pa;
1385 pa = ms->a;
1386
1387 *dest++ = *pb++;
1388 --nb;
1389 if (nb == 0)
1390 goto Succeed;
1391 if (na == 1)
1392 goto CopyB;
1393
1394 compare = ms->compare;
1395 for (;;) {
1396 int acount = 0; /* # of times A won in a row */
1397 int bcount = 0; /* # of times B won in a row */
1398
1399 /* Do the straightforward thing until (if ever) one run
1400 * appears to win consistently.
1401 */
1402 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001403 assert(na > 1 && nb > 0);
Tim Peters66860f62002-08-04 17:47:26 +00001404 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001405 if (k) {
1406 if (k < 0)
1407 goto Fail;
1408 *dest++ = *pb++;
1409 ++bcount;
1410 acount = 0;
1411 --nb;
1412 if (nb == 0)
1413 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001414 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001415 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001416 }
1417 else {
Tim Petersa64dc242002-08-01 02:13:36 +00001418 *dest++ = *pa++;
1419 ++acount;
1420 bcount = 0;
1421 --na;
1422 if (na == 1)
1423 goto CopyB;
Tim Peterse05f65a2002-08-10 05:21:15 +00001424 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001425 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001426 }
Tim Petersa64dc242002-08-01 02:13:36 +00001427 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001428
Tim Petersa64dc242002-08-01 02:13:36 +00001429 /* One run is winning so consistently that galloping may
1430 * be a huge win. So try that, and continue galloping until
1431 * (if ever) neither run appears to be winning consistently
1432 * anymore.
1433 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001434 ++min_gallop;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001435 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001436 assert(na > 1 && nb > 0);
1437 min_gallop -= min_gallop > 1;
1438 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001439 k = gallop_right(*pb, pa, na, 0, compare);
1440 acount = k;
1441 if (k) {
1442 if (k < 0)
1443 goto Fail;
1444 memcpy(dest, pa, k * sizeof(PyObject *));
1445 dest += k;
1446 pa += k;
1447 na -= k;
1448 if (na == 1)
1449 goto CopyB;
1450 /* na==0 is impossible now if the comparison
1451 * function is consistent, but we can't assume
1452 * that it is.
1453 */
1454 if (na == 0)
1455 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001456 }
Tim Petersa64dc242002-08-01 02:13:36 +00001457 *dest++ = *pb++;
1458 --nb;
1459 if (nb == 0)
1460 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001461
Tim Petersa64dc242002-08-01 02:13:36 +00001462 k = gallop_left(*pa, pb, nb, 0, compare);
1463 bcount = k;
1464 if (k) {
1465 if (k < 0)
1466 goto Fail;
1467 memmove(dest, pb, k * sizeof(PyObject *));
1468 dest += k;
1469 pb += k;
1470 nb -= k;
1471 if (nb == 0)
1472 goto Succeed;
1473 }
1474 *dest++ = *pa++;
1475 --na;
1476 if (na == 1)
1477 goto CopyB;
1478 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001479 ++min_gallop; /* penalize it for leaving galloping mode */
1480 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001481 }
1482Succeed:
1483 result = 0;
1484Fail:
1485 if (na)
1486 memcpy(dest, pa, na * sizeof(PyObject*));
1487 return result;
1488CopyB:
1489 assert(na == 1 && nb > 0);
1490 /* The last element of pa belongs at the end of the merge. */
1491 memmove(dest, pb, nb * sizeof(PyObject *));
1492 dest[nb] = *pa;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001493 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001494}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001495
Tim Petersa64dc242002-08-01 02:13:36 +00001496/* Merge the na elements starting at pa with the nb elements starting at pb
1497 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1498 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1499 * merge, and should have na >= nb. See listsort.txt for more info.
1500 * Return 0 if successful, -1 if error.
1501 */
1502static int
1503merge_hi(MergeState *ms, PyObject **pa, int na, PyObject **pb, int nb)
1504{
1505 int k;
1506 PyObject *compare;
1507 PyObject **dest;
1508 int result = -1; /* guilty until proved innocent */
1509 PyObject **basea;
1510 PyObject **baseb;
Tim Peterse05f65a2002-08-10 05:21:15 +00001511 int min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001512
1513 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1514 if (MERGE_GETMEM(ms, nb) < 0)
1515 return -1;
1516 dest = pb + nb - 1;
1517 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1518 basea = pa;
1519 baseb = ms->a;
1520 pb = ms->a + nb - 1;
1521 pa += na - 1;
1522
1523 *dest-- = *pa--;
1524 --na;
1525 if (na == 0)
1526 goto Succeed;
1527 if (nb == 1)
1528 goto CopyA;
1529
1530 compare = ms->compare;
1531 for (;;) {
1532 int acount = 0; /* # of times A won in a row */
1533 int bcount = 0; /* # of times B won in a row */
1534
1535 /* Do the straightforward thing until (if ever) one run
1536 * appears to win consistently.
1537 */
1538 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001539 assert(na > 0 && nb > 1);
Tim Peters66860f62002-08-04 17:47:26 +00001540 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001541 if (k) {
1542 if (k < 0)
1543 goto Fail;
1544 *dest-- = *pa--;
1545 ++acount;
1546 bcount = 0;
1547 --na;
1548 if (na == 0)
1549 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001550 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001551 break;
1552 }
1553 else {
1554 *dest-- = *pb--;
1555 ++bcount;
1556 acount = 0;
1557 --nb;
1558 if (nb == 1)
1559 goto CopyA;
Tim Peterse05f65a2002-08-10 05:21:15 +00001560 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001561 break;
1562 }
1563 }
1564
1565 /* One run is winning so consistently that galloping may
1566 * be a huge win. So try that, and continue galloping until
1567 * (if ever) neither run appears to be winning consistently
1568 * anymore.
1569 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001570 ++min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001571 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001572 assert(na > 0 && nb > 1);
1573 min_gallop -= min_gallop > 1;
1574 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001575 k = gallop_right(*pb, basea, na, na-1, compare);
1576 if (k < 0)
1577 goto Fail;
1578 k = na - k;
1579 acount = k;
1580 if (k) {
1581 dest -= k;
1582 pa -= k;
1583 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1584 na -= k;
1585 if (na == 0)
1586 goto Succeed;
1587 }
1588 *dest-- = *pb--;
1589 --nb;
1590 if (nb == 1)
1591 goto CopyA;
1592
1593 k = gallop_left(*pa, baseb, nb, nb-1, compare);
1594 if (k < 0)
1595 goto Fail;
1596 k = nb - k;
1597 bcount = k;
1598 if (k) {
1599 dest -= k;
1600 pb -= k;
1601 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1602 nb -= k;
1603 if (nb == 1)
1604 goto CopyA;
1605 /* nb==0 is impossible now if the comparison
1606 * function is consistent, but we can't assume
1607 * that it is.
1608 */
1609 if (nb == 0)
1610 goto Succeed;
1611 }
1612 *dest-- = *pa--;
1613 --na;
1614 if (na == 0)
1615 goto Succeed;
1616 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001617 ++min_gallop; /* penalize it for leaving galloping mode */
1618 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001619 }
1620Succeed:
1621 result = 0;
1622Fail:
1623 if (nb)
1624 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1625 return result;
1626CopyA:
1627 assert(nb == 1 && na > 0);
1628 /* The first element of pb belongs at the front of the merge. */
1629 dest -= na;
1630 pa -= na;
1631 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1632 *dest = *pb;
1633 return 0;
1634}
1635
1636/* Merge the two runs at stack indices i and i+1.
1637 * Returns 0 on success, -1 on error.
1638 */
1639static int
1640merge_at(MergeState *ms, int i)
1641{
1642 PyObject **pa, **pb;
1643 int na, nb;
1644 int k;
1645 PyObject *compare;
1646
1647 assert(ms != NULL);
1648 assert(ms->n >= 2);
1649 assert(i >= 0);
1650 assert(i == ms->n - 2 || i == ms->n - 3);
1651
Tim Peterse05f65a2002-08-10 05:21:15 +00001652 pa = ms->pending[i].base;
1653 na = ms->pending[i].len;
1654 pb = ms->pending[i+1].base;
1655 nb = ms->pending[i+1].len;
Tim Petersa64dc242002-08-01 02:13:36 +00001656 assert(na > 0 && nb > 0);
1657 assert(pa + na == pb);
1658
1659 /* Record the length of the combined runs; if i is the 3rd-last
1660 * run now, also slide over the last run (which isn't involved
1661 * in this merge). The current run i+1 goes away in any case.
1662 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001663 ms->pending[i].len = na + nb;
1664 if (i == ms->n - 3)
1665 ms->pending[i+1] = ms->pending[i+2];
Tim Petersa64dc242002-08-01 02:13:36 +00001666 --ms->n;
1667
1668 /* Where does b start in a? Elements in a before that can be
1669 * ignored (already in place).
1670 */
1671 compare = ms->compare;
1672 k = gallop_right(*pb, pa, na, 0, compare);
1673 if (k < 0)
1674 return -1;
1675 pa += k;
1676 na -= k;
1677 if (na == 0)
1678 return 0;
1679
1680 /* Where does a end in b? Elements in b after that can be
1681 * ignored (already in place).
1682 */
1683 nb = gallop_left(pa[na-1], pb, nb, nb-1, compare);
1684 if (nb <= 0)
1685 return nb;
1686
1687 /* Merge what remains of the runs, using a temp array with
1688 * min(na, nb) elements.
1689 */
1690 if (na <= nb)
1691 return merge_lo(ms, pa, na, pb, nb);
1692 else
1693 return merge_hi(ms, pa, na, pb, nb);
1694}
1695
1696/* Examine the stack of runs waiting to be merged, merging adjacent runs
1697 * until the stack invariants are re-established:
1698 *
1699 * 1. len[-3] > len[-2] + len[-1]
1700 * 2. len[-2] > len[-1]
1701 *
1702 * See listsort.txt for more info.
1703 *
1704 * Returns 0 on success, -1 on error.
1705 */
1706static int
1707merge_collapse(MergeState *ms)
1708{
Tim Peterse05f65a2002-08-10 05:21:15 +00001709 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001710
1711 assert(ms);
1712 while (ms->n > 1) {
1713 int n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001714 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1715 if (p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001716 --n;
1717 if (merge_at(ms, n) < 0)
1718 return -1;
1719 }
Tim Peterse05f65a2002-08-10 05:21:15 +00001720 else if (p[n].len <= p[n+1].len) {
Tim Petersa64dc242002-08-01 02:13:36 +00001721 if (merge_at(ms, n) < 0)
1722 return -1;
1723 }
1724 else
1725 break;
1726 }
1727 return 0;
1728}
1729
1730/* Regardless of invariants, merge all runs on the stack until only one
1731 * remains. This is used at the end of the mergesort.
1732 *
1733 * Returns 0 on success, -1 on error.
1734 */
1735static int
1736merge_force_collapse(MergeState *ms)
1737{
Tim Peterse05f65a2002-08-10 05:21:15 +00001738 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001739
1740 assert(ms);
1741 while (ms->n > 1) {
1742 int n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001743 if (n > 0 && p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001744 --n;
1745 if (merge_at(ms, n) < 0)
1746 return -1;
1747 }
1748 return 0;
1749}
1750
1751/* Compute a good value for the minimum run length; natural runs shorter
1752 * than this are boosted artificially via binary insertion.
1753 *
1754 * If n < 64, return n (it's too small to bother with fancy stuff).
1755 * Else if n is an exact power of 2, return 32.
1756 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1757 * strictly less than, an exact power of 2.
1758 *
1759 * See listsort.txt for more info.
1760 */
1761static int
1762merge_compute_minrun(int n)
1763{
1764 int r = 0; /* becomes 1 if any 1 bits are shifted off */
1765
1766 assert(n >= 0);
1767 while (n >= 64) {
1768 r |= n & 1;
1769 n >>= 1;
1770 }
1771 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001772}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001773
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001774/* Special wrapper to support stable sorting using the decorate-sort-undecorate
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001775 pattern. Holds a key which is used for comparisons and the original record
Tim Petersb38e2b62004-07-29 02:29:26 +00001776 which is returned during the undecorate phase. By exposing only the key
1777 during comparisons, the underlying sort stability characteristics are left
1778 unchanged. Also, if a custom comparison function is used, it will only see
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001779 the key instead of a full record. */
1780
1781typedef struct {
1782 PyObject_HEAD
1783 PyObject *key;
1784 PyObject *value;
1785} sortwrapperobject;
1786
1787static PyTypeObject sortwrapper_type;
1788
1789static PyObject *
1790sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
1791{
1792 if (!PyObject_TypeCheck(b, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001793 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001794 "expected a sortwrapperobject");
1795 return NULL;
1796 }
1797 return PyObject_RichCompare(a->key, b->key, op);
1798}
1799
1800static void
1801sortwrapper_dealloc(sortwrapperobject *so)
1802{
1803 Py_XDECREF(so->key);
1804 Py_XDECREF(so->value);
1805 PyObject_Del(so);
1806}
1807
1808PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
1809
1810static PyTypeObject sortwrapper_type = {
1811 PyObject_HEAD_INIT(&PyType_Type)
1812 0, /* ob_size */
1813 "sortwrapper", /* tp_name */
1814 sizeof(sortwrapperobject), /* tp_basicsize */
1815 0, /* tp_itemsize */
1816 /* methods */
1817 (destructor)sortwrapper_dealloc, /* tp_dealloc */
1818 0, /* tp_print */
1819 0, /* tp_getattr */
1820 0, /* tp_setattr */
1821 0, /* tp_compare */
1822 0, /* tp_repr */
1823 0, /* tp_as_number */
1824 0, /* tp_as_sequence */
1825 0, /* tp_as_mapping */
1826 0, /* tp_hash */
1827 0, /* tp_call */
1828 0, /* tp_str */
1829 PyObject_GenericGetAttr, /* tp_getattro */
1830 0, /* tp_setattro */
1831 0, /* tp_as_buffer */
Tim Petersb38e2b62004-07-29 02:29:26 +00001832 Py_TPFLAGS_DEFAULT |
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001833 Py_TPFLAGS_HAVE_RICHCOMPARE, /* tp_flags */
1834 sortwrapper_doc, /* tp_doc */
1835 0, /* tp_traverse */
1836 0, /* tp_clear */
1837 (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
1838};
1839
1840/* Returns a new reference to a sortwrapper.
1841 Consumes the references to the two underlying objects. */
1842
1843static PyObject *
1844build_sortwrapper(PyObject *key, PyObject *value)
1845{
1846 sortwrapperobject *so;
Tim Petersb38e2b62004-07-29 02:29:26 +00001847
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001848 so = PyObject_New(sortwrapperobject, &sortwrapper_type);
1849 if (so == NULL)
1850 return NULL;
1851 so->key = key;
1852 so->value = value;
1853 return (PyObject *)so;
1854}
1855
1856/* Returns a new reference to the value underlying the wrapper. */
1857static PyObject *
1858sortwrapper_getvalue(PyObject *so)
1859{
1860 PyObject *value;
1861
1862 if (!PyObject_TypeCheck(so, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001863 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001864 "expected a sortwrapperobject");
1865 return NULL;
1866 }
1867 value = ((sortwrapperobject *)so)->value;
1868 Py_INCREF(value);
1869 return value;
1870}
1871
1872/* Wrapper for user specified cmp functions in combination with a
1873 specified key function. Makes sure the cmp function is presented
1874 with the actual key instead of the sortwrapper */
1875
1876typedef struct {
1877 PyObject_HEAD
1878 PyObject *func;
1879} cmpwrapperobject;
1880
1881static void
1882cmpwrapper_dealloc(cmpwrapperobject *co)
1883{
1884 Py_XDECREF(co->func);
1885 PyObject_Del(co);
1886}
1887
1888static PyObject *
1889cmpwrapper_call(cmpwrapperobject *co, PyObject *args, PyObject *kwds)
1890{
1891 PyObject *x, *y, *xx, *yy;
1892
1893 if (!PyArg_UnpackTuple(args, "", 2, 2, &x, &y))
1894 return NULL;
1895 if (!PyObject_TypeCheck(x, &sortwrapper_type) ||
Raymond Hettingerae4a2992003-10-16 17:16:30 +00001896 !PyObject_TypeCheck(y, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001897 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001898 "expected a sortwrapperobject");
1899 return NULL;
1900 }
1901 xx = ((sortwrapperobject *)x)->key;
1902 yy = ((sortwrapperobject *)y)->key;
1903 return PyObject_CallFunctionObjArgs(co->func, xx, yy, NULL);
1904}
1905
1906PyDoc_STRVAR(cmpwrapper_doc, "cmp() wrapper for sort with custom keys.");
1907
1908static PyTypeObject cmpwrapper_type = {
1909 PyObject_HEAD_INIT(&PyType_Type)
1910 0, /* ob_size */
1911 "cmpwrapper", /* tp_name */
1912 sizeof(cmpwrapperobject), /* tp_basicsize */
1913 0, /* tp_itemsize */
1914 /* methods */
1915 (destructor)cmpwrapper_dealloc, /* tp_dealloc */
1916 0, /* tp_print */
1917 0, /* tp_getattr */
1918 0, /* tp_setattr */
1919 0, /* tp_compare */
1920 0, /* tp_repr */
1921 0, /* tp_as_number */
1922 0, /* tp_as_sequence */
1923 0, /* tp_as_mapping */
1924 0, /* tp_hash */
1925 (ternaryfunc)cmpwrapper_call, /* tp_call */
1926 0, /* tp_str */
1927 PyObject_GenericGetAttr, /* tp_getattro */
1928 0, /* tp_setattro */
1929 0, /* tp_as_buffer */
1930 Py_TPFLAGS_DEFAULT, /* tp_flags */
1931 cmpwrapper_doc, /* tp_doc */
1932};
1933
1934static PyObject *
1935build_cmpwrapper(PyObject *cmpfunc)
1936{
1937 cmpwrapperobject *co;
Tim Petersb38e2b62004-07-29 02:29:26 +00001938
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001939 co = PyObject_New(cmpwrapperobject, &cmpwrapper_type);
1940 if (co == NULL)
1941 return NULL;
1942 Py_INCREF(cmpfunc);
1943 co->func = cmpfunc;
1944 return (PyObject *)co;
1945}
1946
Tim Petersa64dc242002-08-01 02:13:36 +00001947/* An adaptive, stable, natural mergesort. See listsort.txt.
1948 * Returns Py_None on success, NULL on error. Even in case of error, the
1949 * list will be some permutation of its input state (nothing is lost or
1950 * duplicated).
1951 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001952static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001953listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001954{
Tim Petersa64dc242002-08-01 02:13:36 +00001955 MergeState ms;
1956 PyObject **lo, **hi;
1957 int nremaining;
1958 int minrun;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001959 int saved_ob_size, saved_allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00001960 PyObject **saved_ob_item;
Armin Rigo93677f02004-07-29 12:40:23 +00001961 PyObject **final_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001962 PyObject *compare = NULL;
1963 PyObject *result = NULL; /* guilty until proved innocent */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001964 int reverse = 0;
1965 PyObject *keyfunc = NULL;
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001966 int i;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001967 PyObject *key, *value, *kvpair;
1968 static char *kwlist[] = {"cmp", "key", "reverse", 0};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001969
Tim Petersa64dc242002-08-01 02:13:36 +00001970 assert(self != NULL);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001971 assert (PyList_Check(self));
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001972 if (args != NULL) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001973 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:sort",
1974 kwlist, &compare, &keyfunc, &reverse))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001975 return NULL;
1976 }
Skip Montanaro4abd5f02003-01-02 20:51:08 +00001977 if (compare == Py_None)
1978 compare = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001979 if (keyfunc == Py_None)
1980 keyfunc = NULL;
1981 if (compare != NULL && keyfunc != NULL) {
1982 compare = build_cmpwrapper(compare);
1983 if (compare == NULL)
Hye-Shik Chang19cb1932003-12-10 07:31:08 +00001984 return NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001985 } else
1986 Py_XINCREF(compare);
1987
Tim Petersb9099c32002-11-12 22:08:10 +00001988 /* The list is temporarily made empty, so that mutations performed
1989 * by comparison functions can't affect the slice of memory we're
1990 * sorting (allowing mutations during sorting is a core-dump
1991 * factory, since ob_item may change).
1992 */
1993 saved_ob_size = self->ob_size;
1994 saved_ob_item = self->ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001995 saved_allocated = self->allocated;
Armin Rigo93677f02004-07-29 12:40:23 +00001996 self->ob_size = 0;
Tim Peters51b4ade2004-07-29 04:07:15 +00001997 self->ob_item = NULL;
Armin Rigo93677f02004-07-29 12:40:23 +00001998 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00001999
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002000 if (keyfunc != NULL) {
2001 for (i=0 ; i < saved_ob_size ; i++) {
2002 value = saved_ob_item[i];
Tim Petersb38e2b62004-07-29 02:29:26 +00002003 key = PyObject_CallFunctionObjArgs(keyfunc, value,
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002004 NULL);
2005 if (key == NULL) {
2006 for (i=i-1 ; i>=0 ; i--) {
2007 kvpair = saved_ob_item[i];
2008 value = sortwrapper_getvalue(kvpair);
2009 saved_ob_item[i] = value;
2010 Py_DECREF(kvpair);
2011 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002012 goto dsu_fail;
2013 }
2014 kvpair = build_sortwrapper(key, value);
2015 if (kvpair == NULL)
2016 goto dsu_fail;
2017 saved_ob_item[i] = kvpair;
2018 }
2019 }
2020
2021 /* Reverse sort stability achieved by initially reversing the list,
2022 applying a stable forward sort, then reversing the final result. */
2023 if (reverse && saved_ob_size > 1)
2024 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2025
2026 merge_init(&ms, compare);
2027
Tim Petersb9099c32002-11-12 22:08:10 +00002028 nremaining = saved_ob_size;
Tim Petersa64dc242002-08-01 02:13:36 +00002029 if (nremaining < 2)
2030 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00002031
Tim Petersa64dc242002-08-01 02:13:36 +00002032 /* March over the array once, left to right, finding natural runs,
2033 * and extending short natural runs to minrun elements.
2034 */
Tim Petersb9099c32002-11-12 22:08:10 +00002035 lo = saved_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00002036 hi = lo + nremaining;
2037 minrun = merge_compute_minrun(nremaining);
2038 do {
2039 int descending;
2040 int n;
Tim Peters330f9e92002-07-19 07:05:44 +00002041
Tim Petersa64dc242002-08-01 02:13:36 +00002042 /* Identify next run. */
2043 n = count_run(lo, hi, compare, &descending);
2044 if (n < 0)
2045 goto fail;
2046 if (descending)
2047 reverse_slice(lo, lo + n);
2048 /* If short, extend to min(minrun, nremaining). */
2049 if (n < minrun) {
2050 const int force = nremaining <= minrun ?
2051 nremaining : minrun;
2052 if (binarysort(lo, lo + force, lo + n, compare) < 0)
2053 goto fail;
2054 n = force;
2055 }
2056 /* Push run onto pending-runs stack, and maybe merge. */
2057 assert(ms.n < MAX_MERGE_PENDING);
Tim Peterse05f65a2002-08-10 05:21:15 +00002058 ms.pending[ms.n].base = lo;
2059 ms.pending[ms.n].len = n;
Tim Petersa64dc242002-08-01 02:13:36 +00002060 ++ms.n;
2061 if (merge_collapse(&ms) < 0)
2062 goto fail;
2063 /* Advance to find next run. */
2064 lo += n;
2065 nremaining -= n;
2066 } while (nremaining);
2067 assert(lo == hi);
Tim Peters330f9e92002-07-19 07:05:44 +00002068
Tim Petersa64dc242002-08-01 02:13:36 +00002069 if (merge_force_collapse(&ms) < 0)
2070 goto fail;
2071 assert(ms.n == 1);
Tim Petersb9099c32002-11-12 22:08:10 +00002072 assert(ms.pending[0].base == saved_ob_item);
2073 assert(ms.pending[0].len == saved_ob_size);
Tim Petersa64dc242002-08-01 02:13:36 +00002074
2075succeed:
2076 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002077fail:
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002078 if (keyfunc != NULL) {
2079 for (i=0 ; i < saved_ob_size ; i++) {
2080 kvpair = saved_ob_item[i];
2081 value = sortwrapper_getvalue(kvpair);
2082 saved_ob_item[i] = value;
2083 Py_DECREF(kvpair);
2084 }
2085 }
2086
Armin Rigo93677f02004-07-29 12:40:23 +00002087 if (self->allocated != -1 && result != NULL) {
Tim Peters51b4ade2004-07-29 04:07:15 +00002088 /* The user mucked with the list during the sort,
2089 * and we don't already have another error to report.
2090 */
2091 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2092 result = NULL;
Tim Petersb9099c32002-11-12 22:08:10 +00002093 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002094
2095 if (reverse && saved_ob_size > 1)
2096 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2097
2098 merge_freemem(&ms);
2099
2100dsu_fail:
Armin Rigo93677f02004-07-29 12:40:23 +00002101 final_ob_item = self->ob_item;
2102 i = self->ob_size;
Tim Petersb9099c32002-11-12 22:08:10 +00002103 self->ob_size = saved_ob_size;
2104 self->ob_item = saved_ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002105 self->allocated = saved_allocated;
Armin Rigo93677f02004-07-29 12:40:23 +00002106 if (final_ob_item != NULL) {
2107 /* we cannot use list_clear() for this because it does not
2108 guarantee that the list is really empty when it returns */
2109 while (--i >= 0) {
2110 Py_XDECREF(final_ob_item[i]);
2111 }
2112 PyMem_FREE(final_ob_item);
2113 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002114 Py_XDECREF(compare);
Tim Petersa64dc242002-08-01 02:13:36 +00002115 Py_XINCREF(result);
2116 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002117}
Tim Peters330f9e92002-07-19 07:05:44 +00002118#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002119#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002120
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002121int
Fred Drakea2f55112000-07-09 15:16:51 +00002122PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002123{
2124 if (v == NULL || !PyList_Check(v)) {
2125 PyErr_BadInternalCall();
2126 return -1;
2127 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002128 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002129 if (v == NULL)
2130 return -1;
2131 Py_DECREF(v);
2132 return 0;
2133}
2134
Guido van Rossumb86c5492001-02-12 22:06:02 +00002135static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002136listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002137{
Tim Peters326b4482002-07-19 04:04:16 +00002138 if (self->ob_size > 1)
2139 reverse_slice(self->ob_item, self->ob_item + self->ob_size);
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002140 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002141}
2142
Guido van Rossum84c76f51990-10-30 13:32:20 +00002143int
Fred Drakea2f55112000-07-09 15:16:51 +00002144PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002145{
Tim Peters6063e262002-08-08 01:06:39 +00002146 PyListObject *self = (PyListObject *)v;
2147
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002148 if (v == NULL || !PyList_Check(v)) {
2149 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002150 return -1;
2151 }
Tim Peters6063e262002-08-08 01:06:39 +00002152 if (self->ob_size > 1)
2153 reverse_slice(self->ob_item, self->ob_item + self->ob_size);
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002154 return 0;
2155}
2156
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002157PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002158PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002159{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002160 PyObject *w;
2161 PyObject **p;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002162 int n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002163 if (v == NULL || !PyList_Check(v)) {
2164 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002165 return NULL;
2166 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002167 n = ((PyListObject *)v)->ob_size;
2168 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002169 if (w == NULL)
2170 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002171 p = ((PyTupleObject *)w)->ob_item;
Thomas Wouters334fb892000-07-25 12:56:38 +00002172 memcpy((void *)p,
2173 (void *)((PyListObject *)v)->ob_item,
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002174 n*sizeof(PyObject *));
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002175 while (--n >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002176 Py_INCREF(*p);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002177 p++;
2178 }
2179 return w;
2180}
2181
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002182static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002183listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002184{
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002185 int i, start=0, stop=self->ob_size;
2186 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002187
Walter Dörwalde8049bef2003-06-17 19:27:39 +00002188 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2189 _PyEval_SliceIndex, &start,
2190 _PyEval_SliceIndex, &stop))
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002191 return NULL;
Guido van Rossum2743d872003-06-17 14:25:14 +00002192 if (start < 0) {
2193 start += self->ob_size;
2194 if (start < 0)
2195 start = 0;
2196 }
2197 if (stop < 0) {
2198 stop += self->ob_size;
2199 if (stop < 0)
2200 stop = 0;
2201 }
Neal Norwitzf0769532004-08-13 03:18:29 +00002202 for (i = start; i < stop && i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002203 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2204 if (cmp > 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002205 return PyInt_FromLong((long)i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002206 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002207 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002208 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002209 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002210 return NULL;
2211}
2212
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002213static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002214listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002215{
2216 int count = 0;
2217 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002218
Guido van Rossume6f7d181991-10-20 20:20:40 +00002219 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002220 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2221 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002222 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002223 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002224 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00002225 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002226 return PyInt_FromLong((long)count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002227}
2228
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002229static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002230listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002231{
2232 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002233
Guido van Rossumed98d481991-03-06 13:07:53 +00002234 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002235 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2236 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002237 if (list_ass_slice(self, i, i+1,
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002238 (PyObject *)NULL) == 0)
2239 Py_RETURN_NONE;
2240 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002241 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002242 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002243 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002244 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002245 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002246 return NULL;
2247}
2248
Jeremy Hylton8caad492000-06-23 14:18:11 +00002249static int
2250list_traverse(PyListObject *o, visitproc visit, void *arg)
2251{
2252 int i, err;
2253 PyObject *x;
2254
2255 for (i = o->ob_size; --i >= 0; ) {
2256 x = o->ob_item[i];
2257 if (x != NULL) {
2258 err = visit(x, arg);
2259 if (err)
2260 return err;
2261 }
2262 }
2263 return 0;
2264}
2265
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002266static PyObject *
2267list_richcompare(PyObject *v, PyObject *w, int op)
2268{
2269 PyListObject *vl, *wl;
2270 int i;
2271
2272 if (!PyList_Check(v) || !PyList_Check(w)) {
2273 Py_INCREF(Py_NotImplemented);
2274 return Py_NotImplemented;
2275 }
2276
2277 vl = (PyListObject *)v;
2278 wl = (PyListObject *)w;
2279
2280 if (vl->ob_size != wl->ob_size && (op == Py_EQ || op == Py_NE)) {
2281 /* Shortcut: if the lengths differ, the lists differ */
2282 PyObject *res;
2283 if (op == Py_EQ)
2284 res = Py_False;
2285 else
2286 res = Py_True;
2287 Py_INCREF(res);
2288 return res;
2289 }
2290
2291 /* Search for the first index where items are different */
2292 for (i = 0; i < vl->ob_size && i < wl->ob_size; i++) {
2293 int k = PyObject_RichCompareBool(vl->ob_item[i],
2294 wl->ob_item[i], Py_EQ);
2295 if (k < 0)
2296 return NULL;
2297 if (!k)
2298 break;
2299 }
2300
2301 if (i >= vl->ob_size || i >= wl->ob_size) {
2302 /* No more items to compare -- compare sizes */
2303 int vs = vl->ob_size;
2304 int ws = wl->ob_size;
2305 int cmp;
2306 PyObject *res;
2307 switch (op) {
2308 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00002309 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002310 case Py_EQ: cmp = vs == ws; break;
2311 case Py_NE: cmp = vs != ws; break;
2312 case Py_GT: cmp = vs > ws; break;
2313 case Py_GE: cmp = vs >= ws; break;
2314 default: return NULL; /* cannot happen */
2315 }
2316 if (cmp)
2317 res = Py_True;
2318 else
2319 res = Py_False;
2320 Py_INCREF(res);
2321 return res;
2322 }
2323
2324 /* We have an item that differs -- shortcuts for EQ/NE */
2325 if (op == Py_EQ) {
2326 Py_INCREF(Py_False);
2327 return Py_False;
2328 }
2329 if (op == Py_NE) {
2330 Py_INCREF(Py_True);
2331 return Py_True;
2332 }
2333
2334 /* Compare the final item again using the proper operator */
2335 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
2336}
2337
Tim Peters6d6c1a32001-08-02 04:15:00 +00002338static int
2339list_init(PyListObject *self, PyObject *args, PyObject *kw)
2340{
2341 PyObject *arg = NULL;
2342 static char *kwlist[] = {"sequence", 0};
2343
2344 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2345 return -1;
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002346
2347 /* Verify list invariants established by PyType_GenericAlloc() */
Armin Rigoa37bbf22004-07-30 11:20:18 +00002348 assert(0 <= self->ob_size);
2349 assert(self->ob_size <= self->allocated || self->allocated == -1);
2350 assert(self->ob_item != NULL ||
2351 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002352
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002353 /* Empty previous contents */
Armin Rigo93677f02004-07-29 12:40:23 +00002354 if (self->ob_item != NULL) {
2355 (void)list_clear(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002356 }
2357 if (arg != NULL) {
2358 PyObject *rv = listextend(self, arg);
2359 if (rv == NULL)
2360 return -1;
2361 Py_DECREF(rv);
2362 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002363 return 0;
2364}
2365
Guido van Rossumdbb53d92001-12-03 16:32:18 +00002366static long
2367list_nohash(PyObject *self)
2368{
2369 PyErr_SetString(PyExc_TypeError, "list objects are unhashable");
2370 return -1;
2371}
2372
Raymond Hettinger1021c442003-11-07 15:38:09 +00002373static PyObject *list_iter(PyObject *seq);
2374static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2375
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002376PyDoc_STRVAR(getitem_doc,
2377"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002378PyDoc_STRVAR(reversed_doc,
2379"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002380PyDoc_STRVAR(append_doc,
2381"L.append(object) -- append object to end");
2382PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002383"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002384PyDoc_STRVAR(insert_doc,
2385"L.insert(index, object) -- insert object before index");
2386PyDoc_STRVAR(pop_doc,
2387"L.pop([index]) -> item -- remove and return item at index (default last)");
2388PyDoc_STRVAR(remove_doc,
2389"L.remove(value) -- remove first occurrence of value");
2390PyDoc_STRVAR(index_doc,
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002391"L.index(value, [start, [stop]]) -> integer -- return first index of value");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002392PyDoc_STRVAR(count_doc,
2393"L.count(value) -> integer -- return number of occurrences of value");
2394PyDoc_STRVAR(reverse_doc,
2395"L.reverse() -- reverse *IN PLACE*");
2396PyDoc_STRVAR(sort_doc,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002397"L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n\
2398cmp(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002399
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002400static PyObject *list_subscript(PyListObject*, PyObject*);
2401
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002402static PyMethodDef list_methods[] = {
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002403 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
Raymond Hettinger1021c442003-11-07 15:38:09 +00002404 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002405 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002406 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002407 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002408 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002409 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002410 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002411 {"count", (PyCFunction)listcount, METH_O, count_doc},
2412 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002413 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
Tim Petersa64dc242002-08-01 02:13:36 +00002414 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002415};
2416
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002417static PySequenceMethods list_as_sequence = {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002418 (inquiry)list_length, /* sq_length */
2419 (binaryfunc)list_concat, /* sq_concat */
2420 (intargfunc)list_repeat, /* sq_repeat */
2421 (intargfunc)list_item, /* sq_item */
2422 (intintargfunc)list_slice, /* sq_slice */
2423 (intobjargproc)list_ass_item, /* sq_ass_item */
2424 (intintobjargproc)list_ass_slice, /* sq_ass_slice */
2425 (objobjproc)list_contains, /* sq_contains */
2426 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2427 (intargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002428};
2429
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002430PyDoc_STRVAR(list_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002431"list() -> new list\n"
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002432"list(sequence) -> new list initialized from sequence's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002433
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002434static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002435list_subscript(PyListObject* self, PyObject* item)
2436{
2437 if (PyInt_Check(item)) {
2438 long i = PyInt_AS_LONG(item);
2439 if (i < 0)
2440 i += PyList_GET_SIZE(self);
2441 return list_item(self, i);
2442 }
2443 else if (PyLong_Check(item)) {
2444 long i = PyLong_AsLong(item);
2445 if (i == -1 && PyErr_Occurred())
2446 return NULL;
2447 if (i < 0)
2448 i += PyList_GET_SIZE(self);
2449 return list_item(self, i);
2450 }
2451 else if (PySlice_Check(item)) {
2452 int start, stop, step, slicelength, cur, i;
2453 PyObject* result;
2454 PyObject* it;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002455 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002456
2457 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
2458 &start, &stop, &step, &slicelength) < 0) {
2459 return NULL;
2460 }
2461
2462 if (slicelength <= 0) {
2463 return PyList_New(0);
2464 }
2465 else {
2466 result = PyList_New(slicelength);
2467 if (!result) return NULL;
2468
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002469 src = self->ob_item;
2470 dest = ((PyListObject *)result)->ob_item;
Tim Peters3b01a122002-07-19 02:35:45 +00002471 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002472 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002473 it = src[cur];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002474 Py_INCREF(it);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002475 dest[i] = it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002476 }
Tim Peters3b01a122002-07-19 02:35:45 +00002477
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002478 return result;
2479 }
2480 }
2481 else {
2482 PyErr_SetString(PyExc_TypeError,
2483 "list indices must be integers");
2484 return NULL;
2485 }
2486}
2487
Tim Peters3b01a122002-07-19 02:35:45 +00002488static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002489list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2490{
2491 if (PyInt_Check(item)) {
2492 long i = PyInt_AS_LONG(item);
2493 if (i < 0)
2494 i += PyList_GET_SIZE(self);
2495 return list_ass_item(self, i, value);
2496 }
2497 else if (PyLong_Check(item)) {
2498 long i = PyLong_AsLong(item);
2499 if (i == -1 && PyErr_Occurred())
2500 return -1;
2501 if (i < 0)
2502 i += PyList_GET_SIZE(self);
2503 return list_ass_item(self, i, value);
2504 }
2505 else if (PySlice_Check(item)) {
2506 int start, stop, step, slicelength;
2507
2508 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
2509 &start, &stop, &step, &slicelength) < 0) {
2510 return -1;
2511 }
2512
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002513 /* treat L[slice(a,b)] = v _exactly_ like L[a:b] = v */
2514 if (step == 1 && ((PySliceObject*)item)->step == Py_None)
2515 return list_ass_slice(self, start, stop, value);
2516
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002517 if (value == NULL) {
2518 /* delete slice */
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002519 PyObject **garbage;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002520 int cur, i;
Tim Peters3b01a122002-07-19 02:35:45 +00002521
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002522 if (slicelength <= 0)
2523 return 0;
2524
2525 if (step < 0) {
2526 stop = start + 1;
2527 start = stop + step*(slicelength - 1) - 1;
2528 step = -step;
2529 }
2530
2531 garbage = (PyObject**)
2532 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Tim Peters3b01a122002-07-19 02:35:45 +00002533
2534 /* drawing pictures might help
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002535 understand these for loops */
Guido van Rossum75a20b12002-06-11 12:22:28 +00002536 for (cur = start, i = 0;
2537 cur < stop;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002538 cur += step, i++) {
2539 int lim = step;
2540
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002541 garbage[i] = PyList_GET_ITEM(self, cur);
2542
Michael W. Hudson56796f62002-07-29 14:35:04 +00002543 if (cur + step >= self->ob_size) {
2544 lim = self->ob_size - cur - 1;
2545 }
2546
Tim Petersb38e2b62004-07-29 02:29:26 +00002547 memmove(self->ob_item + cur - i,
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002548 self->ob_item + cur + 1,
2549 lim * sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002550 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002551
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002552 for (cur = start + slicelength*step + 1;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002553 cur < self->ob_size; cur++) {
2554 PyList_SET_ITEM(self, cur - slicelength,
2555 PyList_GET_ITEM(self, cur));
2556 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002557
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002558 self->ob_size -= slicelength;
Raymond Hettingerd4ff7412004-03-15 09:01:31 +00002559 list_resize(self, self->ob_size);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002560
2561 for (i = 0; i < slicelength; i++) {
2562 Py_DECREF(garbage[i]);
2563 }
2564 PyMem_FREE(garbage);
2565
2566 return 0;
2567 }
2568 else {
2569 /* assign slice */
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002570 PyObject **garbage, *ins, *seq, **seqitems, **selfitems;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002571 int cur, i;
2572
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002573 /* protect against a[::-1] = a */
Tim Peters3b01a122002-07-19 02:35:45 +00002574 if (self == (PyListObject*)value) {
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002575 seq = list_slice((PyListObject*)value, 0,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002576 PyList_GET_SIZE(value));
Tim Peters3b01a122002-07-19 02:35:45 +00002577 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002578 else {
Tim Petersb38e2b62004-07-29 02:29:26 +00002579 seq = PySequence_Fast(value,
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002580 "must assign iterable to extended slice");
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002581 if (!seq)
2582 return -1;
2583 }
2584
2585 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2586 PyErr_Format(PyExc_ValueError,
2587 "attempt to assign sequence of size %d to extended slice of size %d",
2588 PySequence_Fast_GET_SIZE(seq),
2589 slicelength);
2590 Py_DECREF(seq);
2591 return -1;
2592 }
2593
2594 if (!slicelength) {
2595 Py_DECREF(seq);
2596 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002597 }
2598
2599 garbage = (PyObject**)
2600 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Tim Peters3b01a122002-07-19 02:35:45 +00002601
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002602 selfitems = self->ob_item;
Raymond Hettinger42bec932004-03-12 16:38:17 +00002603 seqitems = PySequence_Fast_ITEMS(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002604 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002605 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002606 garbage[i] = selfitems[cur];
2607 ins = seqitems[i];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002608 Py_INCREF(ins);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002609 selfitems[cur] = ins;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002610 }
2611
2612 for (i = 0; i < slicelength; i++) {
2613 Py_DECREF(garbage[i]);
2614 }
Tim Peters3b01a122002-07-19 02:35:45 +00002615
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002616 PyMem_FREE(garbage);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002617 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002618
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002619 return 0;
2620 }
Tim Peters3b01a122002-07-19 02:35:45 +00002621 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002622 else {
Tim Peters3b01a122002-07-19 02:35:45 +00002623 PyErr_SetString(PyExc_TypeError,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002624 "list indices must be integers");
2625 return -1;
2626 }
2627}
2628
2629static PyMappingMethods list_as_mapping = {
2630 (inquiry)list_length,
2631 (binaryfunc)list_subscript,
2632 (objobjargproc)list_ass_subscript
2633};
2634
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002635PyTypeObject PyList_Type = {
2636 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002637 0,
2638 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002639 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002640 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002641 (destructor)list_dealloc, /* tp_dealloc */
2642 (printfunc)list_print, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002643 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002644 0, /* tp_setattr */
2645 0, /* tp_compare */
2646 (reprfunc)list_repr, /* tp_repr */
2647 0, /* tp_as_number */
2648 &list_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002649 &list_as_mapping, /* tp_as_mapping */
Guido van Rossumdbb53d92001-12-03 16:32:18 +00002650 list_nohash, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002651 0, /* tp_call */
2652 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002653 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002654 0, /* tp_setattro */
2655 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002656 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Tim Peters6d6c1a32001-08-02 04:15:00 +00002657 Py_TPFLAGS_BASETYPE, /* tp_flags */
2658 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002659 (traverseproc)list_traverse, /* tp_traverse */
2660 (inquiry)list_clear, /* tp_clear */
2661 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002662 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002663 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002664 0, /* tp_iternext */
2665 list_methods, /* tp_methods */
2666 0, /* tp_members */
2667 0, /* tp_getset */
2668 0, /* tp_base */
2669 0, /* tp_dict */
2670 0, /* tp_descr_get */
2671 0, /* tp_descr_set */
2672 0, /* tp_dictoffset */
2673 (initproc)list_init, /* tp_init */
2674 PyType_GenericAlloc, /* tp_alloc */
2675 PyType_GenericNew, /* tp_new */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002676 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002677};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002678
2679
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002680/*********************** List Iterator **************************/
2681
2682typedef struct {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002683 PyObject_HEAD
2684 long it_index;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002685 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002686} listiterobject;
2687
2688PyTypeObject PyListIter_Type;
2689
Guido van Rossum5086e492002-07-16 15:56:52 +00002690static PyObject *
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002691list_iter(PyObject *seq)
2692{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002693 listiterobject *it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002694
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002695 if (!PyList_Check(seq)) {
2696 PyErr_BadInternalCall();
2697 return NULL;
2698 }
2699 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2700 if (it == NULL)
2701 return NULL;
2702 it->it_index = 0;
2703 Py_INCREF(seq);
2704 it->it_seq = (PyListObject *)seq;
2705 _PyObject_GC_TRACK(it);
2706 return (PyObject *)it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002707}
2708
2709static void
2710listiter_dealloc(listiterobject *it)
2711{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002712 _PyObject_GC_UNTRACK(it);
Guido van Rossum86103ae2002-07-16 20:07:32 +00002713 Py_XDECREF(it->it_seq);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002714 PyObject_GC_Del(it);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002715}
2716
2717static int
2718listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2719{
Guido van Rossum86103ae2002-07-16 20:07:32 +00002720 if (it->it_seq == NULL)
2721 return 0;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002722 return visit((PyObject *)it->it_seq, arg);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002723}
2724
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002725static PyObject *
Tim Peters93b2cc42002-06-01 05:22:55 +00002726listiter_next(listiterobject *it)
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002727{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002728 PyListObject *seq;
2729 PyObject *item;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002730
Tim Peters93b2cc42002-06-01 05:22:55 +00002731 assert(it != NULL);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002732 seq = it->it_seq;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002733 if (seq == NULL)
2734 return NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002735 assert(PyList_Check(seq));
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002736
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002737 if (it->it_index < PyList_GET_SIZE(seq)) {
Tim Peters93b2cc42002-06-01 05:22:55 +00002738 item = PyList_GET_ITEM(seq, it->it_index);
2739 ++it->it_index;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002740 Py_INCREF(item);
2741 return item;
2742 }
Guido van Rossum86103ae2002-07-16 20:07:32 +00002743
2744 Py_DECREF(seq);
2745 it->it_seq = NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002746 return NULL;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002747}
2748
Raymond Hettinger435bf582004-03-18 22:43:10 +00002749static int
2750listiter_len(listiterobject *it)
2751{
Raymond Hettinger40a03822004-04-12 13:05:09 +00002752 int len;
2753 if (it->it_seq) {
2754 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2755 if (len >= 0)
2756 return len;
2757 }
Raymond Hettinger435bf582004-03-18 22:43:10 +00002758 return 0;
2759}
2760
2761static PySequenceMethods listiter_as_sequence = {
2762 (inquiry)listiter_len, /* sq_length */
2763 0, /* sq_concat */
2764};
2765
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002766PyTypeObject PyListIter_Type = {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002767 PyObject_HEAD_INIT(&PyType_Type)
2768 0, /* ob_size */
2769 "listiterator", /* tp_name */
2770 sizeof(listiterobject), /* tp_basicsize */
2771 0, /* tp_itemsize */
2772 /* methods */
2773 (destructor)listiter_dealloc, /* tp_dealloc */
2774 0, /* tp_print */
2775 0, /* tp_getattr */
2776 0, /* tp_setattr */
2777 0, /* tp_compare */
2778 0, /* tp_repr */
2779 0, /* tp_as_number */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002780 &listiter_as_sequence, /* tp_as_sequence */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002781 0, /* tp_as_mapping */
2782 0, /* tp_hash */
2783 0, /* tp_call */
2784 0, /* tp_str */
2785 PyObject_GenericGetAttr, /* tp_getattro */
2786 0, /* tp_setattro */
2787 0, /* tp_as_buffer */
2788 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2789 0, /* tp_doc */
2790 (traverseproc)listiter_traverse, /* tp_traverse */
2791 0, /* tp_clear */
2792 0, /* tp_richcompare */
2793 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00002794 PyObject_SelfIter, /* tp_iter */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002795 (iternextfunc)listiter_next, /* tp_iternext */
Guido van Rossum86103ae2002-07-16 20:07:32 +00002796 0, /* tp_methods */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002797 0, /* tp_members */
2798 0, /* tp_getset */
2799 0, /* tp_base */
2800 0, /* tp_dict */
2801 0, /* tp_descr_get */
2802 0, /* tp_descr_set */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002803};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002804
2805/*********************** List Reverse Iterator **************************/
2806
2807typedef struct {
2808 PyObject_HEAD
2809 long it_index;
Raymond Hettinger001f2282003-11-08 11:58:44 +00002810 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002811} listreviterobject;
2812
2813PyTypeObject PyListRevIter_Type;
2814
2815static PyObject *
2816list_reversed(PyListObject *seq, PyObject *unused)
2817{
2818 listreviterobject *it;
2819
2820 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2821 if (it == NULL)
2822 return NULL;
2823 assert(PyList_Check(seq));
2824 it->it_index = PyList_GET_SIZE(seq) - 1;
2825 Py_INCREF(seq);
2826 it->it_seq = seq;
2827 PyObject_GC_Track(it);
2828 return (PyObject *)it;
2829}
2830
2831static void
2832listreviter_dealloc(listreviterobject *it)
2833{
2834 PyObject_GC_UnTrack(it);
2835 Py_XDECREF(it->it_seq);
2836 PyObject_GC_Del(it);
2837}
2838
2839static int
2840listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2841{
2842 if (it->it_seq == NULL)
2843 return 0;
2844 return visit((PyObject *)it->it_seq, arg);
2845}
2846
2847static PyObject *
2848listreviter_next(listreviterobject *it)
2849{
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002850 PyObject *item;
2851 long index = it->it_index;
2852 PyListObject *seq = it->it_seq;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002853
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002854 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2855 item = PyList_GET_ITEM(seq, index);
Raymond Hettinger1021c442003-11-07 15:38:09 +00002856 it->it_index--;
2857 Py_INCREF(item);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002858 return item;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002859 }
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002860 it->it_index = -1;
2861 if (seq != NULL) {
2862 it->it_seq = NULL;
2863 Py_DECREF(seq);
2864 }
2865 return NULL;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002866}
2867
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002868static int
2869listreviter_len(listreviterobject *it)
2870{
Raymond Hettinger40a03822004-04-12 13:05:09 +00002871 int len = it->it_index + 1;
2872 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
2873 return 0;
2874 return len;
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002875}
2876
2877static PySequenceMethods listreviter_as_sequence = {
2878 (inquiry)listreviter_len, /* sq_length */
2879 0, /* sq_concat */
2880};
2881
Raymond Hettinger1021c442003-11-07 15:38:09 +00002882PyTypeObject PyListRevIter_Type = {
2883 PyObject_HEAD_INIT(&PyType_Type)
2884 0, /* ob_size */
2885 "listreverseiterator", /* tp_name */
2886 sizeof(listreviterobject), /* tp_basicsize */
2887 0, /* tp_itemsize */
2888 /* methods */
2889 (destructor)listreviter_dealloc, /* tp_dealloc */
2890 0, /* tp_print */
2891 0, /* tp_getattr */
2892 0, /* tp_setattr */
2893 0, /* tp_compare */
2894 0, /* tp_repr */
2895 0, /* tp_as_number */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002896 &listreviter_as_sequence, /* tp_as_sequence */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002897 0, /* tp_as_mapping */
2898 0, /* tp_hash */
2899 0, /* tp_call */
2900 0, /* tp_str */
2901 PyObject_GenericGetAttr, /* tp_getattro */
2902 0, /* tp_setattro */
2903 0, /* tp_as_buffer */
2904 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2905 0, /* tp_doc */
2906 (traverseproc)listreviter_traverse, /* tp_traverse */
2907 0, /* tp_clear */
2908 0, /* tp_richcompare */
2909 0, /* tp_weaklistoffset */
2910 PyObject_SelfIter, /* tp_iter */
2911 (iternextfunc)listreviter_next, /* tp_iternext */
2912 0,
2913};