blob: 08ab0951c9bda74303aca0e081ef3daccbfabbca [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
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +000071void
72PyList_Fini(void)
73{
74 PyListObject *op;
75
76 while (num_free_lists) {
77 num_free_lists--;
78 op = free_lists[num_free_lists];
79 assert(PyList_CheckExact(op));
80 PyObject_GC_Del(op);
81 }
82}
83
Guido van Rossumc0b618a1997-05-02 03:12:38 +000084PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +000085PyList_New(int size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000086{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000087 PyListObject *op;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +000088 size_t nbytes;
Tim Peters3986d4e2004-07-29 02:28:42 +000089
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000090 if (size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000091 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000092 return NULL;
93 }
Tim Peters7049d812004-01-18 20:31:02 +000094 nbytes = size * sizeof(PyObject *);
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000095 /* Check for overflow */
Raymond Hettingerfdfe6182004-05-05 06:28:16 +000096 if (nbytes / sizeof(PyObject *) != (size_t)size)
Guido van Rossumc0b618a1997-05-02 03:12:38 +000097 return PyErr_NoMemory();
Raymond Hettinger0468e412004-05-05 05:37:53 +000098 if (num_free_lists) {
99 num_free_lists--;
100 op = free_lists[num_free_lists];
101 _Py_NewReference((PyObject *)op);
102 } else {
103 op = PyObject_GC_New(PyListObject, &PyList_Type);
104 if (op == NULL)
105 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000106 }
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000107 if (size <= 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000108 op->ob_item = NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000109 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +0000110 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000111 if (op->ob_item == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000112 return PyErr_NoMemory();
Tim Peters3986d4e2004-07-29 02:28:42 +0000113 memset(op->ob_item, 0, nbytes);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000114 }
Neil Schemenauere83c00e2001-08-29 23:54:21 +0000115 op->ob_size = size;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000116 op->allocated = size;
Neil Schemenauere83c00e2001-08-29 23:54:21 +0000117 _PyObject_GC_TRACK(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000118 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000119}
120
121int
Fred Drakea2f55112000-07-09 15:16:51 +0000122PyList_Size(PyObject *op)
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 -1;
127 }
128 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000129 return ((PyListObject *)op) -> ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000130}
131
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000132static PyObject *indexerr = NULL;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000133
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000134PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000135PyList_GetItem(PyObject *op, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000136{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000137 if (!PyList_Check(op)) {
138 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000139 return NULL;
140 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000141 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000142 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000143 indexerr = PyString_FromString(
144 "list index out of range");
145 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000146 return NULL;
147 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000148 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000149}
150
151int
Fred Drakea2f55112000-07-09 15:16:51 +0000152PyList_SetItem(register PyObject *op, register int i,
153 register PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000154{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000155 register PyObject *olditem;
156 register PyObject **p;
157 if (!PyList_Check(op)) {
158 Py_XDECREF(newitem);
159 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000160 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000161 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000162 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
163 Py_XDECREF(newitem);
164 PyErr_SetString(PyExc_IndexError,
165 "list assignment index out of range");
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000166 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000167 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000168 p = ((PyListObject *)op) -> ob_item + i;
Guido van Rossum5fe60581995-03-09 12:12:50 +0000169 olditem = *p;
170 *p = newitem;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000171 Py_XDECREF(olditem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000172 return 0;
173}
174
175static int
Fred Drakea2f55112000-07-09 15:16:51 +0000176ins1(PyListObject *self, int where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000177{
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000178 int i, n = self->ob_size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000179 PyObject **items;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000180 if (v == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000181 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000182 return -1;
183 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000184 if (n == INT_MAX) {
Trent Micka5846642000-08-13 22:47:45 +0000185 PyErr_SetString(PyExc_OverflowError,
186 "cannot add more objects to list");
187 return -1;
188 }
Tim Petersb38e2b62004-07-29 02:29:26 +0000189
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000190 if (list_resize(self, n+1) == -1)
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000191 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000192
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000193 if (where < 0) {
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000194 where += n;
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000195 if (where < 0)
196 where = 0;
197 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000198 if (where > n)
199 where = n;
200 items = self->ob_item;
201 for (i = n; --i >= where; )
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000202 items[i+1] = items[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000203 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000204 items[where] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000205 return 0;
206}
207
208int
Fred Drakea2f55112000-07-09 15:16:51 +0000209PyList_Insert(PyObject *op, int where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000210{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000211 if (!PyList_Check(op)) {
212 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000213 return -1;
214 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000215 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000216}
217
Raymond Hettinger40a03822004-04-12 13:05:09 +0000218static int
219app1(PyListObject *self, PyObject *v)
220{
221 int n = PyList_GET_SIZE(self);
222
223 assert (v != NULL);
224 if (n == INT_MAX) {
225 PyErr_SetString(PyExc_OverflowError,
226 "cannot add more objects to list");
227 return -1;
228 }
229
230 if (list_resize(self, n+1) == -1)
231 return -1;
232
233 Py_INCREF(v);
234 PyList_SET_ITEM(self, n, v);
235 return 0;
236}
237
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000238int
Fred Drakea2f55112000-07-09 15:16:51 +0000239PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000240{
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000241 if (PyList_Check(op) && (newitem != NULL))
242 return app1((PyListObject *)op, newitem);
243 PyErr_BadInternalCall();
244 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000245}
246
247/* Methods */
248
249static void
Fred Drakea2f55112000-07-09 15:16:51 +0000250list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000251{
252 int i;
Guido van Rossumff413af2002-03-28 20:34:59 +0000253 PyObject_GC_UnTrack(op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000254 Py_TRASHCAN_SAFE_BEGIN(op)
Jack Jansen7874d1f1995-01-19 12:09:27 +0000255 if (op->ob_item != NULL) {
Guido van Rossumfa717011999-06-09 15:19:34 +0000256 /* Do it backwards, for Christian Tismer.
257 There's a simple test case where somehow this reduces
258 thrashing when a *very* large list is created and
259 immediately deleted. */
260 i = op->ob_size;
261 while (--i >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000262 Py_XDECREF(op->ob_item[i]);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000263 }
Guido van Rossumb18618d2000-05-03 23:44:39 +0000264 PyMem_FREE(op->ob_item);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000265 }
Raymond Hettinger0468e412004-05-05 05:37:53 +0000266 if (num_free_lists < MAXFREELISTS && PyList_CheckExact(op))
267 free_lists[num_free_lists++] = op;
Tim Petersb38e2b62004-07-29 02:29:26 +0000268 else
269 op->ob_type->tp_free((PyObject *)op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000270 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000271}
272
Guido van Rossum90933611991-06-07 16:10:43 +0000273static int
Fred Drakea2f55112000-07-09 15:16:51 +0000274list_print(PyListObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000275{
276 int i;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000277
278 i = Py_ReprEnter((PyObject*)op);
279 if (i != 0) {
280 if (i < 0)
281 return i;
282 fprintf(fp, "[...]");
283 return 0;
284 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000285 fprintf(fp, "[");
Guido van Rossum90933611991-06-07 16:10:43 +0000286 for (i = 0; i < op->ob_size; i++) {
287 if (i > 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000288 fprintf(fp, ", ");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000289 if (PyObject_Print(op->ob_item[i], fp, 0) != 0) {
290 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000291 return -1;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000292 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000293 }
294 fprintf(fp, "]");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000295 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000296 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000297}
298
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000299static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000300list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000301{
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000302 int i;
Tim Petersa7259592001-06-16 05:11:17 +0000303 PyObject *s, *temp;
304 PyObject *pieces = NULL, *result = NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000305
306 i = Py_ReprEnter((PyObject*)v);
307 if (i != 0) {
Tim Petersa7259592001-06-16 05:11:17 +0000308 return i > 0 ? PyString_FromString("[...]") : NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000309 }
Tim Petersa7259592001-06-16 05:11:17 +0000310
311 if (v->ob_size == 0) {
312 result = PyString_FromString("[]");
313 goto Done;
314 }
315
316 pieces = PyList_New(0);
317 if (pieces == NULL)
318 goto Done;
319
320 /* Do repr() on each element. Note that this may mutate the list,
321 so must refetch the list size on each iteration. */
322 for (i = 0; i < v->ob_size; ++i) {
323 int status;
324 s = PyObject_Repr(v->ob_item[i]);
325 if (s == NULL)
326 goto Done;
327 status = PyList_Append(pieces, s);
328 Py_DECREF(s); /* append created a new ref */
329 if (status < 0)
330 goto Done;
331 }
332
333 /* Add "[]" decorations to the first and last items. */
334 assert(PyList_GET_SIZE(pieces) > 0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000335 s = PyString_FromString("[");
Tim Petersa7259592001-06-16 05:11:17 +0000336 if (s == NULL)
337 goto Done;
338 temp = PyList_GET_ITEM(pieces, 0);
339 PyString_ConcatAndDel(&s, temp);
340 PyList_SET_ITEM(pieces, 0, s);
341 if (s == NULL)
342 goto Done;
343
344 s = PyString_FromString("]");
345 if (s == NULL)
346 goto Done;
347 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
348 PyString_ConcatAndDel(&temp, s);
349 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
350 if (temp == NULL)
351 goto Done;
352
353 /* Paste them all together with ", " between. */
354 s = PyString_FromString(", ");
355 if (s == NULL)
356 goto Done;
357 result = _PyString_Join(s, pieces);
Tim Peters3b01a122002-07-19 02:35:45 +0000358 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +0000359
360Done:
361 Py_XDECREF(pieces);
Guido van Rossumfb376de1998-04-10 22:47:27 +0000362 Py_ReprLeave((PyObject *)v);
Tim Petersa7259592001-06-16 05:11:17 +0000363 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000364}
365
366static int
Fred Drakea2f55112000-07-09 15:16:51 +0000367list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000368{
369 return a->ob_size;
370}
371
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000372static int
Fred Drakea2f55112000-07-09 15:16:51 +0000373list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000374{
Raymond Hettingeraae59992002-09-05 14:23:49 +0000375 int i, cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000376
Raymond Hettingeraae59992002-09-05 14:23:49 +0000377 for (i = 0, cmp = 0 ; cmp == 0 && i < a->ob_size; ++i)
378 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000379 Py_EQ);
Neal Norwitzbb9c5f52002-09-05 21:32:55 +0000380 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000381}
382
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000383static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000384list_item(PyListObject *a, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000385{
386 if (i < 0 || i >= a->ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000387 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000388 indexerr = PyString_FromString(
389 "list index out of range");
390 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000391 return NULL;
392 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000393 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000394 return a->ob_item[i];
395}
396
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000397static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000398list_slice(PyListObject *a, int ilow, int ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000399{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000400 PyListObject *np;
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000401 PyObject **src, **dest;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000402 int i, len;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000403 if (ilow < 0)
404 ilow = 0;
405 else if (ilow > a->ob_size)
406 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000407 if (ihigh < ilow)
408 ihigh = ilow;
409 else if (ihigh > a->ob_size)
410 ihigh = a->ob_size;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000411 len = ihigh - ilow;
412 np = (PyListObject *) PyList_New(len);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000413 if (np == NULL)
414 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000415
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000416 src = a->ob_item + ilow;
417 dest = np->ob_item;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000418 for (i = 0; i < len; i++) {
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000419 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000420 Py_INCREF(v);
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000421 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000422 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000423 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000424}
425
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000426PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000427PyList_GetSlice(PyObject *a, int ilow, int ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000428{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000429 if (!PyList_Check(a)) {
430 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000431 return NULL;
432 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000433 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000434}
435
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000436static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000437list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000438{
439 int size;
440 int i;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000441 PyObject **src, **dest;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000442 PyListObject *np;
443 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000444 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000445 "can only concatenate list (not \"%.200s\") to list",
446 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000447 return NULL;
448 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000449#define b ((PyListObject *)bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000450 size = a->ob_size + b->ob_size;
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000451 if (size < 0)
452 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000453 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000454 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000455 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000456 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000457 src = a->ob_item;
458 dest = np->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000459 for (i = 0; i < a->ob_size; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000460 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000461 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000462 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000463 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000464 src = b->ob_item;
465 dest = np->ob_item + a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000466 for (i = 0; i < b->ob_size; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000467 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000468 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000469 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000470 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000471 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000472#undef b
473}
474
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000475static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000476list_repeat(PyListObject *a, int n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000477{
478 int i, j;
479 int size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000480 PyListObject *np;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000481 PyObject **p, **items;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000482 PyObject *elem;
Guido van Rossumed98d481991-03-06 13:07:53 +0000483 if (n < 0)
484 n = 0;
485 size = a->ob_size * n;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000486 if (size == 0)
487 return PyList_New(0);
Guido van Rossumbfa5a142002-10-11 23:39:35 +0000488 if (n && size/n != a->ob_size)
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000489 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000490 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000491 if (np == NULL)
492 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000493
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000494 items = np->ob_item;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000495 if (a->ob_size == 1) {
496 elem = a->ob_item[0];
497 for (i = 0; i < n; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000498 items[i] = elem;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000499 Py_INCREF(elem);
500 }
501 return (PyObject *) np;
502 }
Guido van Rossumed98d481991-03-06 13:07:53 +0000503 p = np->ob_item;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000504 items = a->ob_item;
Guido van Rossumed98d481991-03-06 13:07:53 +0000505 for (i = 0; i < n; i++) {
506 for (j = 0; j < a->ob_size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000507 *p = items[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000508 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000509 p++;
510 }
511 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000512 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000513}
514
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000515static int
Armin Rigo93677f02004-07-29 12:40:23 +0000516list_clear(PyListObject *a)
517{
518 int i;
519 PyObject **item = a->ob_item;
520 if (item != NULL) {
521 /* Because XDECREF can recursively invoke operations on
522 this list, we make it empty first. */
523 i = a->ob_size;
524 a->ob_size = 0;
525 a->ob_item = NULL;
526 a->allocated = 0;
527 while (--i >= 0) {
528 Py_XDECREF(item[i]);
529 }
530 PyMem_FREE(item);
531 }
532 /* Never fails; the return value can be ignored.
533 Note that there is no guarantee that the list is actually empty
534 at this point, because XDECREF may have populated it again! */
535 return 0;
536}
537
Tim Peters8fc4a912004-07-31 21:53:19 +0000538/* a[ilow:ihigh] = v if v != NULL.
539 * del a[ilow:ihigh] if v == NULL.
540 *
541 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
542 * guaranteed the call cannot fail.
543 */
Armin Rigo93677f02004-07-29 12:40:23 +0000544static int
Fred Drakea2f55112000-07-09 15:16:51 +0000545list_ass_slice(PyListObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000546{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000547 /* Because [X]DECREF can recursively invoke list operations on
548 this list, we must postpone all [X]DECREF activity until
549 after the list is back in its canonical shape. Therefore
550 we must allocate an additional array, 'recycle', into which
551 we temporarily copy the items that are deleted from the
552 list. :-( */
Tim Peters73572222004-07-31 02:54:42 +0000553 PyObject *recycle_on_stack[8];
554 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000555 PyObject **item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000556 PyObject **vitem = NULL;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000557 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
Tim Peters8d9eb102004-07-31 02:24:20 +0000558 int n; /* # of elements in replacement list */
559 int norig; /* # of elements in list getting replaced */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000560 int d; /* Change in size */
Tim Peters73572222004-07-31 02:54:42 +0000561 int k;
Tim Peters8d9eb102004-07-31 02:24:20 +0000562 size_t s;
563 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000564#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000565 if (v == NULL)
566 n = 0;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000567 else {
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000568 if (a == b) {
569 /* Special case "a[i:j] = a" -- copy b first */
Michael W. Hudsonda0a0672003-08-15 12:06:41 +0000570 v = list_slice(b, 0, b->ob_size);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000571 if (v == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000572 return result;
573 result = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000574 Py_DECREF(v);
Tim Peters8d9eb102004-07-31 02:24:20 +0000575 return result;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000576 }
Raymond Hettingerf889e102004-03-09 08:04:33 +0000577 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000578 if(v_as_SF == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000579 goto Error;
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000580 n = PySequence_Fast_GET_SIZE(v_as_SF);
Raymond Hettinger42bec932004-03-12 16:38:17 +0000581 vitem = PySequence_Fast_ITEMS(v_as_SF);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000582 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000583 if (ilow < 0)
584 ilow = 0;
585 else if (ilow > a->ob_size)
586 ilow = a->ob_size;
Tim Peters8d9eb102004-07-31 02:24:20 +0000587
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000588 if (ihigh < ilow)
589 ihigh = ilow;
590 else if (ihigh > a->ob_size)
591 ihigh = a->ob_size;
Armin Rigo93677f02004-07-29 12:40:23 +0000592
Tim Peters8d9eb102004-07-31 02:24:20 +0000593 norig = ihigh - ilow;
594 assert(norig >= 0);
595 d = n - norig;
Armin Rigo93677f02004-07-29 12:40:23 +0000596 if (a->ob_size + d == 0) {
597 Py_XDECREF(v_as_SF);
598 return list_clear(a);
599 }
600 item = a->ob_item;
Tim Peters8d9eb102004-07-31 02:24:20 +0000601 /* recycle the items that we are about to remove */
602 s = norig * sizeof(PyObject *);
Tim Peters73572222004-07-31 02:54:42 +0000603 if (s > sizeof(recycle_on_stack)) {
Armin Rigo1dd04a02004-07-30 11:38:22 +0000604 recycle = (PyObject **)PyMem_MALLOC(s);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000605 if (recycle == NULL) {
606 PyErr_NoMemory();
Tim Peters8d9eb102004-07-31 02:24:20 +0000607 goto Error;
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000608 }
609 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000610 memcpy(recycle, &item[ilow], s);
Tim Peters8d9eb102004-07-31 02:24:20 +0000611
Armin Rigo1dd04a02004-07-30 11:38:22 +0000612 if (d < 0) { /* Delete -d items */
613 memmove(&item[ihigh+d], &item[ihigh],
614 (a->ob_size - ihigh)*sizeof(PyObject *));
615 list_resize(a, a->ob_size + d);
616 item = a->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000617 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000618 else if (d > 0) { /* Insert d items */
Tim Peters73572222004-07-31 02:54:42 +0000619 k = a->ob_size;
620 if (list_resize(a, k+d) < 0)
Tim Peters8d9eb102004-07-31 02:24:20 +0000621 goto Error;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000622 item = a->ob_item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000623 memmove(&item[ihigh+d], &item[ihigh],
Tim Peters73572222004-07-31 02:54:42 +0000624 (k - ihigh)*sizeof(PyObject *));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000625 }
626 for (k = 0; k < n; k++, ilow++) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000627 PyObject *w = vitem[k];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000628 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000629 item[ilow] = w;
630 }
Tim Peters73572222004-07-31 02:54:42 +0000631 for (k = norig - 1; k >= 0; --k)
632 Py_XDECREF(recycle[k]);
Tim Peters8d9eb102004-07-31 02:24:20 +0000633 result = 0;
634 Error:
Tim Peters73572222004-07-31 02:54:42 +0000635 if (recycle != recycle_on_stack)
Armin Rigo1dd04a02004-07-30 11:38:22 +0000636 PyMem_FREE(recycle);
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000637 Py_XDECREF(v_as_SF);
Tim Peters8d9eb102004-07-31 02:24:20 +0000638 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000639#undef b
640}
641
Guido van Rossum234f9421993-06-17 12:35:49 +0000642int
Fred Drakea2f55112000-07-09 15:16:51 +0000643PyList_SetSlice(PyObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000644{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000645 if (!PyList_Check(a)) {
646 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000647 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000648 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000649 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000650}
651
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000652static PyObject *
653list_inplace_repeat(PyListObject *self, int n)
654{
655 PyObject **items;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000656 int size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000657
658
659 size = PyList_GET_SIZE(self);
660 if (size == 0) {
661 Py_INCREF(self);
662 return (PyObject *)self;
663 }
664
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000665 if (n < 1) {
Armin Rigo93677f02004-07-29 12:40:23 +0000666 (void)list_clear(self);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000667 Py_INCREF(self);
668 return (PyObject *)self;
669 }
670
Tim Petersb38e2b62004-07-29 02:29:26 +0000671 if (list_resize(self, size*n) == -1)
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000672 return NULL;
673
674 p = size;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000675 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000676 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
677 for (j = 0; j < size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000678 PyObject *o = items[j];
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000679 Py_INCREF(o);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000680 items[p++] = o;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000681 }
682 }
683 Py_INCREF(self);
684 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000685}
686
Guido van Rossum4a450d01991-04-03 19:05:18 +0000687static int
Fred Drakea2f55112000-07-09 15:16:51 +0000688list_ass_item(PyListObject *a, int i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000689{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000690 PyObject *old_value;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000691 if (i < 0 || i >= a->ob_size) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000692 PyErr_SetString(PyExc_IndexError,
693 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000694 return -1;
695 }
696 if (v == NULL)
697 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000698 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000699 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000700 a->ob_item[i] = v;
Tim Peters3b01a122002-07-19 02:35:45 +0000701 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000702 return 0;
703}
704
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000705static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000706listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000707{
708 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000709 PyObject *v;
Guido van Rossumc00a9382000-02-24 21:48:29 +0000710 if (!PyArg_ParseTuple(args, "iO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000711 return NULL;
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000712 if (ins1(self, i, v) == 0)
713 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000714 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000715}
716
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000717static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000718listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000719{
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000720 if (app1(self, v) == 0)
721 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000722 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000723}
724
Barry Warsawdedf6d61998-10-09 16:37:25 +0000725static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000726listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000727{
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000728 PyObject *it; /* iter(v) */
729 int m; /* size of self */
730 int n; /* guess for size of b */
731 int mn; /* m + n */
732 int i;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000733 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000734
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000735 /* Special cases:
Tim Petersb38e2b62004-07-29 02:29:26 +0000736 1) lists and tuples which can use PySequence_Fast ops
737 2) extending self to self requires making a copy first
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000738 */
739 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
Armin Rigo70d172d2004-03-20 22:19:23 +0000740 PyObject **src, **dest;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000741 b = PySequence_Fast(b, "argument must be iterable");
742 if (!b)
743 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000744 n = PySequence_Fast_GET_SIZE(b);
745 if (n == 0) {
746 /* short circuit when b is empty */
747 Py_DECREF(b);
748 Py_RETURN_NONE;
749 }
750 m = self->ob_size;
751 if (list_resize(self, m + n) == -1) {
752 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000753 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000754 }
755 /* note that we may still have self == b here for the
756 * situation a.extend(a), but the following code works
757 * in that case too. Just make sure to resize self
758 * before calling PySequence_Fast_ITEMS.
759 */
760 /* populate the end of self with b's items */
761 src = PySequence_Fast_ITEMS(b);
762 dest = self->ob_item + m;
763 for (i = 0; i < n; i++) {
764 PyObject *o = src[i];
765 Py_INCREF(o);
766 dest[i] = o;
767 }
768 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000769 Py_RETURN_NONE;
770 }
771
772 it = PyObject_GetIter(b);
773 if (it == NULL)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000774 return NULL;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000775 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000776
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000777 /* Guess a result list size. */
778 n = PyObject_Size(b);
779 if (n < 0) {
780 PyErr_Clear();
781 n = 8; /* arbitrary */
782 }
783 m = self->ob_size;
784 mn = m + n;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000785 if (mn >= m) {
786 /* Make room. */
787 if (list_resize(self, mn) == -1)
788 goto error;
789 /* Make the list sane again. */
790 self->ob_size = m;
791 }
792 /* Else m + n overflowed; on the chance that n lied, and there really
793 * is enough room, ignore it. If n was telling the truth, we'll
794 * eventually run out of memory during the loop.
795 */
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000796
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000797 /* Run iterator to exhaustion. */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000798 for (;;) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000799 PyObject *item = iternext(it);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000800 if (item == NULL) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000801 if (PyErr_Occurred()) {
802 if (PyErr_ExceptionMatches(PyExc_StopIteration))
803 PyErr_Clear();
804 else
805 goto error;
806 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000807 break;
808 }
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000809 if (self->ob_size < self->allocated) {
810 /* steals ref */
811 PyList_SET_ITEM(self, self->ob_size, item);
812 ++self->ob_size;
813 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000814 else {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000815 int status = app1(self, item);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000816 Py_DECREF(item); /* append creates a new ref */
817 if (status < 0)
818 goto error;
819 }
820 }
821
822 /* Cut back result list if initial guess was too large. */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000823 if (self->ob_size < self->allocated)
824 list_resize(self, self->ob_size); /* shrinking can't fail */
825
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000826 Py_DECREF(it);
827 Py_RETURN_NONE;
828
829 error:
830 Py_DECREF(it);
831 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000832}
833
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000834PyObject *
835_PyList_Extend(PyListObject *self, PyObject *b)
836{
837 return listextend(self, b);
838}
839
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000840static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000841list_inplace_concat(PyListObject *self, PyObject *other)
842{
843 PyObject *result;
844
845 result = listextend(self, other);
846 if (result == NULL)
847 return result;
848 Py_DECREF(result);
849 Py_INCREF(self);
850 return (PyObject *)self;
851}
852
853static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000854listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000855{
856 int i = -1;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000857 PyObject *v, *arg = NULL;
Tim Peters8fc4a912004-07-31 21:53:19 +0000858 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000859
860 if (!PyArg_UnpackTuple(args, "pop", 0, 1, &arg))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000861 return NULL;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000862 if (arg != NULL) {
863 if (PyInt_Check(arg))
864 i = (int)(PyInt_AS_LONG((PyIntObject*) arg));
Raymond Hettingerfa6c6f82004-02-19 06:12:06 +0000865 else if (!PyArg_ParseTuple(args, "|i:pop", &i))
866 return NULL;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000867 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000868 if (self->ob_size == 0) {
869 /* Special-case most common failure cause */
870 PyErr_SetString(PyExc_IndexError, "pop from empty list");
871 return NULL;
872 }
873 if (i < 0)
874 i += self->ob_size;
875 if (i < 0 || i >= self->ob_size) {
876 PyErr_SetString(PyExc_IndexError, "pop index out of range");
877 return NULL;
878 }
879 v = self->ob_item[i];
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000880 if (i == self->ob_size - 1) {
Tim Peters8fc4a912004-07-31 21:53:19 +0000881 status = list_resize(self, self->ob_size - 1);
882 assert(status >= 0);
883 return v; /* and v now owns the reference the list had */
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000884 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000885 Py_INCREF(v);
Tim Peters8fc4a912004-07-31 21:53:19 +0000886 status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
887 assert(status >= 0);
888 /* Use status, so that in a release build compilers don't
889 * complain about the unused name.
890 */
Brett Cannon651dd522004-08-08 21:21:18 +0000891 (void) status;
892
893 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000894}
895
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000896/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
897static void
898reverse_slice(PyObject **lo, PyObject **hi)
899{
900 assert(lo && hi);
901
902 --hi;
903 while (lo < hi) {
904 PyObject *t = *lo;
905 *lo = *hi;
906 *hi = t;
907 ++lo;
908 --hi;
909 }
910}
911
Tim Petersa64dc242002-08-01 02:13:36 +0000912/* Lots of code for an adaptive, stable, natural mergesort. There are many
913 * pieces to this algorithm; read listsort.txt for overviews and details.
914 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000915
Guido van Rossum3f236de1996-12-10 23:55:39 +0000916/* Comparison function. Takes care of calling a user-supplied
Tim Peters66860f62002-08-04 17:47:26 +0000917 * comparison function (any callable Python object), which must not be
918 * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool
919 * with Py_LT if you know it's NULL).
Tim Petersa64dc242002-08-01 02:13:36 +0000920 * Returns -1 on error, 1 if x < y, 0 if x >= y.
921 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000922static int
Tim Petersa8c974c2002-07-19 03:30:57 +0000923islt(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000924{
Tim Petersf2a04732002-07-11 21:46:16 +0000925 PyObject *res;
926 PyObject *args;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000927 int i;
928
Tim Peters66860f62002-08-04 17:47:26 +0000929 assert(compare != NULL);
Tim Petersa8c974c2002-07-19 03:30:57 +0000930 /* Call the user's comparison function and translate the 3-way
931 * result into true or false (or error).
932 */
Tim Petersf2a04732002-07-11 21:46:16 +0000933 args = PyTuple_New(2);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000934 if (args == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000935 return -1;
Tim Petersf2a04732002-07-11 21:46:16 +0000936 Py_INCREF(x);
937 Py_INCREF(y);
938 PyTuple_SET_ITEM(args, 0, x);
939 PyTuple_SET_ITEM(args, 1, y);
Tim Peters58cf3612002-07-15 05:16:13 +0000940 res = PyObject_Call(compare, args, NULL);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000941 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000942 if (res == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000943 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000944 if (!PyInt_Check(res)) {
945 Py_DECREF(res);
946 PyErr_SetString(PyExc_TypeError,
Guido van Rossum9bcd1d71999-04-19 17:44:39 +0000947 "comparison function must return int");
Tim Petersa8c974c2002-07-19 03:30:57 +0000948 return -1;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000949 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000950 i = PyInt_AsLong(res);
951 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +0000952 return i < 0;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000953}
954
Tim Peters66860f62002-08-04 17:47:26 +0000955/* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
956 * islt. This avoids a layer of function call in the usual case, and
957 * sorting does many comparisons.
958 * Returns -1 on error, 1 if x < y, 0 if x >= y.
959 */
960#define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
961 PyObject_RichCompareBool(X, Y, Py_LT) : \
962 islt(X, Y, COMPARE))
963
964/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +0000965 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
966 started. It makes more sense in context <wink>. X and Y are PyObject*s.
967*/
Tim Peters66860f62002-08-04 17:47:26 +0000968#define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
Tim Petersa8c974c2002-07-19 03:30:57 +0000969 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000970
971/* binarysort is the best method for sorting small arrays: it does
972 few compares, but can do data movement quadratic in the number of
973 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000974 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +0000975 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000976 On entry, must have lo <= start <= hi, and that [lo, start) is already
977 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +0000978 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000979 Even in case of error, the output slice will be some permutation of
980 the input (nothing is lost or duplicated).
981*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000982static int
Fred Drakea2f55112000-07-09 15:16:51 +0000983binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
984 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000985{
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000986 register int k;
987 register PyObject **l, **p, **r;
988 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000989
Tim Petersa8c974c2002-07-19 03:30:57 +0000990 assert(lo <= start && start <= hi);
991 /* assert [lo, start) is sorted */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000992 if (lo == start)
993 ++start;
994 for (; start < hi; ++start) {
995 /* set l to where *start belongs */
996 l = lo;
997 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000998 pivot = *r;
Tim Peters0fe977c2002-07-19 06:12:32 +0000999 /* Invariants:
1000 * pivot >= all in [lo, l).
1001 * pivot < all in [r, start).
1002 * The second is vacuously true at the start.
1003 */
1004 assert(l < r);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001005 do {
1006 p = l + ((r - l) >> 1);
Tim Petersa8c974c2002-07-19 03:30:57 +00001007 IFLT(pivot, *p)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001008 r = p;
1009 else
Tim Peters0fe977c2002-07-19 06:12:32 +00001010 l = p+1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001011 } while (l < r);
Tim Peters0fe977c2002-07-19 06:12:32 +00001012 assert(l == r);
1013 /* The invariants still hold, so pivot >= all in [lo, l) and
1014 pivot < all in [l, start), so pivot belongs at l. Note
1015 that if there are elements equal to pivot, l points to the
1016 first slot after them -- that's why this sort is stable.
1017 Slide over to make room.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001018 Caution: using memmove is much slower under MSVC 5;
1019 we're not usually moving many slots. */
1020 for (p = start; p > l; --p)
1021 *p = *(p-1);
1022 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001023 }
Guido van Rossum3f236de1996-12-10 23:55:39 +00001024 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001025
1026 fail:
1027 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001028}
1029
Tim Petersa64dc242002-08-01 02:13:36 +00001030/*
1031Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1032is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001033
Tim Petersa64dc242002-08-01 02:13:36 +00001034 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001035
Tim Petersa64dc242002-08-01 02:13:36 +00001036or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001037
Tim Petersa64dc242002-08-01 02:13:36 +00001038 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001039
Tim Petersa64dc242002-08-01 02:13:36 +00001040Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1041For its intended use in a stable mergesort, the strictness of the defn of
1042"descending" is needed so that the caller can safely reverse a descending
1043sequence without violating stability (strict > ensures there are no equal
1044elements to get out of order).
1045
1046Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001047*/
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001048static int
Tim Petersa64dc242002-08-01 02:13:36 +00001049count_run(PyObject **lo, PyObject **hi, PyObject *compare, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001050{
Tim Petersa64dc242002-08-01 02:13:36 +00001051 int k;
1052 int n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001053
Tim Petersa64dc242002-08-01 02:13:36 +00001054 assert(lo < hi);
1055 *descending = 0;
1056 ++lo;
1057 if (lo == hi)
1058 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001059
Tim Petersa64dc242002-08-01 02:13:36 +00001060 n = 2;
1061 IFLT(*lo, *(lo-1)) {
1062 *descending = 1;
1063 for (lo = lo+1; lo < hi; ++lo, ++n) {
1064 IFLT(*lo, *(lo-1))
1065 ;
1066 else
1067 break;
1068 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001069 }
Tim Petersa64dc242002-08-01 02:13:36 +00001070 else {
1071 for (lo = lo+1; lo < hi; ++lo, ++n) {
1072 IFLT(*lo, *(lo-1))
1073 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001074 }
1075 }
1076
Tim Petersa64dc242002-08-01 02:13:36 +00001077 return n;
1078fail:
1079 return -1;
1080}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001081
Tim Petersa64dc242002-08-01 02:13:36 +00001082/*
1083Locate the proper position of key in a sorted vector; if the vector contains
1084an element equal to key, return the position immediately to the left of
1085the leftmost equal element. [gallop_right() does the same except returns
1086the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001087
Tim Petersa64dc242002-08-01 02:13:36 +00001088"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001089
Tim Petersa64dc242002-08-01 02:13:36 +00001090"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1091hint is to the final result, the faster this runs.
1092
1093The return value is the int k in 0..n such that
1094
1095 a[k-1] < key <= a[k]
1096
1097pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1098key belongs at index k; or, IOW, the first k elements of a should precede
1099key, and the last n-k should follow key.
1100
1101Returns -1 on error. See listsort.txt for info on the method.
1102*/
1103static int
1104gallop_left(PyObject *key, PyObject **a, int n, int hint, PyObject *compare)
1105{
1106 int ofs;
1107 int lastofs;
1108 int k;
1109
1110 assert(key && a && n > 0 && hint >= 0 && hint < n);
1111
1112 a += hint;
1113 lastofs = 0;
1114 ofs = 1;
1115 IFLT(*a, key) {
1116 /* a[hint] < key -- gallop right, until
1117 * a[hint + lastofs] < key <= a[hint + ofs]
1118 */
1119 const int maxofs = n - hint; /* &a[n-1] is highest */
1120 while (ofs < maxofs) {
1121 IFLT(a[ofs], key) {
1122 lastofs = ofs;
1123 ofs = (ofs << 1) + 1;
1124 if (ofs <= 0) /* int overflow */
1125 ofs = maxofs;
1126 }
1127 else /* key <= a[hint + ofs] */
1128 break;
1129 }
1130 if (ofs > maxofs)
1131 ofs = maxofs;
1132 /* Translate back to offsets relative to &a[0]. */
1133 lastofs += hint;
1134 ofs += hint;
1135 }
1136 else {
1137 /* key <= a[hint] -- gallop left, until
1138 * a[hint - ofs] < key <= a[hint - lastofs]
1139 */
1140 const int maxofs = hint + 1; /* &a[0] is lowest */
1141 while (ofs < maxofs) {
1142 IFLT(*(a-ofs), key)
1143 break;
1144 /* key <= a[hint - ofs] */
1145 lastofs = ofs;
1146 ofs = (ofs << 1) + 1;
1147 if (ofs <= 0) /* int overflow */
1148 ofs = maxofs;
1149 }
1150 if (ofs > maxofs)
1151 ofs = maxofs;
1152 /* Translate back to positive offsets relative to &a[0]. */
1153 k = lastofs;
1154 lastofs = hint - ofs;
1155 ofs = hint - k;
1156 }
1157 a -= hint;
1158
1159 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1160 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1161 * right of lastofs but no farther right than ofs. Do a binary
1162 * search, with invariant a[lastofs-1] < key <= a[ofs].
1163 */
1164 ++lastofs;
1165 while (lastofs < ofs) {
1166 int m = lastofs + ((ofs - lastofs) >> 1);
1167
1168 IFLT(a[m], key)
1169 lastofs = m+1; /* a[m] < key */
1170 else
1171 ofs = m; /* key <= a[m] */
1172 }
1173 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1174 return ofs;
1175
1176fail:
1177 return -1;
1178}
1179
1180/*
1181Exactly like gallop_left(), except that if key already exists in a[0:n],
1182finds the position immediately to the right of the rightmost equal value.
1183
1184The return value is the int k in 0..n such that
1185
1186 a[k-1] <= key < a[k]
1187
1188or -1 if error.
1189
1190The code duplication is massive, but this is enough different given that
1191we're sticking to "<" comparisons that it's much harder to follow if
1192written as one routine with yet another "left or right?" flag.
1193*/
1194static int
1195gallop_right(PyObject *key, PyObject **a, int n, int hint, PyObject *compare)
1196{
1197 int ofs;
1198 int lastofs;
1199 int k;
1200
1201 assert(key && a && n > 0 && hint >= 0 && hint < n);
1202
1203 a += hint;
1204 lastofs = 0;
1205 ofs = 1;
1206 IFLT(key, *a) {
1207 /* key < a[hint] -- gallop left, until
1208 * a[hint - ofs] <= key < a[hint - lastofs]
1209 */
1210 const int maxofs = hint + 1; /* &a[0] is lowest */
1211 while (ofs < maxofs) {
1212 IFLT(key, *(a-ofs)) {
1213 lastofs = ofs;
1214 ofs = (ofs << 1) + 1;
1215 if (ofs <= 0) /* int overflow */
1216 ofs = maxofs;
1217 }
1218 else /* a[hint - ofs] <= key */
1219 break;
1220 }
1221 if (ofs > maxofs)
1222 ofs = maxofs;
1223 /* Translate back to positive offsets relative to &a[0]. */
1224 k = lastofs;
1225 lastofs = hint - ofs;
1226 ofs = hint - k;
1227 }
1228 else {
1229 /* a[hint] <= key -- gallop right, until
1230 * a[hint + lastofs] <= key < a[hint + ofs]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001231 */
Tim Petersa64dc242002-08-01 02:13:36 +00001232 const int maxofs = n - hint; /* &a[n-1] is highest */
1233 while (ofs < maxofs) {
1234 IFLT(key, a[ofs])
1235 break;
1236 /* a[hint + ofs] <= key */
1237 lastofs = ofs;
1238 ofs = (ofs << 1) + 1;
1239 if (ofs <= 0) /* int overflow */
1240 ofs = maxofs;
1241 }
1242 if (ofs > maxofs)
1243 ofs = maxofs;
1244 /* Translate back to offsets relative to &a[0]. */
1245 lastofs += hint;
1246 ofs += hint;
1247 }
1248 a -= hint;
1249
1250 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1251 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1252 * right of lastofs but no farther right than ofs. Do a binary
1253 * search, with invariant a[lastofs-1] <= key < a[ofs].
1254 */
1255 ++lastofs;
1256 while (lastofs < ofs) {
1257 int m = lastofs + ((ofs - lastofs) >> 1);
1258
1259 IFLT(key, a[m])
1260 ofs = m; /* key < a[m] */
1261 else
1262 lastofs = m+1; /* a[m] <= key */
1263 }
1264 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1265 return ofs;
1266
1267fail:
1268 return -1;
1269}
1270
1271/* The maximum number of entries in a MergeState's pending-runs stack.
1272 * This is enough to sort arrays of size up to about
1273 * 32 * phi ** MAX_MERGE_PENDING
1274 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1275 * with 2**64 elements.
1276 */
1277#define MAX_MERGE_PENDING 85
1278
Tim Peterse05f65a2002-08-10 05:21:15 +00001279/* When we get into galloping mode, we stay there until both runs win less
1280 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001281 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001282#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001283
1284/* Avoid malloc for small temp arrays. */
1285#define MERGESTATE_TEMP_SIZE 256
1286
1287/* One MergeState exists on the stack per invocation of mergesort. It's just
1288 * a convenient way to pass state around among the helper functions.
1289 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001290struct s_slice {
1291 PyObject **base;
1292 int len;
1293};
1294
Tim Petersa64dc242002-08-01 02:13:36 +00001295typedef struct s_MergeState {
1296 /* The user-supplied comparison function. or NULL if none given. */
1297 PyObject *compare;
1298
Tim Peterse05f65a2002-08-10 05:21:15 +00001299 /* This controls when we get *into* galloping mode. It's initialized
1300 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1301 * random data, and lower for highly structured data.
1302 */
1303 int min_gallop;
1304
Tim Petersa64dc242002-08-01 02:13:36 +00001305 /* 'a' is temp storage to help with merges. It contains room for
1306 * alloced entries.
1307 */
1308 PyObject **a; /* may point to temparray below */
1309 int alloced;
1310
1311 /* A stack of n pending runs yet to be merged. Run #i starts at
1312 * address base[i] and extends for len[i] elements. It's always
1313 * true (so long as the indices are in bounds) that
1314 *
Tim Peterse05f65a2002-08-10 05:21:15 +00001315 * pending[i].base + pending[i].len == pending[i+1].base
Tim Petersa64dc242002-08-01 02:13:36 +00001316 *
1317 * so we could cut the storage for this, but it's a minor amount,
1318 * and keeping all the info explicit simplifies the code.
1319 */
1320 int n;
Tim Peterse05f65a2002-08-10 05:21:15 +00001321 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001322
1323 /* 'a' points to this when possible, rather than muck with malloc. */
1324 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1325} MergeState;
1326
1327/* Conceptually a MergeState's constructor. */
1328static void
1329merge_init(MergeState *ms, PyObject *compare)
1330{
1331 assert(ms != NULL);
1332 ms->compare = compare;
1333 ms->a = ms->temparray;
1334 ms->alloced = MERGESTATE_TEMP_SIZE;
1335 ms->n = 0;
Tim Peterse05f65a2002-08-10 05:21:15 +00001336 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001337}
1338
1339/* Free all the temp memory owned by the MergeState. This must be called
1340 * when you're done with a MergeState, and may be called before then if
1341 * you want to free the temp memory early.
1342 */
1343static void
1344merge_freemem(MergeState *ms)
1345{
1346 assert(ms != NULL);
1347 if (ms->a != ms->temparray)
1348 PyMem_Free(ms->a);
1349 ms->a = ms->temparray;
1350 ms->alloced = MERGESTATE_TEMP_SIZE;
1351}
1352
1353/* Ensure enough temp memory for 'need' array slots is available.
1354 * Returns 0 on success and -1 if the memory can't be gotten.
1355 */
1356static int
1357merge_getmem(MergeState *ms, int need)
1358{
1359 assert(ms != NULL);
1360 if (need <= ms->alloced)
1361 return 0;
1362 /* Don't realloc! That can cost cycles to copy the old data, but
1363 * we don't care what's in the block.
1364 */
1365 merge_freemem(ms);
1366 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1367 if (ms->a) {
1368 ms->alloced = need;
1369 return 0;
1370 }
1371 PyErr_NoMemory();
1372 merge_freemem(ms); /* reset to sane state */
1373 return -1;
1374}
1375#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1376 merge_getmem(MS, NEED))
1377
1378/* Merge the na elements starting at pa with the nb elements starting at pb
1379 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1380 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1381 * merge, and should have na <= nb. See listsort.txt for more info.
1382 * Return 0 if successful, -1 if error.
1383 */
1384static int
1385merge_lo(MergeState *ms, PyObject **pa, int na, PyObject **pb, int nb)
1386{
1387 int k;
1388 PyObject *compare;
1389 PyObject **dest;
1390 int result = -1; /* guilty until proved innocent */
Tim Peterse05f65a2002-08-10 05:21:15 +00001391 int min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001392
1393 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1394 if (MERGE_GETMEM(ms, na) < 0)
1395 return -1;
1396 memcpy(ms->a, pa, na * sizeof(PyObject*));
1397 dest = pa;
1398 pa = ms->a;
1399
1400 *dest++ = *pb++;
1401 --nb;
1402 if (nb == 0)
1403 goto Succeed;
1404 if (na == 1)
1405 goto CopyB;
1406
1407 compare = ms->compare;
1408 for (;;) {
1409 int acount = 0; /* # of times A won in a row */
1410 int bcount = 0; /* # of times B won in a row */
1411
1412 /* Do the straightforward thing until (if ever) one run
1413 * appears to win consistently.
1414 */
1415 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001416 assert(na > 1 && nb > 0);
Tim Peters66860f62002-08-04 17:47:26 +00001417 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001418 if (k) {
1419 if (k < 0)
1420 goto Fail;
1421 *dest++ = *pb++;
1422 ++bcount;
1423 acount = 0;
1424 --nb;
1425 if (nb == 0)
1426 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001427 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001428 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001429 }
1430 else {
Tim Petersa64dc242002-08-01 02:13:36 +00001431 *dest++ = *pa++;
1432 ++acount;
1433 bcount = 0;
1434 --na;
1435 if (na == 1)
1436 goto CopyB;
Tim Peterse05f65a2002-08-10 05:21:15 +00001437 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001438 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001439 }
Tim Petersa64dc242002-08-01 02:13:36 +00001440 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001441
Tim Petersa64dc242002-08-01 02:13:36 +00001442 /* One run is winning so consistently that galloping may
1443 * be a huge win. So try that, and continue galloping until
1444 * (if ever) neither run appears to be winning consistently
1445 * anymore.
1446 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001447 ++min_gallop;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001448 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001449 assert(na > 1 && nb > 0);
1450 min_gallop -= min_gallop > 1;
1451 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001452 k = gallop_right(*pb, pa, na, 0, compare);
1453 acount = k;
1454 if (k) {
1455 if (k < 0)
1456 goto Fail;
1457 memcpy(dest, pa, k * sizeof(PyObject *));
1458 dest += k;
1459 pa += k;
1460 na -= k;
1461 if (na == 1)
1462 goto CopyB;
1463 /* na==0 is impossible now if the comparison
1464 * function is consistent, but we can't assume
1465 * that it is.
1466 */
1467 if (na == 0)
1468 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001469 }
Tim Petersa64dc242002-08-01 02:13:36 +00001470 *dest++ = *pb++;
1471 --nb;
1472 if (nb == 0)
1473 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001474
Tim Petersa64dc242002-08-01 02:13:36 +00001475 k = gallop_left(*pa, pb, nb, 0, compare);
1476 bcount = k;
1477 if (k) {
1478 if (k < 0)
1479 goto Fail;
1480 memmove(dest, pb, k * sizeof(PyObject *));
1481 dest += k;
1482 pb += k;
1483 nb -= k;
1484 if (nb == 0)
1485 goto Succeed;
1486 }
1487 *dest++ = *pa++;
1488 --na;
1489 if (na == 1)
1490 goto CopyB;
1491 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001492 ++min_gallop; /* penalize it for leaving galloping mode */
1493 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001494 }
1495Succeed:
1496 result = 0;
1497Fail:
1498 if (na)
1499 memcpy(dest, pa, na * sizeof(PyObject*));
1500 return result;
1501CopyB:
1502 assert(na == 1 && nb > 0);
1503 /* The last element of pa belongs at the end of the merge. */
1504 memmove(dest, pb, nb * sizeof(PyObject *));
1505 dest[nb] = *pa;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001506 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001507}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001508
Tim Petersa64dc242002-08-01 02:13:36 +00001509/* Merge the na elements starting at pa with the nb elements starting at pb
1510 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1511 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1512 * merge, and should have na >= nb. See listsort.txt for more info.
1513 * Return 0 if successful, -1 if error.
1514 */
1515static int
1516merge_hi(MergeState *ms, PyObject **pa, int na, PyObject **pb, int nb)
1517{
1518 int k;
1519 PyObject *compare;
1520 PyObject **dest;
1521 int result = -1; /* guilty until proved innocent */
1522 PyObject **basea;
1523 PyObject **baseb;
Tim Peterse05f65a2002-08-10 05:21:15 +00001524 int min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001525
1526 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1527 if (MERGE_GETMEM(ms, nb) < 0)
1528 return -1;
1529 dest = pb + nb - 1;
1530 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1531 basea = pa;
1532 baseb = ms->a;
1533 pb = ms->a + nb - 1;
1534 pa += na - 1;
1535
1536 *dest-- = *pa--;
1537 --na;
1538 if (na == 0)
1539 goto Succeed;
1540 if (nb == 1)
1541 goto CopyA;
1542
1543 compare = ms->compare;
1544 for (;;) {
1545 int acount = 0; /* # of times A won in a row */
1546 int bcount = 0; /* # of times B won in a row */
1547
1548 /* Do the straightforward thing until (if ever) one run
1549 * appears to win consistently.
1550 */
1551 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001552 assert(na > 0 && nb > 1);
Tim Peters66860f62002-08-04 17:47:26 +00001553 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001554 if (k) {
1555 if (k < 0)
1556 goto Fail;
1557 *dest-- = *pa--;
1558 ++acount;
1559 bcount = 0;
1560 --na;
1561 if (na == 0)
1562 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001563 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001564 break;
1565 }
1566 else {
1567 *dest-- = *pb--;
1568 ++bcount;
1569 acount = 0;
1570 --nb;
1571 if (nb == 1)
1572 goto CopyA;
Tim Peterse05f65a2002-08-10 05:21:15 +00001573 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001574 break;
1575 }
1576 }
1577
1578 /* One run is winning so consistently that galloping may
1579 * be a huge win. So try that, and continue galloping until
1580 * (if ever) neither run appears to be winning consistently
1581 * anymore.
1582 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001583 ++min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001584 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001585 assert(na > 0 && nb > 1);
1586 min_gallop -= min_gallop > 1;
1587 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001588 k = gallop_right(*pb, basea, na, na-1, compare);
1589 if (k < 0)
1590 goto Fail;
1591 k = na - k;
1592 acount = k;
1593 if (k) {
1594 dest -= k;
1595 pa -= k;
1596 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1597 na -= k;
1598 if (na == 0)
1599 goto Succeed;
1600 }
1601 *dest-- = *pb--;
1602 --nb;
1603 if (nb == 1)
1604 goto CopyA;
1605
1606 k = gallop_left(*pa, baseb, nb, nb-1, compare);
1607 if (k < 0)
1608 goto Fail;
1609 k = nb - k;
1610 bcount = k;
1611 if (k) {
1612 dest -= k;
1613 pb -= k;
1614 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1615 nb -= k;
1616 if (nb == 1)
1617 goto CopyA;
1618 /* nb==0 is impossible now if the comparison
1619 * function is consistent, but we can't assume
1620 * that it is.
1621 */
1622 if (nb == 0)
1623 goto Succeed;
1624 }
1625 *dest-- = *pa--;
1626 --na;
1627 if (na == 0)
1628 goto Succeed;
1629 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001630 ++min_gallop; /* penalize it for leaving galloping mode */
1631 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001632 }
1633Succeed:
1634 result = 0;
1635Fail:
1636 if (nb)
1637 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1638 return result;
1639CopyA:
1640 assert(nb == 1 && na > 0);
1641 /* The first element of pb belongs at the front of the merge. */
1642 dest -= na;
1643 pa -= na;
1644 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1645 *dest = *pb;
1646 return 0;
1647}
1648
1649/* Merge the two runs at stack indices i and i+1.
1650 * Returns 0 on success, -1 on error.
1651 */
1652static int
1653merge_at(MergeState *ms, int i)
1654{
1655 PyObject **pa, **pb;
1656 int na, nb;
1657 int k;
1658 PyObject *compare;
1659
1660 assert(ms != NULL);
1661 assert(ms->n >= 2);
1662 assert(i >= 0);
1663 assert(i == ms->n - 2 || i == ms->n - 3);
1664
Tim Peterse05f65a2002-08-10 05:21:15 +00001665 pa = ms->pending[i].base;
1666 na = ms->pending[i].len;
1667 pb = ms->pending[i+1].base;
1668 nb = ms->pending[i+1].len;
Tim Petersa64dc242002-08-01 02:13:36 +00001669 assert(na > 0 && nb > 0);
1670 assert(pa + na == pb);
1671
1672 /* Record the length of the combined runs; if i is the 3rd-last
1673 * run now, also slide over the last run (which isn't involved
1674 * in this merge). The current run i+1 goes away in any case.
1675 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001676 ms->pending[i].len = na + nb;
1677 if (i == ms->n - 3)
1678 ms->pending[i+1] = ms->pending[i+2];
Tim Petersa64dc242002-08-01 02:13:36 +00001679 --ms->n;
1680
1681 /* Where does b start in a? Elements in a before that can be
1682 * ignored (already in place).
1683 */
1684 compare = ms->compare;
1685 k = gallop_right(*pb, pa, na, 0, compare);
1686 if (k < 0)
1687 return -1;
1688 pa += k;
1689 na -= k;
1690 if (na == 0)
1691 return 0;
1692
1693 /* Where does a end in b? Elements in b after that can be
1694 * ignored (already in place).
1695 */
1696 nb = gallop_left(pa[na-1], pb, nb, nb-1, compare);
1697 if (nb <= 0)
1698 return nb;
1699
1700 /* Merge what remains of the runs, using a temp array with
1701 * min(na, nb) elements.
1702 */
1703 if (na <= nb)
1704 return merge_lo(ms, pa, na, pb, nb);
1705 else
1706 return merge_hi(ms, pa, na, pb, nb);
1707}
1708
1709/* Examine the stack of runs waiting to be merged, merging adjacent runs
1710 * until the stack invariants are re-established:
1711 *
1712 * 1. len[-3] > len[-2] + len[-1]
1713 * 2. len[-2] > len[-1]
1714 *
1715 * See listsort.txt for more info.
1716 *
1717 * Returns 0 on success, -1 on error.
1718 */
1719static int
1720merge_collapse(MergeState *ms)
1721{
Tim Peterse05f65a2002-08-10 05:21:15 +00001722 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001723
1724 assert(ms);
1725 while (ms->n > 1) {
1726 int n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001727 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1728 if (p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001729 --n;
1730 if (merge_at(ms, n) < 0)
1731 return -1;
1732 }
Tim Peterse05f65a2002-08-10 05:21:15 +00001733 else if (p[n].len <= p[n+1].len) {
Tim Petersa64dc242002-08-01 02:13:36 +00001734 if (merge_at(ms, n) < 0)
1735 return -1;
1736 }
1737 else
1738 break;
1739 }
1740 return 0;
1741}
1742
1743/* Regardless of invariants, merge all runs on the stack until only one
1744 * remains. This is used at the end of the mergesort.
1745 *
1746 * Returns 0 on success, -1 on error.
1747 */
1748static int
1749merge_force_collapse(MergeState *ms)
1750{
Tim Peterse05f65a2002-08-10 05:21:15 +00001751 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001752
1753 assert(ms);
1754 while (ms->n > 1) {
1755 int n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001756 if (n > 0 && p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001757 --n;
1758 if (merge_at(ms, n) < 0)
1759 return -1;
1760 }
1761 return 0;
1762}
1763
1764/* Compute a good value for the minimum run length; natural runs shorter
1765 * than this are boosted artificially via binary insertion.
1766 *
1767 * If n < 64, return n (it's too small to bother with fancy stuff).
1768 * Else if n is an exact power of 2, return 32.
1769 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1770 * strictly less than, an exact power of 2.
1771 *
1772 * See listsort.txt for more info.
1773 */
1774static int
1775merge_compute_minrun(int n)
1776{
1777 int r = 0; /* becomes 1 if any 1 bits are shifted off */
1778
1779 assert(n >= 0);
1780 while (n >= 64) {
1781 r |= n & 1;
1782 n >>= 1;
1783 }
1784 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001785}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001786
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001787/* Special wrapper to support stable sorting using the decorate-sort-undecorate
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001788 pattern. Holds a key which is used for comparisons and the original record
Tim Petersb38e2b62004-07-29 02:29:26 +00001789 which is returned during the undecorate phase. By exposing only the key
1790 during comparisons, the underlying sort stability characteristics are left
1791 unchanged. Also, if a custom comparison function is used, it will only see
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001792 the key instead of a full record. */
1793
1794typedef struct {
1795 PyObject_HEAD
1796 PyObject *key;
1797 PyObject *value;
1798} sortwrapperobject;
1799
1800static PyTypeObject sortwrapper_type;
1801
1802static PyObject *
1803sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
1804{
1805 if (!PyObject_TypeCheck(b, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001806 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001807 "expected a sortwrapperobject");
1808 return NULL;
1809 }
1810 return PyObject_RichCompare(a->key, b->key, op);
1811}
1812
1813static void
1814sortwrapper_dealloc(sortwrapperobject *so)
1815{
1816 Py_XDECREF(so->key);
1817 Py_XDECREF(so->value);
1818 PyObject_Del(so);
1819}
1820
1821PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
1822
1823static PyTypeObject sortwrapper_type = {
1824 PyObject_HEAD_INIT(&PyType_Type)
1825 0, /* ob_size */
1826 "sortwrapper", /* tp_name */
1827 sizeof(sortwrapperobject), /* tp_basicsize */
1828 0, /* tp_itemsize */
1829 /* methods */
1830 (destructor)sortwrapper_dealloc, /* tp_dealloc */
1831 0, /* tp_print */
1832 0, /* tp_getattr */
1833 0, /* tp_setattr */
1834 0, /* tp_compare */
1835 0, /* tp_repr */
1836 0, /* tp_as_number */
1837 0, /* tp_as_sequence */
1838 0, /* tp_as_mapping */
1839 0, /* tp_hash */
1840 0, /* tp_call */
1841 0, /* tp_str */
1842 PyObject_GenericGetAttr, /* tp_getattro */
1843 0, /* tp_setattro */
1844 0, /* tp_as_buffer */
Tim Petersb38e2b62004-07-29 02:29:26 +00001845 Py_TPFLAGS_DEFAULT |
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001846 Py_TPFLAGS_HAVE_RICHCOMPARE, /* tp_flags */
1847 sortwrapper_doc, /* tp_doc */
1848 0, /* tp_traverse */
1849 0, /* tp_clear */
1850 (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
1851};
1852
1853/* Returns a new reference to a sortwrapper.
1854 Consumes the references to the two underlying objects. */
1855
1856static PyObject *
1857build_sortwrapper(PyObject *key, PyObject *value)
1858{
1859 sortwrapperobject *so;
Tim Petersb38e2b62004-07-29 02:29:26 +00001860
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001861 so = PyObject_New(sortwrapperobject, &sortwrapper_type);
1862 if (so == NULL)
1863 return NULL;
1864 so->key = key;
1865 so->value = value;
1866 return (PyObject *)so;
1867}
1868
1869/* Returns a new reference to the value underlying the wrapper. */
1870static PyObject *
1871sortwrapper_getvalue(PyObject *so)
1872{
1873 PyObject *value;
1874
1875 if (!PyObject_TypeCheck(so, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001876 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001877 "expected a sortwrapperobject");
1878 return NULL;
1879 }
1880 value = ((sortwrapperobject *)so)->value;
1881 Py_INCREF(value);
1882 return value;
1883}
1884
1885/* Wrapper for user specified cmp functions in combination with a
1886 specified key function. Makes sure the cmp function is presented
1887 with the actual key instead of the sortwrapper */
1888
1889typedef struct {
1890 PyObject_HEAD
1891 PyObject *func;
1892} cmpwrapperobject;
1893
1894static void
1895cmpwrapper_dealloc(cmpwrapperobject *co)
1896{
1897 Py_XDECREF(co->func);
1898 PyObject_Del(co);
1899}
1900
1901static PyObject *
1902cmpwrapper_call(cmpwrapperobject *co, PyObject *args, PyObject *kwds)
1903{
1904 PyObject *x, *y, *xx, *yy;
1905
1906 if (!PyArg_UnpackTuple(args, "", 2, 2, &x, &y))
1907 return NULL;
1908 if (!PyObject_TypeCheck(x, &sortwrapper_type) ||
Raymond Hettingerae4a2992003-10-16 17:16:30 +00001909 !PyObject_TypeCheck(y, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001910 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001911 "expected a sortwrapperobject");
1912 return NULL;
1913 }
1914 xx = ((sortwrapperobject *)x)->key;
1915 yy = ((sortwrapperobject *)y)->key;
1916 return PyObject_CallFunctionObjArgs(co->func, xx, yy, NULL);
1917}
1918
1919PyDoc_STRVAR(cmpwrapper_doc, "cmp() wrapper for sort with custom keys.");
1920
1921static PyTypeObject cmpwrapper_type = {
1922 PyObject_HEAD_INIT(&PyType_Type)
1923 0, /* ob_size */
1924 "cmpwrapper", /* tp_name */
1925 sizeof(cmpwrapperobject), /* tp_basicsize */
1926 0, /* tp_itemsize */
1927 /* methods */
1928 (destructor)cmpwrapper_dealloc, /* tp_dealloc */
1929 0, /* tp_print */
1930 0, /* tp_getattr */
1931 0, /* tp_setattr */
1932 0, /* tp_compare */
1933 0, /* tp_repr */
1934 0, /* tp_as_number */
1935 0, /* tp_as_sequence */
1936 0, /* tp_as_mapping */
1937 0, /* tp_hash */
1938 (ternaryfunc)cmpwrapper_call, /* tp_call */
1939 0, /* tp_str */
1940 PyObject_GenericGetAttr, /* tp_getattro */
1941 0, /* tp_setattro */
1942 0, /* tp_as_buffer */
1943 Py_TPFLAGS_DEFAULT, /* tp_flags */
1944 cmpwrapper_doc, /* tp_doc */
1945};
1946
1947static PyObject *
1948build_cmpwrapper(PyObject *cmpfunc)
1949{
1950 cmpwrapperobject *co;
Tim Petersb38e2b62004-07-29 02:29:26 +00001951
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001952 co = PyObject_New(cmpwrapperobject, &cmpwrapper_type);
1953 if (co == NULL)
1954 return NULL;
1955 Py_INCREF(cmpfunc);
1956 co->func = cmpfunc;
1957 return (PyObject *)co;
1958}
1959
Tim Petersa64dc242002-08-01 02:13:36 +00001960/* An adaptive, stable, natural mergesort. See listsort.txt.
1961 * Returns Py_None on success, NULL on error. Even in case of error, the
1962 * list will be some permutation of its input state (nothing is lost or
1963 * duplicated).
1964 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001965static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001966listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001967{
Tim Petersa64dc242002-08-01 02:13:36 +00001968 MergeState ms;
1969 PyObject **lo, **hi;
1970 int nremaining;
1971 int minrun;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001972 int saved_ob_size, saved_allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00001973 PyObject **saved_ob_item;
Armin Rigo93677f02004-07-29 12:40:23 +00001974 PyObject **final_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001975 PyObject *compare = NULL;
1976 PyObject *result = NULL; /* guilty until proved innocent */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001977 int reverse = 0;
1978 PyObject *keyfunc = NULL;
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001979 int i;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001980 PyObject *key, *value, *kvpair;
1981 static char *kwlist[] = {"cmp", "key", "reverse", 0};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001982
Tim Petersa64dc242002-08-01 02:13:36 +00001983 assert(self != NULL);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001984 assert (PyList_Check(self));
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001985 if (args != NULL) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001986 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:sort",
1987 kwlist, &compare, &keyfunc, &reverse))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001988 return NULL;
1989 }
Skip Montanaro4abd5f02003-01-02 20:51:08 +00001990 if (compare == Py_None)
1991 compare = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001992 if (keyfunc == Py_None)
1993 keyfunc = NULL;
1994 if (compare != NULL && keyfunc != NULL) {
1995 compare = build_cmpwrapper(compare);
1996 if (compare == NULL)
Hye-Shik Chang19cb1932003-12-10 07:31:08 +00001997 return NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001998 } else
1999 Py_XINCREF(compare);
2000
Tim Petersb9099c32002-11-12 22:08:10 +00002001 /* The list is temporarily made empty, so that mutations performed
2002 * by comparison functions can't affect the slice of memory we're
2003 * sorting (allowing mutations during sorting is a core-dump
2004 * factory, since ob_item may change).
2005 */
2006 saved_ob_size = self->ob_size;
2007 saved_ob_item = self->ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002008 saved_allocated = self->allocated;
Armin Rigo93677f02004-07-29 12:40:23 +00002009 self->ob_size = 0;
Tim Peters51b4ade2004-07-29 04:07:15 +00002010 self->ob_item = NULL;
Armin Rigo93677f02004-07-29 12:40:23 +00002011 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00002012
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002013 if (keyfunc != NULL) {
2014 for (i=0 ; i < saved_ob_size ; i++) {
2015 value = saved_ob_item[i];
Tim Petersb38e2b62004-07-29 02:29:26 +00002016 key = PyObject_CallFunctionObjArgs(keyfunc, value,
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002017 NULL);
2018 if (key == NULL) {
2019 for (i=i-1 ; i>=0 ; i--) {
2020 kvpair = saved_ob_item[i];
2021 value = sortwrapper_getvalue(kvpair);
2022 saved_ob_item[i] = value;
2023 Py_DECREF(kvpair);
2024 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002025 goto dsu_fail;
2026 }
2027 kvpair = build_sortwrapper(key, value);
2028 if (kvpair == NULL)
2029 goto dsu_fail;
2030 saved_ob_item[i] = kvpair;
2031 }
2032 }
2033
2034 /* Reverse sort stability achieved by initially reversing the list,
2035 applying a stable forward sort, then reversing the final result. */
2036 if (reverse && saved_ob_size > 1)
2037 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2038
2039 merge_init(&ms, compare);
2040
Tim Petersb9099c32002-11-12 22:08:10 +00002041 nremaining = saved_ob_size;
Tim Petersa64dc242002-08-01 02:13:36 +00002042 if (nremaining < 2)
2043 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00002044
Tim Petersa64dc242002-08-01 02:13:36 +00002045 /* March over the array once, left to right, finding natural runs,
2046 * and extending short natural runs to minrun elements.
2047 */
Tim Petersb9099c32002-11-12 22:08:10 +00002048 lo = saved_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00002049 hi = lo + nremaining;
2050 minrun = merge_compute_minrun(nremaining);
2051 do {
2052 int descending;
2053 int n;
Tim Peters330f9e92002-07-19 07:05:44 +00002054
Tim Petersa64dc242002-08-01 02:13:36 +00002055 /* Identify next run. */
2056 n = count_run(lo, hi, compare, &descending);
2057 if (n < 0)
2058 goto fail;
2059 if (descending)
2060 reverse_slice(lo, lo + n);
2061 /* If short, extend to min(minrun, nremaining). */
2062 if (n < minrun) {
2063 const int force = nremaining <= minrun ?
2064 nremaining : minrun;
2065 if (binarysort(lo, lo + force, lo + n, compare) < 0)
2066 goto fail;
2067 n = force;
2068 }
2069 /* Push run onto pending-runs stack, and maybe merge. */
2070 assert(ms.n < MAX_MERGE_PENDING);
Tim Peterse05f65a2002-08-10 05:21:15 +00002071 ms.pending[ms.n].base = lo;
2072 ms.pending[ms.n].len = n;
Tim Petersa64dc242002-08-01 02:13:36 +00002073 ++ms.n;
2074 if (merge_collapse(&ms) < 0)
2075 goto fail;
2076 /* Advance to find next run. */
2077 lo += n;
2078 nremaining -= n;
2079 } while (nremaining);
2080 assert(lo == hi);
Tim Peters330f9e92002-07-19 07:05:44 +00002081
Tim Petersa64dc242002-08-01 02:13:36 +00002082 if (merge_force_collapse(&ms) < 0)
2083 goto fail;
2084 assert(ms.n == 1);
Tim Petersb9099c32002-11-12 22:08:10 +00002085 assert(ms.pending[0].base == saved_ob_item);
2086 assert(ms.pending[0].len == saved_ob_size);
Tim Petersa64dc242002-08-01 02:13:36 +00002087
2088succeed:
2089 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002090fail:
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002091 if (keyfunc != NULL) {
2092 for (i=0 ; i < saved_ob_size ; i++) {
2093 kvpair = saved_ob_item[i];
2094 value = sortwrapper_getvalue(kvpair);
2095 saved_ob_item[i] = value;
2096 Py_DECREF(kvpair);
2097 }
2098 }
2099
Armin Rigo93677f02004-07-29 12:40:23 +00002100 if (self->allocated != -1 && result != NULL) {
Tim Peters51b4ade2004-07-29 04:07:15 +00002101 /* The user mucked with the list during the sort,
2102 * and we don't already have another error to report.
2103 */
2104 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2105 result = NULL;
Tim Petersb9099c32002-11-12 22:08:10 +00002106 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002107
2108 if (reverse && saved_ob_size > 1)
2109 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2110
2111 merge_freemem(&ms);
2112
2113dsu_fail:
Armin Rigo93677f02004-07-29 12:40:23 +00002114 final_ob_item = self->ob_item;
2115 i = self->ob_size;
Tim Petersb9099c32002-11-12 22:08:10 +00002116 self->ob_size = saved_ob_size;
2117 self->ob_item = saved_ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002118 self->allocated = saved_allocated;
Armin Rigo93677f02004-07-29 12:40:23 +00002119 if (final_ob_item != NULL) {
2120 /* we cannot use list_clear() for this because it does not
2121 guarantee that the list is really empty when it returns */
2122 while (--i >= 0) {
2123 Py_XDECREF(final_ob_item[i]);
2124 }
2125 PyMem_FREE(final_ob_item);
2126 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002127 Py_XDECREF(compare);
Tim Petersa64dc242002-08-01 02:13:36 +00002128 Py_XINCREF(result);
2129 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002130}
Tim Peters330f9e92002-07-19 07:05:44 +00002131#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002132#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002133
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002134int
Fred Drakea2f55112000-07-09 15:16:51 +00002135PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002136{
2137 if (v == NULL || !PyList_Check(v)) {
2138 PyErr_BadInternalCall();
2139 return -1;
2140 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002141 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002142 if (v == NULL)
2143 return -1;
2144 Py_DECREF(v);
2145 return 0;
2146}
2147
Guido van Rossumb86c5492001-02-12 22:06:02 +00002148static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002149listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002150{
Tim Peters326b4482002-07-19 04:04:16 +00002151 if (self->ob_size > 1)
2152 reverse_slice(self->ob_item, self->ob_item + self->ob_size);
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002153 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002154}
2155
Guido van Rossum84c76f51990-10-30 13:32:20 +00002156int
Fred Drakea2f55112000-07-09 15:16:51 +00002157PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002158{
Tim Peters6063e262002-08-08 01:06:39 +00002159 PyListObject *self = (PyListObject *)v;
2160
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002161 if (v == NULL || !PyList_Check(v)) {
2162 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002163 return -1;
2164 }
Tim Peters6063e262002-08-08 01:06:39 +00002165 if (self->ob_size > 1)
2166 reverse_slice(self->ob_item, self->ob_item + self->ob_size);
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002167 return 0;
2168}
2169
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002170PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002171PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002172{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002173 PyObject *w;
2174 PyObject **p;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002175 int n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002176 if (v == NULL || !PyList_Check(v)) {
2177 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002178 return NULL;
2179 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002180 n = ((PyListObject *)v)->ob_size;
2181 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002182 if (w == NULL)
2183 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002184 p = ((PyTupleObject *)w)->ob_item;
Thomas Wouters334fb892000-07-25 12:56:38 +00002185 memcpy((void *)p,
2186 (void *)((PyListObject *)v)->ob_item,
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002187 n*sizeof(PyObject *));
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002188 while (--n >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002189 Py_INCREF(*p);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002190 p++;
2191 }
2192 return w;
2193}
2194
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002195static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002196listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002197{
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002198 int i, start=0, stop=self->ob_size;
2199 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002200
Walter Dörwalde8049bef2003-06-17 19:27:39 +00002201 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2202 _PyEval_SliceIndex, &start,
2203 _PyEval_SliceIndex, &stop))
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002204 return NULL;
Guido van Rossum2743d872003-06-17 14:25:14 +00002205 if (start < 0) {
2206 start += self->ob_size;
2207 if (start < 0)
2208 start = 0;
2209 }
2210 if (stop < 0) {
2211 stop += self->ob_size;
2212 if (stop < 0)
2213 stop = 0;
2214 }
Neal Norwitzf0769532004-08-13 03:18:29 +00002215 for (i = start; i < stop && i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002216 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2217 if (cmp > 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002218 return PyInt_FromLong((long)i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002219 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002220 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002221 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002222 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002223 return NULL;
2224}
2225
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002226static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002227listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002228{
2229 int count = 0;
2230 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002231
Guido van Rossume6f7d181991-10-20 20:20:40 +00002232 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002233 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2234 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002235 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002236 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002237 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00002238 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002239 return PyInt_FromLong((long)count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002240}
2241
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002242static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002243listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002244{
2245 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002246
Guido van Rossumed98d481991-03-06 13:07:53 +00002247 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002248 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2249 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002250 if (list_ass_slice(self, i, i+1,
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002251 (PyObject *)NULL) == 0)
2252 Py_RETURN_NONE;
2253 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002254 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002255 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002256 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002257 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002258 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002259 return NULL;
2260}
2261
Jeremy Hylton8caad492000-06-23 14:18:11 +00002262static int
2263list_traverse(PyListObject *o, visitproc visit, void *arg)
2264{
2265 int i, err;
2266 PyObject *x;
2267
2268 for (i = o->ob_size; --i >= 0; ) {
2269 x = o->ob_item[i];
2270 if (x != NULL) {
2271 err = visit(x, arg);
2272 if (err)
2273 return err;
2274 }
2275 }
2276 return 0;
2277}
2278
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002279static PyObject *
2280list_richcompare(PyObject *v, PyObject *w, int op)
2281{
2282 PyListObject *vl, *wl;
2283 int i;
2284
2285 if (!PyList_Check(v) || !PyList_Check(w)) {
2286 Py_INCREF(Py_NotImplemented);
2287 return Py_NotImplemented;
2288 }
2289
2290 vl = (PyListObject *)v;
2291 wl = (PyListObject *)w;
2292
2293 if (vl->ob_size != wl->ob_size && (op == Py_EQ || op == Py_NE)) {
2294 /* Shortcut: if the lengths differ, the lists differ */
2295 PyObject *res;
2296 if (op == Py_EQ)
2297 res = Py_False;
2298 else
2299 res = Py_True;
2300 Py_INCREF(res);
2301 return res;
2302 }
2303
2304 /* Search for the first index where items are different */
2305 for (i = 0; i < vl->ob_size && i < wl->ob_size; i++) {
2306 int k = PyObject_RichCompareBool(vl->ob_item[i],
2307 wl->ob_item[i], Py_EQ);
2308 if (k < 0)
2309 return NULL;
2310 if (!k)
2311 break;
2312 }
2313
2314 if (i >= vl->ob_size || i >= wl->ob_size) {
2315 /* No more items to compare -- compare sizes */
2316 int vs = vl->ob_size;
2317 int ws = wl->ob_size;
2318 int cmp;
2319 PyObject *res;
2320 switch (op) {
2321 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00002322 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002323 case Py_EQ: cmp = vs == ws; break;
2324 case Py_NE: cmp = vs != ws; break;
2325 case Py_GT: cmp = vs > ws; break;
2326 case Py_GE: cmp = vs >= ws; break;
2327 default: return NULL; /* cannot happen */
2328 }
2329 if (cmp)
2330 res = Py_True;
2331 else
2332 res = Py_False;
2333 Py_INCREF(res);
2334 return res;
2335 }
2336
2337 /* We have an item that differs -- shortcuts for EQ/NE */
2338 if (op == Py_EQ) {
2339 Py_INCREF(Py_False);
2340 return Py_False;
2341 }
2342 if (op == Py_NE) {
2343 Py_INCREF(Py_True);
2344 return Py_True;
2345 }
2346
2347 /* Compare the final item again using the proper operator */
2348 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
2349}
2350
Tim Peters6d6c1a32001-08-02 04:15:00 +00002351static int
2352list_init(PyListObject *self, PyObject *args, PyObject *kw)
2353{
2354 PyObject *arg = NULL;
2355 static char *kwlist[] = {"sequence", 0};
2356
2357 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2358 return -1;
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002359
2360 /* Verify list invariants established by PyType_GenericAlloc() */
Armin Rigoa37bbf22004-07-30 11:20:18 +00002361 assert(0 <= self->ob_size);
2362 assert(self->ob_size <= self->allocated || self->allocated == -1);
2363 assert(self->ob_item != NULL ||
2364 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002365
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002366 /* Empty previous contents */
Armin Rigo93677f02004-07-29 12:40:23 +00002367 if (self->ob_item != NULL) {
2368 (void)list_clear(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002369 }
2370 if (arg != NULL) {
2371 PyObject *rv = listextend(self, arg);
2372 if (rv == NULL)
2373 return -1;
2374 Py_DECREF(rv);
2375 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002376 return 0;
2377}
2378
Guido van Rossumdbb53d92001-12-03 16:32:18 +00002379static long
2380list_nohash(PyObject *self)
2381{
2382 PyErr_SetString(PyExc_TypeError, "list objects are unhashable");
2383 return -1;
2384}
2385
Raymond Hettinger1021c442003-11-07 15:38:09 +00002386static PyObject *list_iter(PyObject *seq);
2387static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2388
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002389PyDoc_STRVAR(getitem_doc,
2390"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002391PyDoc_STRVAR(reversed_doc,
2392"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002393PyDoc_STRVAR(append_doc,
2394"L.append(object) -- append object to end");
2395PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002396"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002397PyDoc_STRVAR(insert_doc,
2398"L.insert(index, object) -- insert object before index");
2399PyDoc_STRVAR(pop_doc,
2400"L.pop([index]) -> item -- remove and return item at index (default last)");
2401PyDoc_STRVAR(remove_doc,
2402"L.remove(value) -- remove first occurrence of value");
2403PyDoc_STRVAR(index_doc,
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002404"L.index(value, [start, [stop]]) -> integer -- return first index of value");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002405PyDoc_STRVAR(count_doc,
2406"L.count(value) -> integer -- return number of occurrences of value");
2407PyDoc_STRVAR(reverse_doc,
2408"L.reverse() -- reverse *IN PLACE*");
2409PyDoc_STRVAR(sort_doc,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002410"L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n\
2411cmp(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002412
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002413static PyObject *list_subscript(PyListObject*, PyObject*);
2414
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002415static PyMethodDef list_methods[] = {
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002416 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
Raymond Hettinger1021c442003-11-07 15:38:09 +00002417 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002418 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002419 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002420 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002421 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002422 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002423 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002424 {"count", (PyCFunction)listcount, METH_O, count_doc},
2425 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002426 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
Tim Petersa64dc242002-08-01 02:13:36 +00002427 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002428};
2429
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002430static PySequenceMethods list_as_sequence = {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002431 (inquiry)list_length, /* sq_length */
2432 (binaryfunc)list_concat, /* sq_concat */
2433 (intargfunc)list_repeat, /* sq_repeat */
2434 (intargfunc)list_item, /* sq_item */
2435 (intintargfunc)list_slice, /* sq_slice */
2436 (intobjargproc)list_ass_item, /* sq_ass_item */
2437 (intintobjargproc)list_ass_slice, /* sq_ass_slice */
2438 (objobjproc)list_contains, /* sq_contains */
2439 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2440 (intargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002441};
2442
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002443PyDoc_STRVAR(list_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002444"list() -> new list\n"
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002445"list(sequence) -> new list initialized from sequence's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002446
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002447static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002448list_subscript(PyListObject* self, PyObject* item)
2449{
2450 if (PyInt_Check(item)) {
2451 long i = PyInt_AS_LONG(item);
2452 if (i < 0)
2453 i += PyList_GET_SIZE(self);
2454 return list_item(self, i);
2455 }
2456 else if (PyLong_Check(item)) {
2457 long i = PyLong_AsLong(item);
2458 if (i == -1 && PyErr_Occurred())
2459 return NULL;
2460 if (i < 0)
2461 i += PyList_GET_SIZE(self);
2462 return list_item(self, i);
2463 }
2464 else if (PySlice_Check(item)) {
2465 int start, stop, step, slicelength, cur, i;
2466 PyObject* result;
2467 PyObject* it;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002468 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002469
2470 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
2471 &start, &stop, &step, &slicelength) < 0) {
2472 return NULL;
2473 }
2474
2475 if (slicelength <= 0) {
2476 return PyList_New(0);
2477 }
2478 else {
2479 result = PyList_New(slicelength);
2480 if (!result) return NULL;
2481
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002482 src = self->ob_item;
2483 dest = ((PyListObject *)result)->ob_item;
Tim Peters3b01a122002-07-19 02:35:45 +00002484 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002485 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002486 it = src[cur];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002487 Py_INCREF(it);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002488 dest[i] = it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002489 }
Tim Peters3b01a122002-07-19 02:35:45 +00002490
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002491 return result;
2492 }
2493 }
2494 else {
2495 PyErr_SetString(PyExc_TypeError,
2496 "list indices must be integers");
2497 return NULL;
2498 }
2499}
2500
Tim Peters3b01a122002-07-19 02:35:45 +00002501static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002502list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2503{
2504 if (PyInt_Check(item)) {
2505 long i = PyInt_AS_LONG(item);
2506 if (i < 0)
2507 i += PyList_GET_SIZE(self);
2508 return list_ass_item(self, i, value);
2509 }
2510 else if (PyLong_Check(item)) {
2511 long i = PyLong_AsLong(item);
2512 if (i == -1 && PyErr_Occurred())
2513 return -1;
2514 if (i < 0)
2515 i += PyList_GET_SIZE(self);
2516 return list_ass_item(self, i, value);
2517 }
2518 else if (PySlice_Check(item)) {
2519 int start, stop, step, slicelength;
2520
2521 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
2522 &start, &stop, &step, &slicelength) < 0) {
2523 return -1;
2524 }
2525
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002526 /* treat L[slice(a,b)] = v _exactly_ like L[a:b] = v */
2527 if (step == 1 && ((PySliceObject*)item)->step == Py_None)
2528 return list_ass_slice(self, start, stop, value);
2529
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002530 if (value == NULL) {
2531 /* delete slice */
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002532 PyObject **garbage;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002533 int cur, i;
Tim Peters3b01a122002-07-19 02:35:45 +00002534
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002535 if (slicelength <= 0)
2536 return 0;
2537
2538 if (step < 0) {
2539 stop = start + 1;
2540 start = stop + step*(slicelength - 1) - 1;
2541 step = -step;
2542 }
2543
2544 garbage = (PyObject**)
2545 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Tim Peters3b01a122002-07-19 02:35:45 +00002546
2547 /* drawing pictures might help
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002548 understand these for loops */
Guido van Rossum75a20b12002-06-11 12:22:28 +00002549 for (cur = start, i = 0;
2550 cur < stop;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002551 cur += step, i++) {
2552 int lim = step;
2553
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002554 garbage[i] = PyList_GET_ITEM(self, cur);
2555
Michael W. Hudson56796f62002-07-29 14:35:04 +00002556 if (cur + step >= self->ob_size) {
2557 lim = self->ob_size - cur - 1;
2558 }
2559
Tim Petersb38e2b62004-07-29 02:29:26 +00002560 memmove(self->ob_item + cur - i,
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002561 self->ob_item + cur + 1,
2562 lim * sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002563 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002564
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002565 for (cur = start + slicelength*step + 1;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002566 cur < self->ob_size; cur++) {
2567 PyList_SET_ITEM(self, cur - slicelength,
2568 PyList_GET_ITEM(self, cur));
2569 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002570
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002571 self->ob_size -= slicelength;
Raymond Hettingerd4ff7412004-03-15 09:01:31 +00002572 list_resize(self, self->ob_size);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002573
2574 for (i = 0; i < slicelength; i++) {
2575 Py_DECREF(garbage[i]);
2576 }
2577 PyMem_FREE(garbage);
2578
2579 return 0;
2580 }
2581 else {
2582 /* assign slice */
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002583 PyObject **garbage, *ins, *seq, **seqitems, **selfitems;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002584 int cur, i;
2585
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002586 /* protect against a[::-1] = a */
Tim Peters3b01a122002-07-19 02:35:45 +00002587 if (self == (PyListObject*)value) {
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002588 seq = list_slice((PyListObject*)value, 0,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002589 PyList_GET_SIZE(value));
Tim Peters3b01a122002-07-19 02:35:45 +00002590 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002591 else {
Tim Petersb38e2b62004-07-29 02:29:26 +00002592 seq = PySequence_Fast(value,
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002593 "must assign iterable to extended slice");
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002594 if (!seq)
2595 return -1;
2596 }
2597
2598 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2599 PyErr_Format(PyExc_ValueError,
2600 "attempt to assign sequence of size %d to extended slice of size %d",
2601 PySequence_Fast_GET_SIZE(seq),
2602 slicelength);
2603 Py_DECREF(seq);
2604 return -1;
2605 }
2606
2607 if (!slicelength) {
2608 Py_DECREF(seq);
2609 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002610 }
2611
2612 garbage = (PyObject**)
2613 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Tim Peters3b01a122002-07-19 02:35:45 +00002614
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002615 selfitems = self->ob_item;
Raymond Hettinger42bec932004-03-12 16:38:17 +00002616 seqitems = PySequence_Fast_ITEMS(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002617 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002618 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002619 garbage[i] = selfitems[cur];
2620 ins = seqitems[i];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002621 Py_INCREF(ins);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002622 selfitems[cur] = ins;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002623 }
2624
2625 for (i = 0; i < slicelength; i++) {
2626 Py_DECREF(garbage[i]);
2627 }
Tim Peters3b01a122002-07-19 02:35:45 +00002628
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002629 PyMem_FREE(garbage);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002630 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002631
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002632 return 0;
2633 }
Tim Peters3b01a122002-07-19 02:35:45 +00002634 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002635 else {
Tim Peters3b01a122002-07-19 02:35:45 +00002636 PyErr_SetString(PyExc_TypeError,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002637 "list indices must be integers");
2638 return -1;
2639 }
2640}
2641
2642static PyMappingMethods list_as_mapping = {
2643 (inquiry)list_length,
2644 (binaryfunc)list_subscript,
2645 (objobjargproc)list_ass_subscript
2646};
2647
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002648PyTypeObject PyList_Type = {
2649 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002650 0,
2651 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002652 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002653 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002654 (destructor)list_dealloc, /* tp_dealloc */
2655 (printfunc)list_print, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002656 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002657 0, /* tp_setattr */
2658 0, /* tp_compare */
2659 (reprfunc)list_repr, /* tp_repr */
2660 0, /* tp_as_number */
2661 &list_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002662 &list_as_mapping, /* tp_as_mapping */
Guido van Rossumdbb53d92001-12-03 16:32:18 +00002663 list_nohash, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002664 0, /* tp_call */
2665 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002666 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002667 0, /* tp_setattro */
2668 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002669 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Tim Peters6d6c1a32001-08-02 04:15:00 +00002670 Py_TPFLAGS_BASETYPE, /* tp_flags */
2671 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002672 (traverseproc)list_traverse, /* tp_traverse */
2673 (inquiry)list_clear, /* tp_clear */
2674 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002675 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002676 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002677 0, /* tp_iternext */
2678 list_methods, /* tp_methods */
2679 0, /* tp_members */
2680 0, /* tp_getset */
2681 0, /* tp_base */
2682 0, /* tp_dict */
2683 0, /* tp_descr_get */
2684 0, /* tp_descr_set */
2685 0, /* tp_dictoffset */
2686 (initproc)list_init, /* tp_init */
2687 PyType_GenericAlloc, /* tp_alloc */
2688 PyType_GenericNew, /* tp_new */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002689 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002690};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002691
2692
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002693/*********************** List Iterator **************************/
2694
2695typedef struct {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002696 PyObject_HEAD
2697 long it_index;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002698 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002699} listiterobject;
2700
2701PyTypeObject PyListIter_Type;
2702
Guido van Rossum5086e492002-07-16 15:56:52 +00002703static PyObject *
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002704list_iter(PyObject *seq)
2705{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002706 listiterobject *it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002707
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002708 if (!PyList_Check(seq)) {
2709 PyErr_BadInternalCall();
2710 return NULL;
2711 }
2712 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2713 if (it == NULL)
2714 return NULL;
2715 it->it_index = 0;
2716 Py_INCREF(seq);
2717 it->it_seq = (PyListObject *)seq;
2718 _PyObject_GC_TRACK(it);
2719 return (PyObject *)it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002720}
2721
2722static void
2723listiter_dealloc(listiterobject *it)
2724{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002725 _PyObject_GC_UNTRACK(it);
Guido van Rossum86103ae2002-07-16 20:07:32 +00002726 Py_XDECREF(it->it_seq);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002727 PyObject_GC_Del(it);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002728}
2729
2730static int
2731listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2732{
Guido van Rossum86103ae2002-07-16 20:07:32 +00002733 if (it->it_seq == NULL)
2734 return 0;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002735 return visit((PyObject *)it->it_seq, arg);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002736}
2737
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002738static PyObject *
Tim Peters93b2cc42002-06-01 05:22:55 +00002739listiter_next(listiterobject *it)
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002740{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002741 PyListObject *seq;
2742 PyObject *item;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002743
Tim Peters93b2cc42002-06-01 05:22:55 +00002744 assert(it != NULL);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002745 seq = it->it_seq;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002746 if (seq == NULL)
2747 return NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002748 assert(PyList_Check(seq));
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002749
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002750 if (it->it_index < PyList_GET_SIZE(seq)) {
Tim Peters93b2cc42002-06-01 05:22:55 +00002751 item = PyList_GET_ITEM(seq, it->it_index);
2752 ++it->it_index;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002753 Py_INCREF(item);
2754 return item;
2755 }
Guido van Rossum86103ae2002-07-16 20:07:32 +00002756
2757 Py_DECREF(seq);
2758 it->it_seq = NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002759 return NULL;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002760}
2761
Raymond Hettinger435bf582004-03-18 22:43:10 +00002762static int
2763listiter_len(listiterobject *it)
2764{
Raymond Hettinger40a03822004-04-12 13:05:09 +00002765 int len;
2766 if (it->it_seq) {
2767 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2768 if (len >= 0)
2769 return len;
2770 }
Raymond Hettinger435bf582004-03-18 22:43:10 +00002771 return 0;
2772}
2773
2774static PySequenceMethods listiter_as_sequence = {
2775 (inquiry)listiter_len, /* sq_length */
2776 0, /* sq_concat */
2777};
2778
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002779PyTypeObject PyListIter_Type = {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002780 PyObject_HEAD_INIT(&PyType_Type)
2781 0, /* ob_size */
2782 "listiterator", /* tp_name */
2783 sizeof(listiterobject), /* tp_basicsize */
2784 0, /* tp_itemsize */
2785 /* methods */
2786 (destructor)listiter_dealloc, /* tp_dealloc */
2787 0, /* tp_print */
2788 0, /* tp_getattr */
2789 0, /* tp_setattr */
2790 0, /* tp_compare */
2791 0, /* tp_repr */
2792 0, /* tp_as_number */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002793 &listiter_as_sequence, /* tp_as_sequence */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002794 0, /* tp_as_mapping */
2795 0, /* tp_hash */
2796 0, /* tp_call */
2797 0, /* tp_str */
2798 PyObject_GenericGetAttr, /* tp_getattro */
2799 0, /* tp_setattro */
2800 0, /* tp_as_buffer */
2801 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2802 0, /* tp_doc */
2803 (traverseproc)listiter_traverse, /* tp_traverse */
2804 0, /* tp_clear */
2805 0, /* tp_richcompare */
2806 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00002807 PyObject_SelfIter, /* tp_iter */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002808 (iternextfunc)listiter_next, /* tp_iternext */
Guido van Rossum86103ae2002-07-16 20:07:32 +00002809 0, /* tp_methods */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002810 0, /* tp_members */
2811 0, /* tp_getset */
2812 0, /* tp_base */
2813 0, /* tp_dict */
2814 0, /* tp_descr_get */
2815 0, /* tp_descr_set */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002816};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002817
2818/*********************** List Reverse Iterator **************************/
2819
2820typedef struct {
2821 PyObject_HEAD
2822 long it_index;
Raymond Hettinger001f2282003-11-08 11:58:44 +00002823 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002824} listreviterobject;
2825
2826PyTypeObject PyListRevIter_Type;
2827
2828static PyObject *
2829list_reversed(PyListObject *seq, PyObject *unused)
2830{
2831 listreviterobject *it;
2832
2833 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2834 if (it == NULL)
2835 return NULL;
2836 assert(PyList_Check(seq));
2837 it->it_index = PyList_GET_SIZE(seq) - 1;
2838 Py_INCREF(seq);
2839 it->it_seq = seq;
2840 PyObject_GC_Track(it);
2841 return (PyObject *)it;
2842}
2843
2844static void
2845listreviter_dealloc(listreviterobject *it)
2846{
2847 PyObject_GC_UnTrack(it);
2848 Py_XDECREF(it->it_seq);
2849 PyObject_GC_Del(it);
2850}
2851
2852static int
2853listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2854{
2855 if (it->it_seq == NULL)
2856 return 0;
2857 return visit((PyObject *)it->it_seq, arg);
2858}
2859
2860static PyObject *
2861listreviter_next(listreviterobject *it)
2862{
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002863 PyObject *item;
2864 long index = it->it_index;
2865 PyListObject *seq = it->it_seq;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002866
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002867 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2868 item = PyList_GET_ITEM(seq, index);
Raymond Hettinger1021c442003-11-07 15:38:09 +00002869 it->it_index--;
2870 Py_INCREF(item);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002871 return item;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002872 }
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002873 it->it_index = -1;
2874 if (seq != NULL) {
2875 it->it_seq = NULL;
2876 Py_DECREF(seq);
2877 }
2878 return NULL;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002879}
2880
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002881static int
2882listreviter_len(listreviterobject *it)
2883{
Raymond Hettinger40a03822004-04-12 13:05:09 +00002884 int len = it->it_index + 1;
2885 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
2886 return 0;
2887 return len;
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002888}
2889
2890static PySequenceMethods listreviter_as_sequence = {
2891 (inquiry)listreviter_len, /* sq_length */
2892 0, /* sq_concat */
2893};
2894
Raymond Hettinger1021c442003-11-07 15:38:09 +00002895PyTypeObject PyListRevIter_Type = {
2896 PyObject_HEAD_INIT(&PyType_Type)
2897 0, /* ob_size */
2898 "listreverseiterator", /* tp_name */
2899 sizeof(listreviterobject), /* tp_basicsize */
2900 0, /* tp_itemsize */
2901 /* methods */
2902 (destructor)listreviter_dealloc, /* tp_dealloc */
2903 0, /* tp_print */
2904 0, /* tp_getattr */
2905 0, /* tp_setattr */
2906 0, /* tp_compare */
2907 0, /* tp_repr */
2908 0, /* tp_as_number */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002909 &listreviter_as_sequence, /* tp_as_sequence */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002910 0, /* tp_as_mapping */
2911 0, /* tp_hash */
2912 0, /* tp_call */
2913 0, /* tp_str */
2914 PyObject_GenericGetAttr, /* tp_getattro */
2915 0, /* tp_setattro */
2916 0, /* tp_as_buffer */
2917 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2918 0, /* tp_doc */
2919 (traverseproc)listreviter_traverse, /* tp_traverse */
2920 0, /* tp_clear */
2921 0, /* tp_richcompare */
2922 0, /* tp_weaklistoffset */
2923 PyObject_SelfIter, /* tp_iter */
2924 (iternextfunc)listreviter_next, /* tp_iternext */
2925 0,
2926};