blob: 2bab4ef26b3082ed4732d0ea3fad7acc16029150 [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
Martin v. Löwis18e16552006-02-15 17:27:45 +000025list_resize(PyListObject *self, Py_ssize_t newsize)
Guido van Rossuma46d51d1995-01-26 22:59:43 +000026{
Raymond Hettinger4bb95402004-02-13 11:36:39 +000027 PyObject **items;
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000028 size_t new_allocated;
Martin v. Löwis18e16552006-02-15 17:27:45 +000029 Py_ssize_t allocated = self->allocated;
Tim Peters65b8b842001-05-26 05:28:40 +000030
Raymond Hettinger4bb95402004-02-13 11:36:39 +000031 /* Bypass realloc() when a previous overallocation is large enough
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000032 to accommodate the newsize. If the newsize falls lower than half
33 the allocated size, then proceed with the realloc() to shrink the list.
Raymond Hettinger4bb95402004-02-13 11:36:39 +000034 */
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000035 if (allocated >= newsize && newsize >= (allocated >> 1)) {
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +000036 assert(self->ob_item != NULL || newsize == 0);
Christian Heimes90aa7642007-12-19 02:45:37 +000037 Py_SIZE(self) = newsize;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000038 return 0;
39 }
40
41 /* This over-allocates proportional to the list size, making room
Tim Peters65b8b842001-05-26 05:28:40 +000042 * for additional growth. The over-allocation is mild, but is
43 * enough to give linear-time amortized behavior over a long
44 * sequence of appends() in the presence of a poorly-performing
Raymond Hettingerab517d22004-02-14 18:34:46 +000045 * system realloc().
46 * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
Tim Peters65b8b842001-05-26 05:28:40 +000047 */
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +000048 new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6);
49
50 /* check for integer overflow */
51 if (new_allocated > PY_SIZE_MAX - newsize) {
52 PyErr_NoMemory();
53 return -1;
54 } else {
55 new_allocated += newsize;
56 }
57
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000058 if (newsize == 0)
59 new_allocated = 0;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000060 items = self->ob_item;
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000061 if (new_allocated <= ((~(size_t)0) / sizeof(PyObject *)))
62 PyMem_RESIZE(items, PyObject *, new_allocated);
Raymond Hettinger4bb95402004-02-13 11:36:39 +000063 else
64 items = NULL;
65 if (items == NULL) {
66 PyErr_NoMemory();
67 return -1;
68 }
69 self->ob_item = items;
Christian Heimes90aa7642007-12-19 02:45:37 +000070 Py_SIZE(self) = newsize;
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000071 self->allocated = new_allocated;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000072 return 0;
73}
Guido van Rossuma46d51d1995-01-26 22:59:43 +000074
Christian Heimes77c02eb2008-02-09 02:18:51 +000075/* Debug statistic to compare allocations with reuse through the free list */
76#undef SHOW_ALLOC_COUNT
77#ifdef SHOW_ALLOC_COUNT
78static size_t count_alloc = 0;
79static size_t count_reuse = 0;
80
81static void
82show_alloc(void)
83{
Christian Heimes23daade02008-02-25 12:39:23 +000084 fprintf(stderr, "List allocations: %" PY_FORMAT_SIZE_T "d\n",
85 count_alloc);
86 fprintf(stderr, "List reuse through freelist: %" PY_FORMAT_SIZE_T
87 "d\n", count_reuse);
Christian Heimes77c02eb2008-02-09 02:18:51 +000088 fprintf(stderr, "%.2f%% reuse rate\n\n",
89 (100.0*count_reuse/(count_alloc+count_reuse)));
90}
91#endif
92
Raymond Hettinger0468e412004-05-05 05:37:53 +000093/* Empty list reuse scheme to save calls to malloc and free */
Christian Heimes2202f872008-02-06 14:31:34 +000094#ifndef PyList_MAXFREELIST
95#define PyList_MAXFREELIST 80
96#endif
97static PyListObject *free_list[PyList_MAXFREELIST];
98static int numfree = 0;
Raymond Hettinger0468e412004-05-05 05:37:53 +000099
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000100void
101PyList_Fini(void)
102{
103 PyListObject *op;
104
Christian Heimes2202f872008-02-06 14:31:34 +0000105 while (numfree) {
Christian Heimes77c02eb2008-02-09 02:18:51 +0000106 op = free_list[--numfree];
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000107 assert(PyList_CheckExact(op));
108 PyObject_GC_Del(op);
109 }
110}
111
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000112PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000113PyList_New(Py_ssize_t size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000114{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000115 PyListObject *op;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +0000116 size_t nbytes;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000117#ifdef SHOW_ALLOC_COUNT
118 static int initialized = 0;
119 if (!initialized) {
120 Py_AtExit(show_alloc);
121 initialized = 1;
122 }
123#endif
Tim Peters3986d4e2004-07-29 02:28:42 +0000124
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000125 if (size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000126 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000127 return NULL;
128 }
Tim Peters7049d812004-01-18 20:31:02 +0000129 nbytes = size * sizeof(PyObject *);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +0000130 /* Check for overflow without an actual overflow,
131 * which can cause compiler to optimise out */
132 if (size > PY_SIZE_MAX / sizeof(PyObject *))
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000133 return PyErr_NoMemory();
Christian Heimes2202f872008-02-06 14:31:34 +0000134 if (numfree) {
135 numfree--;
136 op = free_list[numfree];
Raymond Hettinger0468e412004-05-05 05:37:53 +0000137 _Py_NewReference((PyObject *)op);
Christian Heimes77c02eb2008-02-09 02:18:51 +0000138#ifdef SHOW_ALLOC_COUNT
139 count_reuse++;
140#endif
Raymond Hettinger0468e412004-05-05 05:37:53 +0000141 } else {
142 op = PyObject_GC_New(PyListObject, &PyList_Type);
143 if (op == NULL)
144 return NULL;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000145#ifdef SHOW_ALLOC_COUNT
146 count_alloc++;
147#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000148 }
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000149 if (size <= 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000150 op->ob_item = NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000151 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +0000152 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000153 if (op->ob_item == NULL) {
154 Py_DECREF(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000155 return PyErr_NoMemory();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000156 }
Tim Peters3986d4e2004-07-29 02:28:42 +0000157 memset(op->ob_item, 0, nbytes);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000158 }
Christian Heimes90aa7642007-12-19 02:45:37 +0000159 Py_SIZE(op) = size;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000160 op->allocated = size;
Neil Schemenauere83c00e2001-08-29 23:54:21 +0000161 _PyObject_GC_TRACK(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000162 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000163}
164
Martin v. Löwis18e16552006-02-15 17:27:45 +0000165Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000166PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000167{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000168 if (!PyList_Check(op)) {
169 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000170 return -1;
171 }
172 else
Christian Heimes90aa7642007-12-19 02:45:37 +0000173 return Py_SIZE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000174}
175
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000176static PyObject *indexerr = NULL;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000177
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000178PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000179PyList_GetItem(PyObject *op, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000180{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000181 if (!PyList_Check(op)) {
182 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000183 return NULL;
184 }
Christian Heimes90aa7642007-12-19 02:45:37 +0000185 if (i < 0 || i >= Py_SIZE(op)) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000186 if (indexerr == NULL)
Neal Norwitz53cbdaa2007-08-23 21:42:55 +0000187 indexerr = PyUnicode_FromString(
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000188 "list index out of range");
189 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000190 return NULL;
191 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000192 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000193}
194
195int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000196PyList_SetItem(register PyObject *op, register Py_ssize_t i,
Fred Drakea2f55112000-07-09 15:16:51 +0000197 register PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000198{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000199 register PyObject *olditem;
200 register PyObject **p;
201 if (!PyList_Check(op)) {
202 Py_XDECREF(newitem);
203 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000204 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000205 }
Christian Heimes90aa7642007-12-19 02:45:37 +0000206 if (i < 0 || i >= Py_SIZE(op)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000207 Py_XDECREF(newitem);
208 PyErr_SetString(PyExc_IndexError,
209 "list assignment index out of range");
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000210 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000211 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000212 p = ((PyListObject *)op) -> ob_item + i;
Guido van Rossum5fe60581995-03-09 12:12:50 +0000213 olditem = *p;
214 *p = newitem;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000215 Py_XDECREF(olditem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000216 return 0;
217}
218
219static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000220ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000221{
Christian Heimes90aa7642007-12-19 02:45:37 +0000222 Py_ssize_t i, n = Py_SIZE(self);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000223 PyObject **items;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000224 if (v == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000225 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000226 return -1;
227 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000228 if (n == PY_SSIZE_T_MAX) {
Trent Micka5846642000-08-13 22:47:45 +0000229 PyErr_SetString(PyExc_OverflowError,
230 "cannot add more objects to list");
231 return -1;
232 }
Tim Petersb38e2b62004-07-29 02:29:26 +0000233
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000234 if (list_resize(self, n+1) == -1)
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000235 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000236
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000237 if (where < 0) {
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000238 where += n;
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000239 if (where < 0)
240 where = 0;
241 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000242 if (where > n)
243 where = n;
244 items = self->ob_item;
245 for (i = n; --i >= where; )
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000246 items[i+1] = items[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000247 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000248 items[where] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000249 return 0;
250}
251
252int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000253PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000254{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000255 if (!PyList_Check(op)) {
256 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000257 return -1;
258 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000259 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000260}
261
Raymond Hettinger40a03822004-04-12 13:05:09 +0000262static int
263app1(PyListObject *self, PyObject *v)
264{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000265 Py_ssize_t n = PyList_GET_SIZE(self);
Raymond Hettinger40a03822004-04-12 13:05:09 +0000266
267 assert (v != NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000268 if (n == PY_SSIZE_T_MAX) {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000269 PyErr_SetString(PyExc_OverflowError,
270 "cannot add more objects to list");
271 return -1;
272 }
273
274 if (list_resize(self, n+1) == -1)
275 return -1;
276
277 Py_INCREF(v);
278 PyList_SET_ITEM(self, n, v);
279 return 0;
280}
281
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000282int
Fred Drakea2f55112000-07-09 15:16:51 +0000283PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000284{
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000285 if (PyList_Check(op) && (newitem != NULL))
286 return app1((PyListObject *)op, newitem);
287 PyErr_BadInternalCall();
288 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000289}
290
291/* Methods */
292
293static void
Fred Drakea2f55112000-07-09 15:16:51 +0000294list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000295{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000296 Py_ssize_t i;
Guido van Rossumff413af2002-03-28 20:34:59 +0000297 PyObject_GC_UnTrack(op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000298 Py_TRASHCAN_SAFE_BEGIN(op)
Jack Jansen7874d1f1995-01-19 12:09:27 +0000299 if (op->ob_item != NULL) {
Guido van Rossumfa717011999-06-09 15:19:34 +0000300 /* Do it backwards, for Christian Tismer.
301 There's a simple test case where somehow this reduces
302 thrashing when a *very* large list is created and
303 immediately deleted. */
Christian Heimes90aa7642007-12-19 02:45:37 +0000304 i = Py_SIZE(op);
Guido van Rossumfa717011999-06-09 15:19:34 +0000305 while (--i >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000306 Py_XDECREF(op->ob_item[i]);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000307 }
Guido van Rossumb18618d2000-05-03 23:44:39 +0000308 PyMem_FREE(op->ob_item);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000309 }
Christian Heimes2202f872008-02-06 14:31:34 +0000310 if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op))
311 free_list[numfree++] = op;
Tim Petersb38e2b62004-07-29 02:29:26 +0000312 else
Christian Heimes90aa7642007-12-19 02:45:37 +0000313 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000314 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000315}
316
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000317static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000318list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000319{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000320 Py_ssize_t i;
Tim Petersa7259592001-06-16 05:11:17 +0000321 PyObject *s, *temp;
322 PyObject *pieces = NULL, *result = NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000323
324 i = Py_ReprEnter((PyObject*)v);
325 if (i != 0) {
Walter Dörwald1ab83302007-05-18 17:15:44 +0000326 return i > 0 ? PyUnicode_FromString("[...]") : NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000327 }
Tim Petersa7259592001-06-16 05:11:17 +0000328
Christian Heimes90aa7642007-12-19 02:45:37 +0000329 if (Py_SIZE(v) == 0) {
Walter Dörwald1ab83302007-05-18 17:15:44 +0000330 result = PyUnicode_FromString("[]");
Tim Petersa7259592001-06-16 05:11:17 +0000331 goto Done;
332 }
333
334 pieces = PyList_New(0);
335 if (pieces == NULL)
336 goto Done;
337
338 /* Do repr() on each element. Note that this may mutate the list,
339 so must refetch the list size on each iteration. */
Christian Heimes90aa7642007-12-19 02:45:37 +0000340 for (i = 0; i < Py_SIZE(v); ++i) {
Tim Petersa7259592001-06-16 05:11:17 +0000341 int status;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000342 if (Py_EnterRecursiveCall(" while getting the repr of a list"))
343 goto Done;
Tim Petersa7259592001-06-16 05:11:17 +0000344 s = PyObject_Repr(v->ob_item[i]);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000345 Py_LeaveRecursiveCall();
Tim Petersa7259592001-06-16 05:11:17 +0000346 if (s == NULL)
347 goto Done;
348 status = PyList_Append(pieces, s);
349 Py_DECREF(s); /* append created a new ref */
350 if (status < 0)
351 goto Done;
352 }
353
354 /* Add "[]" decorations to the first and last items. */
355 assert(PyList_GET_SIZE(pieces) > 0);
Walter Dörwald1ab83302007-05-18 17:15:44 +0000356 s = PyUnicode_FromString("[");
Tim Petersa7259592001-06-16 05:11:17 +0000357 if (s == NULL)
358 goto Done;
359 temp = PyList_GET_ITEM(pieces, 0);
Walter Dörwald1ab83302007-05-18 17:15:44 +0000360 PyUnicode_AppendAndDel(&s, temp);
Tim Petersa7259592001-06-16 05:11:17 +0000361 PyList_SET_ITEM(pieces, 0, s);
362 if (s == NULL)
363 goto Done;
364
Walter Dörwald1ab83302007-05-18 17:15:44 +0000365 s = PyUnicode_FromString("]");
Tim Petersa7259592001-06-16 05:11:17 +0000366 if (s == NULL)
367 goto Done;
368 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
Walter Dörwald1ab83302007-05-18 17:15:44 +0000369 PyUnicode_AppendAndDel(&temp, s);
Tim Petersa7259592001-06-16 05:11:17 +0000370 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
371 if (temp == NULL)
372 goto Done;
373
374 /* Paste them all together with ", " between. */
Walter Dörwald1ab83302007-05-18 17:15:44 +0000375 s = PyUnicode_FromString(", ");
Tim Petersa7259592001-06-16 05:11:17 +0000376 if (s == NULL)
377 goto Done;
Walter Dörwald1ab83302007-05-18 17:15:44 +0000378 result = PyUnicode_Join(s, pieces);
Tim Peters3b01a122002-07-19 02:35:45 +0000379 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +0000380
381Done:
382 Py_XDECREF(pieces);
Guido van Rossumfb376de1998-04-10 22:47:27 +0000383 Py_ReprLeave((PyObject *)v);
Tim Petersa7259592001-06-16 05:11:17 +0000384 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000385}
386
Martin v. Löwis18e16552006-02-15 17:27:45 +0000387static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000388list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000389{
Christian Heimes90aa7642007-12-19 02:45:37 +0000390 return Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000391}
392
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000393static int
Fred Drakea2f55112000-07-09 15:16:51 +0000394list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000395{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000396 Py_ssize_t i;
397 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000398
Christian Heimes90aa7642007-12-19 02:45:37 +0000399 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
Raymond Hettingeraae59992002-09-05 14:23:49 +0000400 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000401 Py_EQ);
Neal Norwitzbb9c5f52002-09-05 21:32:55 +0000402 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000403}
404
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000405static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000406list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000407{
Christian Heimes90aa7642007-12-19 02:45:37 +0000408 if (i < 0 || i >= Py_SIZE(a)) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000409 if (indexerr == NULL)
Neal Norwitz53cbdaa2007-08-23 21:42:55 +0000410 indexerr = PyUnicode_FromString(
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000411 "list index out of range");
412 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000413 return NULL;
414 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000415 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000416 return a->ob_item[i];
417}
418
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000419static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000420list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000421{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000422 PyListObject *np;
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000423 PyObject **src, **dest;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000424 Py_ssize_t i, len;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000425 if (ilow < 0)
426 ilow = 0;
Christian Heimes90aa7642007-12-19 02:45:37 +0000427 else if (ilow > Py_SIZE(a))
428 ilow = Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000429 if (ihigh < ilow)
430 ihigh = ilow;
Christian Heimes90aa7642007-12-19 02:45:37 +0000431 else if (ihigh > Py_SIZE(a))
432 ihigh = Py_SIZE(a);
Raymond Hettinger99842b62004-03-08 05:56:15 +0000433 len = ihigh - ilow;
434 np = (PyListObject *) PyList_New(len);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000435 if (np == NULL)
436 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000437
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000438 src = a->ob_item + ilow;
439 dest = np->ob_item;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000440 for (i = 0; i < len; i++) {
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000441 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000442 Py_INCREF(v);
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000443 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000444 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000445 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000446}
447
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000448PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000449PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000450{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000451 if (!PyList_Check(a)) {
452 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000453 return NULL;
454 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000455 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000456}
457
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000458static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000459list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000460{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000461 Py_ssize_t size;
462 Py_ssize_t i;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000463 PyObject **src, **dest;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000464 PyListObject *np;
465 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000466 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000467 "can only concatenate list (not \"%.200s\") to list",
468 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000469 return NULL;
470 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000471#define b ((PyListObject *)bb)
Christian Heimes90aa7642007-12-19 02:45:37 +0000472 size = Py_SIZE(a) + Py_SIZE(b);
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000473 if (size < 0)
474 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000475 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000476 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000477 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000478 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000479 src = a->ob_item;
480 dest = np->ob_item;
Christian Heimes90aa7642007-12-19 02:45:37 +0000481 for (i = 0; i < Py_SIZE(a); i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000482 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000483 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000484 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000485 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000486 src = b->ob_item;
Christian Heimes90aa7642007-12-19 02:45:37 +0000487 dest = np->ob_item + Py_SIZE(a);
488 for (i = 0; i < Py_SIZE(b); i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000489 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000490 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000491 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000492 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000493 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000494#undef b
495}
496
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000497static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000498list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000499{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000500 Py_ssize_t i, j;
501 Py_ssize_t size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000502 PyListObject *np;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000503 PyObject **p, **items;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000504 PyObject *elem;
Guido van Rossumed98d481991-03-06 13:07:53 +0000505 if (n < 0)
506 n = 0;
Christian Heimes90aa7642007-12-19 02:45:37 +0000507 size = Py_SIZE(a) * n;
508 if (n && size/n != Py_SIZE(a))
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000509 return PyErr_NoMemory();
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000510 if (size == 0)
Christian Heimesaf98da12008-01-27 15:18:18 +0000511 return PyList_New(0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000512 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000513 if (np == NULL)
514 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000515
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000516 items = np->ob_item;
Christian Heimes90aa7642007-12-19 02:45:37 +0000517 if (Py_SIZE(a) == 1) {
Raymond Hettinger6624e682003-05-21 05:58:46 +0000518 elem = a->ob_item[0];
519 for (i = 0; i < n; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000520 items[i] = elem;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000521 Py_INCREF(elem);
522 }
523 return (PyObject *) np;
524 }
Guido van Rossumed98d481991-03-06 13:07:53 +0000525 p = np->ob_item;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000526 items = a->ob_item;
Guido van Rossumed98d481991-03-06 13:07:53 +0000527 for (i = 0; i < n; i++) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000528 for (j = 0; j < Py_SIZE(a); j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000529 *p = items[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000530 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000531 p++;
532 }
533 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000534 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000535}
536
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000537static int
Armin Rigo93677f02004-07-29 12:40:23 +0000538list_clear(PyListObject *a)
539{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000540 Py_ssize_t i;
Armin Rigo93677f02004-07-29 12:40:23 +0000541 PyObject **item = a->ob_item;
542 if (item != NULL) {
543 /* Because XDECREF can recursively invoke operations on
544 this list, we make it empty first. */
Christian Heimes90aa7642007-12-19 02:45:37 +0000545 i = Py_SIZE(a);
546 Py_SIZE(a) = 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000547 a->ob_item = NULL;
548 a->allocated = 0;
549 while (--i >= 0) {
550 Py_XDECREF(item[i]);
551 }
552 PyMem_FREE(item);
553 }
554 /* Never fails; the return value can be ignored.
555 Note that there is no guarantee that the list is actually empty
556 at this point, because XDECREF may have populated it again! */
557 return 0;
558}
559
Tim Peters8fc4a912004-07-31 21:53:19 +0000560/* a[ilow:ihigh] = v if v != NULL.
561 * del a[ilow:ihigh] if v == NULL.
562 *
563 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
564 * guaranteed the call cannot fail.
565 */
Armin Rigo93677f02004-07-29 12:40:23 +0000566static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000567list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000568{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000569 /* Because [X]DECREF can recursively invoke list operations on
570 this list, we must postpone all [X]DECREF activity until
571 after the list is back in its canonical shape. Therefore
572 we must allocate an additional array, 'recycle', into which
573 we temporarily copy the items that are deleted from the
574 list. :-( */
Tim Peters73572222004-07-31 02:54:42 +0000575 PyObject *recycle_on_stack[8];
576 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000577 PyObject **item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000578 PyObject **vitem = NULL;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000579 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000580 Py_ssize_t n; /* # of elements in replacement list */
581 Py_ssize_t norig; /* # of elements in list getting replaced */
582 Py_ssize_t d; /* Change in size */
583 Py_ssize_t k;
Tim Peters8d9eb102004-07-31 02:24:20 +0000584 size_t s;
585 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000586#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000587 if (v == NULL)
588 n = 0;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000589 else {
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000590 if (a == b) {
591 /* Special case "a[i:j] = a" -- copy b first */
Christian Heimes90aa7642007-12-19 02:45:37 +0000592 v = list_slice(b, 0, Py_SIZE(b));
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000593 if (v == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000594 return result;
595 result = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000596 Py_DECREF(v);
Tim Peters8d9eb102004-07-31 02:24:20 +0000597 return result;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000598 }
Raymond Hettingerf889e102004-03-09 08:04:33 +0000599 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000600 if(v_as_SF == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000601 goto Error;
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000602 n = PySequence_Fast_GET_SIZE(v_as_SF);
Raymond Hettinger42bec932004-03-12 16:38:17 +0000603 vitem = PySequence_Fast_ITEMS(v_as_SF);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000604 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000605 if (ilow < 0)
606 ilow = 0;
Christian Heimes90aa7642007-12-19 02:45:37 +0000607 else if (ilow > Py_SIZE(a))
608 ilow = Py_SIZE(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000609
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000610 if (ihigh < ilow)
611 ihigh = ilow;
Christian Heimes90aa7642007-12-19 02:45:37 +0000612 else if (ihigh > Py_SIZE(a))
613 ihigh = Py_SIZE(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000614
Tim Peters8d9eb102004-07-31 02:24:20 +0000615 norig = ihigh - ilow;
616 assert(norig >= 0);
617 d = n - norig;
Christian Heimes90aa7642007-12-19 02:45:37 +0000618 if (Py_SIZE(a) + d == 0) {
Armin Rigo93677f02004-07-29 12:40:23 +0000619 Py_XDECREF(v_as_SF);
620 return list_clear(a);
621 }
622 item = a->ob_item;
Tim Peters8d9eb102004-07-31 02:24:20 +0000623 /* recycle the items that we are about to remove */
624 s = norig * sizeof(PyObject *);
Tim Peters73572222004-07-31 02:54:42 +0000625 if (s > sizeof(recycle_on_stack)) {
Armin Rigo1dd04a02004-07-30 11:38:22 +0000626 recycle = (PyObject **)PyMem_MALLOC(s);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000627 if (recycle == NULL) {
628 PyErr_NoMemory();
Tim Peters8d9eb102004-07-31 02:24:20 +0000629 goto Error;
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000630 }
631 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000632 memcpy(recycle, &item[ilow], s);
Tim Peters8d9eb102004-07-31 02:24:20 +0000633
Armin Rigo1dd04a02004-07-30 11:38:22 +0000634 if (d < 0) { /* Delete -d items */
635 memmove(&item[ihigh+d], &item[ihigh],
Christian Heimes90aa7642007-12-19 02:45:37 +0000636 (Py_SIZE(a) - ihigh)*sizeof(PyObject *));
637 list_resize(a, Py_SIZE(a) + d);
Armin Rigo1dd04a02004-07-30 11:38:22 +0000638 item = a->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000639 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000640 else if (d > 0) { /* Insert d items */
Christian Heimes90aa7642007-12-19 02:45:37 +0000641 k = Py_SIZE(a);
Tim Peters73572222004-07-31 02:54:42 +0000642 if (list_resize(a, k+d) < 0)
Tim Peters8d9eb102004-07-31 02:24:20 +0000643 goto Error;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000644 item = a->ob_item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000645 memmove(&item[ihigh+d], &item[ihigh],
Tim Peters73572222004-07-31 02:54:42 +0000646 (k - ihigh)*sizeof(PyObject *));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000647 }
648 for (k = 0; k < n; k++, ilow++) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000649 PyObject *w = vitem[k];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000650 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000651 item[ilow] = w;
652 }
Tim Peters73572222004-07-31 02:54:42 +0000653 for (k = norig - 1; k >= 0; --k)
654 Py_XDECREF(recycle[k]);
Tim Peters8d9eb102004-07-31 02:24:20 +0000655 result = 0;
656 Error:
Tim Peters73572222004-07-31 02:54:42 +0000657 if (recycle != recycle_on_stack)
Armin Rigo1dd04a02004-07-30 11:38:22 +0000658 PyMem_FREE(recycle);
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000659 Py_XDECREF(v_as_SF);
Tim Peters8d9eb102004-07-31 02:24:20 +0000660 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000661#undef b
662}
663
Guido van Rossum234f9421993-06-17 12:35:49 +0000664int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000665PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000666{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000667 if (!PyList_Check(a)) {
668 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000669 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000670 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000671 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000672}
673
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000674static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000675list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000676{
677 PyObject **items;
Christian Heimesaf98da12008-01-27 15:18:18 +0000678 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000679
680
681 size = PyList_GET_SIZE(self);
Christian Heimesaf98da12008-01-27 15:18:18 +0000682 if (size == 0 || n == 1) {
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000683 Py_INCREF(self);
684 return (PyObject *)self;
685 }
686
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000687 if (n < 1) {
Armin Rigo93677f02004-07-29 12:40:23 +0000688 (void)list_clear(self);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000689 Py_INCREF(self);
690 return (PyObject *)self;
691 }
692
Christian Heimesaf98da12008-01-27 15:18:18 +0000693 if (size > PY_SSIZE_T_MAX / n) {
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000694 return PyErr_NoMemory();
Christian Heimesaf98da12008-01-27 15:18:18 +0000695 }
696
697 if (list_resize(self, size*n) == -1)
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000698 return NULL;
699
700 p = size;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000701 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000702 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
703 for (j = 0; j < size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000704 PyObject *o = items[j];
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000705 Py_INCREF(o);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000706 items[p++] = o;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000707 }
708 }
709 Py_INCREF(self);
710 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000711}
712
Guido van Rossum4a450d01991-04-03 19:05:18 +0000713static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000714list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000715{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000716 PyObject *old_value;
Christian Heimes90aa7642007-12-19 02:45:37 +0000717 if (i < 0 || i >= Py_SIZE(a)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000718 PyErr_SetString(PyExc_IndexError,
719 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000720 return -1;
721 }
722 if (v == NULL)
723 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000724 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000725 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000726 a->ob_item[i] = v;
Tim Peters3b01a122002-07-19 02:35:45 +0000727 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000728 return 0;
729}
730
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000731static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000732listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000733{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000734 Py_ssize_t i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000735 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000736 if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000737 return NULL;
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000738 if (ins1(self, i, v) == 0)
739 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000740 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000741}
742
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000743static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000744listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000745{
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000746 if (app1(self, v) == 0)
747 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000748 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000749}
750
Barry Warsawdedf6d61998-10-09 16:37:25 +0000751static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000752listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000753{
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000754 PyObject *it; /* iter(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000755 Py_ssize_t m; /* size of self */
756 Py_ssize_t n; /* guess for size of b */
757 Py_ssize_t mn; /* m + n */
758 Py_ssize_t i;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000759 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000760
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000761 /* Special cases:
Tim Petersb38e2b62004-07-29 02:29:26 +0000762 1) lists and tuples which can use PySequence_Fast ops
763 2) extending self to self requires making a copy first
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000764 */
765 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
Armin Rigo70d172d2004-03-20 22:19:23 +0000766 PyObject **src, **dest;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000767 b = PySequence_Fast(b, "argument must be iterable");
768 if (!b)
769 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000770 n = PySequence_Fast_GET_SIZE(b);
771 if (n == 0) {
772 /* short circuit when b is empty */
773 Py_DECREF(b);
774 Py_RETURN_NONE;
775 }
Christian Heimes90aa7642007-12-19 02:45:37 +0000776 m = Py_SIZE(self);
Armin Rigo70d172d2004-03-20 22:19:23 +0000777 if (list_resize(self, m + n) == -1) {
778 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000779 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000780 }
781 /* note that we may still have self == b here for the
782 * situation a.extend(a), but the following code works
783 * in that case too. Just make sure to resize self
784 * before calling PySequence_Fast_ITEMS.
785 */
786 /* populate the end of self with b's items */
787 src = PySequence_Fast_ITEMS(b);
788 dest = self->ob_item + m;
789 for (i = 0; i < n; i++) {
790 PyObject *o = src[i];
791 Py_INCREF(o);
792 dest[i] = o;
793 }
794 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000795 Py_RETURN_NONE;
796 }
797
798 it = PyObject_GetIter(b);
799 if (it == NULL)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000800 return NULL;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000801 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000802
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000803 /* Guess a result list size. */
Christian Heimes255f53b2007-12-08 15:33:56 +0000804 n = _PyObject_LengthHint(b, 8);
Raymond Hettingere8364232009-02-02 22:55:09 +0000805 if (n == -1) {
806 Py_DECREF(it);
807 return NULL;
808 }
Christian Heimes90aa7642007-12-19 02:45:37 +0000809 m = Py_SIZE(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000810 mn = m + n;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000811 if (mn >= m) {
812 /* Make room. */
813 if (list_resize(self, mn) == -1)
814 goto error;
815 /* Make the list sane again. */
Christian Heimes90aa7642007-12-19 02:45:37 +0000816 Py_SIZE(self) = m;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000817 }
818 /* Else m + n overflowed; on the chance that n lied, and there really
819 * is enough room, ignore it. If n was telling the truth, we'll
820 * eventually run out of memory during the loop.
821 */
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000822
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000823 /* Run iterator to exhaustion. */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000824 for (;;) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000825 PyObject *item = iternext(it);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000826 if (item == NULL) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000827 if (PyErr_Occurred()) {
828 if (PyErr_ExceptionMatches(PyExc_StopIteration))
829 PyErr_Clear();
830 else
831 goto error;
832 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000833 break;
834 }
Christian Heimes90aa7642007-12-19 02:45:37 +0000835 if (Py_SIZE(self) < self->allocated) {
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000836 /* steals ref */
Christian Heimes90aa7642007-12-19 02:45:37 +0000837 PyList_SET_ITEM(self, Py_SIZE(self), item);
838 ++Py_SIZE(self);
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000839 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000840 else {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000841 int status = app1(self, item);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000842 Py_DECREF(item); /* append creates a new ref */
843 if (status < 0)
844 goto error;
845 }
846 }
847
848 /* Cut back result list if initial guess was too large. */
Christian Heimes90aa7642007-12-19 02:45:37 +0000849 if (Py_SIZE(self) < self->allocated)
850 list_resize(self, Py_SIZE(self)); /* shrinking can't fail */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000851
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000852 Py_DECREF(it);
853 Py_RETURN_NONE;
854
855 error:
856 Py_DECREF(it);
857 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000858}
859
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000860PyObject *
861_PyList_Extend(PyListObject *self, PyObject *b)
862{
863 return listextend(self, b);
864}
865
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000866static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000867list_inplace_concat(PyListObject *self, PyObject *other)
868{
869 PyObject *result;
870
871 result = listextend(self, other);
872 if (result == NULL)
873 return result;
874 Py_DECREF(result);
875 Py_INCREF(self);
876 return (PyObject *)self;
877}
878
879static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000880listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000881{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000882 Py_ssize_t i = -1;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000883 PyObject *v;
Tim Peters8fc4a912004-07-31 21:53:19 +0000884 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000885
Thomas Wouters89f507f2006-12-13 04:49:30 +0000886 if (!PyArg_ParseTuple(args, "|n:pop", &i))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000887 return NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000888
Christian Heimes90aa7642007-12-19 02:45:37 +0000889 if (Py_SIZE(self) == 0) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000890 /* Special-case most common failure cause */
891 PyErr_SetString(PyExc_IndexError, "pop from empty list");
892 return NULL;
893 }
894 if (i < 0)
Christian Heimes90aa7642007-12-19 02:45:37 +0000895 i += Py_SIZE(self);
896 if (i < 0 || i >= Py_SIZE(self)) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000897 PyErr_SetString(PyExc_IndexError, "pop index out of range");
898 return NULL;
899 }
900 v = self->ob_item[i];
Christian Heimes90aa7642007-12-19 02:45:37 +0000901 if (i == Py_SIZE(self) - 1) {
902 status = list_resize(self, Py_SIZE(self) - 1);
Tim Peters8fc4a912004-07-31 21:53:19 +0000903 assert(status >= 0);
904 return v; /* and v now owns the reference the list had */
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000905 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000906 Py_INCREF(v);
Tim Peters8fc4a912004-07-31 21:53:19 +0000907 status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
908 assert(status >= 0);
909 /* Use status, so that in a release build compilers don't
910 * complain about the unused name.
911 */
Brett Cannon651dd522004-08-08 21:21:18 +0000912 (void) status;
913
914 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000915}
916
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000917/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
918static void
919reverse_slice(PyObject **lo, PyObject **hi)
920{
921 assert(lo && hi);
922
923 --hi;
924 while (lo < hi) {
925 PyObject *t = *lo;
926 *lo = *hi;
927 *hi = t;
928 ++lo;
929 --hi;
930 }
931}
932
Tim Petersa64dc242002-08-01 02:13:36 +0000933/* Lots of code for an adaptive, stable, natural mergesort. There are many
934 * pieces to this algorithm; read listsort.txt for overviews and details.
935 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000936
Raymond Hettinger70b64fc2008-01-30 20:15:17 +0000937/* Comparison function: PyObject_RichCompareBool with Py_LT.
Tim Petersa64dc242002-08-01 02:13:36 +0000938 * Returns -1 on error, 1 if x < y, 0 if x >= y.
939 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000940
Raymond Hettinger70b64fc2008-01-30 20:15:17 +0000941#define ISLT(X, Y) (PyObject_RichCompareBool(X, Y, Py_LT))
Tim Peters66860f62002-08-04 17:47:26 +0000942
943/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +0000944 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
945 started. It makes more sense in context <wink>. X and Y are PyObject*s.
946*/
Raymond Hettinger70b64fc2008-01-30 20:15:17 +0000947#define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail; \
Tim Petersa8c974c2002-07-19 03:30:57 +0000948 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000949
950/* binarysort is the best method for sorting small arrays: it does
951 few compares, but can do data movement quadratic in the number of
952 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000953 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +0000954 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000955 On entry, must have lo <= start <= hi, and that [lo, start) is already
956 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +0000957 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000958 Even in case of error, the output slice will be some permutation of
959 the input (nothing is lost or duplicated).
960*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000961static int
Raymond Hettinger70b64fc2008-01-30 20:15:17 +0000962binarysort(PyObject **lo, PyObject **hi, PyObject **start)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000963{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000964 register Py_ssize_t k;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000965 register PyObject **l, **p, **r;
966 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000967
Tim Petersa8c974c2002-07-19 03:30:57 +0000968 assert(lo <= start && start <= hi);
969 /* assert [lo, start) is sorted */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000970 if (lo == start)
971 ++start;
972 for (; start < hi; ++start) {
973 /* set l to where *start belongs */
974 l = lo;
975 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000976 pivot = *r;
Tim Peters0fe977c2002-07-19 06:12:32 +0000977 /* Invariants:
978 * pivot >= all in [lo, l).
979 * pivot < all in [r, start).
980 * The second is vacuously true at the start.
981 */
982 assert(l < r);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000983 do {
984 p = l + ((r - l) >> 1);
Tim Petersa8c974c2002-07-19 03:30:57 +0000985 IFLT(pivot, *p)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000986 r = p;
987 else
Tim Peters0fe977c2002-07-19 06:12:32 +0000988 l = p+1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000989 } while (l < r);
Tim Peters0fe977c2002-07-19 06:12:32 +0000990 assert(l == r);
991 /* The invariants still hold, so pivot >= all in [lo, l) and
992 pivot < all in [l, start), so pivot belongs at l. Note
993 that if there are elements equal to pivot, l points to the
994 first slot after them -- that's why this sort is stable.
995 Slide over to make room.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000996 Caution: using memmove is much slower under MSVC 5;
997 we're not usually moving many slots. */
998 for (p = start; p > l; --p)
999 *p = *(p-1);
1000 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001001 }
Guido van Rossum3f236de1996-12-10 23:55:39 +00001002 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001003
1004 fail:
1005 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001006}
1007
Tim Petersa64dc242002-08-01 02:13:36 +00001008/*
1009Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1010is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001011
Tim Petersa64dc242002-08-01 02:13:36 +00001012 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001013
Tim Petersa64dc242002-08-01 02:13:36 +00001014or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001015
Tim Petersa64dc242002-08-01 02:13:36 +00001016 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001017
Tim Petersa64dc242002-08-01 02:13:36 +00001018Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1019For its intended use in a stable mergesort, the strictness of the defn of
1020"descending" is needed so that the caller can safely reverse a descending
1021sequence without violating stability (strict > ensures there are no equal
1022elements to get out of order).
1023
1024Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001025*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001026static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001027count_run(PyObject **lo, PyObject **hi, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001028{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001029 Py_ssize_t k;
1030 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001031
Tim Petersa64dc242002-08-01 02:13:36 +00001032 assert(lo < hi);
1033 *descending = 0;
1034 ++lo;
1035 if (lo == hi)
1036 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001037
Tim Petersa64dc242002-08-01 02:13:36 +00001038 n = 2;
1039 IFLT(*lo, *(lo-1)) {
1040 *descending = 1;
1041 for (lo = lo+1; lo < hi; ++lo, ++n) {
1042 IFLT(*lo, *(lo-1))
1043 ;
1044 else
1045 break;
1046 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001047 }
Tim Petersa64dc242002-08-01 02:13:36 +00001048 else {
1049 for (lo = lo+1; lo < hi; ++lo, ++n) {
1050 IFLT(*lo, *(lo-1))
1051 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001052 }
1053 }
1054
Tim Petersa64dc242002-08-01 02:13:36 +00001055 return n;
1056fail:
1057 return -1;
1058}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001059
Tim Petersa64dc242002-08-01 02:13:36 +00001060/*
1061Locate the proper position of key in a sorted vector; if the vector contains
1062an element equal to key, return the position immediately to the left of
1063the leftmost equal element. [gallop_right() does the same except returns
1064the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001065
Tim Petersa64dc242002-08-01 02:13:36 +00001066"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001067
Tim Petersa64dc242002-08-01 02:13:36 +00001068"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1069hint is to the final result, the faster this runs.
1070
1071The return value is the int k in 0..n such that
1072
1073 a[k-1] < key <= a[k]
1074
1075pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1076key belongs at index k; or, IOW, the first k elements of a should precede
1077key, and the last n-k should follow key.
1078
1079Returns -1 on error. See listsort.txt for info on the method.
1080*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001081static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001082gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001083{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001084 Py_ssize_t ofs;
1085 Py_ssize_t lastofs;
1086 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001087
1088 assert(key && a && n > 0 && hint >= 0 && hint < n);
1089
1090 a += hint;
1091 lastofs = 0;
1092 ofs = 1;
1093 IFLT(*a, key) {
1094 /* a[hint] < key -- gallop right, until
1095 * a[hint + lastofs] < key <= a[hint + ofs]
1096 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001097 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001098 while (ofs < maxofs) {
1099 IFLT(a[ofs], key) {
1100 lastofs = ofs;
1101 ofs = (ofs << 1) + 1;
1102 if (ofs <= 0) /* int overflow */
1103 ofs = maxofs;
1104 }
1105 else /* key <= a[hint + ofs] */
1106 break;
1107 }
1108 if (ofs > maxofs)
1109 ofs = maxofs;
1110 /* Translate back to offsets relative to &a[0]. */
1111 lastofs += hint;
1112 ofs += hint;
1113 }
1114 else {
1115 /* key <= a[hint] -- gallop left, until
1116 * a[hint - ofs] < key <= a[hint - lastofs]
1117 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001118 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001119 while (ofs < maxofs) {
1120 IFLT(*(a-ofs), key)
1121 break;
1122 /* key <= a[hint - ofs] */
1123 lastofs = ofs;
1124 ofs = (ofs << 1) + 1;
1125 if (ofs <= 0) /* int overflow */
1126 ofs = maxofs;
1127 }
1128 if (ofs > maxofs)
1129 ofs = maxofs;
1130 /* Translate back to positive offsets relative to &a[0]. */
1131 k = lastofs;
1132 lastofs = hint - ofs;
1133 ofs = hint - k;
1134 }
1135 a -= hint;
1136
1137 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1138 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1139 * right of lastofs but no farther right than ofs. Do a binary
1140 * search, with invariant a[lastofs-1] < key <= a[ofs].
1141 */
1142 ++lastofs;
1143 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001144 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001145
1146 IFLT(a[m], key)
1147 lastofs = m+1; /* a[m] < key */
1148 else
1149 ofs = m; /* key <= a[m] */
1150 }
1151 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1152 return ofs;
1153
1154fail:
1155 return -1;
1156}
1157
1158/*
1159Exactly like gallop_left(), except that if key already exists in a[0:n],
1160finds the position immediately to the right of the rightmost equal value.
1161
1162The return value is the int k in 0..n such that
1163
1164 a[k-1] <= key < a[k]
1165
1166or -1 if error.
1167
1168The code duplication is massive, but this is enough different given that
1169we're sticking to "<" comparisons that it's much harder to follow if
1170written as one routine with yet another "left or right?" flag.
1171*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001172static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001173gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001174{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001175 Py_ssize_t ofs;
1176 Py_ssize_t lastofs;
1177 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001178
1179 assert(key && a && n > 0 && hint >= 0 && hint < n);
1180
1181 a += hint;
1182 lastofs = 0;
1183 ofs = 1;
1184 IFLT(key, *a) {
1185 /* key < a[hint] -- gallop left, until
1186 * a[hint - ofs] <= key < a[hint - lastofs]
1187 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001188 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001189 while (ofs < maxofs) {
1190 IFLT(key, *(a-ofs)) {
1191 lastofs = ofs;
1192 ofs = (ofs << 1) + 1;
1193 if (ofs <= 0) /* int overflow */
1194 ofs = maxofs;
1195 }
1196 else /* a[hint - ofs] <= key */
1197 break;
1198 }
1199 if (ofs > maxofs)
1200 ofs = maxofs;
1201 /* Translate back to positive offsets relative to &a[0]. */
1202 k = lastofs;
1203 lastofs = hint - ofs;
1204 ofs = hint - k;
1205 }
1206 else {
1207 /* a[hint] <= key -- gallop right, until
1208 * a[hint + lastofs] <= key < a[hint + ofs]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001209 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001210 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001211 while (ofs < maxofs) {
1212 IFLT(key, a[ofs])
1213 break;
1214 /* a[hint + ofs] <= key */
1215 lastofs = ofs;
1216 ofs = (ofs << 1) + 1;
1217 if (ofs <= 0) /* int overflow */
1218 ofs = maxofs;
1219 }
1220 if (ofs > maxofs)
1221 ofs = maxofs;
1222 /* Translate back to offsets relative to &a[0]. */
1223 lastofs += hint;
1224 ofs += hint;
1225 }
1226 a -= hint;
1227
1228 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1229 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1230 * right of lastofs but no farther right than ofs. Do a binary
1231 * search, with invariant a[lastofs-1] <= key < a[ofs].
1232 */
1233 ++lastofs;
1234 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001235 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001236
1237 IFLT(key, a[m])
1238 ofs = m; /* key < a[m] */
1239 else
1240 lastofs = m+1; /* a[m] <= key */
1241 }
1242 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1243 return ofs;
1244
1245fail:
1246 return -1;
1247}
1248
1249/* The maximum number of entries in a MergeState's pending-runs stack.
1250 * This is enough to sort arrays of size up to about
1251 * 32 * phi ** MAX_MERGE_PENDING
1252 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1253 * with 2**64 elements.
1254 */
1255#define MAX_MERGE_PENDING 85
1256
Tim Peterse05f65a2002-08-10 05:21:15 +00001257/* When we get into galloping mode, we stay there until both runs win less
1258 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001259 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001260#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001261
1262/* Avoid malloc for small temp arrays. */
1263#define MERGESTATE_TEMP_SIZE 256
1264
1265/* One MergeState exists on the stack per invocation of mergesort. It's just
1266 * a convenient way to pass state around among the helper functions.
1267 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001268struct s_slice {
1269 PyObject **base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001270 Py_ssize_t len;
Tim Peterse05f65a2002-08-10 05:21:15 +00001271};
1272
Tim Petersa64dc242002-08-01 02:13:36 +00001273typedef struct s_MergeState {
Tim Peterse05f65a2002-08-10 05:21:15 +00001274 /* This controls when we get *into* galloping mode. It's initialized
1275 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1276 * random data, and lower for highly structured data.
1277 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001278 Py_ssize_t min_gallop;
Tim Peterse05f65a2002-08-10 05:21:15 +00001279
Tim Petersa64dc242002-08-01 02:13:36 +00001280 /* 'a' is temp storage to help with merges. It contains room for
1281 * alloced entries.
1282 */
1283 PyObject **a; /* may point to temparray below */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001284 Py_ssize_t alloced;
Tim Petersa64dc242002-08-01 02:13:36 +00001285
1286 /* A stack of n pending runs yet to be merged. Run #i starts at
1287 * address base[i] and extends for len[i] elements. It's always
1288 * true (so long as the indices are in bounds) that
1289 *
Tim Peterse05f65a2002-08-10 05:21:15 +00001290 * pending[i].base + pending[i].len == pending[i+1].base
Tim Petersa64dc242002-08-01 02:13:36 +00001291 *
1292 * so we could cut the storage for this, but it's a minor amount,
1293 * and keeping all the info explicit simplifies the code.
1294 */
1295 int n;
Tim Peterse05f65a2002-08-10 05:21:15 +00001296 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001297
1298 /* 'a' points to this when possible, rather than muck with malloc. */
1299 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1300} MergeState;
1301
1302/* Conceptually a MergeState's constructor. */
1303static void
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001304merge_init(MergeState *ms)
Tim Petersa64dc242002-08-01 02:13:36 +00001305{
1306 assert(ms != NULL);
Tim Petersa64dc242002-08-01 02:13:36 +00001307 ms->a = ms->temparray;
1308 ms->alloced = MERGESTATE_TEMP_SIZE;
1309 ms->n = 0;
Tim Peterse05f65a2002-08-10 05:21:15 +00001310 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001311}
1312
1313/* Free all the temp memory owned by the MergeState. This must be called
1314 * when you're done with a MergeState, and may be called before then if
1315 * you want to free the temp memory early.
1316 */
1317static void
1318merge_freemem(MergeState *ms)
1319{
1320 assert(ms != NULL);
1321 if (ms->a != ms->temparray)
1322 PyMem_Free(ms->a);
1323 ms->a = ms->temparray;
1324 ms->alloced = MERGESTATE_TEMP_SIZE;
1325}
1326
1327/* Ensure enough temp memory for 'need' array slots is available.
1328 * Returns 0 on success and -1 if the memory can't be gotten.
1329 */
1330static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001331merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001332{
1333 assert(ms != NULL);
1334 if (need <= ms->alloced)
1335 return 0;
1336 /* Don't realloc! That can cost cycles to copy the old data, but
1337 * we don't care what's in the block.
1338 */
1339 merge_freemem(ms);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00001340 if (need > PY_SSIZE_T_MAX / sizeof(PyObject*)) {
1341 PyErr_NoMemory();
1342 return -1;
1343 }
Tim Petersa64dc242002-08-01 02:13:36 +00001344 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1345 if (ms->a) {
1346 ms->alloced = need;
1347 return 0;
1348 }
1349 PyErr_NoMemory();
1350 merge_freemem(ms); /* reset to sane state */
1351 return -1;
1352}
1353#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1354 merge_getmem(MS, NEED))
1355
1356/* Merge the na elements starting at pa with the nb elements starting at pb
1357 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1358 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1359 * merge, and should have na <= nb. See listsort.txt for more info.
1360 * Return 0 if successful, -1 if error.
1361 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001362static Py_ssize_t
1363merge_lo(MergeState *ms, PyObject **pa, Py_ssize_t na,
1364 PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001365{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001366 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001367 PyObject **dest;
1368 int result = -1; /* guilty until proved innocent */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001369 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001370
1371 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1372 if (MERGE_GETMEM(ms, na) < 0)
1373 return -1;
1374 memcpy(ms->a, pa, na * sizeof(PyObject*));
1375 dest = pa;
1376 pa = ms->a;
1377
1378 *dest++ = *pb++;
1379 --nb;
1380 if (nb == 0)
1381 goto Succeed;
1382 if (na == 1)
1383 goto CopyB;
1384
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001385 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001386 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001387 Py_ssize_t acount = 0; /* # of times A won in a row */
1388 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001389
1390 /* Do the straightforward thing until (if ever) one run
1391 * appears to win consistently.
1392 */
1393 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001394 assert(na > 1 && nb > 0);
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001395 k = ISLT(*pb, *pa);
Tim Petersa64dc242002-08-01 02:13:36 +00001396 if (k) {
1397 if (k < 0)
1398 goto Fail;
1399 *dest++ = *pb++;
1400 ++bcount;
1401 acount = 0;
1402 --nb;
1403 if (nb == 0)
1404 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001405 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001406 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001407 }
1408 else {
Tim Petersa64dc242002-08-01 02:13:36 +00001409 *dest++ = *pa++;
1410 ++acount;
1411 bcount = 0;
1412 --na;
1413 if (na == 1)
1414 goto CopyB;
Tim Peterse05f65a2002-08-10 05:21:15 +00001415 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001416 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001417 }
Tim Petersa64dc242002-08-01 02:13:36 +00001418 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001419
Tim Petersa64dc242002-08-01 02:13:36 +00001420 /* One run is winning so consistently that galloping may
1421 * be a huge win. So try that, and continue galloping until
1422 * (if ever) neither run appears to be winning consistently
1423 * anymore.
1424 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001425 ++min_gallop;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001426 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001427 assert(na > 1 && nb > 0);
1428 min_gallop -= min_gallop > 1;
1429 ms->min_gallop = min_gallop;
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001430 k = gallop_right(*pb, pa, na, 0);
Tim Petersa64dc242002-08-01 02:13:36 +00001431 acount = k;
1432 if (k) {
1433 if (k < 0)
1434 goto Fail;
1435 memcpy(dest, pa, k * sizeof(PyObject *));
1436 dest += k;
1437 pa += k;
1438 na -= k;
1439 if (na == 1)
1440 goto CopyB;
1441 /* na==0 is impossible now if the comparison
1442 * function is consistent, but we can't assume
1443 * that it is.
1444 */
1445 if (na == 0)
1446 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001447 }
Tim Petersa64dc242002-08-01 02:13:36 +00001448 *dest++ = *pb++;
1449 --nb;
1450 if (nb == 0)
1451 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001452
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001453 k = gallop_left(*pa, pb, nb, 0);
Tim Petersa64dc242002-08-01 02:13:36 +00001454 bcount = k;
1455 if (k) {
1456 if (k < 0)
1457 goto Fail;
1458 memmove(dest, pb, k * sizeof(PyObject *));
1459 dest += k;
1460 pb += k;
1461 nb -= k;
1462 if (nb == 0)
1463 goto Succeed;
1464 }
1465 *dest++ = *pa++;
1466 --na;
1467 if (na == 1)
1468 goto CopyB;
1469 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001470 ++min_gallop; /* penalize it for leaving galloping mode */
1471 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001472 }
1473Succeed:
1474 result = 0;
1475Fail:
1476 if (na)
1477 memcpy(dest, pa, na * sizeof(PyObject*));
1478 return result;
1479CopyB:
1480 assert(na == 1 && nb > 0);
1481 /* The last element of pa belongs at the end of the merge. */
1482 memmove(dest, pb, nb * sizeof(PyObject *));
1483 dest[nb] = *pa;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001484 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001485}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001486
Tim Petersa64dc242002-08-01 02:13:36 +00001487/* Merge the na elements starting at pa with the nb elements starting at pb
1488 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1489 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1490 * merge, and should have na >= nb. See listsort.txt for more info.
1491 * Return 0 if successful, -1 if error.
1492 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001493static Py_ssize_t
1494merge_hi(MergeState *ms, PyObject **pa, Py_ssize_t na, PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001495{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001496 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001497 PyObject **dest;
1498 int result = -1; /* guilty until proved innocent */
1499 PyObject **basea;
1500 PyObject **baseb;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001501 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001502
1503 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1504 if (MERGE_GETMEM(ms, nb) < 0)
1505 return -1;
1506 dest = pb + nb - 1;
1507 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1508 basea = pa;
1509 baseb = ms->a;
1510 pb = ms->a + nb - 1;
1511 pa += na - 1;
1512
1513 *dest-- = *pa--;
1514 --na;
1515 if (na == 0)
1516 goto Succeed;
1517 if (nb == 1)
1518 goto CopyA;
1519
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001520 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001521 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001522 Py_ssize_t acount = 0; /* # of times A won in a row */
1523 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001524
1525 /* Do the straightforward thing until (if ever) one run
1526 * appears to win consistently.
1527 */
1528 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001529 assert(na > 0 && nb > 1);
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001530 k = ISLT(*pb, *pa);
Tim Petersa64dc242002-08-01 02:13:36 +00001531 if (k) {
1532 if (k < 0)
1533 goto Fail;
1534 *dest-- = *pa--;
1535 ++acount;
1536 bcount = 0;
1537 --na;
1538 if (na == 0)
1539 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001540 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001541 break;
1542 }
1543 else {
1544 *dest-- = *pb--;
1545 ++bcount;
1546 acount = 0;
1547 --nb;
1548 if (nb == 1)
1549 goto CopyA;
Tim Peterse05f65a2002-08-10 05:21:15 +00001550 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001551 break;
1552 }
1553 }
1554
1555 /* One run is winning so consistently that galloping may
1556 * be a huge win. So try that, and continue galloping until
1557 * (if ever) neither run appears to be winning consistently
1558 * anymore.
1559 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001560 ++min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001561 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001562 assert(na > 0 && nb > 1);
1563 min_gallop -= min_gallop > 1;
1564 ms->min_gallop = min_gallop;
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001565 k = gallop_right(*pb, basea, na, na-1);
Tim Petersa64dc242002-08-01 02:13:36 +00001566 if (k < 0)
1567 goto Fail;
1568 k = na - k;
1569 acount = k;
1570 if (k) {
1571 dest -= k;
1572 pa -= k;
1573 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1574 na -= k;
1575 if (na == 0)
1576 goto Succeed;
1577 }
1578 *dest-- = *pb--;
1579 --nb;
1580 if (nb == 1)
1581 goto CopyA;
1582
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001583 k = gallop_left(*pa, baseb, nb, nb-1);
Tim Petersa64dc242002-08-01 02:13:36 +00001584 if (k < 0)
1585 goto Fail;
1586 k = nb - k;
1587 bcount = k;
1588 if (k) {
1589 dest -= k;
1590 pb -= k;
1591 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1592 nb -= k;
1593 if (nb == 1)
1594 goto CopyA;
1595 /* nb==0 is impossible now if the comparison
1596 * function is consistent, but we can't assume
1597 * that it is.
1598 */
1599 if (nb == 0)
1600 goto Succeed;
1601 }
1602 *dest-- = *pa--;
1603 --na;
1604 if (na == 0)
1605 goto Succeed;
1606 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001607 ++min_gallop; /* penalize it for leaving galloping mode */
1608 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001609 }
1610Succeed:
1611 result = 0;
1612Fail:
1613 if (nb)
1614 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1615 return result;
1616CopyA:
1617 assert(nb == 1 && na > 0);
1618 /* The first element of pb belongs at the front of the merge. */
1619 dest -= na;
1620 pa -= na;
1621 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1622 *dest = *pb;
1623 return 0;
1624}
1625
1626/* Merge the two runs at stack indices i and i+1.
1627 * Returns 0 on success, -1 on error.
1628 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001629static Py_ssize_t
1630merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001631{
1632 PyObject **pa, **pb;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001633 Py_ssize_t na, nb;
1634 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001635
1636 assert(ms != NULL);
1637 assert(ms->n >= 2);
1638 assert(i >= 0);
1639 assert(i == ms->n - 2 || i == ms->n - 3);
1640
Tim Peterse05f65a2002-08-10 05:21:15 +00001641 pa = ms->pending[i].base;
1642 na = ms->pending[i].len;
1643 pb = ms->pending[i+1].base;
1644 nb = ms->pending[i+1].len;
Tim Petersa64dc242002-08-01 02:13:36 +00001645 assert(na > 0 && nb > 0);
1646 assert(pa + na == pb);
1647
1648 /* Record the length of the combined runs; if i is the 3rd-last
1649 * run now, also slide over the last run (which isn't involved
1650 * in this merge). The current run i+1 goes away in any case.
1651 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001652 ms->pending[i].len = na + nb;
1653 if (i == ms->n - 3)
1654 ms->pending[i+1] = ms->pending[i+2];
Tim Petersa64dc242002-08-01 02:13:36 +00001655 --ms->n;
1656
1657 /* Where does b start in a? Elements in a before that can be
1658 * ignored (already in place).
1659 */
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001660 k = gallop_right(*pb, pa, na, 0);
Tim Petersa64dc242002-08-01 02:13:36 +00001661 if (k < 0)
1662 return -1;
1663 pa += k;
1664 na -= k;
1665 if (na == 0)
1666 return 0;
1667
1668 /* Where does a end in b? Elements in b after that can be
1669 * ignored (already in place).
1670 */
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001671 nb = gallop_left(pa[na-1], pb, nb, nb-1);
Tim Petersa64dc242002-08-01 02:13:36 +00001672 if (nb <= 0)
1673 return nb;
1674
1675 /* Merge what remains of the runs, using a temp array with
1676 * min(na, nb) elements.
1677 */
1678 if (na <= nb)
1679 return merge_lo(ms, pa, na, pb, nb);
1680 else
1681 return merge_hi(ms, pa, na, pb, nb);
1682}
1683
1684/* Examine the stack of runs waiting to be merged, merging adjacent runs
1685 * until the stack invariants are re-established:
1686 *
1687 * 1. len[-3] > len[-2] + len[-1]
1688 * 2. len[-2] > len[-1]
1689 *
1690 * See listsort.txt for more info.
1691 *
1692 * Returns 0 on success, -1 on error.
1693 */
1694static int
1695merge_collapse(MergeState *ms)
1696{
Tim Peterse05f65a2002-08-10 05:21:15 +00001697 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001698
1699 assert(ms);
1700 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001701 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001702 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1703 if (p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001704 --n;
1705 if (merge_at(ms, n) < 0)
1706 return -1;
1707 }
Tim Peterse05f65a2002-08-10 05:21:15 +00001708 else if (p[n].len <= p[n+1].len) {
Tim Petersa64dc242002-08-01 02:13:36 +00001709 if (merge_at(ms, n) < 0)
1710 return -1;
1711 }
1712 else
1713 break;
1714 }
1715 return 0;
1716}
1717
1718/* Regardless of invariants, merge all runs on the stack until only one
1719 * remains. This is used at the end of the mergesort.
1720 *
1721 * Returns 0 on success, -1 on error.
1722 */
1723static int
1724merge_force_collapse(MergeState *ms)
1725{
Tim Peterse05f65a2002-08-10 05:21:15 +00001726 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001727
1728 assert(ms);
1729 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001730 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001731 if (n > 0 && p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001732 --n;
1733 if (merge_at(ms, n) < 0)
1734 return -1;
1735 }
1736 return 0;
1737}
1738
1739/* Compute a good value for the minimum run length; natural runs shorter
1740 * than this are boosted artificially via binary insertion.
1741 *
1742 * If n < 64, return n (it's too small to bother with fancy stuff).
1743 * Else if n is an exact power of 2, return 32.
1744 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1745 * strictly less than, an exact power of 2.
1746 *
1747 * See listsort.txt for more info.
1748 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001749static Py_ssize_t
1750merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001751{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001752 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001753
1754 assert(n >= 0);
1755 while (n >= 64) {
1756 r |= n & 1;
1757 n >>= 1;
1758 }
1759 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001760}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001761
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001762/* Special wrapper to support stable sorting using the decorate-sort-undecorate
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001763 pattern. Holds a key which is used for comparisons and the original record
Tim Petersb38e2b62004-07-29 02:29:26 +00001764 which is returned during the undecorate phase. By exposing only the key
1765 during comparisons, the underlying sort stability characteristics are left
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001766 unchanged. Also, the comparison function will only see the key instead of
1767 a full record. */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001768
1769typedef struct {
1770 PyObject_HEAD
1771 PyObject *key;
1772 PyObject *value;
1773} sortwrapperobject;
1774
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001775PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001776static PyObject *
1777sortwrapper_richcompare(sortwrapperobject *, sortwrapperobject *, int);
1778static void
1779sortwrapper_dealloc(sortwrapperobject *);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001780
Christian Heimesa22e8bd2007-11-29 22:35:39 +00001781PyTypeObject PySortWrapper_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001782 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001783 "sortwrapper", /* tp_name */
1784 sizeof(sortwrapperobject), /* tp_basicsize */
1785 0, /* tp_itemsize */
1786 /* methods */
1787 (destructor)sortwrapper_dealloc, /* tp_dealloc */
1788 0, /* tp_print */
1789 0, /* tp_getattr */
1790 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00001791 0, /* tp_reserved */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001792 0, /* tp_repr */
1793 0, /* tp_as_number */
1794 0, /* tp_as_sequence */
1795 0, /* tp_as_mapping */
1796 0, /* tp_hash */
1797 0, /* tp_call */
1798 0, /* tp_str */
1799 PyObject_GenericGetAttr, /* tp_getattro */
1800 0, /* tp_setattro */
1801 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001802 Py_TPFLAGS_DEFAULT, /* tp_flags */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001803 sortwrapper_doc, /* tp_doc */
1804 0, /* tp_traverse */
1805 0, /* tp_clear */
1806 (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
1807};
1808
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001809
1810static PyObject *
1811sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
1812{
Christian Heimesa22e8bd2007-11-29 22:35:39 +00001813 if (!PyObject_TypeCheck(b, &PySortWrapper_Type)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001814 PyErr_SetString(PyExc_TypeError,
1815 "expected a sortwrapperobject");
1816 return NULL;
1817 }
1818 return PyObject_RichCompare(a->key, b->key, op);
1819}
1820
1821static void
1822sortwrapper_dealloc(sortwrapperobject *so)
1823{
1824 Py_XDECREF(so->key);
1825 Py_XDECREF(so->value);
1826 PyObject_Del(so);
1827}
1828
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001829/* Returns a new reference to a sortwrapper.
1830 Consumes the references to the two underlying objects. */
1831
1832static PyObject *
1833build_sortwrapper(PyObject *key, PyObject *value)
1834{
1835 sortwrapperobject *so;
Tim Petersb38e2b62004-07-29 02:29:26 +00001836
Christian Heimesa22e8bd2007-11-29 22:35:39 +00001837 so = PyObject_New(sortwrapperobject, &PySortWrapper_Type);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001838 if (so == NULL)
1839 return NULL;
1840 so->key = key;
1841 so->value = value;
1842 return (PyObject *)so;
1843}
1844
1845/* Returns a new reference to the value underlying the wrapper. */
1846static PyObject *
1847sortwrapper_getvalue(PyObject *so)
1848{
1849 PyObject *value;
1850
Christian Heimesa22e8bd2007-11-29 22:35:39 +00001851 if (!PyObject_TypeCheck(so, &PySortWrapper_Type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001852 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001853 "expected a sortwrapperobject");
1854 return NULL;
1855 }
1856 value = ((sortwrapperobject *)so)->value;
1857 Py_INCREF(value);
1858 return value;
1859}
1860
Tim Petersa64dc242002-08-01 02:13:36 +00001861/* An adaptive, stable, natural mergesort. See listsort.txt.
1862 * Returns Py_None on success, NULL on error. Even in case of error, the
1863 * list will be some permutation of its input state (nothing is lost or
1864 * duplicated).
1865 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001866static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001867listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001868{
Tim Petersa64dc242002-08-01 02:13:36 +00001869 MergeState ms;
1870 PyObject **lo, **hi;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001871 Py_ssize_t nremaining;
1872 Py_ssize_t minrun;
1873 Py_ssize_t saved_ob_size, saved_allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00001874 PyObject **saved_ob_item;
Armin Rigo93677f02004-07-29 12:40:23 +00001875 PyObject **final_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001876 PyObject *result = NULL; /* guilty until proved innocent */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001877 int reverse = 0;
1878 PyObject *keyfunc = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001879 Py_ssize_t i;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001880 PyObject *key, *value, *kvpair;
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001881 static char *kwlist[] = {"key", "reverse", 0};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001882
Tim Petersa64dc242002-08-01 02:13:36 +00001883 assert(self != NULL);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001884 assert (PyList_Check(self));
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001885 if (args != NULL) {
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001886 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:sort",
1887 kwlist, &keyfunc, &reverse))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001888 return NULL;
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001889 if (Py_SIZE(args) > 0) {
1890 PyErr_SetString(PyExc_TypeError,
1891 "must use keyword argument for key function");
1892 return NULL;
1893 }
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001894 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001895 if (keyfunc == Py_None)
1896 keyfunc = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001897
Tim Petersb9099c32002-11-12 22:08:10 +00001898 /* The list is temporarily made empty, so that mutations performed
1899 * by comparison functions can't affect the slice of memory we're
1900 * sorting (allowing mutations during sorting is a core-dump
1901 * factory, since ob_item may change).
1902 */
Christian Heimes90aa7642007-12-19 02:45:37 +00001903 saved_ob_size = Py_SIZE(self);
Tim Petersb9099c32002-11-12 22:08:10 +00001904 saved_ob_item = self->ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001905 saved_allocated = self->allocated;
Christian Heimes90aa7642007-12-19 02:45:37 +00001906 Py_SIZE(self) = 0;
Tim Peters51b4ade2004-07-29 04:07:15 +00001907 self->ob_item = NULL;
Armin Rigo93677f02004-07-29 12:40:23 +00001908 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00001909
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001910 if (keyfunc != NULL) {
1911 for (i=0 ; i < saved_ob_size ; i++) {
1912 value = saved_ob_item[i];
Tim Petersb38e2b62004-07-29 02:29:26 +00001913 key = PyObject_CallFunctionObjArgs(keyfunc, value,
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001914 NULL);
1915 if (key == NULL) {
1916 for (i=i-1 ; i>=0 ; i--) {
1917 kvpair = saved_ob_item[i];
1918 value = sortwrapper_getvalue(kvpair);
1919 saved_ob_item[i] = value;
1920 Py_DECREF(kvpair);
1921 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001922 goto dsu_fail;
1923 }
1924 kvpair = build_sortwrapper(key, value);
1925 if (kvpair == NULL)
1926 goto dsu_fail;
1927 saved_ob_item[i] = kvpair;
1928 }
1929 }
1930
1931 /* Reverse sort stability achieved by initially reversing the list,
1932 applying a stable forward sort, then reversing the final result. */
1933 if (reverse && saved_ob_size > 1)
1934 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
1935
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001936 merge_init(&ms);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001937
Tim Petersb9099c32002-11-12 22:08:10 +00001938 nremaining = saved_ob_size;
Tim Petersa64dc242002-08-01 02:13:36 +00001939 if (nremaining < 2)
1940 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00001941
Tim Petersa64dc242002-08-01 02:13:36 +00001942 /* March over the array once, left to right, finding natural runs,
1943 * and extending short natural runs to minrun elements.
1944 */
Tim Petersb9099c32002-11-12 22:08:10 +00001945 lo = saved_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001946 hi = lo + nremaining;
1947 minrun = merge_compute_minrun(nremaining);
1948 do {
1949 int descending;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001950 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00001951
Tim Petersa64dc242002-08-01 02:13:36 +00001952 /* Identify next run. */
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001953 n = count_run(lo, hi, &descending);
Tim Petersa64dc242002-08-01 02:13:36 +00001954 if (n < 0)
1955 goto fail;
1956 if (descending)
1957 reverse_slice(lo, lo + n);
1958 /* If short, extend to min(minrun, nremaining). */
1959 if (n < minrun) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001960 const Py_ssize_t force = nremaining <= minrun ?
Tim Petersa64dc242002-08-01 02:13:36 +00001961 nremaining : minrun;
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001962 if (binarysort(lo, lo + force, lo + n) < 0)
Tim Petersa64dc242002-08-01 02:13:36 +00001963 goto fail;
1964 n = force;
1965 }
1966 /* Push run onto pending-runs stack, and maybe merge. */
1967 assert(ms.n < MAX_MERGE_PENDING);
Tim Peterse05f65a2002-08-10 05:21:15 +00001968 ms.pending[ms.n].base = lo;
1969 ms.pending[ms.n].len = n;
Tim Petersa64dc242002-08-01 02:13:36 +00001970 ++ms.n;
1971 if (merge_collapse(&ms) < 0)
1972 goto fail;
1973 /* Advance to find next run. */
1974 lo += n;
1975 nremaining -= n;
1976 } while (nremaining);
1977 assert(lo == hi);
Tim Peters330f9e92002-07-19 07:05:44 +00001978
Tim Petersa64dc242002-08-01 02:13:36 +00001979 if (merge_force_collapse(&ms) < 0)
1980 goto fail;
1981 assert(ms.n == 1);
Tim Petersb9099c32002-11-12 22:08:10 +00001982 assert(ms.pending[0].base == saved_ob_item);
1983 assert(ms.pending[0].len == saved_ob_size);
Tim Petersa64dc242002-08-01 02:13:36 +00001984
1985succeed:
1986 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00001987fail:
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001988 if (keyfunc != NULL) {
1989 for (i=0 ; i < saved_ob_size ; i++) {
1990 kvpair = saved_ob_item[i];
1991 value = sortwrapper_getvalue(kvpair);
1992 saved_ob_item[i] = value;
1993 Py_DECREF(kvpair);
1994 }
1995 }
1996
Armin Rigo93677f02004-07-29 12:40:23 +00001997 if (self->allocated != -1 && result != NULL) {
Tim Peters51b4ade2004-07-29 04:07:15 +00001998 /* The user mucked with the list during the sort,
1999 * and we don't already have another error to report.
2000 */
2001 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2002 result = NULL;
Tim Petersb9099c32002-11-12 22:08:10 +00002003 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002004
2005 if (reverse && saved_ob_size > 1)
2006 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2007
2008 merge_freemem(&ms);
2009
2010dsu_fail:
Armin Rigo93677f02004-07-29 12:40:23 +00002011 final_ob_item = self->ob_item;
Christian Heimes90aa7642007-12-19 02:45:37 +00002012 i = Py_SIZE(self);
2013 Py_SIZE(self) = saved_ob_size;
Tim Petersb9099c32002-11-12 22:08:10 +00002014 self->ob_item = saved_ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002015 self->allocated = saved_allocated;
Armin Rigo93677f02004-07-29 12:40:23 +00002016 if (final_ob_item != NULL) {
2017 /* we cannot use list_clear() for this because it does not
2018 guarantee that the list is really empty when it returns */
2019 while (--i >= 0) {
2020 Py_XDECREF(final_ob_item[i]);
2021 }
2022 PyMem_FREE(final_ob_item);
2023 }
Tim Petersa64dc242002-08-01 02:13:36 +00002024 Py_XINCREF(result);
2025 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002026}
Tim Peters330f9e92002-07-19 07:05:44 +00002027#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002028#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002029
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002030int
Fred Drakea2f55112000-07-09 15:16:51 +00002031PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002032{
2033 if (v == NULL || !PyList_Check(v)) {
2034 PyErr_BadInternalCall();
2035 return -1;
2036 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002037 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002038 if (v == NULL)
2039 return -1;
2040 Py_DECREF(v);
2041 return 0;
2042}
2043
Guido van Rossumb86c5492001-02-12 22:06:02 +00002044static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002045listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002046{
Christian Heimes90aa7642007-12-19 02:45:37 +00002047 if (Py_SIZE(self) > 1)
2048 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002049 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002050}
2051
Guido van Rossum84c76f51990-10-30 13:32:20 +00002052int
Fred Drakea2f55112000-07-09 15:16:51 +00002053PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002054{
Tim Peters6063e262002-08-08 01:06:39 +00002055 PyListObject *self = (PyListObject *)v;
2056
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002057 if (v == NULL || !PyList_Check(v)) {
2058 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002059 return -1;
2060 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002061 if (Py_SIZE(self) > 1)
2062 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002063 return 0;
2064}
2065
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002066PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002067PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002068{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002069 PyObject *w;
Christian Heimes2c181612007-12-17 20:04:13 +00002070 PyObject **p, **q;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002071 Py_ssize_t n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002072 if (v == NULL || !PyList_Check(v)) {
2073 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002074 return NULL;
2075 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002076 n = Py_SIZE(v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002077 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002078 if (w == NULL)
2079 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002080 p = ((PyTupleObject *)w)->ob_item;
Christian Heimes2c181612007-12-17 20:04:13 +00002081 q = ((PyListObject *)v)->ob_item;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002082 while (--n >= 0) {
Christian Heimes2c181612007-12-17 20:04:13 +00002083 Py_INCREF(*q);
2084 *p = *q;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002085 p++;
Christian Heimes2c181612007-12-17 20:04:13 +00002086 q++;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002087 }
2088 return w;
2089}
2090
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002091static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002092listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002093{
Christian Heimes90aa7642007-12-19 02:45:37 +00002094 Py_ssize_t i, start=0, stop=Py_SIZE(self);
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002095 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002096
Walter Dörwalde8049bef2003-06-17 19:27:39 +00002097 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2098 _PyEval_SliceIndex, &start,
2099 _PyEval_SliceIndex, &stop))
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002100 return NULL;
Guido van Rossum2743d872003-06-17 14:25:14 +00002101 if (start < 0) {
Christian Heimes90aa7642007-12-19 02:45:37 +00002102 start += Py_SIZE(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002103 if (start < 0)
2104 start = 0;
2105 }
2106 if (stop < 0) {
Christian Heimes90aa7642007-12-19 02:45:37 +00002107 stop += Py_SIZE(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002108 if (stop < 0)
2109 stop = 0;
2110 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002111 for (i = start; i < stop && i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002112 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2113 if (cmp > 0)
Christian Heimes217cfd12007-12-02 14:31:20 +00002114 return PyLong_FromSsize_t(i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002115 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002116 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002117 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002118 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002119 return NULL;
2120}
2121
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002122static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002123listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002124{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002125 Py_ssize_t count = 0;
2126 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002127
Christian Heimes90aa7642007-12-19 02:45:37 +00002128 for (i = 0; i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002129 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2130 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002131 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002132 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002133 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00002134 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002135 return PyLong_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002136}
2137
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002138static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002139listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002140{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002141 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002142
Christian Heimes90aa7642007-12-19 02:45:37 +00002143 for (i = 0; i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002144 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2145 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002146 if (list_ass_slice(self, i, i+1,
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002147 (PyObject *)NULL) == 0)
2148 Py_RETURN_NONE;
2149 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002150 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002151 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002152 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002153 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002154 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002155 return NULL;
2156}
2157
Jeremy Hylton8caad492000-06-23 14:18:11 +00002158static int
2159list_traverse(PyListObject *o, visitproc visit, void *arg)
2160{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002161 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002162
Christian Heimes90aa7642007-12-19 02:45:37 +00002163 for (i = Py_SIZE(o); --i >= 0; )
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002164 Py_VISIT(o->ob_item[i]);
Jeremy Hylton8caad492000-06-23 14:18:11 +00002165 return 0;
2166}
2167
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002168static PyObject *
2169list_richcompare(PyObject *v, PyObject *w, int op)
2170{
2171 PyListObject *vl, *wl;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002172 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002173
2174 if (!PyList_Check(v) || !PyList_Check(w)) {
2175 Py_INCREF(Py_NotImplemented);
2176 return Py_NotImplemented;
2177 }
2178
2179 vl = (PyListObject *)v;
2180 wl = (PyListObject *)w;
2181
Christian Heimes90aa7642007-12-19 02:45:37 +00002182 if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002183 /* Shortcut: if the lengths differ, the lists differ */
2184 PyObject *res;
2185 if (op == Py_EQ)
2186 res = Py_False;
2187 else
2188 res = Py_True;
2189 Py_INCREF(res);
2190 return res;
2191 }
2192
2193 /* Search for the first index where items are different */
Christian Heimes90aa7642007-12-19 02:45:37 +00002194 for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002195 int k = PyObject_RichCompareBool(vl->ob_item[i],
2196 wl->ob_item[i], Py_EQ);
2197 if (k < 0)
2198 return NULL;
2199 if (!k)
2200 break;
2201 }
2202
Christian Heimes90aa7642007-12-19 02:45:37 +00002203 if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002204 /* No more items to compare -- compare sizes */
Christian Heimes90aa7642007-12-19 02:45:37 +00002205 Py_ssize_t vs = Py_SIZE(vl);
2206 Py_ssize_t ws = Py_SIZE(wl);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002207 int cmp;
2208 PyObject *res;
2209 switch (op) {
2210 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00002211 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002212 case Py_EQ: cmp = vs == ws; break;
2213 case Py_NE: cmp = vs != ws; break;
2214 case Py_GT: cmp = vs > ws; break;
2215 case Py_GE: cmp = vs >= ws; break;
2216 default: return NULL; /* cannot happen */
2217 }
2218 if (cmp)
2219 res = Py_True;
2220 else
2221 res = Py_False;
2222 Py_INCREF(res);
2223 return res;
2224 }
2225
2226 /* We have an item that differs -- shortcuts for EQ/NE */
2227 if (op == Py_EQ) {
2228 Py_INCREF(Py_False);
2229 return Py_False;
2230 }
2231 if (op == Py_NE) {
2232 Py_INCREF(Py_True);
2233 return Py_True;
2234 }
2235
2236 /* Compare the final item again using the proper operator */
2237 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
2238}
2239
Tim Peters6d6c1a32001-08-02 04:15:00 +00002240static int
2241list_init(PyListObject *self, PyObject *args, PyObject *kw)
2242{
2243 PyObject *arg = NULL;
Martin v. Löwis15e62742006-02-27 16:46:16 +00002244 static char *kwlist[] = {"sequence", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002245
2246 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2247 return -1;
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002248
2249 /* Verify list invariants established by PyType_GenericAlloc() */
Christian Heimes90aa7642007-12-19 02:45:37 +00002250 assert(0 <= Py_SIZE(self));
2251 assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
Armin Rigoa37bbf22004-07-30 11:20:18 +00002252 assert(self->ob_item != NULL ||
2253 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002254
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002255 /* Empty previous contents */
Armin Rigo93677f02004-07-29 12:40:23 +00002256 if (self->ob_item != NULL) {
2257 (void)list_clear(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002258 }
2259 if (arg != NULL) {
2260 PyObject *rv = listextend(self, arg);
2261 if (rv == NULL)
2262 return -1;
2263 Py_DECREF(rv);
2264 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002265 return 0;
2266}
2267
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002268static PyObject *
2269list_sizeof(PyListObject *self)
2270{
2271 Py_ssize_t res;
2272
2273 res = sizeof(PyListObject) + self->allocated * sizeof(void*);
2274 return PyLong_FromSsize_t(res);
2275}
2276
Raymond Hettinger1021c442003-11-07 15:38:09 +00002277static PyObject *list_iter(PyObject *seq);
2278static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2279
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002280PyDoc_STRVAR(getitem_doc,
2281"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002282PyDoc_STRVAR(reversed_doc,
2283"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002284PyDoc_STRVAR(sizeof_doc,
2285"L.__sizeof__() -- size of L in memory, in bytes");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002286PyDoc_STRVAR(append_doc,
2287"L.append(object) -- append object to end");
2288PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002289"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002290PyDoc_STRVAR(insert_doc,
2291"L.insert(index, object) -- insert object before index");
2292PyDoc_STRVAR(pop_doc,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002293"L.pop([index]) -> item -- remove and return item at index (default last).\n"
2294"Raises IndexError if list is empty or index is out of range.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002295PyDoc_STRVAR(remove_doc,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002296"L.remove(value) -- remove first occurrence of value.\n"
2297"Raises ValueError if the value is not present.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002298PyDoc_STRVAR(index_doc,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002299"L.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
2300"Raises ValueError if the value is not present.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002301PyDoc_STRVAR(count_doc,
2302"L.count(value) -> integer -- return number of occurrences of value");
2303PyDoc_STRVAR(reverse_doc,
2304"L.reverse() -- reverse *IN PLACE*");
2305PyDoc_STRVAR(sort_doc,
Benjamin Petersoncb9a5512008-09-30 02:08:36 +00002306"L.sort(key=None, reverse=False) -- stable sort *IN PLACE*");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002307
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002308static PyObject *list_subscript(PyListObject*, PyObject*);
2309
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002310static PyMethodDef list_methods[] = {
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002311 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
Raymond Hettinger1021c442003-11-07 15:38:09 +00002312 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002313 {"__sizeof__", (PyCFunction)list_sizeof, METH_NOARGS, sizeof_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002314 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002315 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002316 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002317 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002318 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002319 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002320 {"count", (PyCFunction)listcount, METH_O, count_doc},
2321 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002322 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
Tim Petersa64dc242002-08-01 02:13:36 +00002323 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002324};
2325
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002326static PySequenceMethods list_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002327 (lenfunc)list_length, /* sq_length */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002328 (binaryfunc)list_concat, /* sq_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002329 (ssizeargfunc)list_repeat, /* sq_repeat */
2330 (ssizeargfunc)list_item, /* sq_item */
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002331 0, /* sq_slice */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002332 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002333 0, /* sq_ass_slice */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002334 (objobjproc)list_contains, /* sq_contains */
2335 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002336 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002337};
2338
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002339PyDoc_STRVAR(list_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002340"list() -> new list\n"
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002341"list(sequence) -> new list initialized from sequence's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002342
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002343static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002344list_subscript(PyListObject* self, PyObject* item)
2345{
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002346 if (PyIndex_Check(item)) {
2347 Py_ssize_t i;
2348 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002349 if (i == -1 && PyErr_Occurred())
2350 return NULL;
2351 if (i < 0)
2352 i += PyList_GET_SIZE(self);
2353 return list_item(self, i);
2354 }
2355 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002356 Py_ssize_t start, stop, step, slicelength, cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002357 PyObject* result;
2358 PyObject* it;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002359 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002360
Christian Heimes90aa7642007-12-19 02:45:37 +00002361 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002362 &start, &stop, &step, &slicelength) < 0) {
2363 return NULL;
2364 }
2365
2366 if (slicelength <= 0) {
2367 return PyList_New(0);
2368 }
Thomas Woutersed03b412007-08-28 21:37:11 +00002369 else if (step == 1) {
2370 return list_slice(self, start, stop);
2371 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002372 else {
2373 result = PyList_New(slicelength);
2374 if (!result) return NULL;
2375
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002376 src = self->ob_item;
2377 dest = ((PyListObject *)result)->ob_item;
Tim Peters3b01a122002-07-19 02:35:45 +00002378 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002379 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002380 it = src[cur];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002381 Py_INCREF(it);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002382 dest[i] = it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002383 }
Tim Peters3b01a122002-07-19 02:35:45 +00002384
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002385 return result;
2386 }
2387 }
2388 else {
Thomas Wouters89f507f2006-12-13 04:49:30 +00002389 PyErr_Format(PyExc_TypeError,
2390 "list indices must be integers, not %.200s",
2391 item->ob_type->tp_name);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002392 return NULL;
2393 }
2394}
2395
Tim Peters3b01a122002-07-19 02:35:45 +00002396static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002397list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2398{
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002399 if (PyIndex_Check(item)) {
2400 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002401 if (i == -1 && PyErr_Occurred())
2402 return -1;
2403 if (i < 0)
2404 i += PyList_GET_SIZE(self);
2405 return list_ass_item(self, i, value);
2406 }
2407 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002408 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002409
Christian Heimes90aa7642007-12-19 02:45:37 +00002410 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002411 &start, &stop, &step, &slicelength) < 0) {
2412 return -1;
2413 }
2414
Thomas Woutersed03b412007-08-28 21:37:11 +00002415 if (step == 1)
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002416 return list_ass_slice(self, start, stop, value);
2417
Thomas Woutersed03b412007-08-28 21:37:11 +00002418 /* Make sure s[5:2] = [..] inserts at the right place:
2419 before 5, not before 2. */
2420 if ((step < 0 && start < stop) ||
2421 (step > 0 && start > stop))
2422 stop = start;
2423
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002424 if (value == NULL) {
2425 /* delete slice */
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002426 PyObject **garbage;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002427 Py_ssize_t cur, i;
Tim Peters3b01a122002-07-19 02:35:45 +00002428
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002429 if (slicelength <= 0)
2430 return 0;
2431
2432 if (step < 0) {
2433 stop = start + 1;
2434 start = stop + step*(slicelength - 1) - 1;
2435 step = -step;
2436 }
2437
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00002438 assert(slicelength <= PY_SIZE_MAX / sizeof(PyObject*));
2439
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002440 garbage = (PyObject**)
2441 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002442 if (!garbage) {
2443 PyErr_NoMemory();
2444 return -1;
2445 }
Tim Peters3b01a122002-07-19 02:35:45 +00002446
Thomas Woutersed03b412007-08-28 21:37:11 +00002447 /* drawing pictures might help understand these for
2448 loops. Basically, we memmove the parts of the
2449 list that are *not* part of the slice: step-1
2450 items for each item that is part of the slice,
2451 and then tail end of the list that was not
2452 covered by the slice */
Guido van Rossum75a20b12002-06-11 12:22:28 +00002453 for (cur = start, i = 0;
2454 cur < stop;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002455 cur += step, i++) {
Thomas Woutersed03b412007-08-28 21:37:11 +00002456 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002457
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002458 garbage[i] = PyList_GET_ITEM(self, cur);
2459
Christian Heimes90aa7642007-12-19 02:45:37 +00002460 if (cur + step >= Py_SIZE(self)) {
2461 lim = Py_SIZE(self) - cur - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002462 }
2463
Tim Petersb38e2b62004-07-29 02:29:26 +00002464 memmove(self->ob_item + cur - i,
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002465 self->ob_item + cur + 1,
2466 lim * sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002467 }
Thomas Woutersed03b412007-08-28 21:37:11 +00002468 cur = start + slicelength*step;
Christian Heimes90aa7642007-12-19 02:45:37 +00002469 if (cur < Py_SIZE(self)) {
Thomas Woutersed03b412007-08-28 21:37:11 +00002470 memmove(self->ob_item + cur - slicelength,
2471 self->ob_item + cur,
Christian Heimes90aa7642007-12-19 02:45:37 +00002472 (Py_SIZE(self) - cur) *
Thomas Woutersed03b412007-08-28 21:37:11 +00002473 sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002474 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002475
Christian Heimes90aa7642007-12-19 02:45:37 +00002476 Py_SIZE(self) -= slicelength;
2477 list_resize(self, Py_SIZE(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002478
2479 for (i = 0; i < slicelength; i++) {
2480 Py_DECREF(garbage[i]);
2481 }
2482 PyMem_FREE(garbage);
2483
2484 return 0;
2485 }
2486 else {
2487 /* assign slice */
Thomas Woutersed03b412007-08-28 21:37:11 +00002488 PyObject *ins, *seq;
2489 PyObject **garbage, **seqitems, **selfitems;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002490 Py_ssize_t cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002491
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002492 /* protect against a[::-1] = a */
Tim Peters3b01a122002-07-19 02:35:45 +00002493 if (self == (PyListObject*)value) {
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002494 seq = list_slice((PyListObject*)value, 0,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002495 PyList_GET_SIZE(value));
Tim Peters3b01a122002-07-19 02:35:45 +00002496 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002497 else {
Tim Petersb38e2b62004-07-29 02:29:26 +00002498 seq = PySequence_Fast(value,
Thomas Woutersed03b412007-08-28 21:37:11 +00002499 "must assign iterable "
2500 "to extended slice");
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002501 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002502 if (!seq)
2503 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002504
2505 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2506 PyErr_Format(PyExc_ValueError,
Thomas Woutersed03b412007-08-28 21:37:11 +00002507 "attempt to assign sequence of "
2508 "size %zd to extended slice of "
2509 "size %zd",
Martin v. Löwise0e89f72006-02-16 06:59:22 +00002510 PySequence_Fast_GET_SIZE(seq),
2511 slicelength);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002512 Py_DECREF(seq);
2513 return -1;
2514 }
2515
2516 if (!slicelength) {
2517 Py_DECREF(seq);
2518 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002519 }
2520
2521 garbage = (PyObject**)
2522 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Thomas Wouters89f507f2006-12-13 04:49:30 +00002523 if (!garbage) {
2524 Py_DECREF(seq);
2525 PyErr_NoMemory();
2526 return -1;
2527 }
Tim Peters3b01a122002-07-19 02:35:45 +00002528
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002529 selfitems = self->ob_item;
Raymond Hettinger42bec932004-03-12 16:38:17 +00002530 seqitems = PySequence_Fast_ITEMS(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002531 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002532 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002533 garbage[i] = selfitems[cur];
2534 ins = seqitems[i];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002535 Py_INCREF(ins);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002536 selfitems[cur] = ins;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002537 }
2538
2539 for (i = 0; i < slicelength; i++) {
2540 Py_DECREF(garbage[i]);
2541 }
Tim Peters3b01a122002-07-19 02:35:45 +00002542
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002543 PyMem_FREE(garbage);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002544 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002545
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002546 return 0;
2547 }
Tim Peters3b01a122002-07-19 02:35:45 +00002548 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002549 else {
Thomas Wouters89f507f2006-12-13 04:49:30 +00002550 PyErr_Format(PyExc_TypeError,
2551 "list indices must be integers, not %.200s",
2552 item->ob_type->tp_name);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002553 return -1;
2554 }
2555}
2556
2557static PyMappingMethods list_as_mapping = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002558 (lenfunc)list_length,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002559 (binaryfunc)list_subscript,
2560 (objobjargproc)list_ass_subscript
2561};
2562
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002563PyTypeObject PyList_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002564 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002565 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002566 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002567 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002568 (destructor)list_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00002569 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002570 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002571 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00002572 0, /* tp_reserved */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002573 (reprfunc)list_repr, /* tp_repr */
2574 0, /* tp_as_number */
2575 &list_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002576 &list_as_mapping, /* tp_as_mapping */
Nick Coghland1abd252008-07-15 15:46:38 +00002577 (hashfunc)PyObject_HashNotImplemented, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002578 0, /* tp_call */
2579 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002580 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002581 0, /* tp_setattro */
2582 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002583 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Thomas Wouters27d517b2007-02-25 20:39:11 +00002584 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002585 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002586 (traverseproc)list_traverse, /* tp_traverse */
2587 (inquiry)list_clear, /* tp_clear */
2588 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002589 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002590 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002591 0, /* tp_iternext */
2592 list_methods, /* tp_methods */
2593 0, /* tp_members */
2594 0, /* tp_getset */
2595 0, /* tp_base */
2596 0, /* tp_dict */
2597 0, /* tp_descr_get */
2598 0, /* tp_descr_set */
2599 0, /* tp_dictoffset */
2600 (initproc)list_init, /* tp_init */
2601 PyType_GenericAlloc, /* tp_alloc */
2602 PyType_GenericNew, /* tp_new */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002603 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002604};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002605
2606
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002607/*********************** List Iterator **************************/
2608
2609typedef struct {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002610 PyObject_HEAD
2611 long it_index;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002612 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002613} listiterobject;
2614
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002615static PyObject *list_iter(PyObject *);
2616static void listiter_dealloc(listiterobject *);
2617static int listiter_traverse(listiterobject *, visitproc, void *);
2618static PyObject *listiter_next(listiterobject *);
2619static PyObject *listiter_len(listiterobject *);
Raymond Hettinger435bf582004-03-18 22:43:10 +00002620
Armin Rigof5b3e362006-02-11 21:32:43 +00002621PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002622
2623static PyMethodDef listiter_methods[] = {
Armin Rigof5b3e362006-02-11 21:32:43 +00002624 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002625 {NULL, NULL} /* sentinel */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002626};
2627
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002628PyTypeObject PyListIter_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002629 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Christian Heimesf83be4e2007-11-28 09:44:38 +00002630 "list_iterator", /* tp_name */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002631 sizeof(listiterobject), /* tp_basicsize */
2632 0, /* tp_itemsize */
2633 /* methods */
2634 (destructor)listiter_dealloc, /* tp_dealloc */
2635 0, /* tp_print */
2636 0, /* tp_getattr */
2637 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00002638 0, /* tp_reserved */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002639 0, /* tp_repr */
2640 0, /* tp_as_number */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002641 0, /* tp_as_sequence */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002642 0, /* tp_as_mapping */
2643 0, /* tp_hash */
2644 0, /* tp_call */
2645 0, /* tp_str */
2646 PyObject_GenericGetAttr, /* tp_getattro */
2647 0, /* tp_setattro */
2648 0, /* tp_as_buffer */
2649 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2650 0, /* tp_doc */
2651 (traverseproc)listiter_traverse, /* tp_traverse */
2652 0, /* tp_clear */
2653 0, /* tp_richcompare */
2654 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00002655 PyObject_SelfIter, /* tp_iter */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002656 (iternextfunc)listiter_next, /* tp_iternext */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002657 listiter_methods, /* tp_methods */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002658 0, /* tp_members */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002659};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002660
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002661
2662static PyObject *
2663list_iter(PyObject *seq)
2664{
2665 listiterobject *it;
2666
2667 if (!PyList_Check(seq)) {
2668 PyErr_BadInternalCall();
2669 return NULL;
2670 }
2671 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2672 if (it == NULL)
2673 return NULL;
2674 it->it_index = 0;
2675 Py_INCREF(seq);
2676 it->it_seq = (PyListObject *)seq;
2677 _PyObject_GC_TRACK(it);
2678 return (PyObject *)it;
2679}
2680
2681static void
2682listiter_dealloc(listiterobject *it)
2683{
2684 _PyObject_GC_UNTRACK(it);
2685 Py_XDECREF(it->it_seq);
2686 PyObject_GC_Del(it);
2687}
2688
2689static int
2690listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2691{
2692 Py_VISIT(it->it_seq);
2693 return 0;
2694}
2695
2696static PyObject *
2697listiter_next(listiterobject *it)
2698{
2699 PyListObject *seq;
2700 PyObject *item;
2701
2702 assert(it != NULL);
2703 seq = it->it_seq;
2704 if (seq == NULL)
2705 return NULL;
2706 assert(PyList_Check(seq));
2707
2708 if (it->it_index < PyList_GET_SIZE(seq)) {
2709 item = PyList_GET_ITEM(seq, it->it_index);
2710 ++it->it_index;
2711 Py_INCREF(item);
2712 return item;
2713 }
2714
2715 Py_DECREF(seq);
2716 it->it_seq = NULL;
2717 return NULL;
2718}
2719
2720static PyObject *
2721listiter_len(listiterobject *it)
2722{
2723 Py_ssize_t len;
2724 if (it->it_seq) {
2725 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2726 if (len >= 0)
Christian Heimes217cfd12007-12-02 14:31:20 +00002727 return PyLong_FromSsize_t(len);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002728 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002729 return PyLong_FromLong(0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002730}
Raymond Hettinger1021c442003-11-07 15:38:09 +00002731/*********************** List Reverse Iterator **************************/
2732
2733typedef struct {
2734 PyObject_HEAD
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002735 Py_ssize_t it_index;
Raymond Hettinger001f2282003-11-08 11:58:44 +00002736 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002737} listreviterobject;
2738
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002739static PyObject *list_reversed(PyListObject *, PyObject *);
2740static void listreviter_dealloc(listreviterobject *);
2741static int listreviter_traverse(listreviterobject *, visitproc, void *);
2742static PyObject *listreviter_next(listreviterobject *);
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002743static PyObject *listreviter_len(listreviterobject *);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002744
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002745static PyMethodDef listreviter_methods[] = {
2746 {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc},
2747 {NULL, NULL} /* sentinel */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002748};
2749
Raymond Hettinger1021c442003-11-07 15:38:09 +00002750PyTypeObject PyListRevIter_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002751 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Christian Heimesf83be4e2007-11-28 09:44:38 +00002752 "list_reverseiterator", /* tp_name */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002753 sizeof(listreviterobject), /* tp_basicsize */
2754 0, /* tp_itemsize */
2755 /* methods */
2756 (destructor)listreviter_dealloc, /* tp_dealloc */
2757 0, /* tp_print */
2758 0, /* tp_getattr */
2759 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +00002760 0, /* tp_reserved */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002761 0, /* tp_repr */
2762 0, /* tp_as_number */
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002763 0, /* tp_as_sequence */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002764 0, /* tp_as_mapping */
2765 0, /* tp_hash */
2766 0, /* tp_call */
2767 0, /* tp_str */
2768 PyObject_GenericGetAttr, /* tp_getattro */
2769 0, /* tp_setattro */
2770 0, /* tp_as_buffer */
2771 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2772 0, /* tp_doc */
2773 (traverseproc)listreviter_traverse, /* tp_traverse */
2774 0, /* tp_clear */
2775 0, /* tp_richcompare */
2776 0, /* tp_weaklistoffset */
2777 PyObject_SelfIter, /* tp_iter */
2778 (iternextfunc)listreviter_next, /* tp_iternext */
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002779 listreviter_methods, /* tp_methods */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002780 0,
2781};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002782
2783static PyObject *
2784list_reversed(PyListObject *seq, PyObject *unused)
2785{
2786 listreviterobject *it;
2787
2788 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2789 if (it == NULL)
2790 return NULL;
2791 assert(PyList_Check(seq));
2792 it->it_index = PyList_GET_SIZE(seq) - 1;
2793 Py_INCREF(seq);
2794 it->it_seq = seq;
2795 PyObject_GC_Track(it);
2796 return (PyObject *)it;
2797}
2798
2799static void
2800listreviter_dealloc(listreviterobject *it)
2801{
2802 PyObject_GC_UnTrack(it);
2803 Py_XDECREF(it->it_seq);
2804 PyObject_GC_Del(it);
2805}
2806
2807static int
2808listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2809{
2810 Py_VISIT(it->it_seq);
2811 return 0;
2812}
2813
2814static PyObject *
2815listreviter_next(listreviterobject *it)
2816{
2817 PyObject *item;
2818 Py_ssize_t index = it->it_index;
2819 PyListObject *seq = it->it_seq;
2820
2821 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2822 item = PyList_GET_ITEM(seq, index);
2823 it->it_index--;
2824 Py_INCREF(item);
2825 return item;
2826 }
2827 it->it_index = -1;
2828 if (seq != NULL) {
2829 it->it_seq = NULL;
2830 Py_DECREF(seq);
2831 }
2832 return NULL;
2833}
2834
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002835static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002836listreviter_len(listreviterobject *it)
2837{
2838 Py_ssize_t len = it->it_index + 1;
2839 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002840 len = 0;
2841 return PyLong_FromSsize_t(len);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002842}
2843