blob: 179dd14e9e6683a9aebb5214fcf1351f8cad1991 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* List object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
4
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00005#ifdef STDC_HEADERS
6#include <stddef.h>
7#else
8#include <sys/types.h> /* For size_t */
9#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000010
Tim Peters8d9eb102004-07-31 02:24:20 +000011/* Ensure ob_item has room for at least newsize elements, and set
12 * ob_size to newsize. If newsize > ob_size on entry, the content
13 * of the new slots at exit is undefined heap trash; it's the caller's
14 * responsiblity to overwrite them with sane values.
15 * The number of allocated elements may grow, shrink, or stay the same.
16 * Failure is impossible if newsize <= self.allocated on entry, although
17 * that partly relies on an assumption that the system realloc() never
18 * fails when passed a number of bytes <= the number of bytes last
19 * allocated (the C standard doesn't guarantee this, but it's hard to
20 * imagine a realloc implementation where it wouldn't be true).
21 * Note that self->ob_item may change, and even if newsize is less
22 * than ob_size on entry.
23 */
Guido van Rossuma46d51d1995-01-26 22:59:43 +000024static int
Raymond Hettingerd4ff7412004-03-15 09:01:31 +000025list_resize(PyListObject *self, int newsize)
Guido van Rossuma46d51d1995-01-26 22:59:43 +000026{
Raymond Hettinger4bb95402004-02-13 11:36:39 +000027 PyObject **items;
28 size_t _new_size;
Tim Peters65b8b842001-05-26 05:28:40 +000029
Raymond Hettinger4bb95402004-02-13 11:36:39 +000030 /* Bypass realloc() when a previous overallocation is large enough
31 to accommodate the newsize. If the newsize is 16 smaller than the
32 current size, then proceed with the realloc() to shrink the list.
33 */
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +000034 if (self->allocated >= newsize && self->ob_size < newsize + 16) {
35 assert(self->ob_item != NULL || newsize == 0);
Raymond Hettinger4bb95402004-02-13 11:36:39 +000036 self->ob_size = newsize;
37 return 0;
38 }
39
40 /* This over-allocates proportional to the list size, making room
Tim Peters65b8b842001-05-26 05:28:40 +000041 * for additional growth. The over-allocation is mild, but is
42 * enough to give linear-time amortized behavior over a long
43 * sequence of appends() in the presence of a poorly-performing
Raymond Hettingerab517d22004-02-14 18:34:46 +000044 * system realloc().
45 * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
Tim Peters65b8b842001-05-26 05:28:40 +000046 */
Raymond Hettingerd4ff7412004-03-15 09:01:31 +000047 _new_size = (newsize >> 3) + (self->ob_size < 8 ? 3 : 6) + newsize;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000048 items = self->ob_item;
49 if (_new_size <= ((~(size_t)0) / sizeof(PyObject *)))
50 PyMem_RESIZE(items, PyObject *, _new_size);
51 else
52 items = NULL;
53 if (items == NULL) {
54 PyErr_NoMemory();
55 return -1;
56 }
57 self->ob_item = items;
58 self->ob_size = newsize;
59 self->allocated = _new_size;
60 return 0;
61}
Guido van Rossuma46d51d1995-01-26 22:59:43 +000062
Raymond Hettinger0468e412004-05-05 05:37:53 +000063/* Empty list reuse scheme to save calls to malloc and free */
64#define MAXFREELISTS 80
65static PyListObject *free_lists[MAXFREELISTS];
66static int num_free_lists = 0;
67
Guido van Rossumc0b618a1997-05-02 03:12:38 +000068PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +000069PyList_New(int size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000070{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000071 PyListObject *op;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +000072 size_t nbytes;
Tim Peters3986d4e2004-07-29 02:28:42 +000073
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000074 if (size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000075 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000076 return NULL;
77 }
Tim Peters7049d812004-01-18 20:31:02 +000078 nbytes = size * sizeof(PyObject *);
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000079 /* Check for overflow */
Raymond Hettingerfdfe6182004-05-05 06:28:16 +000080 if (nbytes / sizeof(PyObject *) != (size_t)size)
Guido van Rossumc0b618a1997-05-02 03:12:38 +000081 return PyErr_NoMemory();
Raymond Hettinger0468e412004-05-05 05:37:53 +000082 if (num_free_lists) {
83 num_free_lists--;
84 op = free_lists[num_free_lists];
85 _Py_NewReference((PyObject *)op);
86 } else {
87 op = PyObject_GC_New(PyListObject, &PyList_Type);
88 if (op == NULL)
89 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000090 }
Raymond Hettingerfdfe6182004-05-05 06:28:16 +000091 if (size <= 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000092 op->ob_item = NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000093 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +000094 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
Raymond Hettingerfdfe6182004-05-05 06:28:16 +000095 if (op->ob_item == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +000096 return PyErr_NoMemory();
Tim Peters3986d4e2004-07-29 02:28:42 +000097 memset(op->ob_item, 0, nbytes);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000098 }
Neil Schemenauere83c00e2001-08-29 23:54:21 +000099 op->ob_size = size;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000100 op->allocated = size;
Neil Schemenauere83c00e2001-08-29 23:54:21 +0000101 _PyObject_GC_TRACK(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000102 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000103}
104
105int
Fred Drakea2f55112000-07-09 15:16:51 +0000106PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000107{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000108 if (!PyList_Check(op)) {
109 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000110 return -1;
111 }
112 else
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000113 return ((PyListObject *)op) -> ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000114}
115
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000116static PyObject *indexerr = NULL;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000117
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000118PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000119PyList_GetItem(PyObject *op, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000120{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000121 if (!PyList_Check(op)) {
122 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000123 return NULL;
124 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000125 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000126 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000127 indexerr = PyString_FromString(
128 "list index out of range");
129 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000130 return NULL;
131 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000132 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000133}
134
135int
Fred Drakea2f55112000-07-09 15:16:51 +0000136PyList_SetItem(register PyObject *op, register int i,
137 register PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000138{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000139 register PyObject *olditem;
140 register PyObject **p;
141 if (!PyList_Check(op)) {
142 Py_XDECREF(newitem);
143 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000144 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000145 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000146 if (i < 0 || i >= ((PyListObject *)op) -> ob_size) {
147 Py_XDECREF(newitem);
148 PyErr_SetString(PyExc_IndexError,
149 "list assignment index out of range");
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000150 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000151 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000152 p = ((PyListObject *)op) -> ob_item + i;
Guido van Rossum5fe60581995-03-09 12:12:50 +0000153 olditem = *p;
154 *p = newitem;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000155 Py_XDECREF(olditem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000156 return 0;
157}
158
159static int
Fred Drakea2f55112000-07-09 15:16:51 +0000160ins1(PyListObject *self, int where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000161{
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000162 int i, n = self->ob_size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000163 PyObject **items;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000164 if (v == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000165 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000166 return -1;
167 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000168 if (n == INT_MAX) {
Trent Micka5846642000-08-13 22:47:45 +0000169 PyErr_SetString(PyExc_OverflowError,
170 "cannot add more objects to list");
171 return -1;
172 }
Tim Petersb38e2b62004-07-29 02:29:26 +0000173
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000174 if (list_resize(self, n+1) == -1)
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000175 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000176
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000177 if (where < 0) {
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000178 where += n;
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000179 if (where < 0)
180 where = 0;
181 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000182 if (where > n)
183 where = n;
184 items = self->ob_item;
185 for (i = n; --i >= where; )
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000186 items[i+1] = items[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000187 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000188 items[where] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000189 return 0;
190}
191
192int
Fred Drakea2f55112000-07-09 15:16:51 +0000193PyList_Insert(PyObject *op, int where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000194{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000195 if (!PyList_Check(op)) {
196 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000197 return -1;
198 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000199 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000200}
201
Raymond Hettinger40a03822004-04-12 13:05:09 +0000202static int
203app1(PyListObject *self, PyObject *v)
204{
205 int n = PyList_GET_SIZE(self);
206
207 assert (v != NULL);
208 if (n == INT_MAX) {
209 PyErr_SetString(PyExc_OverflowError,
210 "cannot add more objects to list");
211 return -1;
212 }
213
214 if (list_resize(self, n+1) == -1)
215 return -1;
216
217 Py_INCREF(v);
218 PyList_SET_ITEM(self, n, v);
219 return 0;
220}
221
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000222int
Fred Drakea2f55112000-07-09 15:16:51 +0000223PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000224{
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000225 if (PyList_Check(op) && (newitem != NULL))
226 return app1((PyListObject *)op, newitem);
227 PyErr_BadInternalCall();
228 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000229}
230
231/* Methods */
232
233static void
Fred Drakea2f55112000-07-09 15:16:51 +0000234list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000235{
236 int i;
Guido van Rossumff413af2002-03-28 20:34:59 +0000237 PyObject_GC_UnTrack(op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000238 Py_TRASHCAN_SAFE_BEGIN(op)
Jack Jansen7874d1f1995-01-19 12:09:27 +0000239 if (op->ob_item != NULL) {
Guido van Rossumfa717011999-06-09 15:19:34 +0000240 /* Do it backwards, for Christian Tismer.
241 There's a simple test case where somehow this reduces
242 thrashing when a *very* large list is created and
243 immediately deleted. */
244 i = op->ob_size;
245 while (--i >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000246 Py_XDECREF(op->ob_item[i]);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000247 }
Guido van Rossumb18618d2000-05-03 23:44:39 +0000248 PyMem_FREE(op->ob_item);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000249 }
Raymond Hettinger0468e412004-05-05 05:37:53 +0000250 if (num_free_lists < MAXFREELISTS && PyList_CheckExact(op))
251 free_lists[num_free_lists++] = op;
Tim Petersb38e2b62004-07-29 02:29:26 +0000252 else
253 op->ob_type->tp_free((PyObject *)op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000254 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000255}
256
Guido van Rossum90933611991-06-07 16:10:43 +0000257static int
Fred Drakea2f55112000-07-09 15:16:51 +0000258list_print(PyListObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000259{
260 int i;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000261
262 i = Py_ReprEnter((PyObject*)op);
263 if (i != 0) {
264 if (i < 0)
265 return i;
266 fprintf(fp, "[...]");
267 return 0;
268 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000269 fprintf(fp, "[");
Guido van Rossum90933611991-06-07 16:10:43 +0000270 for (i = 0; i < op->ob_size; i++) {
271 if (i > 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000272 fprintf(fp, ", ");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000273 if (PyObject_Print(op->ob_item[i], fp, 0) != 0) {
274 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000275 return -1;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000276 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000277 }
278 fprintf(fp, "]");
Guido van Rossumfb376de1998-04-10 22:47:27 +0000279 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000280 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000281}
282
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000283static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000284list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000285{
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000286 int i;
Tim Petersa7259592001-06-16 05:11:17 +0000287 PyObject *s, *temp;
288 PyObject *pieces = NULL, *result = NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000289
290 i = Py_ReprEnter((PyObject*)v);
291 if (i != 0) {
Tim Petersa7259592001-06-16 05:11:17 +0000292 return i > 0 ? PyString_FromString("[...]") : NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000293 }
Tim Petersa7259592001-06-16 05:11:17 +0000294
295 if (v->ob_size == 0) {
296 result = PyString_FromString("[]");
297 goto Done;
298 }
299
300 pieces = PyList_New(0);
301 if (pieces == NULL)
302 goto Done;
303
304 /* Do repr() on each element. Note that this may mutate the list,
305 so must refetch the list size on each iteration. */
306 for (i = 0; i < v->ob_size; ++i) {
307 int status;
308 s = PyObject_Repr(v->ob_item[i]);
309 if (s == NULL)
310 goto Done;
311 status = PyList_Append(pieces, s);
312 Py_DECREF(s); /* append created a new ref */
313 if (status < 0)
314 goto Done;
315 }
316
317 /* Add "[]" decorations to the first and last items. */
318 assert(PyList_GET_SIZE(pieces) > 0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000319 s = PyString_FromString("[");
Tim Petersa7259592001-06-16 05:11:17 +0000320 if (s == NULL)
321 goto Done;
322 temp = PyList_GET_ITEM(pieces, 0);
323 PyString_ConcatAndDel(&s, temp);
324 PyList_SET_ITEM(pieces, 0, s);
325 if (s == NULL)
326 goto Done;
327
328 s = PyString_FromString("]");
329 if (s == NULL)
330 goto Done;
331 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
332 PyString_ConcatAndDel(&temp, s);
333 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
334 if (temp == NULL)
335 goto Done;
336
337 /* Paste them all together with ", " between. */
338 s = PyString_FromString(", ");
339 if (s == NULL)
340 goto Done;
341 result = _PyString_Join(s, pieces);
Tim Peters3b01a122002-07-19 02:35:45 +0000342 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +0000343
344Done:
345 Py_XDECREF(pieces);
Guido van Rossumfb376de1998-04-10 22:47:27 +0000346 Py_ReprLeave((PyObject *)v);
Tim Petersa7259592001-06-16 05:11:17 +0000347 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000348}
349
350static int
Fred Drakea2f55112000-07-09 15:16:51 +0000351list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000352{
353 return a->ob_size;
354}
355
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000356static int
Fred Drakea2f55112000-07-09 15:16:51 +0000357list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000358{
Raymond Hettingeraae59992002-09-05 14:23:49 +0000359 int i, cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000360
Raymond Hettingeraae59992002-09-05 14:23:49 +0000361 for (i = 0, cmp = 0 ; cmp == 0 && i < a->ob_size; ++i)
362 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000363 Py_EQ);
Neal Norwitzbb9c5f52002-09-05 21:32:55 +0000364 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000365}
366
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000367static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000368list_item(PyListObject *a, int i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000369{
370 if (i < 0 || i >= a->ob_size) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000371 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000372 indexerr = PyString_FromString(
373 "list index out of range");
374 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000375 return NULL;
376 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000377 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000378 return a->ob_item[i];
379}
380
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000381static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000382list_slice(PyListObject *a, int ilow, int ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000383{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000384 PyListObject *np;
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000385 PyObject **src, **dest;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000386 int i, len;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000387 if (ilow < 0)
388 ilow = 0;
389 else if (ilow > a->ob_size)
390 ilow = a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000391 if (ihigh < ilow)
392 ihigh = ilow;
393 else if (ihigh > a->ob_size)
394 ihigh = a->ob_size;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000395 len = ihigh - ilow;
396 np = (PyListObject *) PyList_New(len);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000397 if (np == NULL)
398 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000399
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000400 src = a->ob_item + ilow;
401 dest = np->ob_item;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000402 for (i = 0; i < len; i++) {
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000403 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000404 Py_INCREF(v);
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000405 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000406 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000407 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000408}
409
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000410PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000411PyList_GetSlice(PyObject *a, int ilow, int ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000412{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000413 if (!PyList_Check(a)) {
414 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000415 return NULL;
416 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000417 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000418}
419
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000420static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000421list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000422{
423 int size;
424 int i;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000425 PyObject **src, **dest;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000426 PyListObject *np;
427 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000428 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000429 "can only concatenate list (not \"%.200s\") to list",
430 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000431 return NULL;
432 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000433#define b ((PyListObject *)bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000434 size = a->ob_size + b->ob_size;
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000435 if (size < 0)
436 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000437 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000438 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000439 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000440 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000441 src = a->ob_item;
442 dest = np->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000443 for (i = 0; i < a->ob_size; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000444 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000445 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000446 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000447 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000448 src = b->ob_item;
449 dest = np->ob_item + a->ob_size;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000450 for (i = 0; i < b->ob_size; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000451 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000452 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000453 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000454 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000455 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000456#undef b
457}
458
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000459static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000460list_repeat(PyListObject *a, int n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000461{
462 int i, j;
463 int size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000464 PyListObject *np;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000465 PyObject **p, **items;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000466 PyObject *elem;
Guido van Rossumed98d481991-03-06 13:07:53 +0000467 if (n < 0)
468 n = 0;
469 size = a->ob_size * n;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000470 if (size == 0)
471 return PyList_New(0);
Guido van Rossumbfa5a142002-10-11 23:39:35 +0000472 if (n && size/n != a->ob_size)
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000473 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000474 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000475 if (np == NULL)
476 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000477
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000478 items = np->ob_item;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000479 if (a->ob_size == 1) {
480 elem = a->ob_item[0];
481 for (i = 0; i < n; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000482 items[i] = elem;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000483 Py_INCREF(elem);
484 }
485 return (PyObject *) np;
486 }
Guido van Rossumed98d481991-03-06 13:07:53 +0000487 p = np->ob_item;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000488 items = a->ob_item;
Guido van Rossumed98d481991-03-06 13:07:53 +0000489 for (i = 0; i < n; i++) {
490 for (j = 0; j < a->ob_size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000491 *p = items[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000492 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000493 p++;
494 }
495 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000496 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000497}
498
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000499static int
Armin Rigo93677f02004-07-29 12:40:23 +0000500list_clear(PyListObject *a)
501{
502 int i;
503 PyObject **item = a->ob_item;
504 if (item != NULL) {
505 /* Because XDECREF can recursively invoke operations on
506 this list, we make it empty first. */
507 i = a->ob_size;
508 a->ob_size = 0;
509 a->ob_item = NULL;
510 a->allocated = 0;
511 while (--i >= 0) {
512 Py_XDECREF(item[i]);
513 }
514 PyMem_FREE(item);
515 }
516 /* Never fails; the return value can be ignored.
517 Note that there is no guarantee that the list is actually empty
518 at this point, because XDECREF may have populated it again! */
519 return 0;
520}
521
522static int
Fred Drakea2f55112000-07-09 15:16:51 +0000523list_ass_slice(PyListObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000524{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000525 /* Because [X]DECREF can recursively invoke list operations on
526 this list, we must postpone all [X]DECREF activity until
527 after the list is back in its canonical shape. Therefore
528 we must allocate an additional array, 'recycle', into which
529 we temporarily copy the items that are deleted from the
530 list. :-( */
Armin Rigo1dd04a02004-07-30 11:38:22 +0000531 PyObject *recycled[8];
Tim Peters8d9eb102004-07-31 02:24:20 +0000532 PyObject **recycle = recycled; /* will allocate more if needed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000533 PyObject **item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000534 PyObject **vitem = NULL;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000535 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
Tim Peters8d9eb102004-07-31 02:24:20 +0000536 int n; /* # of elements in replacement list */
537 int norig; /* # of elements in list getting replaced */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000538 int d; /* Change in size */
539 int k; /* Loop index */
Tim Peters8d9eb102004-07-31 02:24:20 +0000540 size_t s;
541 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000542#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000543 if (v == NULL)
544 n = 0;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000545 else {
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000546 if (a == b) {
547 /* Special case "a[i:j] = a" -- copy b first */
Michael W. Hudsonda0a0672003-08-15 12:06:41 +0000548 v = list_slice(b, 0, b->ob_size);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000549 if (v == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000550 return result;
551 result = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000552 Py_DECREF(v);
Tim Peters8d9eb102004-07-31 02:24:20 +0000553 return result;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000554 }
Raymond Hettingerf889e102004-03-09 08:04:33 +0000555 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000556 if(v_as_SF == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000557 goto Error;
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000558 n = PySequence_Fast_GET_SIZE(v_as_SF);
Raymond Hettinger42bec932004-03-12 16:38:17 +0000559 vitem = PySequence_Fast_ITEMS(v_as_SF);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000560 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000561 if (ilow < 0)
562 ilow = 0;
563 else if (ilow > a->ob_size)
564 ilow = a->ob_size;
Tim Peters8d9eb102004-07-31 02:24:20 +0000565
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000566 if (ihigh < ilow)
567 ihigh = ilow;
568 else if (ihigh > a->ob_size)
569 ihigh = a->ob_size;
Armin Rigo93677f02004-07-29 12:40:23 +0000570
Tim Peters8d9eb102004-07-31 02:24:20 +0000571 norig = ihigh - ilow;
572 assert(norig >= 0);
573 d = n - norig;
Armin Rigo93677f02004-07-29 12:40:23 +0000574 if (a->ob_size + d == 0) {
575 Py_XDECREF(v_as_SF);
576 return list_clear(a);
577 }
578 item = a->ob_item;
Tim Peters8d9eb102004-07-31 02:24:20 +0000579 /* recycle the items that we are about to remove */
580 s = norig * sizeof(PyObject *);
Armin Rigo1dd04a02004-07-30 11:38:22 +0000581 if (s > sizeof(recycled)) {
582 recycle = (PyObject **)PyMem_MALLOC(s);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000583 if (recycle == NULL) {
584 PyErr_NoMemory();
Tim Peters8d9eb102004-07-31 02:24:20 +0000585 goto Error;
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000586 }
587 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000588 memcpy(recycle, &item[ilow], s);
Tim Peters8d9eb102004-07-31 02:24:20 +0000589
Armin Rigo1dd04a02004-07-30 11:38:22 +0000590 if (d < 0) { /* Delete -d items */
591 memmove(&item[ihigh+d], &item[ihigh],
592 (a->ob_size - ihigh)*sizeof(PyObject *));
593 list_resize(a, a->ob_size + d);
594 item = a->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000595 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000596 else if (d > 0) { /* Insert d items */
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000597 s = a->ob_size;
Tim Peters8d9eb102004-07-31 02:24:20 +0000598 if (list_resize(a, s+d) < 0)
599 goto Error;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000600 item = a->ob_item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000601 memmove(&item[ihigh+d], &item[ihigh],
602 (s - ihigh)*sizeof(PyObject *));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000603 }
604 for (k = 0; k < n; k++, ilow++) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000605 PyObject *w = vitem[k];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000606 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000607 item[ilow] = w;
608 }
Tim Peters8d9eb102004-07-31 02:24:20 +0000609 /* Convoluted: there's some obscure reason for wanting to do
610 * the decrefs "backwards", but C doesn't guarantee you can compute
611 * a pointer to one slot *before* an allocated vector. So checking
612 * for item >= recycle is incorrect.
613 */
614 for (item = recycle + norig; item > recycle; ) {
615 --item;
616 Py_XDECREF(*item);
617 }
618 result = 0;
619 Error:
Armin Rigo1dd04a02004-07-30 11:38:22 +0000620 if (recycle != recycled)
621 PyMem_FREE(recycle);
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000622 Py_XDECREF(v_as_SF);
Tim Peters8d9eb102004-07-31 02:24:20 +0000623 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000624#undef b
625}
626
Guido van Rossum234f9421993-06-17 12:35:49 +0000627int
Fred Drakea2f55112000-07-09 15:16:51 +0000628PyList_SetSlice(PyObject *a, int ilow, int ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000629{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000630 if (!PyList_Check(a)) {
631 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000632 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000633 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000634 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000635}
636
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000637static PyObject *
638list_inplace_repeat(PyListObject *self, int n)
639{
640 PyObject **items;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000641 int size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000642
643
644 size = PyList_GET_SIZE(self);
645 if (size == 0) {
646 Py_INCREF(self);
647 return (PyObject *)self;
648 }
649
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000650 if (n < 1) {
Armin Rigo93677f02004-07-29 12:40:23 +0000651 (void)list_clear(self);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000652 Py_INCREF(self);
653 return (PyObject *)self;
654 }
655
Tim Petersb38e2b62004-07-29 02:29:26 +0000656 if (list_resize(self, size*n) == -1)
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000657 return NULL;
658
659 p = size;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000660 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000661 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
662 for (j = 0; j < size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000663 PyObject *o = items[j];
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000664 Py_INCREF(o);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000665 items[p++] = o;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000666 }
667 }
668 Py_INCREF(self);
669 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000670}
671
Guido van Rossum4a450d01991-04-03 19:05:18 +0000672static int
Fred Drakea2f55112000-07-09 15:16:51 +0000673list_ass_item(PyListObject *a, int i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000674{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000675 PyObject *old_value;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000676 if (i < 0 || i >= a->ob_size) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000677 PyErr_SetString(PyExc_IndexError,
678 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000679 return -1;
680 }
681 if (v == NULL)
682 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000683 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000684 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000685 a->ob_item[i] = v;
Tim Peters3b01a122002-07-19 02:35:45 +0000686 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000687 return 0;
688}
689
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000690static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000691listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000692{
693 int i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000694 PyObject *v;
Guido van Rossumc00a9382000-02-24 21:48:29 +0000695 if (!PyArg_ParseTuple(args, "iO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000696 return NULL;
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000697 if (ins1(self, i, v) == 0)
698 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000699 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000700}
701
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000702static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000703listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000704{
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000705 if (app1(self, v) == 0)
706 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000707 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000708}
709
Barry Warsawdedf6d61998-10-09 16:37:25 +0000710static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000711listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000712{
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000713 PyObject *it; /* iter(v) */
714 int m; /* size of self */
715 int n; /* guess for size of b */
716 int mn; /* m + n */
717 int i;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000718 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000719
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000720 /* Special cases:
Tim Petersb38e2b62004-07-29 02:29:26 +0000721 1) lists and tuples which can use PySequence_Fast ops
722 2) extending self to self requires making a copy first
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000723 */
724 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
Armin Rigo70d172d2004-03-20 22:19:23 +0000725 PyObject **src, **dest;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000726 b = PySequence_Fast(b, "argument must be iterable");
727 if (!b)
728 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000729 n = PySequence_Fast_GET_SIZE(b);
730 if (n == 0) {
731 /* short circuit when b is empty */
732 Py_DECREF(b);
733 Py_RETURN_NONE;
734 }
735 m = self->ob_size;
736 if (list_resize(self, m + n) == -1) {
737 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000738 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000739 }
740 /* note that we may still have self == b here for the
741 * situation a.extend(a), but the following code works
742 * in that case too. Just make sure to resize self
743 * before calling PySequence_Fast_ITEMS.
744 */
745 /* populate the end of self with b's items */
746 src = PySequence_Fast_ITEMS(b);
747 dest = self->ob_item + m;
748 for (i = 0; i < n; i++) {
749 PyObject *o = src[i];
750 Py_INCREF(o);
751 dest[i] = o;
752 }
753 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000754 Py_RETURN_NONE;
755 }
756
757 it = PyObject_GetIter(b);
758 if (it == NULL)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000759 return NULL;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000760 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000761
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000762 /* Guess a result list size. */
763 n = PyObject_Size(b);
764 if (n < 0) {
765 PyErr_Clear();
766 n = 8; /* arbitrary */
767 }
768 m = self->ob_size;
769 mn = m + n;
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000770 if (list_resize(self, mn) == -1)
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000771 goto error;
772 memset(&(self->ob_item[m]), 0, sizeof(*self->ob_item) * n);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000773
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000774 /* Run iterator to exhaustion. */
775 for (i = m; ; i++) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000776 PyObject *item = iternext(it);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000777 if (item == NULL) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000778 if (PyErr_Occurred()) {
779 if (PyErr_ExceptionMatches(PyExc_StopIteration))
780 PyErr_Clear();
781 else
782 goto error;
783 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000784 break;
785 }
786 if (i < mn)
787 PyList_SET_ITEM(self, i, item); /* steals ref */
788 else {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000789 int status = app1(self, item);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000790 Py_DECREF(item); /* append creates a new ref */
791 if (status < 0)
792 goto error;
793 }
794 }
795
796 /* Cut back result list if initial guess was too large. */
797 if (i < mn && self != NULL) {
798 if (list_ass_slice(self, i, mn, (PyObject *)NULL) != 0)
799 goto error;
800 }
801 Py_DECREF(it);
802 Py_RETURN_NONE;
803
804 error:
805 Py_DECREF(it);
806 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000807}
808
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000809PyObject *
810_PyList_Extend(PyListObject *self, PyObject *b)
811{
812 return listextend(self, b);
813}
814
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000815static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000816list_inplace_concat(PyListObject *self, PyObject *other)
817{
818 PyObject *result;
819
820 result = listextend(self, other);
821 if (result == NULL)
822 return result;
823 Py_DECREF(result);
824 Py_INCREF(self);
825 return (PyObject *)self;
826}
827
828static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000829listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000830{
831 int i = -1;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000832 PyObject *v, *arg = NULL;
833
834 if (!PyArg_UnpackTuple(args, "pop", 0, 1, &arg))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000835 return NULL;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000836 if (arg != NULL) {
837 if (PyInt_Check(arg))
838 i = (int)(PyInt_AS_LONG((PyIntObject*) arg));
Raymond Hettingerfa6c6f82004-02-19 06:12:06 +0000839 else if (!PyArg_ParseTuple(args, "|i:pop", &i))
840 return NULL;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000841 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000842 if (self->ob_size == 0) {
843 /* Special-case most common failure cause */
844 PyErr_SetString(PyExc_IndexError, "pop from empty list");
845 return NULL;
846 }
847 if (i < 0)
848 i += self->ob_size;
849 if (i < 0 || i >= self->ob_size) {
850 PyErr_SetString(PyExc_IndexError, "pop index out of range");
851 return NULL;
852 }
853 v = self->ob_item[i];
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000854 if (i == self->ob_size - 1) {
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000855 if (list_resize(self, self->ob_size - 1) == -1)
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000856 return NULL;
857 return v;
858 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000859 Py_INCREF(v);
860 if (list_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) {
861 Py_DECREF(v);
862 return NULL;
863 }
864 return v;
865}
866
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000867/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
868static void
869reverse_slice(PyObject **lo, PyObject **hi)
870{
871 assert(lo && hi);
872
873 --hi;
874 while (lo < hi) {
875 PyObject *t = *lo;
876 *lo = *hi;
877 *hi = t;
878 ++lo;
879 --hi;
880 }
881}
882
Tim Petersa64dc242002-08-01 02:13:36 +0000883/* Lots of code for an adaptive, stable, natural mergesort. There are many
884 * pieces to this algorithm; read listsort.txt for overviews and details.
885 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000886
Guido van Rossum3f236de1996-12-10 23:55:39 +0000887/* Comparison function. Takes care of calling a user-supplied
Tim Peters66860f62002-08-04 17:47:26 +0000888 * comparison function (any callable Python object), which must not be
889 * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool
890 * with Py_LT if you know it's NULL).
Tim Petersa64dc242002-08-01 02:13:36 +0000891 * Returns -1 on error, 1 if x < y, 0 if x >= y.
892 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000893static int
Tim Petersa8c974c2002-07-19 03:30:57 +0000894islt(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000895{
Tim Petersf2a04732002-07-11 21:46:16 +0000896 PyObject *res;
897 PyObject *args;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000898 int i;
899
Tim Peters66860f62002-08-04 17:47:26 +0000900 assert(compare != NULL);
Tim Petersa8c974c2002-07-19 03:30:57 +0000901 /* Call the user's comparison function and translate the 3-way
902 * result into true or false (or error).
903 */
Tim Petersf2a04732002-07-11 21:46:16 +0000904 args = PyTuple_New(2);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000905 if (args == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000906 return -1;
Tim Petersf2a04732002-07-11 21:46:16 +0000907 Py_INCREF(x);
908 Py_INCREF(y);
909 PyTuple_SET_ITEM(args, 0, x);
910 PyTuple_SET_ITEM(args, 1, y);
Tim Peters58cf3612002-07-15 05:16:13 +0000911 res = PyObject_Call(compare, args, NULL);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000912 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000913 if (res == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000914 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000915 if (!PyInt_Check(res)) {
916 Py_DECREF(res);
917 PyErr_SetString(PyExc_TypeError,
Guido van Rossum9bcd1d71999-04-19 17:44:39 +0000918 "comparison function must return int");
Tim Petersa8c974c2002-07-19 03:30:57 +0000919 return -1;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000920 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000921 i = PyInt_AsLong(res);
922 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +0000923 return i < 0;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000924}
925
Tim Peters66860f62002-08-04 17:47:26 +0000926/* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
927 * islt. This avoids a layer of function call in the usual case, and
928 * sorting does many comparisons.
929 * Returns -1 on error, 1 if x < y, 0 if x >= y.
930 */
931#define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
932 PyObject_RichCompareBool(X, Y, Py_LT) : \
933 islt(X, Y, COMPARE))
934
935/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +0000936 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
937 started. It makes more sense in context <wink>. X and Y are PyObject*s.
938*/
Tim Peters66860f62002-08-04 17:47:26 +0000939#define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
Tim Petersa8c974c2002-07-19 03:30:57 +0000940 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000941
942/* binarysort is the best method for sorting small arrays: it does
943 few compares, but can do data movement quadratic in the number of
944 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000945 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +0000946 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000947 On entry, must have lo <= start <= hi, and that [lo, start) is already
948 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +0000949 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000950 Even in case of error, the output slice will be some permutation of
951 the input (nothing is lost or duplicated).
952*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000953static int
Fred Drakea2f55112000-07-09 15:16:51 +0000954binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
955 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000956{
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000957 register int k;
958 register PyObject **l, **p, **r;
959 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000960
Tim Petersa8c974c2002-07-19 03:30:57 +0000961 assert(lo <= start && start <= hi);
962 /* assert [lo, start) is sorted */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000963 if (lo == start)
964 ++start;
965 for (; start < hi; ++start) {
966 /* set l to where *start belongs */
967 l = lo;
968 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000969 pivot = *r;
Tim Peters0fe977c2002-07-19 06:12:32 +0000970 /* Invariants:
971 * pivot >= all in [lo, l).
972 * pivot < all in [r, start).
973 * The second is vacuously true at the start.
974 */
975 assert(l < r);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000976 do {
977 p = l + ((r - l) >> 1);
Tim Petersa8c974c2002-07-19 03:30:57 +0000978 IFLT(pivot, *p)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000979 r = p;
980 else
Tim Peters0fe977c2002-07-19 06:12:32 +0000981 l = p+1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000982 } while (l < r);
Tim Peters0fe977c2002-07-19 06:12:32 +0000983 assert(l == r);
984 /* The invariants still hold, so pivot >= all in [lo, l) and
985 pivot < all in [l, start), so pivot belongs at l. Note
986 that if there are elements equal to pivot, l points to the
987 first slot after them -- that's why this sort is stable.
988 Slide over to make room.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000989 Caution: using memmove is much slower under MSVC 5;
990 we're not usually moving many slots. */
991 for (p = start; p > l; --p)
992 *p = *(p-1);
993 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000994 }
Guido van Rossum3f236de1996-12-10 23:55:39 +0000995 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000996
997 fail:
998 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000999}
1000
Tim Petersa64dc242002-08-01 02:13:36 +00001001/*
1002Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1003is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001004
Tim Petersa64dc242002-08-01 02:13:36 +00001005 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001006
Tim Petersa64dc242002-08-01 02:13:36 +00001007or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001008
Tim Petersa64dc242002-08-01 02:13:36 +00001009 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001010
Tim Petersa64dc242002-08-01 02:13:36 +00001011Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1012For its intended use in a stable mergesort, the strictness of the defn of
1013"descending" is needed so that the caller can safely reverse a descending
1014sequence without violating stability (strict > ensures there are no equal
1015elements to get out of order).
1016
1017Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001018*/
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001019static int
Tim Petersa64dc242002-08-01 02:13:36 +00001020count_run(PyObject **lo, PyObject **hi, PyObject *compare, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001021{
Tim Petersa64dc242002-08-01 02:13:36 +00001022 int k;
1023 int n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001024
Tim Petersa64dc242002-08-01 02:13:36 +00001025 assert(lo < hi);
1026 *descending = 0;
1027 ++lo;
1028 if (lo == hi)
1029 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001030
Tim Petersa64dc242002-08-01 02:13:36 +00001031 n = 2;
1032 IFLT(*lo, *(lo-1)) {
1033 *descending = 1;
1034 for (lo = lo+1; lo < hi; ++lo, ++n) {
1035 IFLT(*lo, *(lo-1))
1036 ;
1037 else
1038 break;
1039 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001040 }
Tim Petersa64dc242002-08-01 02:13:36 +00001041 else {
1042 for (lo = lo+1; lo < hi; ++lo, ++n) {
1043 IFLT(*lo, *(lo-1))
1044 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001045 }
1046 }
1047
Tim Petersa64dc242002-08-01 02:13:36 +00001048 return n;
1049fail:
1050 return -1;
1051}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001052
Tim Petersa64dc242002-08-01 02:13:36 +00001053/*
1054Locate the proper position of key in a sorted vector; if the vector contains
1055an element equal to key, return the position immediately to the left of
1056the leftmost equal element. [gallop_right() does the same except returns
1057the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001058
Tim Petersa64dc242002-08-01 02:13:36 +00001059"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001060
Tim Petersa64dc242002-08-01 02:13:36 +00001061"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1062hint is to the final result, the faster this runs.
1063
1064The return value is the int k in 0..n such that
1065
1066 a[k-1] < key <= a[k]
1067
1068pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1069key belongs at index k; or, IOW, the first k elements of a should precede
1070key, and the last n-k should follow key.
1071
1072Returns -1 on error. See listsort.txt for info on the method.
1073*/
1074static int
1075gallop_left(PyObject *key, PyObject **a, int n, int hint, PyObject *compare)
1076{
1077 int ofs;
1078 int lastofs;
1079 int k;
1080
1081 assert(key && a && n > 0 && hint >= 0 && hint < n);
1082
1083 a += hint;
1084 lastofs = 0;
1085 ofs = 1;
1086 IFLT(*a, key) {
1087 /* a[hint] < key -- gallop right, until
1088 * a[hint + lastofs] < key <= a[hint + ofs]
1089 */
1090 const int maxofs = n - hint; /* &a[n-1] is highest */
1091 while (ofs < maxofs) {
1092 IFLT(a[ofs], key) {
1093 lastofs = ofs;
1094 ofs = (ofs << 1) + 1;
1095 if (ofs <= 0) /* int overflow */
1096 ofs = maxofs;
1097 }
1098 else /* key <= a[hint + ofs] */
1099 break;
1100 }
1101 if (ofs > maxofs)
1102 ofs = maxofs;
1103 /* Translate back to offsets relative to &a[0]. */
1104 lastofs += hint;
1105 ofs += hint;
1106 }
1107 else {
1108 /* key <= a[hint] -- gallop left, until
1109 * a[hint - ofs] < key <= a[hint - lastofs]
1110 */
1111 const int maxofs = hint + 1; /* &a[0] is lowest */
1112 while (ofs < maxofs) {
1113 IFLT(*(a-ofs), key)
1114 break;
1115 /* key <= a[hint - ofs] */
1116 lastofs = ofs;
1117 ofs = (ofs << 1) + 1;
1118 if (ofs <= 0) /* int overflow */
1119 ofs = maxofs;
1120 }
1121 if (ofs > maxofs)
1122 ofs = maxofs;
1123 /* Translate back to positive offsets relative to &a[0]. */
1124 k = lastofs;
1125 lastofs = hint - ofs;
1126 ofs = hint - k;
1127 }
1128 a -= hint;
1129
1130 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1131 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1132 * right of lastofs but no farther right than ofs. Do a binary
1133 * search, with invariant a[lastofs-1] < key <= a[ofs].
1134 */
1135 ++lastofs;
1136 while (lastofs < ofs) {
1137 int m = lastofs + ((ofs - lastofs) >> 1);
1138
1139 IFLT(a[m], key)
1140 lastofs = m+1; /* a[m] < key */
1141 else
1142 ofs = m; /* key <= a[m] */
1143 }
1144 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1145 return ofs;
1146
1147fail:
1148 return -1;
1149}
1150
1151/*
1152Exactly like gallop_left(), except that if key already exists in a[0:n],
1153finds the position immediately to the right of the rightmost equal value.
1154
1155The return value is the int k in 0..n such that
1156
1157 a[k-1] <= key < a[k]
1158
1159or -1 if error.
1160
1161The code duplication is massive, but this is enough different given that
1162we're sticking to "<" comparisons that it's much harder to follow if
1163written as one routine with yet another "left or right?" flag.
1164*/
1165static int
1166gallop_right(PyObject *key, PyObject **a, int n, int hint, PyObject *compare)
1167{
1168 int ofs;
1169 int lastofs;
1170 int k;
1171
1172 assert(key && a && n > 0 && hint >= 0 && hint < n);
1173
1174 a += hint;
1175 lastofs = 0;
1176 ofs = 1;
1177 IFLT(key, *a) {
1178 /* key < a[hint] -- gallop left, until
1179 * a[hint - ofs] <= key < a[hint - lastofs]
1180 */
1181 const int maxofs = hint + 1; /* &a[0] is lowest */
1182 while (ofs < maxofs) {
1183 IFLT(key, *(a-ofs)) {
1184 lastofs = ofs;
1185 ofs = (ofs << 1) + 1;
1186 if (ofs <= 0) /* int overflow */
1187 ofs = maxofs;
1188 }
1189 else /* a[hint - ofs] <= key */
1190 break;
1191 }
1192 if (ofs > maxofs)
1193 ofs = maxofs;
1194 /* Translate back to positive offsets relative to &a[0]. */
1195 k = lastofs;
1196 lastofs = hint - ofs;
1197 ofs = hint - k;
1198 }
1199 else {
1200 /* a[hint] <= key -- gallop right, until
1201 * a[hint + lastofs] <= key < a[hint + ofs]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001202 */
Tim Petersa64dc242002-08-01 02:13:36 +00001203 const int maxofs = n - hint; /* &a[n-1] is highest */
1204 while (ofs < maxofs) {
1205 IFLT(key, a[ofs])
1206 break;
1207 /* a[hint + ofs] <= key */
1208 lastofs = ofs;
1209 ofs = (ofs << 1) + 1;
1210 if (ofs <= 0) /* int overflow */
1211 ofs = maxofs;
1212 }
1213 if (ofs > maxofs)
1214 ofs = maxofs;
1215 /* Translate back to offsets relative to &a[0]. */
1216 lastofs += hint;
1217 ofs += hint;
1218 }
1219 a -= hint;
1220
1221 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1222 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1223 * right of lastofs but no farther right than ofs. Do a binary
1224 * search, with invariant a[lastofs-1] <= key < a[ofs].
1225 */
1226 ++lastofs;
1227 while (lastofs < ofs) {
1228 int m = lastofs + ((ofs - lastofs) >> 1);
1229
1230 IFLT(key, a[m])
1231 ofs = m; /* key < a[m] */
1232 else
1233 lastofs = m+1; /* a[m] <= key */
1234 }
1235 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1236 return ofs;
1237
1238fail:
1239 return -1;
1240}
1241
1242/* The maximum number of entries in a MergeState's pending-runs stack.
1243 * This is enough to sort arrays of size up to about
1244 * 32 * phi ** MAX_MERGE_PENDING
1245 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1246 * with 2**64 elements.
1247 */
1248#define MAX_MERGE_PENDING 85
1249
Tim Peterse05f65a2002-08-10 05:21:15 +00001250/* When we get into galloping mode, we stay there until both runs win less
1251 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001252 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001253#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001254
1255/* Avoid malloc for small temp arrays. */
1256#define MERGESTATE_TEMP_SIZE 256
1257
1258/* One MergeState exists on the stack per invocation of mergesort. It's just
1259 * a convenient way to pass state around among the helper functions.
1260 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001261struct s_slice {
1262 PyObject **base;
1263 int len;
1264};
1265
Tim Petersa64dc242002-08-01 02:13:36 +00001266typedef struct s_MergeState {
1267 /* The user-supplied comparison function. or NULL if none given. */
1268 PyObject *compare;
1269
Tim Peterse05f65a2002-08-10 05:21:15 +00001270 /* This controls when we get *into* galloping mode. It's initialized
1271 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1272 * random data, and lower for highly structured data.
1273 */
1274 int min_gallop;
1275
Tim Petersa64dc242002-08-01 02:13:36 +00001276 /* 'a' is temp storage to help with merges. It contains room for
1277 * alloced entries.
1278 */
1279 PyObject **a; /* may point to temparray below */
1280 int alloced;
1281
1282 /* A stack of n pending runs yet to be merged. Run #i starts at
1283 * address base[i] and extends for len[i] elements. It's always
1284 * true (so long as the indices are in bounds) that
1285 *
Tim Peterse05f65a2002-08-10 05:21:15 +00001286 * pending[i].base + pending[i].len == pending[i+1].base
Tim Petersa64dc242002-08-01 02:13:36 +00001287 *
1288 * so we could cut the storage for this, but it's a minor amount,
1289 * and keeping all the info explicit simplifies the code.
1290 */
1291 int n;
Tim Peterse05f65a2002-08-10 05:21:15 +00001292 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001293
1294 /* 'a' points to this when possible, rather than muck with malloc. */
1295 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1296} MergeState;
1297
1298/* Conceptually a MergeState's constructor. */
1299static void
1300merge_init(MergeState *ms, PyObject *compare)
1301{
1302 assert(ms != NULL);
1303 ms->compare = compare;
1304 ms->a = ms->temparray;
1305 ms->alloced = MERGESTATE_TEMP_SIZE;
1306 ms->n = 0;
Tim Peterse05f65a2002-08-10 05:21:15 +00001307 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001308}
1309
1310/* Free all the temp memory owned by the MergeState. This must be called
1311 * when you're done with a MergeState, and may be called before then if
1312 * you want to free the temp memory early.
1313 */
1314static void
1315merge_freemem(MergeState *ms)
1316{
1317 assert(ms != NULL);
1318 if (ms->a != ms->temparray)
1319 PyMem_Free(ms->a);
1320 ms->a = ms->temparray;
1321 ms->alloced = MERGESTATE_TEMP_SIZE;
1322}
1323
1324/* Ensure enough temp memory for 'need' array slots is available.
1325 * Returns 0 on success and -1 if the memory can't be gotten.
1326 */
1327static int
1328merge_getmem(MergeState *ms, int need)
1329{
1330 assert(ms != NULL);
1331 if (need <= ms->alloced)
1332 return 0;
1333 /* Don't realloc! That can cost cycles to copy the old data, but
1334 * we don't care what's in the block.
1335 */
1336 merge_freemem(ms);
1337 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1338 if (ms->a) {
1339 ms->alloced = need;
1340 return 0;
1341 }
1342 PyErr_NoMemory();
1343 merge_freemem(ms); /* reset to sane state */
1344 return -1;
1345}
1346#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1347 merge_getmem(MS, NEED))
1348
1349/* Merge the na elements starting at pa with the nb elements starting at pb
1350 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1351 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1352 * merge, and should have na <= nb. See listsort.txt for more info.
1353 * Return 0 if successful, -1 if error.
1354 */
1355static int
1356merge_lo(MergeState *ms, PyObject **pa, int na, PyObject **pb, int nb)
1357{
1358 int k;
1359 PyObject *compare;
1360 PyObject **dest;
1361 int result = -1; /* guilty until proved innocent */
Tim Peterse05f65a2002-08-10 05:21:15 +00001362 int min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001363
1364 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1365 if (MERGE_GETMEM(ms, na) < 0)
1366 return -1;
1367 memcpy(ms->a, pa, na * sizeof(PyObject*));
1368 dest = pa;
1369 pa = ms->a;
1370
1371 *dest++ = *pb++;
1372 --nb;
1373 if (nb == 0)
1374 goto Succeed;
1375 if (na == 1)
1376 goto CopyB;
1377
1378 compare = ms->compare;
1379 for (;;) {
1380 int acount = 0; /* # of times A won in a row */
1381 int bcount = 0; /* # of times B won in a row */
1382
1383 /* Do the straightforward thing until (if ever) one run
1384 * appears to win consistently.
1385 */
1386 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001387 assert(na > 1 && nb > 0);
Tim Peters66860f62002-08-04 17:47:26 +00001388 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001389 if (k) {
1390 if (k < 0)
1391 goto Fail;
1392 *dest++ = *pb++;
1393 ++bcount;
1394 acount = 0;
1395 --nb;
1396 if (nb == 0)
1397 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001398 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001399 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001400 }
1401 else {
Tim Petersa64dc242002-08-01 02:13:36 +00001402 *dest++ = *pa++;
1403 ++acount;
1404 bcount = 0;
1405 --na;
1406 if (na == 1)
1407 goto CopyB;
Tim Peterse05f65a2002-08-10 05:21:15 +00001408 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001409 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001410 }
Tim Petersa64dc242002-08-01 02:13:36 +00001411 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001412
Tim Petersa64dc242002-08-01 02:13:36 +00001413 /* One run is winning so consistently that galloping may
1414 * be a huge win. So try that, and continue galloping until
1415 * (if ever) neither run appears to be winning consistently
1416 * anymore.
1417 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001418 ++min_gallop;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001419 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001420 assert(na > 1 && nb > 0);
1421 min_gallop -= min_gallop > 1;
1422 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001423 k = gallop_right(*pb, pa, na, 0, compare);
1424 acount = k;
1425 if (k) {
1426 if (k < 0)
1427 goto Fail;
1428 memcpy(dest, pa, k * sizeof(PyObject *));
1429 dest += k;
1430 pa += k;
1431 na -= k;
1432 if (na == 1)
1433 goto CopyB;
1434 /* na==0 is impossible now if the comparison
1435 * function is consistent, but we can't assume
1436 * that it is.
1437 */
1438 if (na == 0)
1439 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001440 }
Tim Petersa64dc242002-08-01 02:13:36 +00001441 *dest++ = *pb++;
1442 --nb;
1443 if (nb == 0)
1444 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001445
Tim Petersa64dc242002-08-01 02:13:36 +00001446 k = gallop_left(*pa, pb, nb, 0, compare);
1447 bcount = k;
1448 if (k) {
1449 if (k < 0)
1450 goto Fail;
1451 memmove(dest, pb, k * sizeof(PyObject *));
1452 dest += k;
1453 pb += k;
1454 nb -= k;
1455 if (nb == 0)
1456 goto Succeed;
1457 }
1458 *dest++ = *pa++;
1459 --na;
1460 if (na == 1)
1461 goto CopyB;
1462 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001463 ++min_gallop; /* penalize it for leaving galloping mode */
1464 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001465 }
1466Succeed:
1467 result = 0;
1468Fail:
1469 if (na)
1470 memcpy(dest, pa, na * sizeof(PyObject*));
1471 return result;
1472CopyB:
1473 assert(na == 1 && nb > 0);
1474 /* The last element of pa belongs at the end of the merge. */
1475 memmove(dest, pb, nb * sizeof(PyObject *));
1476 dest[nb] = *pa;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001477 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001478}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001479
Tim Petersa64dc242002-08-01 02:13:36 +00001480/* Merge the na elements starting at pa with the nb elements starting at pb
1481 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1482 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1483 * merge, and should have na >= nb. See listsort.txt for more info.
1484 * Return 0 if successful, -1 if error.
1485 */
1486static int
1487merge_hi(MergeState *ms, PyObject **pa, int na, PyObject **pb, int nb)
1488{
1489 int k;
1490 PyObject *compare;
1491 PyObject **dest;
1492 int result = -1; /* guilty until proved innocent */
1493 PyObject **basea;
1494 PyObject **baseb;
Tim Peterse05f65a2002-08-10 05:21:15 +00001495 int min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001496
1497 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1498 if (MERGE_GETMEM(ms, nb) < 0)
1499 return -1;
1500 dest = pb + nb - 1;
1501 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1502 basea = pa;
1503 baseb = ms->a;
1504 pb = ms->a + nb - 1;
1505 pa += na - 1;
1506
1507 *dest-- = *pa--;
1508 --na;
1509 if (na == 0)
1510 goto Succeed;
1511 if (nb == 1)
1512 goto CopyA;
1513
1514 compare = ms->compare;
1515 for (;;) {
1516 int acount = 0; /* # of times A won in a row */
1517 int bcount = 0; /* # of times B won in a row */
1518
1519 /* Do the straightforward thing until (if ever) one run
1520 * appears to win consistently.
1521 */
1522 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001523 assert(na > 0 && nb > 1);
Tim Peters66860f62002-08-04 17:47:26 +00001524 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001525 if (k) {
1526 if (k < 0)
1527 goto Fail;
1528 *dest-- = *pa--;
1529 ++acount;
1530 bcount = 0;
1531 --na;
1532 if (na == 0)
1533 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001534 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001535 break;
1536 }
1537 else {
1538 *dest-- = *pb--;
1539 ++bcount;
1540 acount = 0;
1541 --nb;
1542 if (nb == 1)
1543 goto CopyA;
Tim Peterse05f65a2002-08-10 05:21:15 +00001544 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001545 break;
1546 }
1547 }
1548
1549 /* One run is winning so consistently that galloping may
1550 * be a huge win. So try that, and continue galloping until
1551 * (if ever) neither run appears to be winning consistently
1552 * anymore.
1553 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001554 ++min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001555 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001556 assert(na > 0 && nb > 1);
1557 min_gallop -= min_gallop > 1;
1558 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001559 k = gallop_right(*pb, basea, na, na-1, compare);
1560 if (k < 0)
1561 goto Fail;
1562 k = na - k;
1563 acount = k;
1564 if (k) {
1565 dest -= k;
1566 pa -= k;
1567 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1568 na -= k;
1569 if (na == 0)
1570 goto Succeed;
1571 }
1572 *dest-- = *pb--;
1573 --nb;
1574 if (nb == 1)
1575 goto CopyA;
1576
1577 k = gallop_left(*pa, baseb, nb, nb-1, compare);
1578 if (k < 0)
1579 goto Fail;
1580 k = nb - k;
1581 bcount = k;
1582 if (k) {
1583 dest -= k;
1584 pb -= k;
1585 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1586 nb -= k;
1587 if (nb == 1)
1588 goto CopyA;
1589 /* nb==0 is impossible now if the comparison
1590 * function is consistent, but we can't assume
1591 * that it is.
1592 */
1593 if (nb == 0)
1594 goto Succeed;
1595 }
1596 *dest-- = *pa--;
1597 --na;
1598 if (na == 0)
1599 goto Succeed;
1600 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001601 ++min_gallop; /* penalize it for leaving galloping mode */
1602 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001603 }
1604Succeed:
1605 result = 0;
1606Fail:
1607 if (nb)
1608 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1609 return result;
1610CopyA:
1611 assert(nb == 1 && na > 0);
1612 /* The first element of pb belongs at the front of the merge. */
1613 dest -= na;
1614 pa -= na;
1615 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1616 *dest = *pb;
1617 return 0;
1618}
1619
1620/* Merge the two runs at stack indices i and i+1.
1621 * Returns 0 on success, -1 on error.
1622 */
1623static int
1624merge_at(MergeState *ms, int i)
1625{
1626 PyObject **pa, **pb;
1627 int na, nb;
1628 int k;
1629 PyObject *compare;
1630
1631 assert(ms != NULL);
1632 assert(ms->n >= 2);
1633 assert(i >= 0);
1634 assert(i == ms->n - 2 || i == ms->n - 3);
1635
Tim Peterse05f65a2002-08-10 05:21:15 +00001636 pa = ms->pending[i].base;
1637 na = ms->pending[i].len;
1638 pb = ms->pending[i+1].base;
1639 nb = ms->pending[i+1].len;
Tim Petersa64dc242002-08-01 02:13:36 +00001640 assert(na > 0 && nb > 0);
1641 assert(pa + na == pb);
1642
1643 /* Record the length of the combined runs; if i is the 3rd-last
1644 * run now, also slide over the last run (which isn't involved
1645 * in this merge). The current run i+1 goes away in any case.
1646 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001647 ms->pending[i].len = na + nb;
1648 if (i == ms->n - 3)
1649 ms->pending[i+1] = ms->pending[i+2];
Tim Petersa64dc242002-08-01 02:13:36 +00001650 --ms->n;
1651
1652 /* Where does b start in a? Elements in a before that can be
1653 * ignored (already in place).
1654 */
1655 compare = ms->compare;
1656 k = gallop_right(*pb, pa, na, 0, compare);
1657 if (k < 0)
1658 return -1;
1659 pa += k;
1660 na -= k;
1661 if (na == 0)
1662 return 0;
1663
1664 /* Where does a end in b? Elements in b after that can be
1665 * ignored (already in place).
1666 */
1667 nb = gallop_left(pa[na-1], pb, nb, nb-1, compare);
1668 if (nb <= 0)
1669 return nb;
1670
1671 /* Merge what remains of the runs, using a temp array with
1672 * min(na, nb) elements.
1673 */
1674 if (na <= nb)
1675 return merge_lo(ms, pa, na, pb, nb);
1676 else
1677 return merge_hi(ms, pa, na, pb, nb);
1678}
1679
1680/* Examine the stack of runs waiting to be merged, merging adjacent runs
1681 * until the stack invariants are re-established:
1682 *
1683 * 1. len[-3] > len[-2] + len[-1]
1684 * 2. len[-2] > len[-1]
1685 *
1686 * See listsort.txt for more info.
1687 *
1688 * Returns 0 on success, -1 on error.
1689 */
1690static int
1691merge_collapse(MergeState *ms)
1692{
Tim Peterse05f65a2002-08-10 05:21:15 +00001693 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001694
1695 assert(ms);
1696 while (ms->n > 1) {
1697 int n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001698 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1699 if (p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001700 --n;
1701 if (merge_at(ms, n) < 0)
1702 return -1;
1703 }
Tim Peterse05f65a2002-08-10 05:21:15 +00001704 else if (p[n].len <= p[n+1].len) {
Tim Petersa64dc242002-08-01 02:13:36 +00001705 if (merge_at(ms, n) < 0)
1706 return -1;
1707 }
1708 else
1709 break;
1710 }
1711 return 0;
1712}
1713
1714/* Regardless of invariants, merge all runs on the stack until only one
1715 * remains. This is used at the end of the mergesort.
1716 *
1717 * Returns 0 on success, -1 on error.
1718 */
1719static int
1720merge_force_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+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001728 --n;
1729 if (merge_at(ms, n) < 0)
1730 return -1;
1731 }
1732 return 0;
1733}
1734
1735/* Compute a good value for the minimum run length; natural runs shorter
1736 * than this are boosted artificially via binary insertion.
1737 *
1738 * If n < 64, return n (it's too small to bother with fancy stuff).
1739 * Else if n is an exact power of 2, return 32.
1740 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1741 * strictly less than, an exact power of 2.
1742 *
1743 * See listsort.txt for more info.
1744 */
1745static int
1746merge_compute_minrun(int n)
1747{
1748 int r = 0; /* becomes 1 if any 1 bits are shifted off */
1749
1750 assert(n >= 0);
1751 while (n >= 64) {
1752 r |= n & 1;
1753 n >>= 1;
1754 }
1755 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001756}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001757
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001758/* Special wrapper to support stable sorting using the decorate-sort-undecorate
1759 pattern. Holds a key which is used for comparisions and the original record
Tim Petersb38e2b62004-07-29 02:29:26 +00001760 which is returned during the undecorate phase. By exposing only the key
1761 during comparisons, the underlying sort stability characteristics are left
1762 unchanged. Also, if a custom comparison function is used, it will only see
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001763 the key instead of a full record. */
1764
1765typedef struct {
1766 PyObject_HEAD
1767 PyObject *key;
1768 PyObject *value;
1769} sortwrapperobject;
1770
1771static PyTypeObject sortwrapper_type;
1772
1773static PyObject *
1774sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
1775{
1776 if (!PyObject_TypeCheck(b, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001777 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001778 "expected a sortwrapperobject");
1779 return NULL;
1780 }
1781 return PyObject_RichCompare(a->key, b->key, op);
1782}
1783
1784static void
1785sortwrapper_dealloc(sortwrapperobject *so)
1786{
1787 Py_XDECREF(so->key);
1788 Py_XDECREF(so->value);
1789 PyObject_Del(so);
1790}
1791
1792PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
1793
1794static PyTypeObject sortwrapper_type = {
1795 PyObject_HEAD_INIT(&PyType_Type)
1796 0, /* ob_size */
1797 "sortwrapper", /* tp_name */
1798 sizeof(sortwrapperobject), /* tp_basicsize */
1799 0, /* tp_itemsize */
1800 /* methods */
1801 (destructor)sortwrapper_dealloc, /* tp_dealloc */
1802 0, /* tp_print */
1803 0, /* tp_getattr */
1804 0, /* tp_setattr */
1805 0, /* tp_compare */
1806 0, /* tp_repr */
1807 0, /* tp_as_number */
1808 0, /* tp_as_sequence */
1809 0, /* tp_as_mapping */
1810 0, /* tp_hash */
1811 0, /* tp_call */
1812 0, /* tp_str */
1813 PyObject_GenericGetAttr, /* tp_getattro */
1814 0, /* tp_setattro */
1815 0, /* tp_as_buffer */
Tim Petersb38e2b62004-07-29 02:29:26 +00001816 Py_TPFLAGS_DEFAULT |
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001817 Py_TPFLAGS_HAVE_RICHCOMPARE, /* tp_flags */
1818 sortwrapper_doc, /* tp_doc */
1819 0, /* tp_traverse */
1820 0, /* tp_clear */
1821 (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
1822};
1823
1824/* Returns a new reference to a sortwrapper.
1825 Consumes the references to the two underlying objects. */
1826
1827static PyObject *
1828build_sortwrapper(PyObject *key, PyObject *value)
1829{
1830 sortwrapperobject *so;
Tim Petersb38e2b62004-07-29 02:29:26 +00001831
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001832 so = PyObject_New(sortwrapperobject, &sortwrapper_type);
1833 if (so == NULL)
1834 return NULL;
1835 so->key = key;
1836 so->value = value;
1837 return (PyObject *)so;
1838}
1839
1840/* Returns a new reference to the value underlying the wrapper. */
1841static PyObject *
1842sortwrapper_getvalue(PyObject *so)
1843{
1844 PyObject *value;
1845
1846 if (!PyObject_TypeCheck(so, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001847 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001848 "expected a sortwrapperobject");
1849 return NULL;
1850 }
1851 value = ((sortwrapperobject *)so)->value;
1852 Py_INCREF(value);
1853 return value;
1854}
1855
1856/* Wrapper for user specified cmp functions in combination with a
1857 specified key function. Makes sure the cmp function is presented
1858 with the actual key instead of the sortwrapper */
1859
1860typedef struct {
1861 PyObject_HEAD
1862 PyObject *func;
1863} cmpwrapperobject;
1864
1865static void
1866cmpwrapper_dealloc(cmpwrapperobject *co)
1867{
1868 Py_XDECREF(co->func);
1869 PyObject_Del(co);
1870}
1871
1872static PyObject *
1873cmpwrapper_call(cmpwrapperobject *co, PyObject *args, PyObject *kwds)
1874{
1875 PyObject *x, *y, *xx, *yy;
1876
1877 if (!PyArg_UnpackTuple(args, "", 2, 2, &x, &y))
1878 return NULL;
1879 if (!PyObject_TypeCheck(x, &sortwrapper_type) ||
Raymond Hettingerae4a2992003-10-16 17:16:30 +00001880 !PyObject_TypeCheck(y, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001881 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001882 "expected a sortwrapperobject");
1883 return NULL;
1884 }
1885 xx = ((sortwrapperobject *)x)->key;
1886 yy = ((sortwrapperobject *)y)->key;
1887 return PyObject_CallFunctionObjArgs(co->func, xx, yy, NULL);
1888}
1889
1890PyDoc_STRVAR(cmpwrapper_doc, "cmp() wrapper for sort with custom keys.");
1891
1892static PyTypeObject cmpwrapper_type = {
1893 PyObject_HEAD_INIT(&PyType_Type)
1894 0, /* ob_size */
1895 "cmpwrapper", /* tp_name */
1896 sizeof(cmpwrapperobject), /* tp_basicsize */
1897 0, /* tp_itemsize */
1898 /* methods */
1899 (destructor)cmpwrapper_dealloc, /* tp_dealloc */
1900 0, /* tp_print */
1901 0, /* tp_getattr */
1902 0, /* tp_setattr */
1903 0, /* tp_compare */
1904 0, /* tp_repr */
1905 0, /* tp_as_number */
1906 0, /* tp_as_sequence */
1907 0, /* tp_as_mapping */
1908 0, /* tp_hash */
1909 (ternaryfunc)cmpwrapper_call, /* tp_call */
1910 0, /* tp_str */
1911 PyObject_GenericGetAttr, /* tp_getattro */
1912 0, /* tp_setattro */
1913 0, /* tp_as_buffer */
1914 Py_TPFLAGS_DEFAULT, /* tp_flags */
1915 cmpwrapper_doc, /* tp_doc */
1916};
1917
1918static PyObject *
1919build_cmpwrapper(PyObject *cmpfunc)
1920{
1921 cmpwrapperobject *co;
Tim Petersb38e2b62004-07-29 02:29:26 +00001922
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001923 co = PyObject_New(cmpwrapperobject, &cmpwrapper_type);
1924 if (co == NULL)
1925 return NULL;
1926 Py_INCREF(cmpfunc);
1927 co->func = cmpfunc;
1928 return (PyObject *)co;
1929}
1930
Tim Petersa64dc242002-08-01 02:13:36 +00001931/* An adaptive, stable, natural mergesort. See listsort.txt.
1932 * Returns Py_None on success, NULL on error. Even in case of error, the
1933 * list will be some permutation of its input state (nothing is lost or
1934 * duplicated).
1935 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001936static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001937listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001938{
Tim Petersa64dc242002-08-01 02:13:36 +00001939 MergeState ms;
1940 PyObject **lo, **hi;
1941 int nremaining;
1942 int minrun;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001943 int saved_ob_size, saved_allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00001944 PyObject **saved_ob_item;
Armin Rigo93677f02004-07-29 12:40:23 +00001945 PyObject **final_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001946 PyObject *compare = NULL;
1947 PyObject *result = NULL; /* guilty until proved innocent */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001948 int reverse = 0;
1949 PyObject *keyfunc = NULL;
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001950 int i;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001951 PyObject *key, *value, *kvpair;
1952 static char *kwlist[] = {"cmp", "key", "reverse", 0};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001953
Tim Petersa64dc242002-08-01 02:13:36 +00001954 assert(self != NULL);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001955 assert (PyList_Check(self));
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001956 if (args != NULL) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001957 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:sort",
1958 kwlist, &compare, &keyfunc, &reverse))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001959 return NULL;
1960 }
Skip Montanaro4abd5f02003-01-02 20:51:08 +00001961 if (compare == Py_None)
1962 compare = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001963 if (keyfunc == Py_None)
1964 keyfunc = NULL;
1965 if (compare != NULL && keyfunc != NULL) {
1966 compare = build_cmpwrapper(compare);
1967 if (compare == NULL)
Hye-Shik Chang19cb1932003-12-10 07:31:08 +00001968 return NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001969 } else
1970 Py_XINCREF(compare);
1971
Tim Petersb9099c32002-11-12 22:08:10 +00001972 /* The list is temporarily made empty, so that mutations performed
1973 * by comparison functions can't affect the slice of memory we're
1974 * sorting (allowing mutations during sorting is a core-dump
1975 * factory, since ob_item may change).
1976 */
1977 saved_ob_size = self->ob_size;
1978 saved_ob_item = self->ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001979 saved_allocated = self->allocated;
Armin Rigo93677f02004-07-29 12:40:23 +00001980 self->ob_size = 0;
Tim Peters51b4ade2004-07-29 04:07:15 +00001981 self->ob_item = NULL;
Armin Rigo93677f02004-07-29 12:40:23 +00001982 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00001983
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001984 if (keyfunc != NULL) {
1985 for (i=0 ; i < saved_ob_size ; i++) {
1986 value = saved_ob_item[i];
Tim Petersb38e2b62004-07-29 02:29:26 +00001987 key = PyObject_CallFunctionObjArgs(keyfunc, value,
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001988 NULL);
1989 if (key == NULL) {
1990 for (i=i-1 ; i>=0 ; i--) {
1991 kvpair = saved_ob_item[i];
1992 value = sortwrapper_getvalue(kvpair);
1993 saved_ob_item[i] = value;
1994 Py_DECREF(kvpair);
1995 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001996 goto dsu_fail;
1997 }
1998 kvpair = build_sortwrapper(key, value);
1999 if (kvpair == NULL)
2000 goto dsu_fail;
2001 saved_ob_item[i] = kvpair;
2002 }
2003 }
2004
2005 /* Reverse sort stability achieved by initially reversing the list,
2006 applying a stable forward sort, then reversing the final result. */
2007 if (reverse && saved_ob_size > 1)
2008 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2009
2010 merge_init(&ms, compare);
2011
Tim Petersb9099c32002-11-12 22:08:10 +00002012 nremaining = saved_ob_size;
Tim Petersa64dc242002-08-01 02:13:36 +00002013 if (nremaining < 2)
2014 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00002015
Tim Petersa64dc242002-08-01 02:13:36 +00002016 /* March over the array once, left to right, finding natural runs,
2017 * and extending short natural runs to minrun elements.
2018 */
Tim Petersb9099c32002-11-12 22:08:10 +00002019 lo = saved_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00002020 hi = lo + nremaining;
2021 minrun = merge_compute_minrun(nremaining);
2022 do {
2023 int descending;
2024 int n;
Tim Peters330f9e92002-07-19 07:05:44 +00002025
Tim Petersa64dc242002-08-01 02:13:36 +00002026 /* Identify next run. */
2027 n = count_run(lo, hi, compare, &descending);
2028 if (n < 0)
2029 goto fail;
2030 if (descending)
2031 reverse_slice(lo, lo + n);
2032 /* If short, extend to min(minrun, nremaining). */
2033 if (n < minrun) {
2034 const int force = nremaining <= minrun ?
2035 nremaining : minrun;
2036 if (binarysort(lo, lo + force, lo + n, compare) < 0)
2037 goto fail;
2038 n = force;
2039 }
2040 /* Push run onto pending-runs stack, and maybe merge. */
2041 assert(ms.n < MAX_MERGE_PENDING);
Tim Peterse05f65a2002-08-10 05:21:15 +00002042 ms.pending[ms.n].base = lo;
2043 ms.pending[ms.n].len = n;
Tim Petersa64dc242002-08-01 02:13:36 +00002044 ++ms.n;
2045 if (merge_collapse(&ms) < 0)
2046 goto fail;
2047 /* Advance to find next run. */
2048 lo += n;
2049 nremaining -= n;
2050 } while (nremaining);
2051 assert(lo == hi);
Tim Peters330f9e92002-07-19 07:05:44 +00002052
Tim Petersa64dc242002-08-01 02:13:36 +00002053 if (merge_force_collapse(&ms) < 0)
2054 goto fail;
2055 assert(ms.n == 1);
Tim Petersb9099c32002-11-12 22:08:10 +00002056 assert(ms.pending[0].base == saved_ob_item);
2057 assert(ms.pending[0].len == saved_ob_size);
Tim Petersa64dc242002-08-01 02:13:36 +00002058
2059succeed:
2060 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002061fail:
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002062 if (keyfunc != NULL) {
2063 for (i=0 ; i < saved_ob_size ; i++) {
2064 kvpair = saved_ob_item[i];
2065 value = sortwrapper_getvalue(kvpair);
2066 saved_ob_item[i] = value;
2067 Py_DECREF(kvpair);
2068 }
2069 }
2070
Armin Rigo93677f02004-07-29 12:40:23 +00002071 if (self->allocated != -1 && result != NULL) {
Tim Peters51b4ade2004-07-29 04:07:15 +00002072 /* The user mucked with the list during the sort,
2073 * and we don't already have another error to report.
2074 */
2075 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2076 result = NULL;
Tim Petersb9099c32002-11-12 22:08:10 +00002077 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002078
2079 if (reverse && saved_ob_size > 1)
2080 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2081
2082 merge_freemem(&ms);
2083
2084dsu_fail:
Armin Rigo93677f02004-07-29 12:40:23 +00002085 final_ob_item = self->ob_item;
2086 i = self->ob_size;
Tim Petersb9099c32002-11-12 22:08:10 +00002087 self->ob_size = saved_ob_size;
2088 self->ob_item = saved_ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002089 self->allocated = saved_allocated;
Armin Rigo93677f02004-07-29 12:40:23 +00002090 if (final_ob_item != NULL) {
2091 /* we cannot use list_clear() for this because it does not
2092 guarantee that the list is really empty when it returns */
2093 while (--i >= 0) {
2094 Py_XDECREF(final_ob_item[i]);
2095 }
2096 PyMem_FREE(final_ob_item);
2097 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002098 Py_XDECREF(compare);
Tim Petersa64dc242002-08-01 02:13:36 +00002099 Py_XINCREF(result);
2100 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002101}
Tim Peters330f9e92002-07-19 07:05:44 +00002102#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002103#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002104
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002105int
Fred Drakea2f55112000-07-09 15:16:51 +00002106PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002107{
2108 if (v == NULL || !PyList_Check(v)) {
2109 PyErr_BadInternalCall();
2110 return -1;
2111 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002112 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002113 if (v == NULL)
2114 return -1;
2115 Py_DECREF(v);
2116 return 0;
2117}
2118
Guido van Rossumb86c5492001-02-12 22:06:02 +00002119static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002120listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002121{
Tim Peters326b4482002-07-19 04:04:16 +00002122 if (self->ob_size > 1)
2123 reverse_slice(self->ob_item, self->ob_item + self->ob_size);
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002124 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002125}
2126
Guido van Rossum84c76f51990-10-30 13:32:20 +00002127int
Fred Drakea2f55112000-07-09 15:16:51 +00002128PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002129{
Tim Peters6063e262002-08-08 01:06:39 +00002130 PyListObject *self = (PyListObject *)v;
2131
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002132 if (v == NULL || !PyList_Check(v)) {
2133 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002134 return -1;
2135 }
Tim Peters6063e262002-08-08 01:06:39 +00002136 if (self->ob_size > 1)
2137 reverse_slice(self->ob_item, self->ob_item + self->ob_size);
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002138 return 0;
2139}
2140
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002141PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002142PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002143{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002144 PyObject *w;
2145 PyObject **p;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002146 int n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002147 if (v == NULL || !PyList_Check(v)) {
2148 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002149 return NULL;
2150 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002151 n = ((PyListObject *)v)->ob_size;
2152 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002153 if (w == NULL)
2154 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002155 p = ((PyTupleObject *)w)->ob_item;
Thomas Wouters334fb892000-07-25 12:56:38 +00002156 memcpy((void *)p,
2157 (void *)((PyListObject *)v)->ob_item,
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002158 n*sizeof(PyObject *));
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002159 while (--n >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002160 Py_INCREF(*p);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002161 p++;
2162 }
2163 return w;
2164}
2165
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002166static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002167listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002168{
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002169 int i, start=0, stop=self->ob_size;
2170 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002171
Walter Dörwalde8049bef2003-06-17 19:27:39 +00002172 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2173 _PyEval_SliceIndex, &start,
2174 _PyEval_SliceIndex, &stop))
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002175 return NULL;
Guido van Rossum2743d872003-06-17 14:25:14 +00002176 if (start < 0) {
2177 start += self->ob_size;
2178 if (start < 0)
2179 start = 0;
2180 }
2181 if (stop < 0) {
2182 stop += self->ob_size;
2183 if (stop < 0)
2184 stop = 0;
2185 }
2186 else if (stop > self->ob_size)
2187 stop = self->ob_size;
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002188 for (i = start; i < stop; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002189 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2190 if (cmp > 0)
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002191 return PyInt_FromLong((long)i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002192 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002193 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002194 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002195 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002196 return NULL;
2197}
2198
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002199static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002200listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002201{
2202 int count = 0;
2203 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002204
Guido van Rossume6f7d181991-10-20 20:20:40 +00002205 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002206 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2207 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002208 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002209 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002210 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00002211 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002212 return PyInt_FromLong((long)count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002213}
2214
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002215static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002216listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002217{
2218 int i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002219
Guido van Rossumed98d481991-03-06 13:07:53 +00002220 for (i = 0; i < self->ob_size; i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002221 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2222 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002223 if (list_ass_slice(self, i, i+1,
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002224 (PyObject *)NULL) == 0)
2225 Py_RETURN_NONE;
2226 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002227 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002228 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002229 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002230 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002231 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002232 return NULL;
2233}
2234
Jeremy Hylton8caad492000-06-23 14:18:11 +00002235static int
2236list_traverse(PyListObject *o, visitproc visit, void *arg)
2237{
2238 int i, err;
2239 PyObject *x;
2240
2241 for (i = o->ob_size; --i >= 0; ) {
2242 x = o->ob_item[i];
2243 if (x != NULL) {
2244 err = visit(x, arg);
2245 if (err)
2246 return err;
2247 }
2248 }
2249 return 0;
2250}
2251
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002252static PyObject *
2253list_richcompare(PyObject *v, PyObject *w, int op)
2254{
2255 PyListObject *vl, *wl;
2256 int i;
2257
2258 if (!PyList_Check(v) || !PyList_Check(w)) {
2259 Py_INCREF(Py_NotImplemented);
2260 return Py_NotImplemented;
2261 }
2262
2263 vl = (PyListObject *)v;
2264 wl = (PyListObject *)w;
2265
2266 if (vl->ob_size != wl->ob_size && (op == Py_EQ || op == Py_NE)) {
2267 /* Shortcut: if the lengths differ, the lists differ */
2268 PyObject *res;
2269 if (op == Py_EQ)
2270 res = Py_False;
2271 else
2272 res = Py_True;
2273 Py_INCREF(res);
2274 return res;
2275 }
2276
2277 /* Search for the first index where items are different */
2278 for (i = 0; i < vl->ob_size && i < wl->ob_size; i++) {
2279 int k = PyObject_RichCompareBool(vl->ob_item[i],
2280 wl->ob_item[i], Py_EQ);
2281 if (k < 0)
2282 return NULL;
2283 if (!k)
2284 break;
2285 }
2286
2287 if (i >= vl->ob_size || i >= wl->ob_size) {
2288 /* No more items to compare -- compare sizes */
2289 int vs = vl->ob_size;
2290 int ws = wl->ob_size;
2291 int cmp;
2292 PyObject *res;
2293 switch (op) {
2294 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00002295 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002296 case Py_EQ: cmp = vs == ws; break;
2297 case Py_NE: cmp = vs != ws; break;
2298 case Py_GT: cmp = vs > ws; break;
2299 case Py_GE: cmp = vs >= ws; break;
2300 default: return NULL; /* cannot happen */
2301 }
2302 if (cmp)
2303 res = Py_True;
2304 else
2305 res = Py_False;
2306 Py_INCREF(res);
2307 return res;
2308 }
2309
2310 /* We have an item that differs -- shortcuts for EQ/NE */
2311 if (op == Py_EQ) {
2312 Py_INCREF(Py_False);
2313 return Py_False;
2314 }
2315 if (op == Py_NE) {
2316 Py_INCREF(Py_True);
2317 return Py_True;
2318 }
2319
2320 /* Compare the final item again using the proper operator */
2321 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
2322}
2323
Tim Peters6d6c1a32001-08-02 04:15:00 +00002324static int
2325list_init(PyListObject *self, PyObject *args, PyObject *kw)
2326{
2327 PyObject *arg = NULL;
2328 static char *kwlist[] = {"sequence", 0};
2329
2330 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2331 return -1;
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002332
2333 /* Verify list invariants established by PyType_GenericAlloc() */
Armin Rigoa37bbf22004-07-30 11:20:18 +00002334 assert(0 <= self->ob_size);
2335 assert(self->ob_size <= self->allocated || self->allocated == -1);
2336 assert(self->ob_item != NULL ||
2337 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002338
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002339 /* Empty previous contents */
Armin Rigo93677f02004-07-29 12:40:23 +00002340 if (self->ob_item != NULL) {
2341 (void)list_clear(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002342 }
2343 if (arg != NULL) {
2344 PyObject *rv = listextend(self, arg);
2345 if (rv == NULL)
2346 return -1;
2347 Py_DECREF(rv);
2348 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002349 return 0;
2350}
2351
Guido van Rossumdbb53d92001-12-03 16:32:18 +00002352static long
2353list_nohash(PyObject *self)
2354{
2355 PyErr_SetString(PyExc_TypeError, "list objects are unhashable");
2356 return -1;
2357}
2358
Raymond Hettinger1021c442003-11-07 15:38:09 +00002359static PyObject *list_iter(PyObject *seq);
2360static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2361
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002362PyDoc_STRVAR(getitem_doc,
2363"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002364PyDoc_STRVAR(reversed_doc,
2365"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002366PyDoc_STRVAR(append_doc,
2367"L.append(object) -- append object to end");
2368PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002369"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002370PyDoc_STRVAR(insert_doc,
2371"L.insert(index, object) -- insert object before index");
2372PyDoc_STRVAR(pop_doc,
2373"L.pop([index]) -> item -- remove and return item at index (default last)");
2374PyDoc_STRVAR(remove_doc,
2375"L.remove(value) -- remove first occurrence of value");
2376PyDoc_STRVAR(index_doc,
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002377"L.index(value, [start, [stop]]) -> integer -- return first index of value");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002378PyDoc_STRVAR(count_doc,
2379"L.count(value) -> integer -- return number of occurrences of value");
2380PyDoc_STRVAR(reverse_doc,
2381"L.reverse() -- reverse *IN PLACE*");
2382PyDoc_STRVAR(sort_doc,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002383"L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n\
2384cmp(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002385
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002386static PyObject *list_subscript(PyListObject*, PyObject*);
2387
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002388static PyMethodDef list_methods[] = {
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002389 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
Raymond Hettinger1021c442003-11-07 15:38:09 +00002390 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002391 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002392 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002393 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002394 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002395 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002396 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002397 {"count", (PyCFunction)listcount, METH_O, count_doc},
2398 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002399 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
Tim Petersa64dc242002-08-01 02:13:36 +00002400 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002401};
2402
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002403static PySequenceMethods list_as_sequence = {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002404 (inquiry)list_length, /* sq_length */
2405 (binaryfunc)list_concat, /* sq_concat */
2406 (intargfunc)list_repeat, /* sq_repeat */
2407 (intargfunc)list_item, /* sq_item */
2408 (intintargfunc)list_slice, /* sq_slice */
2409 (intobjargproc)list_ass_item, /* sq_ass_item */
2410 (intintobjargproc)list_ass_slice, /* sq_ass_slice */
2411 (objobjproc)list_contains, /* sq_contains */
2412 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2413 (intargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002414};
2415
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002416PyDoc_STRVAR(list_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002417"list() -> new list\n"
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002418"list(sequence) -> new list initialized from sequence's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002419
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002420static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002421list_subscript(PyListObject* self, PyObject* item)
2422{
2423 if (PyInt_Check(item)) {
2424 long i = PyInt_AS_LONG(item);
2425 if (i < 0)
2426 i += PyList_GET_SIZE(self);
2427 return list_item(self, i);
2428 }
2429 else if (PyLong_Check(item)) {
2430 long i = PyLong_AsLong(item);
2431 if (i == -1 && PyErr_Occurred())
2432 return NULL;
2433 if (i < 0)
2434 i += PyList_GET_SIZE(self);
2435 return list_item(self, i);
2436 }
2437 else if (PySlice_Check(item)) {
2438 int start, stop, step, slicelength, cur, i;
2439 PyObject* result;
2440 PyObject* it;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002441 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002442
2443 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
2444 &start, &stop, &step, &slicelength) < 0) {
2445 return NULL;
2446 }
2447
2448 if (slicelength <= 0) {
2449 return PyList_New(0);
2450 }
2451 else {
2452 result = PyList_New(slicelength);
2453 if (!result) return NULL;
2454
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002455 src = self->ob_item;
2456 dest = ((PyListObject *)result)->ob_item;
Tim Peters3b01a122002-07-19 02:35:45 +00002457 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002458 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002459 it = src[cur];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002460 Py_INCREF(it);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002461 dest[i] = it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002462 }
Tim Peters3b01a122002-07-19 02:35:45 +00002463
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002464 return result;
2465 }
2466 }
2467 else {
2468 PyErr_SetString(PyExc_TypeError,
2469 "list indices must be integers");
2470 return NULL;
2471 }
2472}
2473
Tim Peters3b01a122002-07-19 02:35:45 +00002474static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002475list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2476{
2477 if (PyInt_Check(item)) {
2478 long i = PyInt_AS_LONG(item);
2479 if (i < 0)
2480 i += PyList_GET_SIZE(self);
2481 return list_ass_item(self, i, value);
2482 }
2483 else if (PyLong_Check(item)) {
2484 long i = PyLong_AsLong(item);
2485 if (i == -1 && PyErr_Occurred())
2486 return -1;
2487 if (i < 0)
2488 i += PyList_GET_SIZE(self);
2489 return list_ass_item(self, i, value);
2490 }
2491 else if (PySlice_Check(item)) {
2492 int start, stop, step, slicelength;
2493
2494 if (PySlice_GetIndicesEx((PySliceObject*)item, self->ob_size,
2495 &start, &stop, &step, &slicelength) < 0) {
2496 return -1;
2497 }
2498
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002499 /* treat L[slice(a,b)] = v _exactly_ like L[a:b] = v */
2500 if (step == 1 && ((PySliceObject*)item)->step == Py_None)
2501 return list_ass_slice(self, start, stop, value);
2502
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002503 if (value == NULL) {
2504 /* delete slice */
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002505 PyObject **garbage;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002506 int cur, i;
Tim Peters3b01a122002-07-19 02:35:45 +00002507
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002508 if (slicelength <= 0)
2509 return 0;
2510
2511 if (step < 0) {
2512 stop = start + 1;
2513 start = stop + step*(slicelength - 1) - 1;
2514 step = -step;
2515 }
2516
2517 garbage = (PyObject**)
2518 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Tim Peters3b01a122002-07-19 02:35:45 +00002519
2520 /* drawing pictures might help
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002521 understand these for loops */
Guido van Rossum75a20b12002-06-11 12:22:28 +00002522 for (cur = start, i = 0;
2523 cur < stop;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002524 cur += step, i++) {
2525 int lim = step;
2526
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002527 garbage[i] = PyList_GET_ITEM(self, cur);
2528
Michael W. Hudson56796f62002-07-29 14:35:04 +00002529 if (cur + step >= self->ob_size) {
2530 lim = self->ob_size - cur - 1;
2531 }
2532
Tim Petersb38e2b62004-07-29 02:29:26 +00002533 memmove(self->ob_item + cur - i,
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002534 self->ob_item + cur + 1,
2535 lim * sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002536 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002537
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002538 for (cur = start + slicelength*step + 1;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002539 cur < self->ob_size; cur++) {
2540 PyList_SET_ITEM(self, cur - slicelength,
2541 PyList_GET_ITEM(self, cur));
2542 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002543
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002544 self->ob_size -= slicelength;
Raymond Hettingerd4ff7412004-03-15 09:01:31 +00002545 list_resize(self, self->ob_size);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002546
2547 for (i = 0; i < slicelength; i++) {
2548 Py_DECREF(garbage[i]);
2549 }
2550 PyMem_FREE(garbage);
2551
2552 return 0;
2553 }
2554 else {
2555 /* assign slice */
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002556 PyObject **garbage, *ins, *seq, **seqitems, **selfitems;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002557 int cur, i;
2558
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002559 /* protect against a[::-1] = a */
Tim Peters3b01a122002-07-19 02:35:45 +00002560 if (self == (PyListObject*)value) {
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002561 seq = list_slice((PyListObject*)value, 0,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002562 PyList_GET_SIZE(value));
Tim Peters3b01a122002-07-19 02:35:45 +00002563 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002564 else {
Tim Petersb38e2b62004-07-29 02:29:26 +00002565 seq = PySequence_Fast(value,
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002566 "must assign iterable to extended slice");
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002567 if (!seq)
2568 return -1;
2569 }
2570
2571 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2572 PyErr_Format(PyExc_ValueError,
2573 "attempt to assign sequence of size %d to extended slice of size %d",
2574 PySequence_Fast_GET_SIZE(seq),
2575 slicelength);
2576 Py_DECREF(seq);
2577 return -1;
2578 }
2579
2580 if (!slicelength) {
2581 Py_DECREF(seq);
2582 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002583 }
2584
2585 garbage = (PyObject**)
2586 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Tim Peters3b01a122002-07-19 02:35:45 +00002587
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002588 selfitems = self->ob_item;
Raymond Hettinger42bec932004-03-12 16:38:17 +00002589 seqitems = PySequence_Fast_ITEMS(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002590 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002591 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002592 garbage[i] = selfitems[cur];
2593 ins = seqitems[i];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002594 Py_INCREF(ins);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002595 selfitems[cur] = ins;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002596 }
2597
2598 for (i = 0; i < slicelength; i++) {
2599 Py_DECREF(garbage[i]);
2600 }
Tim Peters3b01a122002-07-19 02:35:45 +00002601
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002602 PyMem_FREE(garbage);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002603 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002604
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002605 return 0;
2606 }
Tim Peters3b01a122002-07-19 02:35:45 +00002607 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002608 else {
Tim Peters3b01a122002-07-19 02:35:45 +00002609 PyErr_SetString(PyExc_TypeError,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002610 "list indices must be integers");
2611 return -1;
2612 }
2613}
2614
2615static PyMappingMethods list_as_mapping = {
2616 (inquiry)list_length,
2617 (binaryfunc)list_subscript,
2618 (objobjargproc)list_ass_subscript
2619};
2620
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002621PyTypeObject PyList_Type = {
2622 PyObject_HEAD_INIT(&PyType_Type)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002623 0,
2624 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002625 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002626 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002627 (destructor)list_dealloc, /* tp_dealloc */
2628 (printfunc)list_print, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002629 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002630 0, /* tp_setattr */
2631 0, /* tp_compare */
2632 (reprfunc)list_repr, /* tp_repr */
2633 0, /* tp_as_number */
2634 &list_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002635 &list_as_mapping, /* tp_as_mapping */
Guido van Rossumdbb53d92001-12-03 16:32:18 +00002636 list_nohash, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002637 0, /* tp_call */
2638 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002639 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002640 0, /* tp_setattro */
2641 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002642 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Tim Peters6d6c1a32001-08-02 04:15:00 +00002643 Py_TPFLAGS_BASETYPE, /* tp_flags */
2644 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002645 (traverseproc)list_traverse, /* tp_traverse */
2646 (inquiry)list_clear, /* tp_clear */
2647 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002648 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002649 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002650 0, /* tp_iternext */
2651 list_methods, /* tp_methods */
2652 0, /* tp_members */
2653 0, /* tp_getset */
2654 0, /* tp_base */
2655 0, /* tp_dict */
2656 0, /* tp_descr_get */
2657 0, /* tp_descr_set */
2658 0, /* tp_dictoffset */
2659 (initproc)list_init, /* tp_init */
2660 PyType_GenericAlloc, /* tp_alloc */
2661 PyType_GenericNew, /* tp_new */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002662 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002663};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002664
2665
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002666/*********************** List Iterator **************************/
2667
2668typedef struct {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002669 PyObject_HEAD
2670 long it_index;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002671 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002672} listiterobject;
2673
2674PyTypeObject PyListIter_Type;
2675
Guido van Rossum5086e492002-07-16 15:56:52 +00002676static PyObject *
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002677list_iter(PyObject *seq)
2678{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002679 listiterobject *it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002680
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002681 if (!PyList_Check(seq)) {
2682 PyErr_BadInternalCall();
2683 return NULL;
2684 }
2685 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2686 if (it == NULL)
2687 return NULL;
2688 it->it_index = 0;
2689 Py_INCREF(seq);
2690 it->it_seq = (PyListObject *)seq;
2691 _PyObject_GC_TRACK(it);
2692 return (PyObject *)it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002693}
2694
2695static void
2696listiter_dealloc(listiterobject *it)
2697{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002698 _PyObject_GC_UNTRACK(it);
Guido van Rossum86103ae2002-07-16 20:07:32 +00002699 Py_XDECREF(it->it_seq);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002700 PyObject_GC_Del(it);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002701}
2702
2703static int
2704listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2705{
Guido van Rossum86103ae2002-07-16 20:07:32 +00002706 if (it->it_seq == NULL)
2707 return 0;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002708 return visit((PyObject *)it->it_seq, arg);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002709}
2710
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002711static PyObject *
Tim Peters93b2cc42002-06-01 05:22:55 +00002712listiter_next(listiterobject *it)
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002713{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002714 PyListObject *seq;
2715 PyObject *item;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002716
Tim Peters93b2cc42002-06-01 05:22:55 +00002717 assert(it != NULL);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002718 seq = it->it_seq;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002719 if (seq == NULL)
2720 return NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002721 assert(PyList_Check(seq));
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002722
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002723 if (it->it_index < PyList_GET_SIZE(seq)) {
Tim Peters93b2cc42002-06-01 05:22:55 +00002724 item = PyList_GET_ITEM(seq, it->it_index);
2725 ++it->it_index;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002726 Py_INCREF(item);
2727 return item;
2728 }
Guido van Rossum86103ae2002-07-16 20:07:32 +00002729
2730 Py_DECREF(seq);
2731 it->it_seq = NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002732 return NULL;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002733}
2734
Raymond Hettinger435bf582004-03-18 22:43:10 +00002735static int
2736listiter_len(listiterobject *it)
2737{
Raymond Hettinger40a03822004-04-12 13:05:09 +00002738 int len;
2739 if (it->it_seq) {
2740 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2741 if (len >= 0)
2742 return len;
2743 }
Raymond Hettinger435bf582004-03-18 22:43:10 +00002744 return 0;
2745}
2746
2747static PySequenceMethods listiter_as_sequence = {
2748 (inquiry)listiter_len, /* sq_length */
2749 0, /* sq_concat */
2750};
2751
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002752PyTypeObject PyListIter_Type = {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002753 PyObject_HEAD_INIT(&PyType_Type)
2754 0, /* ob_size */
2755 "listiterator", /* tp_name */
2756 sizeof(listiterobject), /* tp_basicsize */
2757 0, /* tp_itemsize */
2758 /* methods */
2759 (destructor)listiter_dealloc, /* tp_dealloc */
2760 0, /* tp_print */
2761 0, /* tp_getattr */
2762 0, /* tp_setattr */
2763 0, /* tp_compare */
2764 0, /* tp_repr */
2765 0, /* tp_as_number */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002766 &listiter_as_sequence, /* tp_as_sequence */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002767 0, /* tp_as_mapping */
2768 0, /* tp_hash */
2769 0, /* tp_call */
2770 0, /* tp_str */
2771 PyObject_GenericGetAttr, /* tp_getattro */
2772 0, /* tp_setattro */
2773 0, /* tp_as_buffer */
2774 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2775 0, /* tp_doc */
2776 (traverseproc)listiter_traverse, /* tp_traverse */
2777 0, /* tp_clear */
2778 0, /* tp_richcompare */
2779 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00002780 PyObject_SelfIter, /* tp_iter */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002781 (iternextfunc)listiter_next, /* tp_iternext */
Guido van Rossum86103ae2002-07-16 20:07:32 +00002782 0, /* tp_methods */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002783 0, /* tp_members */
2784 0, /* tp_getset */
2785 0, /* tp_base */
2786 0, /* tp_dict */
2787 0, /* tp_descr_get */
2788 0, /* tp_descr_set */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002789};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002790
2791/*********************** List Reverse Iterator **************************/
2792
2793typedef struct {
2794 PyObject_HEAD
2795 long it_index;
Raymond Hettinger001f2282003-11-08 11:58:44 +00002796 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002797} listreviterobject;
2798
2799PyTypeObject PyListRevIter_Type;
2800
2801static PyObject *
2802list_reversed(PyListObject *seq, PyObject *unused)
2803{
2804 listreviterobject *it;
2805
2806 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2807 if (it == NULL)
2808 return NULL;
2809 assert(PyList_Check(seq));
2810 it->it_index = PyList_GET_SIZE(seq) - 1;
2811 Py_INCREF(seq);
2812 it->it_seq = seq;
2813 PyObject_GC_Track(it);
2814 return (PyObject *)it;
2815}
2816
2817static void
2818listreviter_dealloc(listreviterobject *it)
2819{
2820 PyObject_GC_UnTrack(it);
2821 Py_XDECREF(it->it_seq);
2822 PyObject_GC_Del(it);
2823}
2824
2825static int
2826listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2827{
2828 if (it->it_seq == NULL)
2829 return 0;
2830 return visit((PyObject *)it->it_seq, arg);
2831}
2832
2833static PyObject *
2834listreviter_next(listreviterobject *it)
2835{
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002836 PyObject *item;
2837 long index = it->it_index;
2838 PyListObject *seq = it->it_seq;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002839
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002840 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2841 item = PyList_GET_ITEM(seq, index);
Raymond Hettinger1021c442003-11-07 15:38:09 +00002842 it->it_index--;
2843 Py_INCREF(item);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002844 return item;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002845 }
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002846 it->it_index = -1;
2847 if (seq != NULL) {
2848 it->it_seq = NULL;
2849 Py_DECREF(seq);
2850 }
2851 return NULL;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002852}
2853
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002854static int
2855listreviter_len(listreviterobject *it)
2856{
Raymond Hettinger40a03822004-04-12 13:05:09 +00002857 int len = it->it_index + 1;
2858 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
2859 return 0;
2860 return len;
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002861}
2862
2863static PySequenceMethods listreviter_as_sequence = {
2864 (inquiry)listreviter_len, /* sq_length */
2865 0, /* sq_concat */
2866};
2867
Raymond Hettinger1021c442003-11-07 15:38:09 +00002868PyTypeObject PyListRevIter_Type = {
2869 PyObject_HEAD_INIT(&PyType_Type)
2870 0, /* ob_size */
2871 "listreverseiterator", /* tp_name */
2872 sizeof(listreviterobject), /* tp_basicsize */
2873 0, /* tp_itemsize */
2874 /* methods */
2875 (destructor)listreviter_dealloc, /* tp_dealloc */
2876 0, /* tp_print */
2877 0, /* tp_getattr */
2878 0, /* tp_setattr */
2879 0, /* tp_compare */
2880 0, /* tp_repr */
2881 0, /* tp_as_number */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002882 &listreviter_as_sequence, /* tp_as_sequence */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002883 0, /* tp_as_mapping */
2884 0, /* tp_hash */
2885 0, /* tp_call */
2886 0, /* tp_str */
2887 PyObject_GenericGetAttr, /* tp_getattro */
2888 0, /* tp_setattro */
2889 0, /* tp_as_buffer */
2890 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2891 0, /* tp_doc */
2892 (traverseproc)listreviter_traverse, /* tp_traverse */
2893 0, /* tp_clear */
2894 0, /* tp_richcompare */
2895 0, /* tp_weaklistoffset */
2896 PyObject_SelfIter, /* tp_iter */
2897 (iternextfunc)listreviter_next, /* tp_iternext */
2898 0,
2899};