blob: d6a99b1bfb44708a809b281f23f5cee159a1e086 [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 Heimese93237d2007-12-19 02:37:44 +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 */
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000048 new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6) + newsize;
49 if (newsize == 0)
50 new_allocated = 0;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000051 items = self->ob_item;
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000052 if (new_allocated <= ((~(size_t)0) / sizeof(PyObject *)))
53 PyMem_RESIZE(items, PyObject *, new_allocated);
Raymond Hettinger4bb95402004-02-13 11:36:39 +000054 else
55 items = NULL;
56 if (items == NULL) {
57 PyErr_NoMemory();
58 return -1;
59 }
60 self->ob_item = items;
Christian Heimese93237d2007-12-19 02:37:44 +000061 Py_SIZE(self) = newsize;
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000062 self->allocated = new_allocated;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000063 return 0;
64}
Guido van Rossuma46d51d1995-01-26 22:59:43 +000065
Christian Heimesb4ee4a12008-02-07 17:15:30 +000066/* Debug statistic to compare allocations with reuse through the free list */
67#undef SHOW_ALLOC_COUNT
68#ifdef SHOW_ALLOC_COUNT
69static size_t count_alloc = 0;
70static size_t count_reuse = 0;
71
72static void
73show_alloc(void)
74{
75 fprintf(stderr, "List allocations: %zd\n", count_alloc);
76 fprintf(stderr, "List reuse through freelist: %zd\n", count_reuse);
77 fprintf(stderr, "%.2f%% reuse rate\n\n",
78 (100.0*count_reuse/(count_alloc+count_reuse)));
79}
80#endif
81
Raymond Hettinger0468e412004-05-05 05:37:53 +000082/* Empty list reuse scheme to save calls to malloc and free */
Christian Heimes5b970ad2008-02-06 13:33:44 +000083#ifndef PyList_MAXFREELIST
84#define PyList_MAXFREELIST 80
85#endif
86static PyListObject *free_list[PyList_MAXFREELIST];
87static int numfree = 0;
Raymond Hettinger0468e412004-05-05 05:37:53 +000088
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +000089void
90PyList_Fini(void)
91{
92 PyListObject *op;
93
Christian Heimes5b970ad2008-02-06 13:33:44 +000094 while (numfree) {
Christian Heimes48397d62008-02-08 00:14:34 +000095 op = free_list[--numfree];
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +000096 assert(PyList_CheckExact(op));
97 PyObject_GC_Del(op);
98 }
99}
100
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000101PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000102PyList_New(Py_ssize_t size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000103{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000104 PyListObject *op;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +0000105 size_t nbytes;
Christian Heimesb4ee4a12008-02-07 17:15:30 +0000106#ifdef SHOW_ALLOC_COUNT
107 static int initialized = 0;
108 if (!initialized) {
109 Py_AtExit(show_alloc);
110 initialized = 1;
111 }
112#endif
Tim Peters3986d4e2004-07-29 02:28:42 +0000113
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000114 if (size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000115 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000116 return NULL;
117 }
Tim Peters7049d812004-01-18 20:31:02 +0000118 nbytes = size * sizeof(PyObject *);
Guido van Rossum1e28e5e1992-08-19 16:46:30 +0000119 /* Check for overflow */
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000120 if (nbytes / sizeof(PyObject *) != (size_t)size)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000121 return PyErr_NoMemory();
Christian Heimes5b970ad2008-02-06 13:33:44 +0000122 if (numfree) {
123 numfree--;
124 op = free_list[numfree];
Raymond Hettinger0468e412004-05-05 05:37:53 +0000125 _Py_NewReference((PyObject *)op);
Christian Heimesb4ee4a12008-02-07 17:15:30 +0000126#ifdef SHOW_ALLOC_COUNT
127 count_reuse++;
128#endif
Raymond Hettinger0468e412004-05-05 05:37:53 +0000129 } else {
130 op = PyObject_GC_New(PyListObject, &PyList_Type);
131 if (op == NULL)
132 return NULL;
Christian Heimesb4ee4a12008-02-07 17:15:30 +0000133#ifdef SHOW_ALLOC_COUNT
134 count_alloc++;
135#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000136 }
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000137 if (size <= 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000138 op->ob_item = NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000139 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +0000140 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
Neal Norwitza00c0b92006-06-12 02:08:41 +0000141 if (op->ob_item == NULL) {
142 Py_DECREF(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000143 return PyErr_NoMemory();
Neal Norwitza00c0b92006-06-12 02:08:41 +0000144 }
Tim Peters3986d4e2004-07-29 02:28:42 +0000145 memset(op->ob_item, 0, nbytes);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000146 }
Christian Heimese93237d2007-12-19 02:37:44 +0000147 Py_SIZE(op) = size;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000148 op->allocated = size;
Neil Schemenauere83c00e2001-08-29 23:54:21 +0000149 _PyObject_GC_TRACK(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000150 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000151}
152
Martin v. Löwis18e16552006-02-15 17:27:45 +0000153Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000154PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000155{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000156 if (!PyList_Check(op)) {
157 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000158 return -1;
159 }
160 else
Christian Heimese93237d2007-12-19 02:37:44 +0000161 return Py_SIZE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000162}
163
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000164static PyObject *indexerr = NULL;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000165
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000166PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000167PyList_GetItem(PyObject *op, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000168{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000169 if (!PyList_Check(op)) {
170 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000171 return NULL;
172 }
Christian Heimese93237d2007-12-19 02:37:44 +0000173 if (i < 0 || i >= Py_SIZE(op)) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000174 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000175 indexerr = PyString_FromString(
176 "list index out of range");
177 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000178 return NULL;
179 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000180 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000181}
182
183int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000184PyList_SetItem(register PyObject *op, register Py_ssize_t i,
Fred Drakea2f55112000-07-09 15:16:51 +0000185 register PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000186{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000187 register PyObject *olditem;
188 register PyObject **p;
189 if (!PyList_Check(op)) {
190 Py_XDECREF(newitem);
191 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000192 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000193 }
Christian Heimese93237d2007-12-19 02:37:44 +0000194 if (i < 0 || i >= Py_SIZE(op)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000195 Py_XDECREF(newitem);
196 PyErr_SetString(PyExc_IndexError,
197 "list assignment index out of range");
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000198 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000199 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000200 p = ((PyListObject *)op) -> ob_item + i;
Guido van Rossum5fe60581995-03-09 12:12:50 +0000201 olditem = *p;
202 *p = newitem;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000203 Py_XDECREF(olditem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000204 return 0;
205}
206
207static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000208ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000209{
Christian Heimese93237d2007-12-19 02:37:44 +0000210 Py_ssize_t i, n = Py_SIZE(self);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000211 PyObject **items;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000212 if (v == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000213 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000214 return -1;
215 }
Martin v. Löwisb1ed7fa2006-04-13 07:52:27 +0000216 if (n == PY_SSIZE_T_MAX) {
Trent Micka5846642000-08-13 22:47:45 +0000217 PyErr_SetString(PyExc_OverflowError,
218 "cannot add more objects to list");
219 return -1;
220 }
Tim Petersb38e2b62004-07-29 02:29:26 +0000221
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000222 if (list_resize(self, n+1) == -1)
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000223 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000224
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000225 if (where < 0) {
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000226 where += n;
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000227 if (where < 0)
228 where = 0;
229 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000230 if (where > n)
231 where = n;
232 items = self->ob_item;
233 for (i = n; --i >= where; )
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000234 items[i+1] = items[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000235 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000236 items[where] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000237 return 0;
238}
239
240int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000241PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000242{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000243 if (!PyList_Check(op)) {
244 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000245 return -1;
246 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000247 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000248}
249
Raymond Hettinger40a03822004-04-12 13:05:09 +0000250static int
251app1(PyListObject *self, PyObject *v)
252{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000253 Py_ssize_t n = PyList_GET_SIZE(self);
Raymond Hettinger40a03822004-04-12 13:05:09 +0000254
255 assert (v != NULL);
Martin v. Löwisb1ed7fa2006-04-13 07:52:27 +0000256 if (n == PY_SSIZE_T_MAX) {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000257 PyErr_SetString(PyExc_OverflowError,
258 "cannot add more objects to list");
259 return -1;
260 }
261
262 if (list_resize(self, n+1) == -1)
263 return -1;
264
265 Py_INCREF(v);
266 PyList_SET_ITEM(self, n, v);
267 return 0;
268}
269
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000270int
Fred Drakea2f55112000-07-09 15:16:51 +0000271PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000272{
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000273 if (PyList_Check(op) && (newitem != NULL))
274 return app1((PyListObject *)op, newitem);
275 PyErr_BadInternalCall();
276 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000277}
278
279/* Methods */
280
281static void
Fred Drakea2f55112000-07-09 15:16:51 +0000282list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000283{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000284 Py_ssize_t i;
Guido van Rossumff413af2002-03-28 20:34:59 +0000285 PyObject_GC_UnTrack(op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000286 Py_TRASHCAN_SAFE_BEGIN(op)
Jack Jansen7874d1f1995-01-19 12:09:27 +0000287 if (op->ob_item != NULL) {
Guido van Rossumfa717011999-06-09 15:19:34 +0000288 /* Do it backwards, for Christian Tismer.
289 There's a simple test case where somehow this reduces
290 thrashing when a *very* large list is created and
291 immediately deleted. */
Christian Heimese93237d2007-12-19 02:37:44 +0000292 i = Py_SIZE(op);
Guido van Rossumfa717011999-06-09 15:19:34 +0000293 while (--i >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000294 Py_XDECREF(op->ob_item[i]);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000295 }
Guido van Rossumb18618d2000-05-03 23:44:39 +0000296 PyMem_FREE(op->ob_item);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000297 }
Christian Heimes5b970ad2008-02-06 13:33:44 +0000298 if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op))
299 free_list[numfree++] = op;
Tim Petersb38e2b62004-07-29 02:29:26 +0000300 else
Christian Heimese93237d2007-12-19 02:37:44 +0000301 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000302 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000303}
304
Guido van Rossum90933611991-06-07 16:10:43 +0000305static int
Fred Drakea2f55112000-07-09 15:16:51 +0000306list_print(PyListObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000307{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000308 int rc;
309 Py_ssize_t i;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000310
Martin v. Löwis18e16552006-02-15 17:27:45 +0000311 rc = Py_ReprEnter((PyObject*)op);
312 if (rc != 0) {
313 if (rc < 0)
314 return rc;
Brett Cannon01531592007-09-17 03:28:34 +0000315 Py_BEGIN_ALLOW_THREADS
Guido van Rossumfb376de1998-04-10 22:47:27 +0000316 fprintf(fp, "[...]");
Brett Cannon01531592007-09-17 03:28:34 +0000317 Py_END_ALLOW_THREADS
Guido van Rossumfb376de1998-04-10 22:47:27 +0000318 return 0;
319 }
Brett Cannon01531592007-09-17 03:28:34 +0000320 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000321 fprintf(fp, "[");
Brett Cannon01531592007-09-17 03:28:34 +0000322 Py_END_ALLOW_THREADS
Christian Heimese93237d2007-12-19 02:37:44 +0000323 for (i = 0; i < Py_SIZE(op); i++) {
Brett Cannon01531592007-09-17 03:28:34 +0000324 if (i > 0) {
325 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000326 fprintf(fp, ", ");
Brett Cannon01531592007-09-17 03:28:34 +0000327 Py_END_ALLOW_THREADS
328 }
Guido van Rossumfb376de1998-04-10 22:47:27 +0000329 if (PyObject_Print(op->ob_item[i], fp, 0) != 0) {
330 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000331 return -1;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000332 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000333 }
Brett Cannon01531592007-09-17 03:28:34 +0000334 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000335 fprintf(fp, "]");
Brett Cannon01531592007-09-17 03:28:34 +0000336 Py_END_ALLOW_THREADS
Guido van Rossumfb376de1998-04-10 22:47:27 +0000337 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000338 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000339}
340
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000341static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000342list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000343{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000344 Py_ssize_t i;
Tim Petersa7259592001-06-16 05:11:17 +0000345 PyObject *s, *temp;
346 PyObject *pieces = NULL, *result = NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000347
348 i = Py_ReprEnter((PyObject*)v);
349 if (i != 0) {
Tim Petersa7259592001-06-16 05:11:17 +0000350 return i > 0 ? PyString_FromString("[...]") : NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000351 }
Tim Petersa7259592001-06-16 05:11:17 +0000352
Christian Heimese93237d2007-12-19 02:37:44 +0000353 if (Py_SIZE(v) == 0) {
Tim Petersa7259592001-06-16 05:11:17 +0000354 result = PyString_FromString("[]");
355 goto Done;
356 }
357
358 pieces = PyList_New(0);
359 if (pieces == NULL)
360 goto Done;
361
362 /* Do repr() on each element. Note that this may mutate the list,
363 so must refetch the list size on each iteration. */
Christian Heimese93237d2007-12-19 02:37:44 +0000364 for (i = 0; i < Py_SIZE(v); ++i) {
Tim Petersa7259592001-06-16 05:11:17 +0000365 int status;
Brett Cannona0c05512007-09-10 21:38:27 +0000366 if (Py_EnterRecursiveCall(" while getting the repr of a list"))
367 goto Done;
Tim Petersa7259592001-06-16 05:11:17 +0000368 s = PyObject_Repr(v->ob_item[i]);
Brett Cannona0c05512007-09-10 21:38:27 +0000369 Py_LeaveRecursiveCall();
Tim Petersa7259592001-06-16 05:11:17 +0000370 if (s == NULL)
371 goto Done;
372 status = PyList_Append(pieces, s);
373 Py_DECREF(s); /* append created a new ref */
374 if (status < 0)
375 goto Done;
376 }
377
378 /* Add "[]" decorations to the first and last items. */
379 assert(PyList_GET_SIZE(pieces) > 0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000380 s = PyString_FromString("[");
Tim Petersa7259592001-06-16 05:11:17 +0000381 if (s == NULL)
382 goto Done;
383 temp = PyList_GET_ITEM(pieces, 0);
384 PyString_ConcatAndDel(&s, temp);
385 PyList_SET_ITEM(pieces, 0, s);
386 if (s == NULL)
387 goto Done;
388
389 s = PyString_FromString("]");
390 if (s == NULL)
391 goto Done;
392 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
393 PyString_ConcatAndDel(&temp, s);
394 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
395 if (temp == NULL)
396 goto Done;
397
398 /* Paste them all together with ", " between. */
399 s = PyString_FromString(", ");
400 if (s == NULL)
401 goto Done;
402 result = _PyString_Join(s, pieces);
Tim Peters3b01a122002-07-19 02:35:45 +0000403 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +0000404
405Done:
406 Py_XDECREF(pieces);
Guido van Rossumfb376de1998-04-10 22:47:27 +0000407 Py_ReprLeave((PyObject *)v);
Tim Petersa7259592001-06-16 05:11:17 +0000408 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000409}
410
Martin v. Löwis18e16552006-02-15 17:27:45 +0000411static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000412list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000413{
Christian Heimese93237d2007-12-19 02:37:44 +0000414 return Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000415}
416
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000417static int
Fred Drakea2f55112000-07-09 15:16:51 +0000418list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000419{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000420 Py_ssize_t i;
421 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000422
Christian Heimese93237d2007-12-19 02:37:44 +0000423 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
Raymond Hettingeraae59992002-09-05 14:23:49 +0000424 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000425 Py_EQ);
Neal Norwitzbb9c5f52002-09-05 21:32:55 +0000426 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000427}
428
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000429static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000430list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000431{
Christian Heimese93237d2007-12-19 02:37:44 +0000432 if (i < 0 || i >= Py_SIZE(a)) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000433 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000434 indexerr = PyString_FromString(
435 "list index out of range");
436 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000437 return NULL;
438 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000439 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000440 return a->ob_item[i];
441}
442
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000443static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000444list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000445{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000446 PyListObject *np;
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000447 PyObject **src, **dest;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000448 Py_ssize_t i, len;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000449 if (ilow < 0)
450 ilow = 0;
Christian Heimese93237d2007-12-19 02:37:44 +0000451 else if (ilow > Py_SIZE(a))
452 ilow = Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000453 if (ihigh < ilow)
454 ihigh = ilow;
Christian Heimese93237d2007-12-19 02:37:44 +0000455 else if (ihigh > Py_SIZE(a))
456 ihigh = Py_SIZE(a);
Raymond Hettinger99842b62004-03-08 05:56:15 +0000457 len = ihigh - ilow;
458 np = (PyListObject *) PyList_New(len);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000459 if (np == NULL)
460 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000461
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000462 src = a->ob_item + ilow;
463 dest = np->ob_item;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000464 for (i = 0; i < len; i++) {
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000465 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000466 Py_INCREF(v);
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000467 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000468 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000469 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000470}
471
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000472PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000473PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000474{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000475 if (!PyList_Check(a)) {
476 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000477 return NULL;
478 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000479 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000480}
481
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000482static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000483list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000484{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000485 Py_ssize_t size;
486 Py_ssize_t i;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000487 PyObject **src, **dest;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000488 PyListObject *np;
489 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000490 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000491 "can only concatenate list (not \"%.200s\") to list",
492 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000493 return NULL;
494 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000495#define b ((PyListObject *)bb)
Christian Heimese93237d2007-12-19 02:37:44 +0000496 size = Py_SIZE(a) + Py_SIZE(b);
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000497 if (size < 0)
498 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000499 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000500 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000501 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000502 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000503 src = a->ob_item;
504 dest = np->ob_item;
Christian Heimese93237d2007-12-19 02:37:44 +0000505 for (i = 0; i < Py_SIZE(a); i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000506 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000507 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000508 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000509 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000510 src = b->ob_item;
Christian Heimese93237d2007-12-19 02:37:44 +0000511 dest = np->ob_item + Py_SIZE(a);
512 for (i = 0; i < Py_SIZE(b); i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000513 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000514 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000515 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000516 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000517 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000518#undef b
519}
520
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000521static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000522list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000523{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000524 Py_ssize_t i, j;
525 Py_ssize_t size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000526 PyListObject *np;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000527 PyObject **p, **items;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000528 PyObject *elem;
Guido van Rossumed98d481991-03-06 13:07:53 +0000529 if (n < 0)
530 n = 0;
Christian Heimese93237d2007-12-19 02:37:44 +0000531 size = Py_SIZE(a) * n;
532 if (n && size/n != Py_SIZE(a))
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000533 return PyErr_NoMemory();
Armin Rigoa1e42e12007-10-17 18:46:37 +0000534 if (size == 0)
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000535 return PyList_New(0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000536 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000537 if (np == NULL)
538 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000539
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000540 items = np->ob_item;
Christian Heimese93237d2007-12-19 02:37:44 +0000541 if (Py_SIZE(a) == 1) {
Raymond Hettinger6624e682003-05-21 05:58:46 +0000542 elem = a->ob_item[0];
543 for (i = 0; i < n; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000544 items[i] = elem;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000545 Py_INCREF(elem);
546 }
547 return (PyObject *) np;
548 }
Guido van Rossumed98d481991-03-06 13:07:53 +0000549 p = np->ob_item;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000550 items = a->ob_item;
Guido van Rossumed98d481991-03-06 13:07:53 +0000551 for (i = 0; i < n; i++) {
Christian Heimese93237d2007-12-19 02:37:44 +0000552 for (j = 0; j < Py_SIZE(a); j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000553 *p = items[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000554 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000555 p++;
556 }
557 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000558 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000559}
560
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000561static int
Armin Rigo93677f02004-07-29 12:40:23 +0000562list_clear(PyListObject *a)
563{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000564 Py_ssize_t i;
Armin Rigo93677f02004-07-29 12:40:23 +0000565 PyObject **item = a->ob_item;
566 if (item != NULL) {
567 /* Because XDECREF can recursively invoke operations on
568 this list, we make it empty first. */
Christian Heimese93237d2007-12-19 02:37:44 +0000569 i = Py_SIZE(a);
570 Py_SIZE(a) = 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000571 a->ob_item = NULL;
572 a->allocated = 0;
573 while (--i >= 0) {
574 Py_XDECREF(item[i]);
575 }
576 PyMem_FREE(item);
577 }
578 /* Never fails; the return value can be ignored.
579 Note that there is no guarantee that the list is actually empty
580 at this point, because XDECREF may have populated it again! */
581 return 0;
582}
583
Tim Peters8fc4a912004-07-31 21:53:19 +0000584/* a[ilow:ihigh] = v if v != NULL.
585 * del a[ilow:ihigh] if v == NULL.
586 *
587 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
588 * guaranteed the call cannot fail.
589 */
Armin Rigo93677f02004-07-29 12:40:23 +0000590static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000591list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000592{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000593 /* Because [X]DECREF can recursively invoke list operations on
594 this list, we must postpone all [X]DECREF activity until
595 after the list is back in its canonical shape. Therefore
596 we must allocate an additional array, 'recycle', into which
597 we temporarily copy the items that are deleted from the
598 list. :-( */
Tim Peters73572222004-07-31 02:54:42 +0000599 PyObject *recycle_on_stack[8];
600 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000601 PyObject **item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000602 PyObject **vitem = NULL;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000603 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000604 Py_ssize_t n; /* # of elements in replacement list */
605 Py_ssize_t norig; /* # of elements in list getting replaced */
606 Py_ssize_t d; /* Change in size */
607 Py_ssize_t k;
Tim Peters8d9eb102004-07-31 02:24:20 +0000608 size_t s;
609 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000610#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000611 if (v == NULL)
612 n = 0;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000613 else {
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000614 if (a == b) {
615 /* Special case "a[i:j] = a" -- copy b first */
Christian Heimese93237d2007-12-19 02:37:44 +0000616 v = list_slice(b, 0, Py_SIZE(b));
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000617 if (v == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000618 return result;
619 result = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000620 Py_DECREF(v);
Tim Peters8d9eb102004-07-31 02:24:20 +0000621 return result;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000622 }
Raymond Hettingerf889e102004-03-09 08:04:33 +0000623 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000624 if(v_as_SF == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000625 goto Error;
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000626 n = PySequence_Fast_GET_SIZE(v_as_SF);
Raymond Hettinger42bec932004-03-12 16:38:17 +0000627 vitem = PySequence_Fast_ITEMS(v_as_SF);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000628 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000629 if (ilow < 0)
630 ilow = 0;
Christian Heimese93237d2007-12-19 02:37:44 +0000631 else if (ilow > Py_SIZE(a))
632 ilow = Py_SIZE(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000633
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000634 if (ihigh < ilow)
635 ihigh = ilow;
Christian Heimese93237d2007-12-19 02:37:44 +0000636 else if (ihigh > Py_SIZE(a))
637 ihigh = Py_SIZE(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000638
Tim Peters8d9eb102004-07-31 02:24:20 +0000639 norig = ihigh - ilow;
640 assert(norig >= 0);
641 d = n - norig;
Christian Heimese93237d2007-12-19 02:37:44 +0000642 if (Py_SIZE(a) + d == 0) {
Armin Rigo93677f02004-07-29 12:40:23 +0000643 Py_XDECREF(v_as_SF);
644 return list_clear(a);
645 }
646 item = a->ob_item;
Tim Peters8d9eb102004-07-31 02:24:20 +0000647 /* recycle the items that we are about to remove */
648 s = norig * sizeof(PyObject *);
Tim Peters73572222004-07-31 02:54:42 +0000649 if (s > sizeof(recycle_on_stack)) {
Armin Rigo1dd04a02004-07-30 11:38:22 +0000650 recycle = (PyObject **)PyMem_MALLOC(s);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000651 if (recycle == NULL) {
652 PyErr_NoMemory();
Tim Peters8d9eb102004-07-31 02:24:20 +0000653 goto Error;
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000654 }
655 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000656 memcpy(recycle, &item[ilow], s);
Tim Peters8d9eb102004-07-31 02:24:20 +0000657
Armin Rigo1dd04a02004-07-30 11:38:22 +0000658 if (d < 0) { /* Delete -d items */
659 memmove(&item[ihigh+d], &item[ihigh],
Christian Heimese93237d2007-12-19 02:37:44 +0000660 (Py_SIZE(a) - ihigh)*sizeof(PyObject *));
661 list_resize(a, Py_SIZE(a) + d);
Armin Rigo1dd04a02004-07-30 11:38:22 +0000662 item = a->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000663 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000664 else if (d > 0) { /* Insert d items */
Christian Heimese93237d2007-12-19 02:37:44 +0000665 k = Py_SIZE(a);
Tim Peters73572222004-07-31 02:54:42 +0000666 if (list_resize(a, k+d) < 0)
Tim Peters8d9eb102004-07-31 02:24:20 +0000667 goto Error;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000668 item = a->ob_item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000669 memmove(&item[ihigh+d], &item[ihigh],
Tim Peters73572222004-07-31 02:54:42 +0000670 (k - ihigh)*sizeof(PyObject *));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000671 }
672 for (k = 0; k < n; k++, ilow++) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000673 PyObject *w = vitem[k];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000674 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000675 item[ilow] = w;
676 }
Tim Peters73572222004-07-31 02:54:42 +0000677 for (k = norig - 1; k >= 0; --k)
678 Py_XDECREF(recycle[k]);
Tim Peters8d9eb102004-07-31 02:24:20 +0000679 result = 0;
680 Error:
Tim Peters73572222004-07-31 02:54:42 +0000681 if (recycle != recycle_on_stack)
Armin Rigo1dd04a02004-07-30 11:38:22 +0000682 PyMem_FREE(recycle);
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000683 Py_XDECREF(v_as_SF);
Tim Peters8d9eb102004-07-31 02:24:20 +0000684 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000685#undef b
686}
687
Guido van Rossum234f9421993-06-17 12:35:49 +0000688int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000689PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000690{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000691 if (!PyList_Check(a)) {
692 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000693 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000694 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000695 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000696}
697
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000698static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000699list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000700{
701 PyObject **items;
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000702 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000703
704
705 size = PyList_GET_SIZE(self);
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000706 if (size == 0 || n == 1) {
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000707 Py_INCREF(self);
708 return (PyObject *)self;
709 }
710
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000711 if (n < 1) {
Armin Rigo93677f02004-07-29 12:40:23 +0000712 (void)list_clear(self);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000713 Py_INCREF(self);
714 return (PyObject *)self;
715 }
716
Thomas Woutersa97744c2008-01-25 21:09:34 +0000717 if (size > PY_SSIZE_T_MAX / n) {
Armin Rigoa1e42e12007-10-17 18:46:37 +0000718 return PyErr_NoMemory();
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000719 }
720
721 if (list_resize(self, size*n) == -1)
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000722 return NULL;
723
724 p = size;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000725 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000726 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
727 for (j = 0; j < size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000728 PyObject *o = items[j];
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000729 Py_INCREF(o);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000730 items[p++] = o;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000731 }
732 }
733 Py_INCREF(self);
734 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000735}
736
Guido van Rossum4a450d01991-04-03 19:05:18 +0000737static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000738list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000739{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000740 PyObject *old_value;
Christian Heimese93237d2007-12-19 02:37:44 +0000741 if (i < 0 || i >= Py_SIZE(a)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000742 PyErr_SetString(PyExc_IndexError,
743 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000744 return -1;
745 }
746 if (v == NULL)
747 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000748 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000749 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000750 a->ob_item[i] = v;
Tim Peters3b01a122002-07-19 02:35:45 +0000751 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000752 return 0;
753}
754
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000755static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000756listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000757{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000758 Py_ssize_t i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000759 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000760 if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000761 return NULL;
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000762 if (ins1(self, i, v) == 0)
763 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000764 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000765}
766
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000767static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000768listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000769{
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000770 if (app1(self, v) == 0)
771 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000772 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000773}
774
Barry Warsawdedf6d61998-10-09 16:37:25 +0000775static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000776listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000777{
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000778 PyObject *it; /* iter(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000779 Py_ssize_t m; /* size of self */
780 Py_ssize_t n; /* guess for size of b */
781 Py_ssize_t mn; /* m + n */
782 Py_ssize_t i;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000783 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000784
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000785 /* Special cases:
Tim Petersb38e2b62004-07-29 02:29:26 +0000786 1) lists and tuples which can use PySequence_Fast ops
787 2) extending self to self requires making a copy first
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000788 */
789 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
Armin Rigo70d172d2004-03-20 22:19:23 +0000790 PyObject **src, **dest;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000791 b = PySequence_Fast(b, "argument must be iterable");
792 if (!b)
793 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000794 n = PySequence_Fast_GET_SIZE(b);
795 if (n == 0) {
796 /* short circuit when b is empty */
797 Py_DECREF(b);
798 Py_RETURN_NONE;
799 }
Christian Heimese93237d2007-12-19 02:37:44 +0000800 m = Py_SIZE(self);
Armin Rigo70d172d2004-03-20 22:19:23 +0000801 if (list_resize(self, m + n) == -1) {
802 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000803 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000804 }
805 /* note that we may still have self == b here for the
806 * situation a.extend(a), but the following code works
807 * in that case too. Just make sure to resize self
808 * before calling PySequence_Fast_ITEMS.
809 */
810 /* populate the end of self with b's items */
811 src = PySequence_Fast_ITEMS(b);
812 dest = self->ob_item + m;
813 for (i = 0; i < n; i++) {
814 PyObject *o = src[i];
815 Py_INCREF(o);
816 dest[i] = o;
817 }
818 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000819 Py_RETURN_NONE;
820 }
821
822 it = PyObject_GetIter(b);
823 if (it == NULL)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000824 return NULL;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000825 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000826
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000827 /* Guess a result list size. */
Raymond Hettinger4e2f7142007-12-06 00:56:53 +0000828 n = _PyObject_LengthHint(b, 8);
Christian Heimese93237d2007-12-19 02:37:44 +0000829 m = Py_SIZE(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000830 mn = m + n;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000831 if (mn >= m) {
832 /* Make room. */
833 if (list_resize(self, mn) == -1)
834 goto error;
835 /* Make the list sane again. */
Christian Heimese93237d2007-12-19 02:37:44 +0000836 Py_SIZE(self) = m;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000837 }
838 /* Else m + n overflowed; on the chance that n lied, and there really
839 * is enough room, ignore it. If n was telling the truth, we'll
840 * eventually run out of memory during the loop.
841 */
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000842
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000843 /* Run iterator to exhaustion. */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000844 for (;;) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000845 PyObject *item = iternext(it);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000846 if (item == NULL) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000847 if (PyErr_Occurred()) {
848 if (PyErr_ExceptionMatches(PyExc_StopIteration))
849 PyErr_Clear();
850 else
851 goto error;
852 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000853 break;
854 }
Christian Heimese93237d2007-12-19 02:37:44 +0000855 if (Py_SIZE(self) < self->allocated) {
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000856 /* steals ref */
Christian Heimese93237d2007-12-19 02:37:44 +0000857 PyList_SET_ITEM(self, Py_SIZE(self), item);
858 ++Py_SIZE(self);
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000859 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000860 else {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000861 int status = app1(self, item);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000862 Py_DECREF(item); /* append creates a new ref */
863 if (status < 0)
864 goto error;
865 }
866 }
867
868 /* Cut back result list if initial guess was too large. */
Christian Heimese93237d2007-12-19 02:37:44 +0000869 if (Py_SIZE(self) < self->allocated)
870 list_resize(self, Py_SIZE(self)); /* shrinking can't fail */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000871
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000872 Py_DECREF(it);
873 Py_RETURN_NONE;
874
875 error:
876 Py_DECREF(it);
877 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000878}
879
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000880PyObject *
881_PyList_Extend(PyListObject *self, PyObject *b)
882{
883 return listextend(self, b);
884}
885
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000886static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000887list_inplace_concat(PyListObject *self, PyObject *other)
888{
889 PyObject *result;
890
891 result = listextend(self, other);
892 if (result == NULL)
893 return result;
894 Py_DECREF(result);
895 Py_INCREF(self);
896 return (PyObject *)self;
897}
898
899static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000900listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000901{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000902 Py_ssize_t i = -1;
Armin Rigo7ccbca92006-10-04 12:17:45 +0000903 PyObject *v;
Tim Peters8fc4a912004-07-31 21:53:19 +0000904 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000905
Armin Rigo7ccbca92006-10-04 12:17:45 +0000906 if (!PyArg_ParseTuple(args, "|n:pop", &i))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000907 return NULL;
Armin Rigo7ccbca92006-10-04 12:17:45 +0000908
Christian Heimese93237d2007-12-19 02:37:44 +0000909 if (Py_SIZE(self) == 0) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000910 /* Special-case most common failure cause */
911 PyErr_SetString(PyExc_IndexError, "pop from empty list");
912 return NULL;
913 }
914 if (i < 0)
Christian Heimese93237d2007-12-19 02:37:44 +0000915 i += Py_SIZE(self);
916 if (i < 0 || i >= Py_SIZE(self)) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000917 PyErr_SetString(PyExc_IndexError, "pop index out of range");
918 return NULL;
919 }
920 v = self->ob_item[i];
Christian Heimese93237d2007-12-19 02:37:44 +0000921 if (i == Py_SIZE(self) - 1) {
922 status = list_resize(self, Py_SIZE(self) - 1);
Tim Peters8fc4a912004-07-31 21:53:19 +0000923 assert(status >= 0);
924 return v; /* and v now owns the reference the list had */
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000925 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000926 Py_INCREF(v);
Tim Peters8fc4a912004-07-31 21:53:19 +0000927 status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
928 assert(status >= 0);
929 /* Use status, so that in a release build compilers don't
930 * complain about the unused name.
931 */
Brett Cannon651dd522004-08-08 21:21:18 +0000932 (void) status;
933
934 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000935}
936
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000937/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
938static void
939reverse_slice(PyObject **lo, PyObject **hi)
940{
941 assert(lo && hi);
942
943 --hi;
944 while (lo < hi) {
945 PyObject *t = *lo;
946 *lo = *hi;
947 *hi = t;
948 ++lo;
949 --hi;
950 }
951}
952
Tim Petersa64dc242002-08-01 02:13:36 +0000953/* Lots of code for an adaptive, stable, natural mergesort. There are many
954 * pieces to this algorithm; read listsort.txt for overviews and details.
955 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000956
Guido van Rossum3f236de1996-12-10 23:55:39 +0000957/* Comparison function. Takes care of calling a user-supplied
Tim Peters66860f62002-08-04 17:47:26 +0000958 * comparison function (any callable Python object), which must not be
959 * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool
960 * with Py_LT if you know it's NULL).
Tim Petersa64dc242002-08-01 02:13:36 +0000961 * Returns -1 on error, 1 if x < y, 0 if x >= y.
962 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000963static int
Tim Petersa8c974c2002-07-19 03:30:57 +0000964islt(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000965{
Tim Petersf2a04732002-07-11 21:46:16 +0000966 PyObject *res;
967 PyObject *args;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000968 Py_ssize_t i;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000969
Tim Peters66860f62002-08-04 17:47:26 +0000970 assert(compare != NULL);
Tim Petersa8c974c2002-07-19 03:30:57 +0000971 /* Call the user's comparison function and translate the 3-way
972 * result into true or false (or error).
973 */
Tim Petersf2a04732002-07-11 21:46:16 +0000974 args = PyTuple_New(2);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000975 if (args == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000976 return -1;
Tim Petersf2a04732002-07-11 21:46:16 +0000977 Py_INCREF(x);
978 Py_INCREF(y);
979 PyTuple_SET_ITEM(args, 0, x);
980 PyTuple_SET_ITEM(args, 1, y);
Tim Peters58cf3612002-07-15 05:16:13 +0000981 res = PyObject_Call(compare, args, NULL);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000982 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000983 if (res == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000984 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000985 if (!PyInt_Check(res)) {
Georg Brandl283a1352006-11-19 08:48:30 +0000986 PyErr_Format(PyExc_TypeError,
987 "comparison function must return int, not %.200s",
988 res->ob_type->tp_name);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000989 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +0000990 return -1;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000991 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000992 i = PyInt_AsLong(res);
993 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +0000994 return i < 0;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000995}
996
Tim Peters66860f62002-08-04 17:47:26 +0000997/* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
998 * islt. This avoids a layer of function call in the usual case, and
999 * sorting does many comparisons.
1000 * Returns -1 on error, 1 if x < y, 0 if x >= y.
1001 */
1002#define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
1003 PyObject_RichCompareBool(X, Y, Py_LT) : \
1004 islt(X, Y, COMPARE))
1005
1006/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +00001007 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
1008 started. It makes more sense in context <wink>. X and Y are PyObject*s.
1009*/
Tim Peters66860f62002-08-04 17:47:26 +00001010#define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
Tim Petersa8c974c2002-07-19 03:30:57 +00001011 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001012
1013/* binarysort is the best method for sorting small arrays: it does
1014 few compares, but can do data movement quadratic in the number of
1015 elements.
Guido van Rossum42812581998-06-17 14:15:44 +00001016 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +00001017 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001018 On entry, must have lo <= start <= hi, and that [lo, start) is already
1019 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +00001020 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001021 Even in case of error, the output slice will be some permutation of
1022 the input (nothing is lost or duplicated).
1023*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00001024static int
Fred Drakea2f55112000-07-09 15:16:51 +00001025binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
1026 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001027{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001028 register Py_ssize_t k;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001029 register PyObject **l, **p, **r;
1030 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001031
Tim Petersa8c974c2002-07-19 03:30:57 +00001032 assert(lo <= start && start <= hi);
1033 /* assert [lo, start) is sorted */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001034 if (lo == start)
1035 ++start;
1036 for (; start < hi; ++start) {
1037 /* set l to where *start belongs */
1038 l = lo;
1039 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001040 pivot = *r;
Tim Peters0fe977c2002-07-19 06:12:32 +00001041 /* Invariants:
1042 * pivot >= all in [lo, l).
1043 * pivot < all in [r, start).
1044 * The second is vacuously true at the start.
1045 */
1046 assert(l < r);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001047 do {
1048 p = l + ((r - l) >> 1);
Tim Petersa8c974c2002-07-19 03:30:57 +00001049 IFLT(pivot, *p)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001050 r = p;
1051 else
Tim Peters0fe977c2002-07-19 06:12:32 +00001052 l = p+1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001053 } while (l < r);
Tim Peters0fe977c2002-07-19 06:12:32 +00001054 assert(l == r);
1055 /* The invariants still hold, so pivot >= all in [lo, l) and
1056 pivot < all in [l, start), so pivot belongs at l. Note
1057 that if there are elements equal to pivot, l points to the
1058 first slot after them -- that's why this sort is stable.
1059 Slide over to make room.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001060 Caution: using memmove is much slower under MSVC 5;
1061 we're not usually moving many slots. */
1062 for (p = start; p > l; --p)
1063 *p = *(p-1);
1064 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001065 }
Guido van Rossum3f236de1996-12-10 23:55:39 +00001066 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001067
1068 fail:
1069 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001070}
1071
Tim Petersa64dc242002-08-01 02:13:36 +00001072/*
1073Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1074is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001075
Tim Petersa64dc242002-08-01 02:13:36 +00001076 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001077
Tim Petersa64dc242002-08-01 02:13:36 +00001078or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001079
Tim Petersa64dc242002-08-01 02:13:36 +00001080 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001081
Tim Petersa64dc242002-08-01 02:13:36 +00001082Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1083For its intended use in a stable mergesort, the strictness of the defn of
1084"descending" is needed so that the caller can safely reverse a descending
1085sequence without violating stability (strict > ensures there are no equal
1086elements to get out of order).
1087
1088Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001089*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001090static Py_ssize_t
Tim Petersa64dc242002-08-01 02:13:36 +00001091count_run(PyObject **lo, PyObject **hi, PyObject *compare, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001092{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001093 Py_ssize_t k;
1094 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001095
Tim Petersa64dc242002-08-01 02:13:36 +00001096 assert(lo < hi);
1097 *descending = 0;
1098 ++lo;
1099 if (lo == hi)
1100 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001101
Tim Petersa64dc242002-08-01 02:13:36 +00001102 n = 2;
1103 IFLT(*lo, *(lo-1)) {
1104 *descending = 1;
1105 for (lo = lo+1; lo < hi; ++lo, ++n) {
1106 IFLT(*lo, *(lo-1))
1107 ;
1108 else
1109 break;
1110 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001111 }
Tim Petersa64dc242002-08-01 02:13:36 +00001112 else {
1113 for (lo = lo+1; lo < hi; ++lo, ++n) {
1114 IFLT(*lo, *(lo-1))
1115 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001116 }
1117 }
1118
Tim Petersa64dc242002-08-01 02:13:36 +00001119 return n;
1120fail:
1121 return -1;
1122}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001123
Tim Petersa64dc242002-08-01 02:13:36 +00001124/*
1125Locate the proper position of key in a sorted vector; if the vector contains
1126an element equal to key, return the position immediately to the left of
1127the leftmost equal element. [gallop_right() does the same except returns
1128the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001129
Tim Petersa64dc242002-08-01 02:13:36 +00001130"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001131
Tim Petersa64dc242002-08-01 02:13:36 +00001132"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1133hint is to the final result, the faster this runs.
1134
1135The return value is the int k in 0..n such that
1136
1137 a[k-1] < key <= a[k]
1138
1139pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1140key belongs at index k; or, IOW, the first k elements of a should precede
1141key, and the last n-k should follow key.
1142
1143Returns -1 on error. See listsort.txt for info on the method.
1144*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001145static Py_ssize_t
1146gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
Tim Petersa64dc242002-08-01 02:13:36 +00001147{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001148 Py_ssize_t ofs;
1149 Py_ssize_t lastofs;
1150 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001151
1152 assert(key && a && n > 0 && hint >= 0 && hint < n);
1153
1154 a += hint;
1155 lastofs = 0;
1156 ofs = 1;
1157 IFLT(*a, key) {
1158 /* a[hint] < key -- gallop right, until
1159 * a[hint + lastofs] < key <= a[hint + ofs]
1160 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001161 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001162 while (ofs < maxofs) {
1163 IFLT(a[ofs], key) {
1164 lastofs = ofs;
1165 ofs = (ofs << 1) + 1;
1166 if (ofs <= 0) /* int overflow */
1167 ofs = maxofs;
1168 }
1169 else /* key <= a[hint + ofs] */
1170 break;
1171 }
1172 if (ofs > maxofs)
1173 ofs = maxofs;
1174 /* Translate back to offsets relative to &a[0]. */
1175 lastofs += hint;
1176 ofs += hint;
1177 }
1178 else {
1179 /* key <= a[hint] -- gallop left, until
1180 * a[hint - ofs] < key <= a[hint - lastofs]
1181 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001182 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001183 while (ofs < maxofs) {
1184 IFLT(*(a-ofs), key)
1185 break;
1186 /* key <= a[hint - ofs] */
1187 lastofs = ofs;
1188 ofs = (ofs << 1) + 1;
1189 if (ofs <= 0) /* int overflow */
1190 ofs = maxofs;
1191 }
1192 if (ofs > maxofs)
1193 ofs = maxofs;
1194 /* Translate back to positive offsets relative to &a[0]. */
1195 k = lastofs;
1196 lastofs = hint - ofs;
1197 ofs = hint - k;
1198 }
1199 a -= hint;
1200
1201 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1202 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1203 * right of lastofs but no farther right than ofs. Do a binary
1204 * search, with invariant a[lastofs-1] < key <= a[ofs].
1205 */
1206 ++lastofs;
1207 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001208 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001209
1210 IFLT(a[m], key)
1211 lastofs = m+1; /* a[m] < key */
1212 else
1213 ofs = m; /* key <= a[m] */
1214 }
1215 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1216 return ofs;
1217
1218fail:
1219 return -1;
1220}
1221
1222/*
1223Exactly like gallop_left(), except that if key already exists in a[0:n],
1224finds the position immediately to the right of the rightmost equal value.
1225
1226The return value is the int k in 0..n such that
1227
1228 a[k-1] <= key < a[k]
1229
1230or -1 if error.
1231
1232The code duplication is massive, but this is enough different given that
1233we're sticking to "<" comparisons that it's much harder to follow if
1234written as one routine with yet another "left or right?" flag.
1235*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001236static Py_ssize_t
1237gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
Tim Petersa64dc242002-08-01 02:13:36 +00001238{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001239 Py_ssize_t ofs;
1240 Py_ssize_t lastofs;
1241 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001242
1243 assert(key && a && n > 0 && hint >= 0 && hint < n);
1244
1245 a += hint;
1246 lastofs = 0;
1247 ofs = 1;
1248 IFLT(key, *a) {
1249 /* key < a[hint] -- gallop left, until
1250 * a[hint - ofs] <= key < a[hint - lastofs]
1251 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001252 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001253 while (ofs < maxofs) {
1254 IFLT(key, *(a-ofs)) {
1255 lastofs = ofs;
1256 ofs = (ofs << 1) + 1;
1257 if (ofs <= 0) /* int overflow */
1258 ofs = maxofs;
1259 }
1260 else /* a[hint - ofs] <= key */
1261 break;
1262 }
1263 if (ofs > maxofs)
1264 ofs = maxofs;
1265 /* Translate back to positive offsets relative to &a[0]. */
1266 k = lastofs;
1267 lastofs = hint - ofs;
1268 ofs = hint - k;
1269 }
1270 else {
1271 /* a[hint] <= key -- gallop right, until
1272 * a[hint + lastofs] <= key < a[hint + ofs]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001273 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001274 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001275 while (ofs < maxofs) {
1276 IFLT(key, a[ofs])
1277 break;
1278 /* a[hint + ofs] <= key */
1279 lastofs = ofs;
1280 ofs = (ofs << 1) + 1;
1281 if (ofs <= 0) /* int overflow */
1282 ofs = maxofs;
1283 }
1284 if (ofs > maxofs)
1285 ofs = maxofs;
1286 /* Translate back to offsets relative to &a[0]. */
1287 lastofs += hint;
1288 ofs += hint;
1289 }
1290 a -= hint;
1291
1292 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1293 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1294 * right of lastofs but no farther right than ofs. Do a binary
1295 * search, with invariant a[lastofs-1] <= key < a[ofs].
1296 */
1297 ++lastofs;
1298 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001299 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001300
1301 IFLT(key, a[m])
1302 ofs = m; /* key < a[m] */
1303 else
1304 lastofs = m+1; /* a[m] <= key */
1305 }
1306 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1307 return ofs;
1308
1309fail:
1310 return -1;
1311}
1312
1313/* The maximum number of entries in a MergeState's pending-runs stack.
1314 * This is enough to sort arrays of size up to about
1315 * 32 * phi ** MAX_MERGE_PENDING
1316 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1317 * with 2**64 elements.
1318 */
1319#define MAX_MERGE_PENDING 85
1320
Tim Peterse05f65a2002-08-10 05:21:15 +00001321/* When we get into galloping mode, we stay there until both runs win less
1322 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001323 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001324#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001325
1326/* Avoid malloc for small temp arrays. */
1327#define MERGESTATE_TEMP_SIZE 256
1328
1329/* One MergeState exists on the stack per invocation of mergesort. It's just
1330 * a convenient way to pass state around among the helper functions.
1331 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001332struct s_slice {
1333 PyObject **base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001334 Py_ssize_t len;
Tim Peterse05f65a2002-08-10 05:21:15 +00001335};
1336
Tim Petersa64dc242002-08-01 02:13:36 +00001337typedef struct s_MergeState {
1338 /* The user-supplied comparison function. or NULL if none given. */
1339 PyObject *compare;
1340
Tim Peterse05f65a2002-08-10 05:21:15 +00001341 /* This controls when we get *into* galloping mode. It's initialized
1342 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1343 * random data, and lower for highly structured data.
1344 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001345 Py_ssize_t min_gallop;
Tim Peterse05f65a2002-08-10 05:21:15 +00001346
Tim Petersa64dc242002-08-01 02:13:36 +00001347 /* 'a' is temp storage to help with merges. It contains room for
1348 * alloced entries.
1349 */
1350 PyObject **a; /* may point to temparray below */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001351 Py_ssize_t alloced;
Tim Petersa64dc242002-08-01 02:13:36 +00001352
1353 /* A stack of n pending runs yet to be merged. Run #i starts at
1354 * address base[i] and extends for len[i] elements. It's always
1355 * true (so long as the indices are in bounds) that
1356 *
Tim Peterse05f65a2002-08-10 05:21:15 +00001357 * pending[i].base + pending[i].len == pending[i+1].base
Tim Petersa64dc242002-08-01 02:13:36 +00001358 *
1359 * so we could cut the storage for this, but it's a minor amount,
1360 * and keeping all the info explicit simplifies the code.
1361 */
1362 int n;
Tim Peterse05f65a2002-08-10 05:21:15 +00001363 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001364
1365 /* 'a' points to this when possible, rather than muck with malloc. */
1366 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1367} MergeState;
1368
1369/* Conceptually a MergeState's constructor. */
1370static void
1371merge_init(MergeState *ms, PyObject *compare)
1372{
1373 assert(ms != NULL);
1374 ms->compare = compare;
1375 ms->a = ms->temparray;
1376 ms->alloced = MERGESTATE_TEMP_SIZE;
1377 ms->n = 0;
Tim Peterse05f65a2002-08-10 05:21:15 +00001378 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001379}
1380
1381/* Free all the temp memory owned by the MergeState. This must be called
1382 * when you're done with a MergeState, and may be called before then if
1383 * you want to free the temp memory early.
1384 */
1385static void
1386merge_freemem(MergeState *ms)
1387{
1388 assert(ms != NULL);
1389 if (ms->a != ms->temparray)
1390 PyMem_Free(ms->a);
1391 ms->a = ms->temparray;
1392 ms->alloced = MERGESTATE_TEMP_SIZE;
1393}
1394
1395/* Ensure enough temp memory for 'need' array slots is available.
1396 * Returns 0 on success and -1 if the memory can't be gotten.
1397 */
1398static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001399merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001400{
1401 assert(ms != NULL);
1402 if (need <= ms->alloced)
1403 return 0;
1404 /* Don't realloc! That can cost cycles to copy the old data, but
1405 * we don't care what's in the block.
1406 */
1407 merge_freemem(ms);
1408 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1409 if (ms->a) {
1410 ms->alloced = need;
1411 return 0;
1412 }
1413 PyErr_NoMemory();
1414 merge_freemem(ms); /* reset to sane state */
1415 return -1;
1416}
1417#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1418 merge_getmem(MS, NEED))
1419
1420/* Merge the na elements starting at pa with the nb elements starting at pb
1421 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1422 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1423 * merge, and should have na <= nb. See listsort.txt for more info.
1424 * Return 0 if successful, -1 if error.
1425 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001426static Py_ssize_t
1427merge_lo(MergeState *ms, PyObject **pa, Py_ssize_t na,
1428 PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001429{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001430 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001431 PyObject *compare;
1432 PyObject **dest;
1433 int result = -1; /* guilty until proved innocent */
Neal Norwitz7fd96072006-08-19 04:28:55 +00001434 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001435
1436 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1437 if (MERGE_GETMEM(ms, na) < 0)
1438 return -1;
1439 memcpy(ms->a, pa, na * sizeof(PyObject*));
1440 dest = pa;
1441 pa = ms->a;
1442
1443 *dest++ = *pb++;
1444 --nb;
1445 if (nb == 0)
1446 goto Succeed;
1447 if (na == 1)
1448 goto CopyB;
1449
Neal Norwitz7fd96072006-08-19 04:28:55 +00001450 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001451 compare = ms->compare;
1452 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001453 Py_ssize_t acount = 0; /* # of times A won in a row */
1454 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001455
1456 /* Do the straightforward thing until (if ever) one run
1457 * appears to win consistently.
1458 */
1459 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001460 assert(na > 1 && nb > 0);
Tim Peters66860f62002-08-04 17:47:26 +00001461 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001462 if (k) {
1463 if (k < 0)
1464 goto Fail;
1465 *dest++ = *pb++;
1466 ++bcount;
1467 acount = 0;
1468 --nb;
1469 if (nb == 0)
1470 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001471 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001472 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001473 }
1474 else {
Tim Petersa64dc242002-08-01 02:13:36 +00001475 *dest++ = *pa++;
1476 ++acount;
1477 bcount = 0;
1478 --na;
1479 if (na == 1)
1480 goto CopyB;
Tim Peterse05f65a2002-08-10 05:21:15 +00001481 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001482 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001483 }
Tim Petersa64dc242002-08-01 02:13:36 +00001484 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001485
Tim Petersa64dc242002-08-01 02:13:36 +00001486 /* One run is winning so consistently that galloping may
1487 * be a huge win. So try that, and continue galloping until
1488 * (if ever) neither run appears to be winning consistently
1489 * anymore.
1490 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001491 ++min_gallop;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001492 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001493 assert(na > 1 && nb > 0);
1494 min_gallop -= min_gallop > 1;
1495 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001496 k = gallop_right(*pb, pa, na, 0, compare);
1497 acount = k;
1498 if (k) {
1499 if (k < 0)
1500 goto Fail;
1501 memcpy(dest, pa, k * sizeof(PyObject *));
1502 dest += k;
1503 pa += k;
1504 na -= k;
1505 if (na == 1)
1506 goto CopyB;
1507 /* na==0 is impossible now if the comparison
1508 * function is consistent, but we can't assume
1509 * that it is.
1510 */
1511 if (na == 0)
1512 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001513 }
Tim Petersa64dc242002-08-01 02:13:36 +00001514 *dest++ = *pb++;
1515 --nb;
1516 if (nb == 0)
1517 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001518
Tim Petersa64dc242002-08-01 02:13:36 +00001519 k = gallop_left(*pa, pb, nb, 0, compare);
1520 bcount = k;
1521 if (k) {
1522 if (k < 0)
1523 goto Fail;
1524 memmove(dest, pb, k * sizeof(PyObject *));
1525 dest += k;
1526 pb += k;
1527 nb -= k;
1528 if (nb == 0)
1529 goto Succeed;
1530 }
1531 *dest++ = *pa++;
1532 --na;
1533 if (na == 1)
1534 goto CopyB;
1535 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001536 ++min_gallop; /* penalize it for leaving galloping mode */
1537 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001538 }
1539Succeed:
1540 result = 0;
1541Fail:
1542 if (na)
1543 memcpy(dest, pa, na * sizeof(PyObject*));
1544 return result;
1545CopyB:
1546 assert(na == 1 && nb > 0);
1547 /* The last element of pa belongs at the end of the merge. */
1548 memmove(dest, pb, nb * sizeof(PyObject *));
1549 dest[nb] = *pa;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001550 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001551}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001552
Tim Petersa64dc242002-08-01 02:13:36 +00001553/* Merge the na elements starting at pa with the nb elements starting at pb
1554 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1555 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1556 * merge, and should have na >= nb. See listsort.txt for more info.
1557 * Return 0 if successful, -1 if error.
1558 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001559static Py_ssize_t
1560merge_hi(MergeState *ms, PyObject **pa, Py_ssize_t na, PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001561{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001562 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001563 PyObject *compare;
1564 PyObject **dest;
1565 int result = -1; /* guilty until proved innocent */
1566 PyObject **basea;
1567 PyObject **baseb;
Neal Norwitz7fd96072006-08-19 04:28:55 +00001568 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001569
1570 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1571 if (MERGE_GETMEM(ms, nb) < 0)
1572 return -1;
1573 dest = pb + nb - 1;
1574 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1575 basea = pa;
1576 baseb = ms->a;
1577 pb = ms->a + nb - 1;
1578 pa += na - 1;
1579
1580 *dest-- = *pa--;
1581 --na;
1582 if (na == 0)
1583 goto Succeed;
1584 if (nb == 1)
1585 goto CopyA;
1586
Neal Norwitz7fd96072006-08-19 04:28:55 +00001587 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001588 compare = ms->compare;
1589 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001590 Py_ssize_t acount = 0; /* # of times A won in a row */
1591 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001592
1593 /* Do the straightforward thing until (if ever) one run
1594 * appears to win consistently.
1595 */
1596 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001597 assert(na > 0 && nb > 1);
Tim Peters66860f62002-08-04 17:47:26 +00001598 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001599 if (k) {
1600 if (k < 0)
1601 goto Fail;
1602 *dest-- = *pa--;
1603 ++acount;
1604 bcount = 0;
1605 --na;
1606 if (na == 0)
1607 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001608 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001609 break;
1610 }
1611 else {
1612 *dest-- = *pb--;
1613 ++bcount;
1614 acount = 0;
1615 --nb;
1616 if (nb == 1)
1617 goto CopyA;
Tim Peterse05f65a2002-08-10 05:21:15 +00001618 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001619 break;
1620 }
1621 }
1622
1623 /* One run is winning so consistently that galloping may
1624 * be a huge win. So try that, and continue galloping until
1625 * (if ever) neither run appears to be winning consistently
1626 * anymore.
1627 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001628 ++min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001629 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001630 assert(na > 0 && nb > 1);
1631 min_gallop -= min_gallop > 1;
1632 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001633 k = gallop_right(*pb, basea, na, na-1, compare);
1634 if (k < 0)
1635 goto Fail;
1636 k = na - k;
1637 acount = k;
1638 if (k) {
1639 dest -= k;
1640 pa -= k;
1641 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1642 na -= k;
1643 if (na == 0)
1644 goto Succeed;
1645 }
1646 *dest-- = *pb--;
1647 --nb;
1648 if (nb == 1)
1649 goto CopyA;
1650
1651 k = gallop_left(*pa, baseb, nb, nb-1, compare);
1652 if (k < 0)
1653 goto Fail;
1654 k = nb - k;
1655 bcount = k;
1656 if (k) {
1657 dest -= k;
1658 pb -= k;
1659 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1660 nb -= k;
1661 if (nb == 1)
1662 goto CopyA;
1663 /* nb==0 is impossible now if the comparison
1664 * function is consistent, but we can't assume
1665 * that it is.
1666 */
1667 if (nb == 0)
1668 goto Succeed;
1669 }
1670 *dest-- = *pa--;
1671 --na;
1672 if (na == 0)
1673 goto Succeed;
1674 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001675 ++min_gallop; /* penalize it for leaving galloping mode */
1676 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001677 }
1678Succeed:
1679 result = 0;
1680Fail:
1681 if (nb)
1682 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1683 return result;
1684CopyA:
1685 assert(nb == 1 && na > 0);
1686 /* The first element of pb belongs at the front of the merge. */
1687 dest -= na;
1688 pa -= na;
1689 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1690 *dest = *pb;
1691 return 0;
1692}
1693
1694/* Merge the two runs at stack indices i and i+1.
1695 * Returns 0 on success, -1 on error.
1696 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001697static Py_ssize_t
1698merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001699{
1700 PyObject **pa, **pb;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001701 Py_ssize_t na, nb;
1702 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001703 PyObject *compare;
1704
1705 assert(ms != NULL);
1706 assert(ms->n >= 2);
1707 assert(i >= 0);
1708 assert(i == ms->n - 2 || i == ms->n - 3);
1709
Tim Peterse05f65a2002-08-10 05:21:15 +00001710 pa = ms->pending[i].base;
1711 na = ms->pending[i].len;
1712 pb = ms->pending[i+1].base;
1713 nb = ms->pending[i+1].len;
Tim Petersa64dc242002-08-01 02:13:36 +00001714 assert(na > 0 && nb > 0);
1715 assert(pa + na == pb);
1716
1717 /* Record the length of the combined runs; if i is the 3rd-last
1718 * run now, also slide over the last run (which isn't involved
1719 * in this merge). The current run i+1 goes away in any case.
1720 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001721 ms->pending[i].len = na + nb;
1722 if (i == ms->n - 3)
1723 ms->pending[i+1] = ms->pending[i+2];
Tim Petersa64dc242002-08-01 02:13:36 +00001724 --ms->n;
1725
1726 /* Where does b start in a? Elements in a before that can be
1727 * ignored (already in place).
1728 */
1729 compare = ms->compare;
1730 k = gallop_right(*pb, pa, na, 0, compare);
1731 if (k < 0)
1732 return -1;
1733 pa += k;
1734 na -= k;
1735 if (na == 0)
1736 return 0;
1737
1738 /* Where does a end in b? Elements in b after that can be
1739 * ignored (already in place).
1740 */
1741 nb = gallop_left(pa[na-1], pb, nb, nb-1, compare);
1742 if (nb <= 0)
1743 return nb;
1744
1745 /* Merge what remains of the runs, using a temp array with
1746 * min(na, nb) elements.
1747 */
1748 if (na <= nb)
1749 return merge_lo(ms, pa, na, pb, nb);
1750 else
1751 return merge_hi(ms, pa, na, pb, nb);
1752}
1753
1754/* Examine the stack of runs waiting to be merged, merging adjacent runs
1755 * until the stack invariants are re-established:
1756 *
1757 * 1. len[-3] > len[-2] + len[-1]
1758 * 2. len[-2] > len[-1]
1759 *
1760 * See listsort.txt for more info.
1761 *
1762 * Returns 0 on success, -1 on error.
1763 */
1764static int
1765merge_collapse(MergeState *ms)
1766{
Tim Peterse05f65a2002-08-10 05:21:15 +00001767 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001768
1769 assert(ms);
1770 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001771 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001772 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1773 if (p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001774 --n;
1775 if (merge_at(ms, n) < 0)
1776 return -1;
1777 }
Tim Peterse05f65a2002-08-10 05:21:15 +00001778 else if (p[n].len <= p[n+1].len) {
Tim Petersa64dc242002-08-01 02:13:36 +00001779 if (merge_at(ms, n) < 0)
1780 return -1;
1781 }
1782 else
1783 break;
1784 }
1785 return 0;
1786}
1787
1788/* Regardless of invariants, merge all runs on the stack until only one
1789 * remains. This is used at the end of the mergesort.
1790 *
1791 * Returns 0 on success, -1 on error.
1792 */
1793static int
1794merge_force_collapse(MergeState *ms)
1795{
Tim Peterse05f65a2002-08-10 05:21:15 +00001796 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001797
1798 assert(ms);
1799 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001800 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001801 if (n > 0 && p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001802 --n;
1803 if (merge_at(ms, n) < 0)
1804 return -1;
1805 }
1806 return 0;
1807}
1808
1809/* Compute a good value for the minimum run length; natural runs shorter
1810 * than this are boosted artificially via binary insertion.
1811 *
1812 * If n < 64, return n (it's too small to bother with fancy stuff).
1813 * Else if n is an exact power of 2, return 32.
1814 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1815 * strictly less than, an exact power of 2.
1816 *
1817 * See listsort.txt for more info.
1818 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001819static Py_ssize_t
1820merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001821{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001822 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001823
1824 assert(n >= 0);
1825 while (n >= 64) {
1826 r |= n & 1;
1827 n >>= 1;
1828 }
1829 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001830}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001831
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001832/* Special wrapper to support stable sorting using the decorate-sort-undecorate
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001833 pattern. Holds a key which is used for comparisons and the original record
Tim Petersb38e2b62004-07-29 02:29:26 +00001834 which is returned during the undecorate phase. By exposing only the key
1835 during comparisons, the underlying sort stability characteristics are left
1836 unchanged. Also, if a custom comparison function is used, it will only see
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001837 the key instead of a full record. */
1838
1839typedef struct {
1840 PyObject_HEAD
1841 PyObject *key;
1842 PyObject *value;
1843} sortwrapperobject;
1844
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001845PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
Anthony Baxter377be112006-04-11 06:54:30 +00001846static PyObject *
1847sortwrapper_richcompare(sortwrapperobject *, sortwrapperobject *, int);
1848static void
1849sortwrapper_dealloc(sortwrapperobject *);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001850
1851static PyTypeObject sortwrapper_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001852 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001853 "sortwrapper", /* tp_name */
1854 sizeof(sortwrapperobject), /* tp_basicsize */
1855 0, /* tp_itemsize */
1856 /* methods */
1857 (destructor)sortwrapper_dealloc, /* tp_dealloc */
1858 0, /* tp_print */
1859 0, /* tp_getattr */
1860 0, /* tp_setattr */
1861 0, /* tp_compare */
1862 0, /* tp_repr */
1863 0, /* tp_as_number */
1864 0, /* tp_as_sequence */
1865 0, /* tp_as_mapping */
1866 0, /* tp_hash */
1867 0, /* tp_call */
1868 0, /* tp_str */
1869 PyObject_GenericGetAttr, /* tp_getattro */
1870 0, /* tp_setattro */
1871 0, /* tp_as_buffer */
Tim Petersb38e2b62004-07-29 02:29:26 +00001872 Py_TPFLAGS_DEFAULT |
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001873 Py_TPFLAGS_HAVE_RICHCOMPARE, /* tp_flags */
1874 sortwrapper_doc, /* tp_doc */
1875 0, /* tp_traverse */
1876 0, /* tp_clear */
1877 (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
1878};
1879
Anthony Baxter377be112006-04-11 06:54:30 +00001880
1881static PyObject *
1882sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
1883{
1884 if (!PyObject_TypeCheck(b, &sortwrapper_type)) {
1885 PyErr_SetString(PyExc_TypeError,
1886 "expected a sortwrapperobject");
1887 return NULL;
1888 }
1889 return PyObject_RichCompare(a->key, b->key, op);
1890}
1891
1892static void
1893sortwrapper_dealloc(sortwrapperobject *so)
1894{
1895 Py_XDECREF(so->key);
1896 Py_XDECREF(so->value);
1897 PyObject_Del(so);
1898}
1899
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001900/* Returns a new reference to a sortwrapper.
1901 Consumes the references to the two underlying objects. */
1902
1903static PyObject *
1904build_sortwrapper(PyObject *key, PyObject *value)
1905{
1906 sortwrapperobject *so;
Tim Petersb38e2b62004-07-29 02:29:26 +00001907
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001908 so = PyObject_New(sortwrapperobject, &sortwrapper_type);
1909 if (so == NULL)
1910 return NULL;
1911 so->key = key;
1912 so->value = value;
1913 return (PyObject *)so;
1914}
1915
1916/* Returns a new reference to the value underlying the wrapper. */
1917static PyObject *
1918sortwrapper_getvalue(PyObject *so)
1919{
1920 PyObject *value;
1921
1922 if (!PyObject_TypeCheck(so, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001923 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001924 "expected a sortwrapperobject");
1925 return NULL;
1926 }
1927 value = ((sortwrapperobject *)so)->value;
1928 Py_INCREF(value);
1929 return value;
1930}
1931
1932/* Wrapper for user specified cmp functions in combination with a
1933 specified key function. Makes sure the cmp function is presented
1934 with the actual key instead of the sortwrapper */
1935
1936typedef struct {
1937 PyObject_HEAD
1938 PyObject *func;
1939} cmpwrapperobject;
1940
1941static void
1942cmpwrapper_dealloc(cmpwrapperobject *co)
1943{
1944 Py_XDECREF(co->func);
1945 PyObject_Del(co);
1946}
1947
1948static PyObject *
1949cmpwrapper_call(cmpwrapperobject *co, PyObject *args, PyObject *kwds)
1950{
1951 PyObject *x, *y, *xx, *yy;
1952
1953 if (!PyArg_UnpackTuple(args, "", 2, 2, &x, &y))
1954 return NULL;
1955 if (!PyObject_TypeCheck(x, &sortwrapper_type) ||
Raymond Hettingerae4a2992003-10-16 17:16:30 +00001956 !PyObject_TypeCheck(y, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001957 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001958 "expected a sortwrapperobject");
1959 return NULL;
1960 }
1961 xx = ((sortwrapperobject *)x)->key;
1962 yy = ((sortwrapperobject *)y)->key;
1963 return PyObject_CallFunctionObjArgs(co->func, xx, yy, NULL);
1964}
1965
1966PyDoc_STRVAR(cmpwrapper_doc, "cmp() wrapper for sort with custom keys.");
1967
1968static PyTypeObject cmpwrapper_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001969 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001970 "cmpwrapper", /* tp_name */
1971 sizeof(cmpwrapperobject), /* tp_basicsize */
1972 0, /* tp_itemsize */
1973 /* methods */
1974 (destructor)cmpwrapper_dealloc, /* tp_dealloc */
1975 0, /* tp_print */
1976 0, /* tp_getattr */
1977 0, /* tp_setattr */
1978 0, /* tp_compare */
1979 0, /* tp_repr */
1980 0, /* tp_as_number */
1981 0, /* tp_as_sequence */
1982 0, /* tp_as_mapping */
1983 0, /* tp_hash */
1984 (ternaryfunc)cmpwrapper_call, /* tp_call */
1985 0, /* tp_str */
1986 PyObject_GenericGetAttr, /* tp_getattro */
1987 0, /* tp_setattro */
1988 0, /* tp_as_buffer */
1989 Py_TPFLAGS_DEFAULT, /* tp_flags */
1990 cmpwrapper_doc, /* tp_doc */
1991};
1992
1993static PyObject *
1994build_cmpwrapper(PyObject *cmpfunc)
1995{
1996 cmpwrapperobject *co;
Tim Petersb38e2b62004-07-29 02:29:26 +00001997
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001998 co = PyObject_New(cmpwrapperobject, &cmpwrapper_type);
1999 if (co == NULL)
2000 return NULL;
2001 Py_INCREF(cmpfunc);
2002 co->func = cmpfunc;
2003 return (PyObject *)co;
2004}
2005
Tim Petersa64dc242002-08-01 02:13:36 +00002006/* An adaptive, stable, natural mergesort. See listsort.txt.
2007 * Returns Py_None on success, NULL on error. Even in case of error, the
2008 * list will be some permutation of its input state (nothing is lost or
2009 * duplicated).
2010 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002011static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002012listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00002013{
Tim Petersa64dc242002-08-01 02:13:36 +00002014 MergeState ms;
2015 PyObject **lo, **hi;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002016 Py_ssize_t nremaining;
2017 Py_ssize_t minrun;
2018 Py_ssize_t saved_ob_size, saved_allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00002019 PyObject **saved_ob_item;
Armin Rigo93677f02004-07-29 12:40:23 +00002020 PyObject **final_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00002021 PyObject *compare = NULL;
2022 PyObject *result = NULL; /* guilty until proved innocent */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002023 int reverse = 0;
2024 PyObject *keyfunc = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002025 Py_ssize_t i;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002026 PyObject *key, *value, *kvpair;
Martin v. Löwis15e62742006-02-27 16:46:16 +00002027 static char *kwlist[] = {"cmp", "key", "reverse", 0};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002028
Tim Petersa64dc242002-08-01 02:13:36 +00002029 assert(self != NULL);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002030 assert (PyList_Check(self));
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002031 if (args != NULL) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002032 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:sort",
2033 kwlist, &compare, &keyfunc, &reverse))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002034 return NULL;
2035 }
Skip Montanaro4abd5f02003-01-02 20:51:08 +00002036 if (compare == Py_None)
2037 compare = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002038 if (keyfunc == Py_None)
2039 keyfunc = NULL;
2040 if (compare != NULL && keyfunc != NULL) {
2041 compare = build_cmpwrapper(compare);
2042 if (compare == NULL)
Hye-Shik Chang19cb1932003-12-10 07:31:08 +00002043 return NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002044 } else
2045 Py_XINCREF(compare);
2046
Tim Petersb9099c32002-11-12 22:08:10 +00002047 /* The list is temporarily made empty, so that mutations performed
2048 * by comparison functions can't affect the slice of memory we're
2049 * sorting (allowing mutations during sorting is a core-dump
2050 * factory, since ob_item may change).
2051 */
Christian Heimese93237d2007-12-19 02:37:44 +00002052 saved_ob_size = Py_SIZE(self);
Tim Petersb9099c32002-11-12 22:08:10 +00002053 saved_ob_item = self->ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002054 saved_allocated = self->allocated;
Christian Heimese93237d2007-12-19 02:37:44 +00002055 Py_SIZE(self) = 0;
Tim Peters51b4ade2004-07-29 04:07:15 +00002056 self->ob_item = NULL;
Armin Rigo93677f02004-07-29 12:40:23 +00002057 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00002058
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002059 if (keyfunc != NULL) {
2060 for (i=0 ; i < saved_ob_size ; i++) {
2061 value = saved_ob_item[i];
Tim Petersb38e2b62004-07-29 02:29:26 +00002062 key = PyObject_CallFunctionObjArgs(keyfunc, value,
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002063 NULL);
2064 if (key == NULL) {
2065 for (i=i-1 ; i>=0 ; i--) {
2066 kvpair = saved_ob_item[i];
2067 value = sortwrapper_getvalue(kvpair);
2068 saved_ob_item[i] = value;
2069 Py_DECREF(kvpair);
2070 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002071 goto dsu_fail;
2072 }
2073 kvpair = build_sortwrapper(key, value);
2074 if (kvpair == NULL)
2075 goto dsu_fail;
2076 saved_ob_item[i] = kvpair;
2077 }
2078 }
2079
2080 /* Reverse sort stability achieved by initially reversing the list,
2081 applying a stable forward sort, then reversing the final result. */
2082 if (reverse && saved_ob_size > 1)
2083 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2084
2085 merge_init(&ms, compare);
2086
Tim Petersb9099c32002-11-12 22:08:10 +00002087 nremaining = saved_ob_size;
Tim Petersa64dc242002-08-01 02:13:36 +00002088 if (nremaining < 2)
2089 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00002090
Tim Petersa64dc242002-08-01 02:13:36 +00002091 /* March over the array once, left to right, finding natural runs,
2092 * and extending short natural runs to minrun elements.
2093 */
Tim Petersb9099c32002-11-12 22:08:10 +00002094 lo = saved_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00002095 hi = lo + nremaining;
2096 minrun = merge_compute_minrun(nremaining);
2097 do {
2098 int descending;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002099 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00002100
Tim Petersa64dc242002-08-01 02:13:36 +00002101 /* Identify next run. */
2102 n = count_run(lo, hi, compare, &descending);
2103 if (n < 0)
2104 goto fail;
2105 if (descending)
2106 reverse_slice(lo, lo + n);
2107 /* If short, extend to min(minrun, nremaining). */
2108 if (n < minrun) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002109 const Py_ssize_t force = nremaining <= minrun ?
Tim Petersa64dc242002-08-01 02:13:36 +00002110 nremaining : minrun;
2111 if (binarysort(lo, lo + force, lo + n, compare) < 0)
2112 goto fail;
2113 n = force;
2114 }
2115 /* Push run onto pending-runs stack, and maybe merge. */
2116 assert(ms.n < MAX_MERGE_PENDING);
Tim Peterse05f65a2002-08-10 05:21:15 +00002117 ms.pending[ms.n].base = lo;
2118 ms.pending[ms.n].len = n;
Tim Petersa64dc242002-08-01 02:13:36 +00002119 ++ms.n;
2120 if (merge_collapse(&ms) < 0)
2121 goto fail;
2122 /* Advance to find next run. */
2123 lo += n;
2124 nremaining -= n;
2125 } while (nremaining);
2126 assert(lo == hi);
Tim Peters330f9e92002-07-19 07:05:44 +00002127
Tim Petersa64dc242002-08-01 02:13:36 +00002128 if (merge_force_collapse(&ms) < 0)
2129 goto fail;
2130 assert(ms.n == 1);
Tim Petersb9099c32002-11-12 22:08:10 +00002131 assert(ms.pending[0].base == saved_ob_item);
2132 assert(ms.pending[0].len == saved_ob_size);
Tim Petersa64dc242002-08-01 02:13:36 +00002133
2134succeed:
2135 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002136fail:
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002137 if (keyfunc != NULL) {
2138 for (i=0 ; i < saved_ob_size ; i++) {
2139 kvpair = saved_ob_item[i];
2140 value = sortwrapper_getvalue(kvpair);
2141 saved_ob_item[i] = value;
2142 Py_DECREF(kvpair);
2143 }
2144 }
2145
Armin Rigo93677f02004-07-29 12:40:23 +00002146 if (self->allocated != -1 && result != NULL) {
Tim Peters51b4ade2004-07-29 04:07:15 +00002147 /* The user mucked with the list during the sort,
2148 * and we don't already have another error to report.
2149 */
2150 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2151 result = NULL;
Tim Petersb9099c32002-11-12 22:08:10 +00002152 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002153
2154 if (reverse && saved_ob_size > 1)
2155 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2156
2157 merge_freemem(&ms);
2158
2159dsu_fail:
Armin Rigo93677f02004-07-29 12:40:23 +00002160 final_ob_item = self->ob_item;
Christian Heimese93237d2007-12-19 02:37:44 +00002161 i = Py_SIZE(self);
2162 Py_SIZE(self) = saved_ob_size;
Tim Petersb9099c32002-11-12 22:08:10 +00002163 self->ob_item = saved_ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002164 self->allocated = saved_allocated;
Armin Rigo93677f02004-07-29 12:40:23 +00002165 if (final_ob_item != NULL) {
2166 /* we cannot use list_clear() for this because it does not
2167 guarantee that the list is really empty when it returns */
2168 while (--i >= 0) {
2169 Py_XDECREF(final_ob_item[i]);
2170 }
2171 PyMem_FREE(final_ob_item);
2172 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002173 Py_XDECREF(compare);
Tim Petersa64dc242002-08-01 02:13:36 +00002174 Py_XINCREF(result);
2175 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002176}
Tim Peters330f9e92002-07-19 07:05:44 +00002177#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002178#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002179
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002180int
Fred Drakea2f55112000-07-09 15:16:51 +00002181PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002182{
2183 if (v == NULL || !PyList_Check(v)) {
2184 PyErr_BadInternalCall();
2185 return -1;
2186 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002187 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002188 if (v == NULL)
2189 return -1;
2190 Py_DECREF(v);
2191 return 0;
2192}
2193
Guido van Rossumb86c5492001-02-12 22:06:02 +00002194static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002195listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002196{
Christian Heimese93237d2007-12-19 02:37:44 +00002197 if (Py_SIZE(self) > 1)
2198 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002199 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002200}
2201
Guido van Rossum84c76f51990-10-30 13:32:20 +00002202int
Fred Drakea2f55112000-07-09 15:16:51 +00002203PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002204{
Tim Peters6063e262002-08-08 01:06:39 +00002205 PyListObject *self = (PyListObject *)v;
2206
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002207 if (v == NULL || !PyList_Check(v)) {
2208 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002209 return -1;
2210 }
Christian Heimese93237d2007-12-19 02:37:44 +00002211 if (Py_SIZE(self) > 1)
2212 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002213 return 0;
2214}
2215
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002216PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002217PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002218{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002219 PyObject *w;
Raymond Hettinger6c87af52007-12-15 00:07:25 +00002220 PyObject **p, **q;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002221 Py_ssize_t n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002222 if (v == NULL || !PyList_Check(v)) {
2223 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002224 return NULL;
2225 }
Christian Heimese93237d2007-12-19 02:37:44 +00002226 n = Py_SIZE(v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002227 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002228 if (w == NULL)
2229 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002230 p = ((PyTupleObject *)w)->ob_item;
Raymond Hettinger6c87af52007-12-15 00:07:25 +00002231 q = ((PyListObject *)v)->ob_item;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002232 while (--n >= 0) {
Raymond Hettinger6c87af52007-12-15 00:07:25 +00002233 Py_INCREF(*q);
2234 *p = *q;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002235 p++;
Raymond Hettinger6c87af52007-12-15 00:07:25 +00002236 q++;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002237 }
2238 return w;
2239}
2240
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002241static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002242listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002243{
Christian Heimese93237d2007-12-19 02:37:44 +00002244 Py_ssize_t i, start=0, stop=Py_SIZE(self);
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002245 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002246
Walter Dörwalde8049bef2003-06-17 19:27:39 +00002247 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2248 _PyEval_SliceIndex, &start,
2249 _PyEval_SliceIndex, &stop))
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002250 return NULL;
Guido van Rossum2743d872003-06-17 14:25:14 +00002251 if (start < 0) {
Christian Heimese93237d2007-12-19 02:37:44 +00002252 start += Py_SIZE(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002253 if (start < 0)
2254 start = 0;
2255 }
2256 if (stop < 0) {
Christian Heimese93237d2007-12-19 02:37:44 +00002257 stop += Py_SIZE(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002258 if (stop < 0)
2259 stop = 0;
2260 }
Christian Heimese93237d2007-12-19 02:37:44 +00002261 for (i = start; i < stop && i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002262 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2263 if (cmp > 0)
Martin v. Löwis18e16552006-02-15 17:27:45 +00002264 return PyInt_FromSsize_t(i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002265 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002266 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002267 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002268 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002269 return NULL;
2270}
2271
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002272static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002273listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002274{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002275 Py_ssize_t count = 0;
2276 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002277
Christian Heimese93237d2007-12-19 02:37:44 +00002278 for (i = 0; i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002279 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2280 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002281 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002282 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002283 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00002284 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002285 return PyInt_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002286}
2287
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002288static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002289listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002290{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002291 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002292
Christian Heimese93237d2007-12-19 02:37:44 +00002293 for (i = 0; i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002294 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2295 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002296 if (list_ass_slice(self, i, i+1,
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002297 (PyObject *)NULL) == 0)
2298 Py_RETURN_NONE;
2299 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002300 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002301 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002302 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002303 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002304 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002305 return NULL;
2306}
2307
Jeremy Hylton8caad492000-06-23 14:18:11 +00002308static int
2309list_traverse(PyListObject *o, visitproc visit, void *arg)
2310{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002311 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002312
Christian Heimese93237d2007-12-19 02:37:44 +00002313 for (i = Py_SIZE(o); --i >= 0; )
Thomas Woutersc6e55062006-04-15 21:47:09 +00002314 Py_VISIT(o->ob_item[i]);
Jeremy Hylton8caad492000-06-23 14:18:11 +00002315 return 0;
2316}
2317
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002318static PyObject *
2319list_richcompare(PyObject *v, PyObject *w, int op)
2320{
2321 PyListObject *vl, *wl;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002322 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002323
2324 if (!PyList_Check(v) || !PyList_Check(w)) {
2325 Py_INCREF(Py_NotImplemented);
2326 return Py_NotImplemented;
2327 }
2328
2329 vl = (PyListObject *)v;
2330 wl = (PyListObject *)w;
2331
Christian Heimese93237d2007-12-19 02:37:44 +00002332 if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002333 /* Shortcut: if the lengths differ, the lists differ */
2334 PyObject *res;
2335 if (op == Py_EQ)
2336 res = Py_False;
2337 else
2338 res = Py_True;
2339 Py_INCREF(res);
2340 return res;
2341 }
2342
2343 /* Search for the first index where items are different */
Christian Heimese93237d2007-12-19 02:37:44 +00002344 for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002345 int k = PyObject_RichCompareBool(vl->ob_item[i],
2346 wl->ob_item[i], Py_EQ);
2347 if (k < 0)
2348 return NULL;
2349 if (!k)
2350 break;
2351 }
2352
Christian Heimese93237d2007-12-19 02:37:44 +00002353 if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002354 /* No more items to compare -- compare sizes */
Christian Heimese93237d2007-12-19 02:37:44 +00002355 Py_ssize_t vs = Py_SIZE(vl);
2356 Py_ssize_t ws = Py_SIZE(wl);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002357 int cmp;
2358 PyObject *res;
2359 switch (op) {
2360 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00002361 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002362 case Py_EQ: cmp = vs == ws; break;
2363 case Py_NE: cmp = vs != ws; break;
2364 case Py_GT: cmp = vs > ws; break;
2365 case Py_GE: cmp = vs >= ws; break;
2366 default: return NULL; /* cannot happen */
2367 }
2368 if (cmp)
2369 res = Py_True;
2370 else
2371 res = Py_False;
2372 Py_INCREF(res);
2373 return res;
2374 }
2375
2376 /* We have an item that differs -- shortcuts for EQ/NE */
2377 if (op == Py_EQ) {
2378 Py_INCREF(Py_False);
2379 return Py_False;
2380 }
2381 if (op == Py_NE) {
2382 Py_INCREF(Py_True);
2383 return Py_True;
2384 }
2385
2386 /* Compare the final item again using the proper operator */
2387 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
2388}
2389
Tim Peters6d6c1a32001-08-02 04:15:00 +00002390static int
2391list_init(PyListObject *self, PyObject *args, PyObject *kw)
2392{
2393 PyObject *arg = NULL;
Martin v. Löwis15e62742006-02-27 16:46:16 +00002394 static char *kwlist[] = {"sequence", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002395
2396 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2397 return -1;
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002398
2399 /* Verify list invariants established by PyType_GenericAlloc() */
Christian Heimese93237d2007-12-19 02:37:44 +00002400 assert(0 <= Py_SIZE(self));
2401 assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
Armin Rigoa37bbf22004-07-30 11:20:18 +00002402 assert(self->ob_item != NULL ||
2403 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002404
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002405 /* Empty previous contents */
Armin Rigo93677f02004-07-29 12:40:23 +00002406 if (self->ob_item != NULL) {
2407 (void)list_clear(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002408 }
2409 if (arg != NULL) {
2410 PyObject *rv = listextend(self, arg);
2411 if (rv == NULL)
2412 return -1;
2413 Py_DECREF(rv);
2414 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002415 return 0;
2416}
2417
Raymond Hettinger1021c442003-11-07 15:38:09 +00002418static PyObject *list_iter(PyObject *seq);
2419static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2420
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002421PyDoc_STRVAR(getitem_doc,
2422"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002423PyDoc_STRVAR(reversed_doc,
2424"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002425PyDoc_STRVAR(append_doc,
2426"L.append(object) -- append object to end");
2427PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002428"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002429PyDoc_STRVAR(insert_doc,
2430"L.insert(index, object) -- insert object before index");
2431PyDoc_STRVAR(pop_doc,
2432"L.pop([index]) -> item -- remove and return item at index (default last)");
2433PyDoc_STRVAR(remove_doc,
2434"L.remove(value) -- remove first occurrence of value");
2435PyDoc_STRVAR(index_doc,
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002436"L.index(value, [start, [stop]]) -> integer -- return first index of value");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002437PyDoc_STRVAR(count_doc,
2438"L.count(value) -> integer -- return number of occurrences of value");
2439PyDoc_STRVAR(reverse_doc,
2440"L.reverse() -- reverse *IN PLACE*");
2441PyDoc_STRVAR(sort_doc,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002442"L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n\
2443cmp(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002444
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002445static PyObject *list_subscript(PyListObject*, PyObject*);
2446
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002447static PyMethodDef list_methods[] = {
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002448 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
Raymond Hettinger1021c442003-11-07 15:38:09 +00002449 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002450 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002451 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002452 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002453 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002454 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002455 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002456 {"count", (PyCFunction)listcount, METH_O, count_doc},
2457 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002458 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
Tim Petersa64dc242002-08-01 02:13:36 +00002459 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002460};
2461
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002462static PySequenceMethods list_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002463 (lenfunc)list_length, /* sq_length */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002464 (binaryfunc)list_concat, /* sq_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002465 (ssizeargfunc)list_repeat, /* sq_repeat */
2466 (ssizeargfunc)list_item, /* sq_item */
2467 (ssizessizeargfunc)list_slice, /* sq_slice */
2468 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
2469 (ssizessizeobjargproc)list_ass_slice, /* sq_ass_slice */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002470 (objobjproc)list_contains, /* sq_contains */
2471 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002472 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002473};
2474
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002475PyDoc_STRVAR(list_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002476"list() -> new list\n"
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002477"list(sequence) -> new list initialized from sequence's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002478
Guido van Rossum38fff8c2006-03-07 18:50:55 +00002479
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002480static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002481list_subscript(PyListObject* self, PyObject* item)
2482{
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00002483 if (PyIndex_Check(item)) {
2484 Py_ssize_t i;
2485 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002486 if (i == -1 && PyErr_Occurred())
2487 return NULL;
2488 if (i < 0)
2489 i += PyList_GET_SIZE(self);
2490 return list_item(self, i);
2491 }
2492 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002493 Py_ssize_t start, stop, step, slicelength, cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002494 PyObject* result;
2495 PyObject* it;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002496 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002497
Christian Heimese93237d2007-12-19 02:37:44 +00002498 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002499 &start, &stop, &step, &slicelength) < 0) {
2500 return NULL;
2501 }
2502
2503 if (slicelength <= 0) {
2504 return PyList_New(0);
2505 }
Thomas Wouters3ccec682007-08-28 15:28:19 +00002506 else if (step == 1) {
2507 return list_slice(self, start, stop);
2508 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002509 else {
2510 result = PyList_New(slicelength);
2511 if (!result) return NULL;
2512
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002513 src = self->ob_item;
2514 dest = ((PyListObject *)result)->ob_item;
Tim Peters3b01a122002-07-19 02:35:45 +00002515 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002516 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002517 it = src[cur];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002518 Py_INCREF(it);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002519 dest[i] = it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002520 }
Tim Peters3b01a122002-07-19 02:35:45 +00002521
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002522 return result;
2523 }
2524 }
2525 else {
Georg Brandl283a1352006-11-19 08:48:30 +00002526 PyErr_Format(PyExc_TypeError,
2527 "list indices must be integers, not %.200s",
2528 item->ob_type->tp_name);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002529 return NULL;
2530 }
2531}
2532
Tim Peters3b01a122002-07-19 02:35:45 +00002533static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002534list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2535{
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00002536 if (PyIndex_Check(item)) {
2537 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002538 if (i == -1 && PyErr_Occurred())
2539 return -1;
2540 if (i < 0)
2541 i += PyList_GET_SIZE(self);
2542 return list_ass_item(self, i, value);
2543 }
2544 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002545 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002546
Christian Heimese93237d2007-12-19 02:37:44 +00002547 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002548 &start, &stop, &step, &slicelength) < 0) {
2549 return -1;
2550 }
2551
Thomas Wouters3ccec682007-08-28 15:28:19 +00002552 if (step == 1)
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002553 return list_ass_slice(self, start, stop, value);
2554
Thomas Wouters3ccec682007-08-28 15:28:19 +00002555 /* Make sure s[5:2] = [..] inserts at the right place:
2556 before 5, not before 2. */
2557 if ((step < 0 && start < stop) ||
2558 (step > 0 && start > stop))
2559 stop = start;
2560
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002561 if (value == NULL) {
2562 /* delete slice */
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002563 PyObject **garbage;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002564 Py_ssize_t cur, i;
Tim Peters3b01a122002-07-19 02:35:45 +00002565
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002566 if (slicelength <= 0)
2567 return 0;
2568
2569 if (step < 0) {
2570 stop = start + 1;
2571 start = stop + step*(slicelength - 1) - 1;
2572 step = -step;
2573 }
2574
2575 garbage = (PyObject**)
2576 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Neal Norwitzb88cfad2006-08-12 03:16:54 +00002577 if (!garbage) {
2578 PyErr_NoMemory();
2579 return -1;
2580 }
Tim Peters3b01a122002-07-19 02:35:45 +00002581
Thomas Wouters3ccec682007-08-28 15:28:19 +00002582 /* drawing pictures might help understand these for
2583 loops. Basically, we memmove the parts of the
2584 list that are *not* part of the slice: step-1
2585 items for each item that is part of the slice,
2586 and then tail end of the list that was not
2587 covered by the slice */
Guido van Rossum75a20b12002-06-11 12:22:28 +00002588 for (cur = start, i = 0;
2589 cur < stop;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002590 cur += step, i++) {
Thomas Wouters3ccec682007-08-28 15:28:19 +00002591 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002592
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002593 garbage[i] = PyList_GET_ITEM(self, cur);
2594
Christian Heimese93237d2007-12-19 02:37:44 +00002595 if (cur + step >= Py_SIZE(self)) {
2596 lim = Py_SIZE(self) - cur - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002597 }
2598
Tim Petersb38e2b62004-07-29 02:29:26 +00002599 memmove(self->ob_item + cur - i,
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002600 self->ob_item + cur + 1,
2601 lim * sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002602 }
Thomas Wouters3ccec682007-08-28 15:28:19 +00002603 cur = start + slicelength*step;
Christian Heimese93237d2007-12-19 02:37:44 +00002604 if (cur < Py_SIZE(self)) {
Thomas Wouters3ccec682007-08-28 15:28:19 +00002605 memmove(self->ob_item + cur - slicelength,
2606 self->ob_item + cur,
Christian Heimese93237d2007-12-19 02:37:44 +00002607 (Py_SIZE(self) - cur) *
Thomas Wouters3ccec682007-08-28 15:28:19 +00002608 sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002609 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002610
Christian Heimese93237d2007-12-19 02:37:44 +00002611 Py_SIZE(self) -= slicelength;
2612 list_resize(self, Py_SIZE(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002613
2614 for (i = 0; i < slicelength; i++) {
2615 Py_DECREF(garbage[i]);
2616 }
2617 PyMem_FREE(garbage);
2618
2619 return 0;
2620 }
2621 else {
2622 /* assign slice */
Thomas Wouters3ccec682007-08-28 15:28:19 +00002623 PyObject *ins, *seq;
2624 PyObject **garbage, **seqitems, **selfitems;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002625 Py_ssize_t cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002626
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002627 /* protect against a[::-1] = a */
Tim Peters3b01a122002-07-19 02:35:45 +00002628 if (self == (PyListObject*)value) {
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002629 seq = list_slice((PyListObject*)value, 0,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002630 PyList_GET_SIZE(value));
Tim Peters3b01a122002-07-19 02:35:45 +00002631 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002632 else {
Tim Petersb38e2b62004-07-29 02:29:26 +00002633 seq = PySequence_Fast(value,
Thomas Wouters3ccec682007-08-28 15:28:19 +00002634 "must assign iterable "
2635 "to extended slice");
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002636 }
Neal Norwitzb88cfad2006-08-12 03:16:54 +00002637 if (!seq)
2638 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002639
2640 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2641 PyErr_Format(PyExc_ValueError,
Thomas Wouters3ccec682007-08-28 15:28:19 +00002642 "attempt to assign sequence of "
2643 "size %zd to extended slice of "
2644 "size %zd",
Martin v. Löwise0e89f72006-02-16 06:59:22 +00002645 PySequence_Fast_GET_SIZE(seq),
2646 slicelength);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002647 Py_DECREF(seq);
2648 return -1;
2649 }
2650
2651 if (!slicelength) {
2652 Py_DECREF(seq);
2653 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002654 }
2655
2656 garbage = (PyObject**)
2657 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Neal Norwitze7e4e2d2006-10-28 21:20:12 +00002658 if (!garbage) {
2659 Py_DECREF(seq);
2660 PyErr_NoMemory();
2661 return -1;
2662 }
Tim Peters3b01a122002-07-19 02:35:45 +00002663
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002664 selfitems = self->ob_item;
Raymond Hettinger42bec932004-03-12 16:38:17 +00002665 seqitems = PySequence_Fast_ITEMS(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002666 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002667 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002668 garbage[i] = selfitems[cur];
2669 ins = seqitems[i];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002670 Py_INCREF(ins);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002671 selfitems[cur] = ins;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002672 }
2673
2674 for (i = 0; i < slicelength; i++) {
2675 Py_DECREF(garbage[i]);
2676 }
Tim Peters3b01a122002-07-19 02:35:45 +00002677
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002678 PyMem_FREE(garbage);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002679 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002680
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002681 return 0;
2682 }
Tim Peters3b01a122002-07-19 02:35:45 +00002683 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002684 else {
Georg Brandl283a1352006-11-19 08:48:30 +00002685 PyErr_Format(PyExc_TypeError,
2686 "list indices must be integers, not %.200s",
2687 item->ob_type->tp_name);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002688 return -1;
2689 }
2690}
2691
2692static PyMappingMethods list_as_mapping = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002693 (lenfunc)list_length,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002694 (binaryfunc)list_subscript,
2695 (objobjargproc)list_ass_subscript
2696};
2697
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002698PyTypeObject PyList_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002699 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002700 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002701 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002702 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002703 (destructor)list_dealloc, /* tp_dealloc */
2704 (printfunc)list_print, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002705 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002706 0, /* tp_setattr */
2707 0, /* tp_compare */
2708 (reprfunc)list_repr, /* tp_repr */
2709 0, /* tp_as_number */
2710 &list_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002711 &list_as_mapping, /* tp_as_mapping */
Guido van Rossum64c06e32007-11-22 00:55:51 +00002712 0, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002713 0, /* tp_call */
2714 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002715 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002716 0, /* tp_setattro */
2717 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002718 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Neal Norwitzee3a1b52007-02-25 19:44:48 +00002719 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002720 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002721 (traverseproc)list_traverse, /* tp_traverse */
2722 (inquiry)list_clear, /* tp_clear */
2723 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002724 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002725 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002726 0, /* tp_iternext */
2727 list_methods, /* tp_methods */
2728 0, /* tp_members */
2729 0, /* tp_getset */
2730 0, /* tp_base */
2731 0, /* tp_dict */
2732 0, /* tp_descr_get */
2733 0, /* tp_descr_set */
2734 0, /* tp_dictoffset */
2735 (initproc)list_init, /* tp_init */
2736 PyType_GenericAlloc, /* tp_alloc */
2737 PyType_GenericNew, /* tp_new */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002738 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002739};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002740
2741
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002742/*********************** List Iterator **************************/
2743
2744typedef struct {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002745 PyObject_HEAD
2746 long it_index;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002747 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002748} listiterobject;
2749
Anthony Baxter377be112006-04-11 06:54:30 +00002750static PyObject *list_iter(PyObject *);
2751static void listiter_dealloc(listiterobject *);
2752static int listiter_traverse(listiterobject *, visitproc, void *);
2753static PyObject *listiter_next(listiterobject *);
2754static PyObject *listiter_len(listiterobject *);
2755
2756PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
2757
2758static PyMethodDef listiter_methods[] = {
2759 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
2760 {NULL, NULL} /* sentinel */
2761};
2762
2763PyTypeObject PyListIter_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002764 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Anthony Baxter377be112006-04-11 06:54:30 +00002765 "listiterator", /* tp_name */
2766 sizeof(listiterobject), /* tp_basicsize */
2767 0, /* tp_itemsize */
2768 /* methods */
2769 (destructor)listiter_dealloc, /* tp_dealloc */
2770 0, /* tp_print */
2771 0, /* tp_getattr */
2772 0, /* tp_setattr */
2773 0, /* tp_compare */
2774 0, /* tp_repr */
2775 0, /* tp_as_number */
2776 0, /* tp_as_sequence */
2777 0, /* tp_as_mapping */
2778 0, /* tp_hash */
2779 0, /* tp_call */
2780 0, /* tp_str */
2781 PyObject_GenericGetAttr, /* tp_getattro */
2782 0, /* tp_setattro */
2783 0, /* tp_as_buffer */
2784 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2785 0, /* tp_doc */
2786 (traverseproc)listiter_traverse, /* tp_traverse */
2787 0, /* tp_clear */
2788 0, /* tp_richcompare */
2789 0, /* tp_weaklistoffset */
2790 PyObject_SelfIter, /* tp_iter */
2791 (iternextfunc)listiter_next, /* tp_iternext */
2792 listiter_methods, /* tp_methods */
2793 0, /* tp_members */
2794};
2795
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002796
Guido van Rossum5086e492002-07-16 15:56:52 +00002797static PyObject *
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002798list_iter(PyObject *seq)
2799{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002800 listiterobject *it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002801
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002802 if (!PyList_Check(seq)) {
2803 PyErr_BadInternalCall();
2804 return NULL;
2805 }
2806 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2807 if (it == NULL)
2808 return NULL;
2809 it->it_index = 0;
2810 Py_INCREF(seq);
2811 it->it_seq = (PyListObject *)seq;
2812 _PyObject_GC_TRACK(it);
2813 return (PyObject *)it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002814}
2815
2816static void
2817listiter_dealloc(listiterobject *it)
2818{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002819 _PyObject_GC_UNTRACK(it);
Guido van Rossum86103ae2002-07-16 20:07:32 +00002820 Py_XDECREF(it->it_seq);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002821 PyObject_GC_Del(it);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002822}
2823
2824static int
2825listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2826{
Thomas Woutersc6e55062006-04-15 21:47:09 +00002827 Py_VISIT(it->it_seq);
2828 return 0;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002829}
2830
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002831static PyObject *
Tim Peters93b2cc42002-06-01 05:22:55 +00002832listiter_next(listiterobject *it)
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002833{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002834 PyListObject *seq;
2835 PyObject *item;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002836
Tim Peters93b2cc42002-06-01 05:22:55 +00002837 assert(it != NULL);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002838 seq = it->it_seq;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002839 if (seq == NULL)
2840 return NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002841 assert(PyList_Check(seq));
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002842
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002843 if (it->it_index < PyList_GET_SIZE(seq)) {
Tim Peters93b2cc42002-06-01 05:22:55 +00002844 item = PyList_GET_ITEM(seq, it->it_index);
2845 ++it->it_index;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002846 Py_INCREF(item);
2847 return item;
2848 }
Guido van Rossum86103ae2002-07-16 20:07:32 +00002849
2850 Py_DECREF(seq);
2851 it->it_seq = NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002852 return NULL;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002853}
2854
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002855static PyObject *
Raymond Hettinger435bf582004-03-18 22:43:10 +00002856listiter_len(listiterobject *it)
2857{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002858 Py_ssize_t len;
Raymond Hettinger40a03822004-04-12 13:05:09 +00002859 if (it->it_seq) {
2860 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2861 if (len >= 0)
Martin v. Löwis18e16552006-02-15 17:27:45 +00002862 return PyInt_FromSsize_t(len);
Raymond Hettinger40a03822004-04-12 13:05:09 +00002863 }
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002864 return PyInt_FromLong(0);
Raymond Hettinger435bf582004-03-18 22:43:10 +00002865}
Anthony Baxter377be112006-04-11 06:54:30 +00002866/*********************** List Reverse Iterator **************************/
Raymond Hettinger435bf582004-03-18 22:43:10 +00002867
Anthony Baxter377be112006-04-11 06:54:30 +00002868typedef struct {
2869 PyObject_HEAD
2870 Py_ssize_t it_index;
2871 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
2872} listreviterobject;
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002873
Anthony Baxter377be112006-04-11 06:54:30 +00002874static PyObject *list_reversed(PyListObject *, PyObject *);
2875static void listreviter_dealloc(listreviterobject *);
2876static int listreviter_traverse(listreviterobject *, visitproc, void *);
2877static PyObject *listreviter_next(listreviterobject *);
2878static Py_ssize_t listreviter_len(listreviterobject *);
2879
2880static PySequenceMethods listreviter_as_sequence = {
2881 (lenfunc)listreviter_len, /* sq_length */
2882 0, /* sq_concat */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002883};
2884
Anthony Baxter377be112006-04-11 06:54:30 +00002885PyTypeObject PyListRevIter_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002886 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Anthony Baxter377be112006-04-11 06:54:30 +00002887 "listreverseiterator", /* tp_name */
2888 sizeof(listreviterobject), /* tp_basicsize */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002889 0, /* tp_itemsize */
2890 /* methods */
Anthony Baxter377be112006-04-11 06:54:30 +00002891 (destructor)listreviter_dealloc, /* tp_dealloc */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002892 0, /* tp_print */
2893 0, /* tp_getattr */
2894 0, /* tp_setattr */
2895 0, /* tp_compare */
2896 0, /* tp_repr */
2897 0, /* tp_as_number */
Anthony Baxter377be112006-04-11 06:54:30 +00002898 &listreviter_as_sequence, /* tp_as_sequence */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002899 0, /* tp_as_mapping */
2900 0, /* tp_hash */
2901 0, /* tp_call */
2902 0, /* tp_str */
2903 PyObject_GenericGetAttr, /* tp_getattro */
2904 0, /* tp_setattro */
2905 0, /* tp_as_buffer */
2906 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2907 0, /* tp_doc */
Anthony Baxter377be112006-04-11 06:54:30 +00002908 (traverseproc)listreviter_traverse, /* tp_traverse */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002909 0, /* tp_clear */
2910 0, /* tp_richcompare */
2911 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00002912 PyObject_SelfIter, /* tp_iter */
Anthony Baxter377be112006-04-11 06:54:30 +00002913 (iternextfunc)listreviter_next, /* tp_iternext */
2914 0,
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002915};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002916
Raymond Hettinger1021c442003-11-07 15:38:09 +00002917static PyObject *
2918list_reversed(PyListObject *seq, PyObject *unused)
2919{
2920 listreviterobject *it;
2921
2922 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2923 if (it == NULL)
2924 return NULL;
2925 assert(PyList_Check(seq));
2926 it->it_index = PyList_GET_SIZE(seq) - 1;
2927 Py_INCREF(seq);
2928 it->it_seq = seq;
2929 PyObject_GC_Track(it);
2930 return (PyObject *)it;
2931}
2932
2933static void
2934listreviter_dealloc(listreviterobject *it)
2935{
2936 PyObject_GC_UnTrack(it);
2937 Py_XDECREF(it->it_seq);
2938 PyObject_GC_Del(it);
2939}
2940
2941static int
2942listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2943{
Thomas Woutersc6e55062006-04-15 21:47:09 +00002944 Py_VISIT(it->it_seq);
2945 return 0;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002946}
2947
2948static PyObject *
2949listreviter_next(listreviterobject *it)
2950{
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002951 PyObject *item;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002952 Py_ssize_t index = it->it_index;
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002953 PyListObject *seq = it->it_seq;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002954
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002955 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2956 item = PyList_GET_ITEM(seq, index);
Raymond Hettinger1021c442003-11-07 15:38:09 +00002957 it->it_index--;
2958 Py_INCREF(item);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002959 return item;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002960 }
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002961 it->it_index = -1;
2962 if (seq != NULL) {
2963 it->it_seq = NULL;
2964 Py_DECREF(seq);
2965 }
2966 return NULL;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002967}
2968
Martin v. Löwis18e16552006-02-15 17:27:45 +00002969static Py_ssize_t
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002970listreviter_len(listreviterobject *it)
2971{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002972 Py_ssize_t len = it->it_index + 1;
Raymond Hettinger40a03822004-04-12 13:05:09 +00002973 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
2974 return 0;
2975 return len;
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002976}