blob: df7a405f1f49cd1d2a6861e9bc2eabe89b0c7276 [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) {
95 numfree--;
96 op = free_list[numfree];
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +000097 assert(PyList_CheckExact(op));
98 PyObject_GC_Del(op);
99 }
100}
101
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000102PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000103PyList_New(Py_ssize_t size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000104{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000105 PyListObject *op;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +0000106 size_t nbytes;
Christian Heimesb4ee4a12008-02-07 17:15:30 +0000107#ifdef SHOW_ALLOC_COUNT
108 static int initialized = 0;
109 if (!initialized) {
110 Py_AtExit(show_alloc);
111 initialized = 1;
112 }
113#endif
Tim Peters3986d4e2004-07-29 02:28:42 +0000114
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000115 if (size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000116 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000117 return NULL;
118 }
Tim Peters7049d812004-01-18 20:31:02 +0000119 nbytes = size * sizeof(PyObject *);
Guido van Rossum1e28e5e1992-08-19 16:46:30 +0000120 /* Check for overflow */
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000121 if (nbytes / sizeof(PyObject *) != (size_t)size)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000122 return PyErr_NoMemory();
Christian Heimes5b970ad2008-02-06 13:33:44 +0000123 if (numfree) {
124 numfree--;
125 op = free_list[numfree];
Raymond Hettinger0468e412004-05-05 05:37:53 +0000126 _Py_NewReference((PyObject *)op);
Christian Heimesb4ee4a12008-02-07 17:15:30 +0000127#ifdef SHOW_ALLOC_COUNT
128 count_reuse++;
129#endif
Raymond Hettinger0468e412004-05-05 05:37:53 +0000130 } else {
131 op = PyObject_GC_New(PyListObject, &PyList_Type);
132 if (op == NULL)
133 return NULL;
Christian Heimesb4ee4a12008-02-07 17:15:30 +0000134#ifdef SHOW_ALLOC_COUNT
135 count_alloc++;
136#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000137 }
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000138 if (size <= 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000139 op->ob_item = NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000140 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +0000141 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
Neal Norwitza00c0b92006-06-12 02:08:41 +0000142 if (op->ob_item == NULL) {
143 Py_DECREF(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000144 return PyErr_NoMemory();
Neal Norwitza00c0b92006-06-12 02:08:41 +0000145 }
Tim Peters3986d4e2004-07-29 02:28:42 +0000146 memset(op->ob_item, 0, nbytes);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000147 }
Christian Heimese93237d2007-12-19 02:37:44 +0000148 Py_SIZE(op) = size;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000149 op->allocated = size;
Neil Schemenauere83c00e2001-08-29 23:54:21 +0000150 _PyObject_GC_TRACK(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000151 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000152}
153
Martin v. Löwis18e16552006-02-15 17:27:45 +0000154Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000155PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000156{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000157 if (!PyList_Check(op)) {
158 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000159 return -1;
160 }
161 else
Christian Heimese93237d2007-12-19 02:37:44 +0000162 return Py_SIZE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000163}
164
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000165static PyObject *indexerr = NULL;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000166
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000167PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000168PyList_GetItem(PyObject *op, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000169{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000170 if (!PyList_Check(op)) {
171 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000172 return NULL;
173 }
Christian Heimese93237d2007-12-19 02:37:44 +0000174 if (i < 0 || i >= Py_SIZE(op)) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000175 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000176 indexerr = PyString_FromString(
177 "list index out of range");
178 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000179 return NULL;
180 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000181 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000182}
183
184int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000185PyList_SetItem(register PyObject *op, register Py_ssize_t i,
Fred Drakea2f55112000-07-09 15:16:51 +0000186 register PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000187{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000188 register PyObject *olditem;
189 register PyObject **p;
190 if (!PyList_Check(op)) {
191 Py_XDECREF(newitem);
192 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000193 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000194 }
Christian Heimese93237d2007-12-19 02:37:44 +0000195 if (i < 0 || i >= Py_SIZE(op)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000196 Py_XDECREF(newitem);
197 PyErr_SetString(PyExc_IndexError,
198 "list assignment index out of range");
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000199 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000200 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000201 p = ((PyListObject *)op) -> ob_item + i;
Guido van Rossum5fe60581995-03-09 12:12:50 +0000202 olditem = *p;
203 *p = newitem;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000204 Py_XDECREF(olditem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000205 return 0;
206}
207
208static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000209ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000210{
Christian Heimese93237d2007-12-19 02:37:44 +0000211 Py_ssize_t i, n = Py_SIZE(self);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000212 PyObject **items;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000213 if (v == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000214 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000215 return -1;
216 }
Martin v. Löwisb1ed7fa2006-04-13 07:52:27 +0000217 if (n == PY_SSIZE_T_MAX) {
Trent Micka5846642000-08-13 22:47:45 +0000218 PyErr_SetString(PyExc_OverflowError,
219 "cannot add more objects to list");
220 return -1;
221 }
Tim Petersb38e2b62004-07-29 02:29:26 +0000222
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000223 if (list_resize(self, n+1) == -1)
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000224 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000225
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000226 if (where < 0) {
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000227 where += n;
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000228 if (where < 0)
229 where = 0;
230 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000231 if (where > n)
232 where = n;
233 items = self->ob_item;
234 for (i = n; --i >= where; )
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000235 items[i+1] = items[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000236 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000237 items[where] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000238 return 0;
239}
240
241int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000242PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000243{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000244 if (!PyList_Check(op)) {
245 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000246 return -1;
247 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000248 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000249}
250
Raymond Hettinger40a03822004-04-12 13:05:09 +0000251static int
252app1(PyListObject *self, PyObject *v)
253{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000254 Py_ssize_t n = PyList_GET_SIZE(self);
Raymond Hettinger40a03822004-04-12 13:05:09 +0000255
256 assert (v != NULL);
Martin v. Löwisb1ed7fa2006-04-13 07:52:27 +0000257 if (n == PY_SSIZE_T_MAX) {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000258 PyErr_SetString(PyExc_OverflowError,
259 "cannot add more objects to list");
260 return -1;
261 }
262
263 if (list_resize(self, n+1) == -1)
264 return -1;
265
266 Py_INCREF(v);
267 PyList_SET_ITEM(self, n, v);
268 return 0;
269}
270
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000271int
Fred Drakea2f55112000-07-09 15:16:51 +0000272PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000273{
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000274 if (PyList_Check(op) && (newitem != NULL))
275 return app1((PyListObject *)op, newitem);
276 PyErr_BadInternalCall();
277 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000278}
279
280/* Methods */
281
282static void
Fred Drakea2f55112000-07-09 15:16:51 +0000283list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000284{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000285 Py_ssize_t i;
Guido van Rossumff413af2002-03-28 20:34:59 +0000286 PyObject_GC_UnTrack(op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000287 Py_TRASHCAN_SAFE_BEGIN(op)
Jack Jansen7874d1f1995-01-19 12:09:27 +0000288 if (op->ob_item != NULL) {
Guido van Rossumfa717011999-06-09 15:19:34 +0000289 /* Do it backwards, for Christian Tismer.
290 There's a simple test case where somehow this reduces
291 thrashing when a *very* large list is created and
292 immediately deleted. */
Christian Heimese93237d2007-12-19 02:37:44 +0000293 i = Py_SIZE(op);
Guido van Rossumfa717011999-06-09 15:19:34 +0000294 while (--i >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000295 Py_XDECREF(op->ob_item[i]);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000296 }
Guido van Rossumb18618d2000-05-03 23:44:39 +0000297 PyMem_FREE(op->ob_item);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000298 }
Christian Heimes5b970ad2008-02-06 13:33:44 +0000299 if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op))
300 free_list[numfree++] = op;
Tim Petersb38e2b62004-07-29 02:29:26 +0000301 else
Christian Heimese93237d2007-12-19 02:37:44 +0000302 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000303 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000304}
305
Guido van Rossum90933611991-06-07 16:10:43 +0000306static int
Fred Drakea2f55112000-07-09 15:16:51 +0000307list_print(PyListObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000308{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000309 int rc;
310 Py_ssize_t i;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000311
Martin v. Löwis18e16552006-02-15 17:27:45 +0000312 rc = Py_ReprEnter((PyObject*)op);
313 if (rc != 0) {
314 if (rc < 0)
315 return rc;
Brett Cannon01531592007-09-17 03:28:34 +0000316 Py_BEGIN_ALLOW_THREADS
Guido van Rossumfb376de1998-04-10 22:47:27 +0000317 fprintf(fp, "[...]");
Brett Cannon01531592007-09-17 03:28:34 +0000318 Py_END_ALLOW_THREADS
Guido van Rossumfb376de1998-04-10 22:47:27 +0000319 return 0;
320 }
Brett Cannon01531592007-09-17 03:28:34 +0000321 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000322 fprintf(fp, "[");
Brett Cannon01531592007-09-17 03:28:34 +0000323 Py_END_ALLOW_THREADS
Christian Heimese93237d2007-12-19 02:37:44 +0000324 for (i = 0; i < Py_SIZE(op); i++) {
Brett Cannon01531592007-09-17 03:28:34 +0000325 if (i > 0) {
326 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000327 fprintf(fp, ", ");
Brett Cannon01531592007-09-17 03:28:34 +0000328 Py_END_ALLOW_THREADS
329 }
Guido van Rossumfb376de1998-04-10 22:47:27 +0000330 if (PyObject_Print(op->ob_item[i], fp, 0) != 0) {
331 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000332 return -1;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000333 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000334 }
Brett Cannon01531592007-09-17 03:28:34 +0000335 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000336 fprintf(fp, "]");
Brett Cannon01531592007-09-17 03:28:34 +0000337 Py_END_ALLOW_THREADS
Guido van Rossumfb376de1998-04-10 22:47:27 +0000338 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000339 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000340}
341
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000342static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000343list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000344{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000345 Py_ssize_t i;
Tim Petersa7259592001-06-16 05:11:17 +0000346 PyObject *s, *temp;
347 PyObject *pieces = NULL, *result = NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000348
349 i = Py_ReprEnter((PyObject*)v);
350 if (i != 0) {
Tim Petersa7259592001-06-16 05:11:17 +0000351 return i > 0 ? PyString_FromString("[...]") : NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000352 }
Tim Petersa7259592001-06-16 05:11:17 +0000353
Christian Heimese93237d2007-12-19 02:37:44 +0000354 if (Py_SIZE(v) == 0) {
Tim Petersa7259592001-06-16 05:11:17 +0000355 result = PyString_FromString("[]");
356 goto Done;
357 }
358
359 pieces = PyList_New(0);
360 if (pieces == NULL)
361 goto Done;
362
363 /* Do repr() on each element. Note that this may mutate the list,
364 so must refetch the list size on each iteration. */
Christian Heimese93237d2007-12-19 02:37:44 +0000365 for (i = 0; i < Py_SIZE(v); ++i) {
Tim Petersa7259592001-06-16 05:11:17 +0000366 int status;
Brett Cannona0c05512007-09-10 21:38:27 +0000367 if (Py_EnterRecursiveCall(" while getting the repr of a list"))
368 goto Done;
Tim Petersa7259592001-06-16 05:11:17 +0000369 s = PyObject_Repr(v->ob_item[i]);
Brett Cannona0c05512007-09-10 21:38:27 +0000370 Py_LeaveRecursiveCall();
Tim Petersa7259592001-06-16 05:11:17 +0000371 if (s == NULL)
372 goto Done;
373 status = PyList_Append(pieces, s);
374 Py_DECREF(s); /* append created a new ref */
375 if (status < 0)
376 goto Done;
377 }
378
379 /* Add "[]" decorations to the first and last items. */
380 assert(PyList_GET_SIZE(pieces) > 0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000381 s = PyString_FromString("[");
Tim Petersa7259592001-06-16 05:11:17 +0000382 if (s == NULL)
383 goto Done;
384 temp = PyList_GET_ITEM(pieces, 0);
385 PyString_ConcatAndDel(&s, temp);
386 PyList_SET_ITEM(pieces, 0, s);
387 if (s == NULL)
388 goto Done;
389
390 s = PyString_FromString("]");
391 if (s == NULL)
392 goto Done;
393 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
394 PyString_ConcatAndDel(&temp, s);
395 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
396 if (temp == NULL)
397 goto Done;
398
399 /* Paste them all together with ", " between. */
400 s = PyString_FromString(", ");
401 if (s == NULL)
402 goto Done;
403 result = _PyString_Join(s, pieces);
Tim Peters3b01a122002-07-19 02:35:45 +0000404 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +0000405
406Done:
407 Py_XDECREF(pieces);
Guido van Rossumfb376de1998-04-10 22:47:27 +0000408 Py_ReprLeave((PyObject *)v);
Tim Petersa7259592001-06-16 05:11:17 +0000409 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000410}
411
Martin v. Löwis18e16552006-02-15 17:27:45 +0000412static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000413list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000414{
Christian Heimese93237d2007-12-19 02:37:44 +0000415 return Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000416}
417
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000418static int
Fred Drakea2f55112000-07-09 15:16:51 +0000419list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000420{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000421 Py_ssize_t i;
422 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000423
Christian Heimese93237d2007-12-19 02:37:44 +0000424 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
Raymond Hettingeraae59992002-09-05 14:23:49 +0000425 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000426 Py_EQ);
Neal Norwitzbb9c5f52002-09-05 21:32:55 +0000427 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000428}
429
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000430static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000431list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000432{
Christian Heimese93237d2007-12-19 02:37:44 +0000433 if (i < 0 || i >= Py_SIZE(a)) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000434 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000435 indexerr = PyString_FromString(
436 "list index out of range");
437 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000438 return NULL;
439 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000440 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000441 return a->ob_item[i];
442}
443
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000444static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000445list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000446{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000447 PyListObject *np;
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000448 PyObject **src, **dest;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000449 Py_ssize_t i, len;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000450 if (ilow < 0)
451 ilow = 0;
Christian Heimese93237d2007-12-19 02:37:44 +0000452 else if (ilow > Py_SIZE(a))
453 ilow = Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000454 if (ihigh < ilow)
455 ihigh = ilow;
Christian Heimese93237d2007-12-19 02:37:44 +0000456 else if (ihigh > Py_SIZE(a))
457 ihigh = Py_SIZE(a);
Raymond Hettinger99842b62004-03-08 05:56:15 +0000458 len = ihigh - ilow;
459 np = (PyListObject *) PyList_New(len);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000460 if (np == NULL)
461 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000462
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000463 src = a->ob_item + ilow;
464 dest = np->ob_item;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000465 for (i = 0; i < len; i++) {
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000466 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000467 Py_INCREF(v);
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000468 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000469 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000470 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000471}
472
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000473PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000474PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000475{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000476 if (!PyList_Check(a)) {
477 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000478 return NULL;
479 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000480 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000481}
482
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000483static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000484list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000485{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000486 Py_ssize_t size;
487 Py_ssize_t i;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000488 PyObject **src, **dest;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000489 PyListObject *np;
490 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000491 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000492 "can only concatenate list (not \"%.200s\") to list",
493 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000494 return NULL;
495 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000496#define b ((PyListObject *)bb)
Christian Heimese93237d2007-12-19 02:37:44 +0000497 size = Py_SIZE(a) + Py_SIZE(b);
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000498 if (size < 0)
499 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000500 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000501 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000502 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000503 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000504 src = a->ob_item;
505 dest = np->ob_item;
Christian Heimese93237d2007-12-19 02:37:44 +0000506 for (i = 0; i < Py_SIZE(a); i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000507 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000508 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000509 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000510 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000511 src = b->ob_item;
Christian Heimese93237d2007-12-19 02:37:44 +0000512 dest = np->ob_item + Py_SIZE(a);
513 for (i = 0; i < Py_SIZE(b); i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000514 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000515 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000516 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000517 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000518 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000519#undef b
520}
521
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000522static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000523list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000524{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000525 Py_ssize_t i, j;
526 Py_ssize_t size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000527 PyListObject *np;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000528 PyObject **p, **items;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000529 PyObject *elem;
Guido van Rossumed98d481991-03-06 13:07:53 +0000530 if (n < 0)
531 n = 0;
Christian Heimese93237d2007-12-19 02:37:44 +0000532 size = Py_SIZE(a) * n;
533 if (n && size/n != Py_SIZE(a))
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000534 return PyErr_NoMemory();
Armin Rigoa1e42e12007-10-17 18:46:37 +0000535 if (size == 0)
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000536 return PyList_New(0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000537 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000538 if (np == NULL)
539 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000540
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000541 items = np->ob_item;
Christian Heimese93237d2007-12-19 02:37:44 +0000542 if (Py_SIZE(a) == 1) {
Raymond Hettinger6624e682003-05-21 05:58:46 +0000543 elem = a->ob_item[0];
544 for (i = 0; i < n; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000545 items[i] = elem;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000546 Py_INCREF(elem);
547 }
548 return (PyObject *) np;
549 }
Guido van Rossumed98d481991-03-06 13:07:53 +0000550 p = np->ob_item;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000551 items = a->ob_item;
Guido van Rossumed98d481991-03-06 13:07:53 +0000552 for (i = 0; i < n; i++) {
Christian Heimese93237d2007-12-19 02:37:44 +0000553 for (j = 0; j < Py_SIZE(a); j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000554 *p = items[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000555 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000556 p++;
557 }
558 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000559 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000560}
561
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000562static int
Armin Rigo93677f02004-07-29 12:40:23 +0000563list_clear(PyListObject *a)
564{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000565 Py_ssize_t i;
Armin Rigo93677f02004-07-29 12:40:23 +0000566 PyObject **item = a->ob_item;
567 if (item != NULL) {
568 /* Because XDECREF can recursively invoke operations on
569 this list, we make it empty first. */
Christian Heimese93237d2007-12-19 02:37:44 +0000570 i = Py_SIZE(a);
571 Py_SIZE(a) = 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000572 a->ob_item = NULL;
573 a->allocated = 0;
574 while (--i >= 0) {
575 Py_XDECREF(item[i]);
576 }
577 PyMem_FREE(item);
578 }
579 /* Never fails; the return value can be ignored.
580 Note that there is no guarantee that the list is actually empty
581 at this point, because XDECREF may have populated it again! */
582 return 0;
583}
584
Tim Peters8fc4a912004-07-31 21:53:19 +0000585/* a[ilow:ihigh] = v if v != NULL.
586 * del a[ilow:ihigh] if v == NULL.
587 *
588 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
589 * guaranteed the call cannot fail.
590 */
Armin Rigo93677f02004-07-29 12:40:23 +0000591static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000592list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000593{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000594 /* Because [X]DECREF can recursively invoke list operations on
595 this list, we must postpone all [X]DECREF activity until
596 after the list is back in its canonical shape. Therefore
597 we must allocate an additional array, 'recycle', into which
598 we temporarily copy the items that are deleted from the
599 list. :-( */
Tim Peters73572222004-07-31 02:54:42 +0000600 PyObject *recycle_on_stack[8];
601 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000602 PyObject **item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000603 PyObject **vitem = NULL;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000604 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000605 Py_ssize_t n; /* # of elements in replacement list */
606 Py_ssize_t norig; /* # of elements in list getting replaced */
607 Py_ssize_t d; /* Change in size */
608 Py_ssize_t k;
Tim Peters8d9eb102004-07-31 02:24:20 +0000609 size_t s;
610 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000611#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000612 if (v == NULL)
613 n = 0;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000614 else {
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000615 if (a == b) {
616 /* Special case "a[i:j] = a" -- copy b first */
Christian Heimese93237d2007-12-19 02:37:44 +0000617 v = list_slice(b, 0, Py_SIZE(b));
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000618 if (v == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000619 return result;
620 result = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000621 Py_DECREF(v);
Tim Peters8d9eb102004-07-31 02:24:20 +0000622 return result;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000623 }
Raymond Hettingerf889e102004-03-09 08:04:33 +0000624 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000625 if(v_as_SF == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000626 goto Error;
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000627 n = PySequence_Fast_GET_SIZE(v_as_SF);
Raymond Hettinger42bec932004-03-12 16:38:17 +0000628 vitem = PySequence_Fast_ITEMS(v_as_SF);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000629 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000630 if (ilow < 0)
631 ilow = 0;
Christian Heimese93237d2007-12-19 02:37:44 +0000632 else if (ilow > Py_SIZE(a))
633 ilow = Py_SIZE(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000634
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000635 if (ihigh < ilow)
636 ihigh = ilow;
Christian Heimese93237d2007-12-19 02:37:44 +0000637 else if (ihigh > Py_SIZE(a))
638 ihigh = Py_SIZE(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000639
Tim Peters8d9eb102004-07-31 02:24:20 +0000640 norig = ihigh - ilow;
641 assert(norig >= 0);
642 d = n - norig;
Christian Heimese93237d2007-12-19 02:37:44 +0000643 if (Py_SIZE(a) + d == 0) {
Armin Rigo93677f02004-07-29 12:40:23 +0000644 Py_XDECREF(v_as_SF);
645 return list_clear(a);
646 }
647 item = a->ob_item;
Tim Peters8d9eb102004-07-31 02:24:20 +0000648 /* recycle the items that we are about to remove */
649 s = norig * sizeof(PyObject *);
Tim Peters73572222004-07-31 02:54:42 +0000650 if (s > sizeof(recycle_on_stack)) {
Armin Rigo1dd04a02004-07-30 11:38:22 +0000651 recycle = (PyObject **)PyMem_MALLOC(s);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000652 if (recycle == NULL) {
653 PyErr_NoMemory();
Tim Peters8d9eb102004-07-31 02:24:20 +0000654 goto Error;
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000655 }
656 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000657 memcpy(recycle, &item[ilow], s);
Tim Peters8d9eb102004-07-31 02:24:20 +0000658
Armin Rigo1dd04a02004-07-30 11:38:22 +0000659 if (d < 0) { /* Delete -d items */
660 memmove(&item[ihigh+d], &item[ihigh],
Christian Heimese93237d2007-12-19 02:37:44 +0000661 (Py_SIZE(a) - ihigh)*sizeof(PyObject *));
662 list_resize(a, Py_SIZE(a) + d);
Armin Rigo1dd04a02004-07-30 11:38:22 +0000663 item = a->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000664 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000665 else if (d > 0) { /* Insert d items */
Christian Heimese93237d2007-12-19 02:37:44 +0000666 k = Py_SIZE(a);
Tim Peters73572222004-07-31 02:54:42 +0000667 if (list_resize(a, k+d) < 0)
Tim Peters8d9eb102004-07-31 02:24:20 +0000668 goto Error;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000669 item = a->ob_item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000670 memmove(&item[ihigh+d], &item[ihigh],
Tim Peters73572222004-07-31 02:54:42 +0000671 (k - ihigh)*sizeof(PyObject *));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000672 }
673 for (k = 0; k < n; k++, ilow++) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000674 PyObject *w = vitem[k];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000675 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000676 item[ilow] = w;
677 }
Tim Peters73572222004-07-31 02:54:42 +0000678 for (k = norig - 1; k >= 0; --k)
679 Py_XDECREF(recycle[k]);
Tim Peters8d9eb102004-07-31 02:24:20 +0000680 result = 0;
681 Error:
Tim Peters73572222004-07-31 02:54:42 +0000682 if (recycle != recycle_on_stack)
Armin Rigo1dd04a02004-07-30 11:38:22 +0000683 PyMem_FREE(recycle);
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000684 Py_XDECREF(v_as_SF);
Tim Peters8d9eb102004-07-31 02:24:20 +0000685 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000686#undef b
687}
688
Guido van Rossum234f9421993-06-17 12:35:49 +0000689int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000690PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000691{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000692 if (!PyList_Check(a)) {
693 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000694 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000695 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000696 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000697}
698
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000699static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000700list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000701{
702 PyObject **items;
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000703 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000704
705
706 size = PyList_GET_SIZE(self);
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000707 if (size == 0 || n == 1) {
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000708 Py_INCREF(self);
709 return (PyObject *)self;
710 }
711
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000712 if (n < 1) {
Armin Rigo93677f02004-07-29 12:40:23 +0000713 (void)list_clear(self);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000714 Py_INCREF(self);
715 return (PyObject *)self;
716 }
717
Thomas Woutersa97744c2008-01-25 21:09:34 +0000718 if (size > PY_SSIZE_T_MAX / n) {
Armin Rigoa1e42e12007-10-17 18:46:37 +0000719 return PyErr_NoMemory();
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000720 }
721
722 if (list_resize(self, size*n) == -1)
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000723 return NULL;
724
725 p = size;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000726 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000727 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
728 for (j = 0; j < size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000729 PyObject *o = items[j];
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000730 Py_INCREF(o);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000731 items[p++] = o;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000732 }
733 }
734 Py_INCREF(self);
735 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000736}
737
Guido van Rossum4a450d01991-04-03 19:05:18 +0000738static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000739list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000740{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000741 PyObject *old_value;
Christian Heimese93237d2007-12-19 02:37:44 +0000742 if (i < 0 || i >= Py_SIZE(a)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000743 PyErr_SetString(PyExc_IndexError,
744 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000745 return -1;
746 }
747 if (v == NULL)
748 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000749 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000750 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000751 a->ob_item[i] = v;
Tim Peters3b01a122002-07-19 02:35:45 +0000752 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000753 return 0;
754}
755
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000756static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000757listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000758{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000759 Py_ssize_t i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000760 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000761 if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000762 return NULL;
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000763 if (ins1(self, i, v) == 0)
764 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000765 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000766}
767
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000768static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000769listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000770{
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000771 if (app1(self, v) == 0)
772 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000773 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000774}
775
Barry Warsawdedf6d61998-10-09 16:37:25 +0000776static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000777listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000778{
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000779 PyObject *it; /* iter(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000780 Py_ssize_t m; /* size of self */
781 Py_ssize_t n; /* guess for size of b */
782 Py_ssize_t mn; /* m + n */
783 Py_ssize_t i;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000784 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000785
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000786 /* Special cases:
Tim Petersb38e2b62004-07-29 02:29:26 +0000787 1) lists and tuples which can use PySequence_Fast ops
788 2) extending self to self requires making a copy first
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000789 */
790 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
Armin Rigo70d172d2004-03-20 22:19:23 +0000791 PyObject **src, **dest;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000792 b = PySequence_Fast(b, "argument must be iterable");
793 if (!b)
794 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000795 n = PySequence_Fast_GET_SIZE(b);
796 if (n == 0) {
797 /* short circuit when b is empty */
798 Py_DECREF(b);
799 Py_RETURN_NONE;
800 }
Christian Heimese93237d2007-12-19 02:37:44 +0000801 m = Py_SIZE(self);
Armin Rigo70d172d2004-03-20 22:19:23 +0000802 if (list_resize(self, m + n) == -1) {
803 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000804 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000805 }
806 /* note that we may still have self == b here for the
807 * situation a.extend(a), but the following code works
808 * in that case too. Just make sure to resize self
809 * before calling PySequence_Fast_ITEMS.
810 */
811 /* populate the end of self with b's items */
812 src = PySequence_Fast_ITEMS(b);
813 dest = self->ob_item + m;
814 for (i = 0; i < n; i++) {
815 PyObject *o = src[i];
816 Py_INCREF(o);
817 dest[i] = o;
818 }
819 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000820 Py_RETURN_NONE;
821 }
822
823 it = PyObject_GetIter(b);
824 if (it == NULL)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000825 return NULL;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000826 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000827
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000828 /* Guess a result list size. */
Raymond Hettinger4e2f7142007-12-06 00:56:53 +0000829 n = _PyObject_LengthHint(b, 8);
Christian Heimese93237d2007-12-19 02:37:44 +0000830 m = Py_SIZE(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000831 mn = m + n;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000832 if (mn >= m) {
833 /* Make room. */
834 if (list_resize(self, mn) == -1)
835 goto error;
836 /* Make the list sane again. */
Christian Heimese93237d2007-12-19 02:37:44 +0000837 Py_SIZE(self) = m;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000838 }
839 /* Else m + n overflowed; on the chance that n lied, and there really
840 * is enough room, ignore it. If n was telling the truth, we'll
841 * eventually run out of memory during the loop.
842 */
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000843
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000844 /* Run iterator to exhaustion. */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000845 for (;;) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000846 PyObject *item = iternext(it);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000847 if (item == NULL) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000848 if (PyErr_Occurred()) {
849 if (PyErr_ExceptionMatches(PyExc_StopIteration))
850 PyErr_Clear();
851 else
852 goto error;
853 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000854 break;
855 }
Christian Heimese93237d2007-12-19 02:37:44 +0000856 if (Py_SIZE(self) < self->allocated) {
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000857 /* steals ref */
Christian Heimese93237d2007-12-19 02:37:44 +0000858 PyList_SET_ITEM(self, Py_SIZE(self), item);
859 ++Py_SIZE(self);
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000860 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000861 else {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000862 int status = app1(self, item);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000863 Py_DECREF(item); /* append creates a new ref */
864 if (status < 0)
865 goto error;
866 }
867 }
868
869 /* Cut back result list if initial guess was too large. */
Christian Heimese93237d2007-12-19 02:37:44 +0000870 if (Py_SIZE(self) < self->allocated)
871 list_resize(self, Py_SIZE(self)); /* shrinking can't fail */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000872
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000873 Py_DECREF(it);
874 Py_RETURN_NONE;
875
876 error:
877 Py_DECREF(it);
878 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000879}
880
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000881PyObject *
882_PyList_Extend(PyListObject *self, PyObject *b)
883{
884 return listextend(self, b);
885}
886
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000887static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000888list_inplace_concat(PyListObject *self, PyObject *other)
889{
890 PyObject *result;
891
892 result = listextend(self, other);
893 if (result == NULL)
894 return result;
895 Py_DECREF(result);
896 Py_INCREF(self);
897 return (PyObject *)self;
898}
899
900static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000901listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000902{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000903 Py_ssize_t i = -1;
Armin Rigo7ccbca92006-10-04 12:17:45 +0000904 PyObject *v;
Tim Peters8fc4a912004-07-31 21:53:19 +0000905 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000906
Armin Rigo7ccbca92006-10-04 12:17:45 +0000907 if (!PyArg_ParseTuple(args, "|n:pop", &i))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000908 return NULL;
Armin Rigo7ccbca92006-10-04 12:17:45 +0000909
Christian Heimese93237d2007-12-19 02:37:44 +0000910 if (Py_SIZE(self) == 0) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000911 /* Special-case most common failure cause */
912 PyErr_SetString(PyExc_IndexError, "pop from empty list");
913 return NULL;
914 }
915 if (i < 0)
Christian Heimese93237d2007-12-19 02:37:44 +0000916 i += Py_SIZE(self);
917 if (i < 0 || i >= Py_SIZE(self)) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000918 PyErr_SetString(PyExc_IndexError, "pop index out of range");
919 return NULL;
920 }
921 v = self->ob_item[i];
Christian Heimese93237d2007-12-19 02:37:44 +0000922 if (i == Py_SIZE(self) - 1) {
923 status = list_resize(self, Py_SIZE(self) - 1);
Tim Peters8fc4a912004-07-31 21:53:19 +0000924 assert(status >= 0);
925 return v; /* and v now owns the reference the list had */
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000926 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000927 Py_INCREF(v);
Tim Peters8fc4a912004-07-31 21:53:19 +0000928 status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
929 assert(status >= 0);
930 /* Use status, so that in a release build compilers don't
931 * complain about the unused name.
932 */
Brett Cannon651dd522004-08-08 21:21:18 +0000933 (void) status;
934
935 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000936}
937
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000938/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
939static void
940reverse_slice(PyObject **lo, PyObject **hi)
941{
942 assert(lo && hi);
943
944 --hi;
945 while (lo < hi) {
946 PyObject *t = *lo;
947 *lo = *hi;
948 *hi = t;
949 ++lo;
950 --hi;
951 }
952}
953
Tim Petersa64dc242002-08-01 02:13:36 +0000954/* Lots of code for an adaptive, stable, natural mergesort. There are many
955 * pieces to this algorithm; read listsort.txt for overviews and details.
956 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000957
Guido van Rossum3f236de1996-12-10 23:55:39 +0000958/* Comparison function. Takes care of calling a user-supplied
Tim Peters66860f62002-08-04 17:47:26 +0000959 * comparison function (any callable Python object), which must not be
960 * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool
961 * with Py_LT if you know it's NULL).
Tim Petersa64dc242002-08-01 02:13:36 +0000962 * Returns -1 on error, 1 if x < y, 0 if x >= y.
963 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000964static int
Tim Petersa8c974c2002-07-19 03:30:57 +0000965islt(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000966{
Tim Petersf2a04732002-07-11 21:46:16 +0000967 PyObject *res;
968 PyObject *args;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000969 Py_ssize_t i;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000970
Tim Peters66860f62002-08-04 17:47:26 +0000971 assert(compare != NULL);
Tim Petersa8c974c2002-07-19 03:30:57 +0000972 /* Call the user's comparison function and translate the 3-way
973 * result into true or false (or error).
974 */
Tim Petersf2a04732002-07-11 21:46:16 +0000975 args = PyTuple_New(2);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000976 if (args == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000977 return -1;
Tim Petersf2a04732002-07-11 21:46:16 +0000978 Py_INCREF(x);
979 Py_INCREF(y);
980 PyTuple_SET_ITEM(args, 0, x);
981 PyTuple_SET_ITEM(args, 1, y);
Tim Peters58cf3612002-07-15 05:16:13 +0000982 res = PyObject_Call(compare, args, NULL);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000983 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000984 if (res == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000985 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000986 if (!PyInt_Check(res)) {
Georg Brandl283a1352006-11-19 08:48:30 +0000987 PyErr_Format(PyExc_TypeError,
988 "comparison function must return int, not %.200s",
989 res->ob_type->tp_name);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000990 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +0000991 return -1;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000992 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000993 i = PyInt_AsLong(res);
994 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +0000995 return i < 0;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000996}
997
Tim Peters66860f62002-08-04 17:47:26 +0000998/* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
999 * islt. This avoids a layer of function call in the usual case, and
1000 * sorting does many comparisons.
1001 * Returns -1 on error, 1 if x < y, 0 if x >= y.
1002 */
1003#define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
1004 PyObject_RichCompareBool(X, Y, Py_LT) : \
1005 islt(X, Y, COMPARE))
1006
1007/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +00001008 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
1009 started. It makes more sense in context <wink>. X and Y are PyObject*s.
1010*/
Tim Peters66860f62002-08-04 17:47:26 +00001011#define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
Tim Petersa8c974c2002-07-19 03:30:57 +00001012 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001013
1014/* binarysort is the best method for sorting small arrays: it does
1015 few compares, but can do data movement quadratic in the number of
1016 elements.
Guido van Rossum42812581998-06-17 14:15:44 +00001017 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +00001018 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001019 On entry, must have lo <= start <= hi, and that [lo, start) is already
1020 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +00001021 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001022 Even in case of error, the output slice will be some permutation of
1023 the input (nothing is lost or duplicated).
1024*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00001025static int
Fred Drakea2f55112000-07-09 15:16:51 +00001026binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
1027 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001028{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001029 register Py_ssize_t k;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001030 register PyObject **l, **p, **r;
1031 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001032
Tim Petersa8c974c2002-07-19 03:30:57 +00001033 assert(lo <= start && start <= hi);
1034 /* assert [lo, start) is sorted */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001035 if (lo == start)
1036 ++start;
1037 for (; start < hi; ++start) {
1038 /* set l to where *start belongs */
1039 l = lo;
1040 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001041 pivot = *r;
Tim Peters0fe977c2002-07-19 06:12:32 +00001042 /* Invariants:
1043 * pivot >= all in [lo, l).
1044 * pivot < all in [r, start).
1045 * The second is vacuously true at the start.
1046 */
1047 assert(l < r);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001048 do {
1049 p = l + ((r - l) >> 1);
Tim Petersa8c974c2002-07-19 03:30:57 +00001050 IFLT(pivot, *p)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001051 r = p;
1052 else
Tim Peters0fe977c2002-07-19 06:12:32 +00001053 l = p+1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001054 } while (l < r);
Tim Peters0fe977c2002-07-19 06:12:32 +00001055 assert(l == r);
1056 /* The invariants still hold, so pivot >= all in [lo, l) and
1057 pivot < all in [l, start), so pivot belongs at l. Note
1058 that if there are elements equal to pivot, l points to the
1059 first slot after them -- that's why this sort is stable.
1060 Slide over to make room.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001061 Caution: using memmove is much slower under MSVC 5;
1062 we're not usually moving many slots. */
1063 for (p = start; p > l; --p)
1064 *p = *(p-1);
1065 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001066 }
Guido van Rossum3f236de1996-12-10 23:55:39 +00001067 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001068
1069 fail:
1070 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001071}
1072
Tim Petersa64dc242002-08-01 02:13:36 +00001073/*
1074Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1075is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001076
Tim Petersa64dc242002-08-01 02:13:36 +00001077 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001078
Tim Petersa64dc242002-08-01 02:13:36 +00001079or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001080
Tim Petersa64dc242002-08-01 02:13:36 +00001081 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001082
Tim Petersa64dc242002-08-01 02:13:36 +00001083Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1084For its intended use in a stable mergesort, the strictness of the defn of
1085"descending" is needed so that the caller can safely reverse a descending
1086sequence without violating stability (strict > ensures there are no equal
1087elements to get out of order).
1088
1089Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001090*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001091static Py_ssize_t
Tim Petersa64dc242002-08-01 02:13:36 +00001092count_run(PyObject **lo, PyObject **hi, PyObject *compare, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001093{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001094 Py_ssize_t k;
1095 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001096
Tim Petersa64dc242002-08-01 02:13:36 +00001097 assert(lo < hi);
1098 *descending = 0;
1099 ++lo;
1100 if (lo == hi)
1101 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001102
Tim Petersa64dc242002-08-01 02:13:36 +00001103 n = 2;
1104 IFLT(*lo, *(lo-1)) {
1105 *descending = 1;
1106 for (lo = lo+1; lo < hi; ++lo, ++n) {
1107 IFLT(*lo, *(lo-1))
1108 ;
1109 else
1110 break;
1111 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001112 }
Tim Petersa64dc242002-08-01 02:13:36 +00001113 else {
1114 for (lo = lo+1; lo < hi; ++lo, ++n) {
1115 IFLT(*lo, *(lo-1))
1116 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001117 }
1118 }
1119
Tim Petersa64dc242002-08-01 02:13:36 +00001120 return n;
1121fail:
1122 return -1;
1123}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001124
Tim Petersa64dc242002-08-01 02:13:36 +00001125/*
1126Locate the proper position of key in a sorted vector; if the vector contains
1127an element equal to key, return the position immediately to the left of
1128the leftmost equal element. [gallop_right() does the same except returns
1129the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001130
Tim Petersa64dc242002-08-01 02:13:36 +00001131"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001132
Tim Petersa64dc242002-08-01 02:13:36 +00001133"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1134hint is to the final result, the faster this runs.
1135
1136The return value is the int k in 0..n such that
1137
1138 a[k-1] < key <= a[k]
1139
1140pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1141key belongs at index k; or, IOW, the first k elements of a should precede
1142key, and the last n-k should follow key.
1143
1144Returns -1 on error. See listsort.txt for info on the method.
1145*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001146static Py_ssize_t
1147gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
Tim Petersa64dc242002-08-01 02:13:36 +00001148{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001149 Py_ssize_t ofs;
1150 Py_ssize_t lastofs;
1151 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001152
1153 assert(key && a && n > 0 && hint >= 0 && hint < n);
1154
1155 a += hint;
1156 lastofs = 0;
1157 ofs = 1;
1158 IFLT(*a, key) {
1159 /* a[hint] < key -- gallop right, until
1160 * a[hint + lastofs] < key <= a[hint + ofs]
1161 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001162 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001163 while (ofs < maxofs) {
1164 IFLT(a[ofs], key) {
1165 lastofs = ofs;
1166 ofs = (ofs << 1) + 1;
1167 if (ofs <= 0) /* int overflow */
1168 ofs = maxofs;
1169 }
1170 else /* key <= a[hint + ofs] */
1171 break;
1172 }
1173 if (ofs > maxofs)
1174 ofs = maxofs;
1175 /* Translate back to offsets relative to &a[0]. */
1176 lastofs += hint;
1177 ofs += hint;
1178 }
1179 else {
1180 /* key <= a[hint] -- gallop left, until
1181 * a[hint - ofs] < key <= a[hint - lastofs]
1182 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001183 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001184 while (ofs < maxofs) {
1185 IFLT(*(a-ofs), key)
1186 break;
1187 /* key <= a[hint - ofs] */
1188 lastofs = ofs;
1189 ofs = (ofs << 1) + 1;
1190 if (ofs <= 0) /* int overflow */
1191 ofs = maxofs;
1192 }
1193 if (ofs > maxofs)
1194 ofs = maxofs;
1195 /* Translate back to positive offsets relative to &a[0]. */
1196 k = lastofs;
1197 lastofs = hint - ofs;
1198 ofs = hint - k;
1199 }
1200 a -= hint;
1201
1202 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1203 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1204 * right of lastofs but no farther right than ofs. Do a binary
1205 * search, with invariant a[lastofs-1] < key <= a[ofs].
1206 */
1207 ++lastofs;
1208 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001209 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001210
1211 IFLT(a[m], key)
1212 lastofs = m+1; /* a[m] < key */
1213 else
1214 ofs = m; /* key <= a[m] */
1215 }
1216 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1217 return ofs;
1218
1219fail:
1220 return -1;
1221}
1222
1223/*
1224Exactly like gallop_left(), except that if key already exists in a[0:n],
1225finds the position immediately to the right of the rightmost equal value.
1226
1227The return value is the int k in 0..n such that
1228
1229 a[k-1] <= key < a[k]
1230
1231or -1 if error.
1232
1233The code duplication is massive, but this is enough different given that
1234we're sticking to "<" comparisons that it's much harder to follow if
1235written as one routine with yet another "left or right?" flag.
1236*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001237static Py_ssize_t
1238gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
Tim Petersa64dc242002-08-01 02:13:36 +00001239{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001240 Py_ssize_t ofs;
1241 Py_ssize_t lastofs;
1242 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001243
1244 assert(key && a && n > 0 && hint >= 0 && hint < n);
1245
1246 a += hint;
1247 lastofs = 0;
1248 ofs = 1;
1249 IFLT(key, *a) {
1250 /* key < a[hint] -- gallop left, until
1251 * a[hint - ofs] <= key < a[hint - lastofs]
1252 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001253 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001254 while (ofs < maxofs) {
1255 IFLT(key, *(a-ofs)) {
1256 lastofs = ofs;
1257 ofs = (ofs << 1) + 1;
1258 if (ofs <= 0) /* int overflow */
1259 ofs = maxofs;
1260 }
1261 else /* a[hint - ofs] <= key */
1262 break;
1263 }
1264 if (ofs > maxofs)
1265 ofs = maxofs;
1266 /* Translate back to positive offsets relative to &a[0]. */
1267 k = lastofs;
1268 lastofs = hint - ofs;
1269 ofs = hint - k;
1270 }
1271 else {
1272 /* a[hint] <= key -- gallop right, until
1273 * a[hint + lastofs] <= key < a[hint + ofs]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001274 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001275 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001276 while (ofs < maxofs) {
1277 IFLT(key, a[ofs])
1278 break;
1279 /* a[hint + ofs] <= key */
1280 lastofs = ofs;
1281 ofs = (ofs << 1) + 1;
1282 if (ofs <= 0) /* int overflow */
1283 ofs = maxofs;
1284 }
1285 if (ofs > maxofs)
1286 ofs = maxofs;
1287 /* Translate back to offsets relative to &a[0]. */
1288 lastofs += hint;
1289 ofs += hint;
1290 }
1291 a -= hint;
1292
1293 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1294 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1295 * right of lastofs but no farther right than ofs. Do a binary
1296 * search, with invariant a[lastofs-1] <= key < a[ofs].
1297 */
1298 ++lastofs;
1299 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001300 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001301
1302 IFLT(key, a[m])
1303 ofs = m; /* key < a[m] */
1304 else
1305 lastofs = m+1; /* a[m] <= key */
1306 }
1307 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1308 return ofs;
1309
1310fail:
1311 return -1;
1312}
1313
1314/* The maximum number of entries in a MergeState's pending-runs stack.
1315 * This is enough to sort arrays of size up to about
1316 * 32 * phi ** MAX_MERGE_PENDING
1317 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1318 * with 2**64 elements.
1319 */
1320#define MAX_MERGE_PENDING 85
1321
Tim Peterse05f65a2002-08-10 05:21:15 +00001322/* When we get into galloping mode, we stay there until both runs win less
1323 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001324 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001325#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001326
1327/* Avoid malloc for small temp arrays. */
1328#define MERGESTATE_TEMP_SIZE 256
1329
1330/* One MergeState exists on the stack per invocation of mergesort. It's just
1331 * a convenient way to pass state around among the helper functions.
1332 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001333struct s_slice {
1334 PyObject **base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001335 Py_ssize_t len;
Tim Peterse05f65a2002-08-10 05:21:15 +00001336};
1337
Tim Petersa64dc242002-08-01 02:13:36 +00001338typedef struct s_MergeState {
1339 /* The user-supplied comparison function. or NULL if none given. */
1340 PyObject *compare;
1341
Tim Peterse05f65a2002-08-10 05:21:15 +00001342 /* This controls when we get *into* galloping mode. It's initialized
1343 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1344 * random data, and lower for highly structured data.
1345 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001346 Py_ssize_t min_gallop;
Tim Peterse05f65a2002-08-10 05:21:15 +00001347
Tim Petersa64dc242002-08-01 02:13:36 +00001348 /* 'a' is temp storage to help with merges. It contains room for
1349 * alloced entries.
1350 */
1351 PyObject **a; /* may point to temparray below */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001352 Py_ssize_t alloced;
Tim Petersa64dc242002-08-01 02:13:36 +00001353
1354 /* A stack of n pending runs yet to be merged. Run #i starts at
1355 * address base[i] and extends for len[i] elements. It's always
1356 * true (so long as the indices are in bounds) that
1357 *
Tim Peterse05f65a2002-08-10 05:21:15 +00001358 * pending[i].base + pending[i].len == pending[i+1].base
Tim Petersa64dc242002-08-01 02:13:36 +00001359 *
1360 * so we could cut the storage for this, but it's a minor amount,
1361 * and keeping all the info explicit simplifies the code.
1362 */
1363 int n;
Tim Peterse05f65a2002-08-10 05:21:15 +00001364 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001365
1366 /* 'a' points to this when possible, rather than muck with malloc. */
1367 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1368} MergeState;
1369
1370/* Conceptually a MergeState's constructor. */
1371static void
1372merge_init(MergeState *ms, PyObject *compare)
1373{
1374 assert(ms != NULL);
1375 ms->compare = compare;
1376 ms->a = ms->temparray;
1377 ms->alloced = MERGESTATE_TEMP_SIZE;
1378 ms->n = 0;
Tim Peterse05f65a2002-08-10 05:21:15 +00001379 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001380}
1381
1382/* Free all the temp memory owned by the MergeState. This must be called
1383 * when you're done with a MergeState, and may be called before then if
1384 * you want to free the temp memory early.
1385 */
1386static void
1387merge_freemem(MergeState *ms)
1388{
1389 assert(ms != NULL);
1390 if (ms->a != ms->temparray)
1391 PyMem_Free(ms->a);
1392 ms->a = ms->temparray;
1393 ms->alloced = MERGESTATE_TEMP_SIZE;
1394}
1395
1396/* Ensure enough temp memory for 'need' array slots is available.
1397 * Returns 0 on success and -1 if the memory can't be gotten.
1398 */
1399static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001400merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001401{
1402 assert(ms != NULL);
1403 if (need <= ms->alloced)
1404 return 0;
1405 /* Don't realloc! That can cost cycles to copy the old data, but
1406 * we don't care what's in the block.
1407 */
1408 merge_freemem(ms);
1409 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1410 if (ms->a) {
1411 ms->alloced = need;
1412 return 0;
1413 }
1414 PyErr_NoMemory();
1415 merge_freemem(ms); /* reset to sane state */
1416 return -1;
1417}
1418#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1419 merge_getmem(MS, NEED))
1420
1421/* Merge the na elements starting at pa with the nb elements starting at pb
1422 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1423 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1424 * merge, and should have na <= nb. See listsort.txt for more info.
1425 * Return 0 if successful, -1 if error.
1426 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001427static Py_ssize_t
1428merge_lo(MergeState *ms, PyObject **pa, Py_ssize_t na,
1429 PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001430{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001431 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001432 PyObject *compare;
1433 PyObject **dest;
1434 int result = -1; /* guilty until proved innocent */
Neal Norwitz7fd96072006-08-19 04:28:55 +00001435 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001436
1437 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1438 if (MERGE_GETMEM(ms, na) < 0)
1439 return -1;
1440 memcpy(ms->a, pa, na * sizeof(PyObject*));
1441 dest = pa;
1442 pa = ms->a;
1443
1444 *dest++ = *pb++;
1445 --nb;
1446 if (nb == 0)
1447 goto Succeed;
1448 if (na == 1)
1449 goto CopyB;
1450
Neal Norwitz7fd96072006-08-19 04:28:55 +00001451 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001452 compare = ms->compare;
1453 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001454 Py_ssize_t acount = 0; /* # of times A won in a row */
1455 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001456
1457 /* Do the straightforward thing until (if ever) one run
1458 * appears to win consistently.
1459 */
1460 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001461 assert(na > 1 && nb > 0);
Tim Peters66860f62002-08-04 17:47:26 +00001462 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001463 if (k) {
1464 if (k < 0)
1465 goto Fail;
1466 *dest++ = *pb++;
1467 ++bcount;
1468 acount = 0;
1469 --nb;
1470 if (nb == 0)
1471 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001472 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001473 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001474 }
1475 else {
Tim Petersa64dc242002-08-01 02:13:36 +00001476 *dest++ = *pa++;
1477 ++acount;
1478 bcount = 0;
1479 --na;
1480 if (na == 1)
1481 goto CopyB;
Tim Peterse05f65a2002-08-10 05:21:15 +00001482 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001483 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001484 }
Tim Petersa64dc242002-08-01 02:13:36 +00001485 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001486
Tim Petersa64dc242002-08-01 02:13:36 +00001487 /* One run is winning so consistently that galloping may
1488 * be a huge win. So try that, and continue galloping until
1489 * (if ever) neither run appears to be winning consistently
1490 * anymore.
1491 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001492 ++min_gallop;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001493 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001494 assert(na > 1 && nb > 0);
1495 min_gallop -= min_gallop > 1;
1496 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001497 k = gallop_right(*pb, pa, na, 0, compare);
1498 acount = k;
1499 if (k) {
1500 if (k < 0)
1501 goto Fail;
1502 memcpy(dest, pa, k * sizeof(PyObject *));
1503 dest += k;
1504 pa += k;
1505 na -= k;
1506 if (na == 1)
1507 goto CopyB;
1508 /* na==0 is impossible now if the comparison
1509 * function is consistent, but we can't assume
1510 * that it is.
1511 */
1512 if (na == 0)
1513 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001514 }
Tim Petersa64dc242002-08-01 02:13:36 +00001515 *dest++ = *pb++;
1516 --nb;
1517 if (nb == 0)
1518 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001519
Tim Petersa64dc242002-08-01 02:13:36 +00001520 k = gallop_left(*pa, pb, nb, 0, compare);
1521 bcount = k;
1522 if (k) {
1523 if (k < 0)
1524 goto Fail;
1525 memmove(dest, pb, k * sizeof(PyObject *));
1526 dest += k;
1527 pb += k;
1528 nb -= k;
1529 if (nb == 0)
1530 goto Succeed;
1531 }
1532 *dest++ = *pa++;
1533 --na;
1534 if (na == 1)
1535 goto CopyB;
1536 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001537 ++min_gallop; /* penalize it for leaving galloping mode */
1538 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001539 }
1540Succeed:
1541 result = 0;
1542Fail:
1543 if (na)
1544 memcpy(dest, pa, na * sizeof(PyObject*));
1545 return result;
1546CopyB:
1547 assert(na == 1 && nb > 0);
1548 /* The last element of pa belongs at the end of the merge. */
1549 memmove(dest, pb, nb * sizeof(PyObject *));
1550 dest[nb] = *pa;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001551 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001552}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001553
Tim Petersa64dc242002-08-01 02:13:36 +00001554/* Merge the na elements starting at pa with the nb elements starting at pb
1555 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1556 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1557 * merge, and should have na >= nb. See listsort.txt for more info.
1558 * Return 0 if successful, -1 if error.
1559 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001560static Py_ssize_t
1561merge_hi(MergeState *ms, PyObject **pa, Py_ssize_t na, PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001562{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001563 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001564 PyObject *compare;
1565 PyObject **dest;
1566 int result = -1; /* guilty until proved innocent */
1567 PyObject **basea;
1568 PyObject **baseb;
Neal Norwitz7fd96072006-08-19 04:28:55 +00001569 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001570
1571 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1572 if (MERGE_GETMEM(ms, nb) < 0)
1573 return -1;
1574 dest = pb + nb - 1;
1575 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1576 basea = pa;
1577 baseb = ms->a;
1578 pb = ms->a + nb - 1;
1579 pa += na - 1;
1580
1581 *dest-- = *pa--;
1582 --na;
1583 if (na == 0)
1584 goto Succeed;
1585 if (nb == 1)
1586 goto CopyA;
1587
Neal Norwitz7fd96072006-08-19 04:28:55 +00001588 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001589 compare = ms->compare;
1590 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001591 Py_ssize_t acount = 0; /* # of times A won in a row */
1592 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001593
1594 /* Do the straightforward thing until (if ever) one run
1595 * appears to win consistently.
1596 */
1597 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001598 assert(na > 0 && nb > 1);
Tim Peters66860f62002-08-04 17:47:26 +00001599 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001600 if (k) {
1601 if (k < 0)
1602 goto Fail;
1603 *dest-- = *pa--;
1604 ++acount;
1605 bcount = 0;
1606 --na;
1607 if (na == 0)
1608 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001609 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001610 break;
1611 }
1612 else {
1613 *dest-- = *pb--;
1614 ++bcount;
1615 acount = 0;
1616 --nb;
1617 if (nb == 1)
1618 goto CopyA;
Tim Peterse05f65a2002-08-10 05:21:15 +00001619 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001620 break;
1621 }
1622 }
1623
1624 /* One run is winning so consistently that galloping may
1625 * be a huge win. So try that, and continue galloping until
1626 * (if ever) neither run appears to be winning consistently
1627 * anymore.
1628 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001629 ++min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001630 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001631 assert(na > 0 && nb > 1);
1632 min_gallop -= min_gallop > 1;
1633 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001634 k = gallop_right(*pb, basea, na, na-1, compare);
1635 if (k < 0)
1636 goto Fail;
1637 k = na - k;
1638 acount = k;
1639 if (k) {
1640 dest -= k;
1641 pa -= k;
1642 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1643 na -= k;
1644 if (na == 0)
1645 goto Succeed;
1646 }
1647 *dest-- = *pb--;
1648 --nb;
1649 if (nb == 1)
1650 goto CopyA;
1651
1652 k = gallop_left(*pa, baseb, nb, nb-1, compare);
1653 if (k < 0)
1654 goto Fail;
1655 k = nb - k;
1656 bcount = k;
1657 if (k) {
1658 dest -= k;
1659 pb -= k;
1660 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1661 nb -= k;
1662 if (nb == 1)
1663 goto CopyA;
1664 /* nb==0 is impossible now if the comparison
1665 * function is consistent, but we can't assume
1666 * that it is.
1667 */
1668 if (nb == 0)
1669 goto Succeed;
1670 }
1671 *dest-- = *pa--;
1672 --na;
1673 if (na == 0)
1674 goto Succeed;
1675 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001676 ++min_gallop; /* penalize it for leaving galloping mode */
1677 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001678 }
1679Succeed:
1680 result = 0;
1681Fail:
1682 if (nb)
1683 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1684 return result;
1685CopyA:
1686 assert(nb == 1 && na > 0);
1687 /* The first element of pb belongs at the front of the merge. */
1688 dest -= na;
1689 pa -= na;
1690 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1691 *dest = *pb;
1692 return 0;
1693}
1694
1695/* Merge the two runs at stack indices i and i+1.
1696 * Returns 0 on success, -1 on error.
1697 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001698static Py_ssize_t
1699merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001700{
1701 PyObject **pa, **pb;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001702 Py_ssize_t na, nb;
1703 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001704 PyObject *compare;
1705
1706 assert(ms != NULL);
1707 assert(ms->n >= 2);
1708 assert(i >= 0);
1709 assert(i == ms->n - 2 || i == ms->n - 3);
1710
Tim Peterse05f65a2002-08-10 05:21:15 +00001711 pa = ms->pending[i].base;
1712 na = ms->pending[i].len;
1713 pb = ms->pending[i+1].base;
1714 nb = ms->pending[i+1].len;
Tim Petersa64dc242002-08-01 02:13:36 +00001715 assert(na > 0 && nb > 0);
1716 assert(pa + na == pb);
1717
1718 /* Record the length of the combined runs; if i is the 3rd-last
1719 * run now, also slide over the last run (which isn't involved
1720 * in this merge). The current run i+1 goes away in any case.
1721 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001722 ms->pending[i].len = na + nb;
1723 if (i == ms->n - 3)
1724 ms->pending[i+1] = ms->pending[i+2];
Tim Petersa64dc242002-08-01 02:13:36 +00001725 --ms->n;
1726
1727 /* Where does b start in a? Elements in a before that can be
1728 * ignored (already in place).
1729 */
1730 compare = ms->compare;
1731 k = gallop_right(*pb, pa, na, 0, compare);
1732 if (k < 0)
1733 return -1;
1734 pa += k;
1735 na -= k;
1736 if (na == 0)
1737 return 0;
1738
1739 /* Where does a end in b? Elements in b after that can be
1740 * ignored (already in place).
1741 */
1742 nb = gallop_left(pa[na-1], pb, nb, nb-1, compare);
1743 if (nb <= 0)
1744 return nb;
1745
1746 /* Merge what remains of the runs, using a temp array with
1747 * min(na, nb) elements.
1748 */
1749 if (na <= nb)
1750 return merge_lo(ms, pa, na, pb, nb);
1751 else
1752 return merge_hi(ms, pa, na, pb, nb);
1753}
1754
1755/* Examine the stack of runs waiting to be merged, merging adjacent runs
1756 * until the stack invariants are re-established:
1757 *
1758 * 1. len[-3] > len[-2] + len[-1]
1759 * 2. len[-2] > len[-1]
1760 *
1761 * See listsort.txt for more info.
1762 *
1763 * Returns 0 on success, -1 on error.
1764 */
1765static int
1766merge_collapse(MergeState *ms)
1767{
Tim Peterse05f65a2002-08-10 05:21:15 +00001768 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001769
1770 assert(ms);
1771 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001772 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001773 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1774 if (p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001775 --n;
1776 if (merge_at(ms, n) < 0)
1777 return -1;
1778 }
Tim Peterse05f65a2002-08-10 05:21:15 +00001779 else if (p[n].len <= p[n+1].len) {
Tim Petersa64dc242002-08-01 02:13:36 +00001780 if (merge_at(ms, n) < 0)
1781 return -1;
1782 }
1783 else
1784 break;
1785 }
1786 return 0;
1787}
1788
1789/* Regardless of invariants, merge all runs on the stack until only one
1790 * remains. This is used at the end of the mergesort.
1791 *
1792 * Returns 0 on success, -1 on error.
1793 */
1794static int
1795merge_force_collapse(MergeState *ms)
1796{
Tim Peterse05f65a2002-08-10 05:21:15 +00001797 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001798
1799 assert(ms);
1800 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001801 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001802 if (n > 0 && p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001803 --n;
1804 if (merge_at(ms, n) < 0)
1805 return -1;
1806 }
1807 return 0;
1808}
1809
1810/* Compute a good value for the minimum run length; natural runs shorter
1811 * than this are boosted artificially via binary insertion.
1812 *
1813 * If n < 64, return n (it's too small to bother with fancy stuff).
1814 * Else if n is an exact power of 2, return 32.
1815 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1816 * strictly less than, an exact power of 2.
1817 *
1818 * See listsort.txt for more info.
1819 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001820static Py_ssize_t
1821merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001822{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001823 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001824
1825 assert(n >= 0);
1826 while (n >= 64) {
1827 r |= n & 1;
1828 n >>= 1;
1829 }
1830 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001831}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001832
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001833/* Special wrapper to support stable sorting using the decorate-sort-undecorate
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001834 pattern. Holds a key which is used for comparisons and the original record
Tim Petersb38e2b62004-07-29 02:29:26 +00001835 which is returned during the undecorate phase. By exposing only the key
1836 during comparisons, the underlying sort stability characteristics are left
1837 unchanged. Also, if a custom comparison function is used, it will only see
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001838 the key instead of a full record. */
1839
1840typedef struct {
1841 PyObject_HEAD
1842 PyObject *key;
1843 PyObject *value;
1844} sortwrapperobject;
1845
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001846PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
Anthony Baxter377be112006-04-11 06:54:30 +00001847static PyObject *
1848sortwrapper_richcompare(sortwrapperobject *, sortwrapperobject *, int);
1849static void
1850sortwrapper_dealloc(sortwrapperobject *);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001851
1852static PyTypeObject sortwrapper_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001853 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001854 "sortwrapper", /* tp_name */
1855 sizeof(sortwrapperobject), /* tp_basicsize */
1856 0, /* tp_itemsize */
1857 /* methods */
1858 (destructor)sortwrapper_dealloc, /* tp_dealloc */
1859 0, /* tp_print */
1860 0, /* tp_getattr */
1861 0, /* tp_setattr */
1862 0, /* tp_compare */
1863 0, /* tp_repr */
1864 0, /* tp_as_number */
1865 0, /* tp_as_sequence */
1866 0, /* tp_as_mapping */
1867 0, /* tp_hash */
1868 0, /* tp_call */
1869 0, /* tp_str */
1870 PyObject_GenericGetAttr, /* tp_getattro */
1871 0, /* tp_setattro */
1872 0, /* tp_as_buffer */
Tim Petersb38e2b62004-07-29 02:29:26 +00001873 Py_TPFLAGS_DEFAULT |
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001874 Py_TPFLAGS_HAVE_RICHCOMPARE, /* tp_flags */
1875 sortwrapper_doc, /* tp_doc */
1876 0, /* tp_traverse */
1877 0, /* tp_clear */
1878 (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
1879};
1880
Anthony Baxter377be112006-04-11 06:54:30 +00001881
1882static PyObject *
1883sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
1884{
1885 if (!PyObject_TypeCheck(b, &sortwrapper_type)) {
1886 PyErr_SetString(PyExc_TypeError,
1887 "expected a sortwrapperobject");
1888 return NULL;
1889 }
1890 return PyObject_RichCompare(a->key, b->key, op);
1891}
1892
1893static void
1894sortwrapper_dealloc(sortwrapperobject *so)
1895{
1896 Py_XDECREF(so->key);
1897 Py_XDECREF(so->value);
1898 PyObject_Del(so);
1899}
1900
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001901/* Returns a new reference to a sortwrapper.
1902 Consumes the references to the two underlying objects. */
1903
1904static PyObject *
1905build_sortwrapper(PyObject *key, PyObject *value)
1906{
1907 sortwrapperobject *so;
Tim Petersb38e2b62004-07-29 02:29:26 +00001908
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001909 so = PyObject_New(sortwrapperobject, &sortwrapper_type);
1910 if (so == NULL)
1911 return NULL;
1912 so->key = key;
1913 so->value = value;
1914 return (PyObject *)so;
1915}
1916
1917/* Returns a new reference to the value underlying the wrapper. */
1918static PyObject *
1919sortwrapper_getvalue(PyObject *so)
1920{
1921 PyObject *value;
1922
1923 if (!PyObject_TypeCheck(so, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001924 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001925 "expected a sortwrapperobject");
1926 return NULL;
1927 }
1928 value = ((sortwrapperobject *)so)->value;
1929 Py_INCREF(value);
1930 return value;
1931}
1932
1933/* Wrapper for user specified cmp functions in combination with a
1934 specified key function. Makes sure the cmp function is presented
1935 with the actual key instead of the sortwrapper */
1936
1937typedef struct {
1938 PyObject_HEAD
1939 PyObject *func;
1940} cmpwrapperobject;
1941
1942static void
1943cmpwrapper_dealloc(cmpwrapperobject *co)
1944{
1945 Py_XDECREF(co->func);
1946 PyObject_Del(co);
1947}
1948
1949static PyObject *
1950cmpwrapper_call(cmpwrapperobject *co, PyObject *args, PyObject *kwds)
1951{
1952 PyObject *x, *y, *xx, *yy;
1953
1954 if (!PyArg_UnpackTuple(args, "", 2, 2, &x, &y))
1955 return NULL;
1956 if (!PyObject_TypeCheck(x, &sortwrapper_type) ||
Raymond Hettingerae4a2992003-10-16 17:16:30 +00001957 !PyObject_TypeCheck(y, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001958 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001959 "expected a sortwrapperobject");
1960 return NULL;
1961 }
1962 xx = ((sortwrapperobject *)x)->key;
1963 yy = ((sortwrapperobject *)y)->key;
1964 return PyObject_CallFunctionObjArgs(co->func, xx, yy, NULL);
1965}
1966
1967PyDoc_STRVAR(cmpwrapper_doc, "cmp() wrapper for sort with custom keys.");
1968
1969static PyTypeObject cmpwrapper_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001970 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001971 "cmpwrapper", /* tp_name */
1972 sizeof(cmpwrapperobject), /* tp_basicsize */
1973 0, /* tp_itemsize */
1974 /* methods */
1975 (destructor)cmpwrapper_dealloc, /* tp_dealloc */
1976 0, /* tp_print */
1977 0, /* tp_getattr */
1978 0, /* tp_setattr */
1979 0, /* tp_compare */
1980 0, /* tp_repr */
1981 0, /* tp_as_number */
1982 0, /* tp_as_sequence */
1983 0, /* tp_as_mapping */
1984 0, /* tp_hash */
1985 (ternaryfunc)cmpwrapper_call, /* tp_call */
1986 0, /* tp_str */
1987 PyObject_GenericGetAttr, /* tp_getattro */
1988 0, /* tp_setattro */
1989 0, /* tp_as_buffer */
1990 Py_TPFLAGS_DEFAULT, /* tp_flags */
1991 cmpwrapper_doc, /* tp_doc */
1992};
1993
1994static PyObject *
1995build_cmpwrapper(PyObject *cmpfunc)
1996{
1997 cmpwrapperobject *co;
Tim Petersb38e2b62004-07-29 02:29:26 +00001998
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001999 co = PyObject_New(cmpwrapperobject, &cmpwrapper_type);
2000 if (co == NULL)
2001 return NULL;
2002 Py_INCREF(cmpfunc);
2003 co->func = cmpfunc;
2004 return (PyObject *)co;
2005}
2006
Tim Petersa64dc242002-08-01 02:13:36 +00002007/* An adaptive, stable, natural mergesort. See listsort.txt.
2008 * Returns Py_None on success, NULL on error. Even in case of error, the
2009 * list will be some permutation of its input state (nothing is lost or
2010 * duplicated).
2011 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002012static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002013listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00002014{
Tim Petersa64dc242002-08-01 02:13:36 +00002015 MergeState ms;
2016 PyObject **lo, **hi;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002017 Py_ssize_t nremaining;
2018 Py_ssize_t minrun;
2019 Py_ssize_t saved_ob_size, saved_allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00002020 PyObject **saved_ob_item;
Armin Rigo93677f02004-07-29 12:40:23 +00002021 PyObject **final_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00002022 PyObject *compare = NULL;
2023 PyObject *result = NULL; /* guilty until proved innocent */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002024 int reverse = 0;
2025 PyObject *keyfunc = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002026 Py_ssize_t i;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002027 PyObject *key, *value, *kvpair;
Martin v. Löwis15e62742006-02-27 16:46:16 +00002028 static char *kwlist[] = {"cmp", "key", "reverse", 0};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002029
Tim Petersa64dc242002-08-01 02:13:36 +00002030 assert(self != NULL);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002031 assert (PyList_Check(self));
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002032 if (args != NULL) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002033 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:sort",
2034 kwlist, &compare, &keyfunc, &reverse))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002035 return NULL;
2036 }
Skip Montanaro4abd5f02003-01-02 20:51:08 +00002037 if (compare == Py_None)
2038 compare = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002039 if (keyfunc == Py_None)
2040 keyfunc = NULL;
2041 if (compare != NULL && keyfunc != NULL) {
2042 compare = build_cmpwrapper(compare);
2043 if (compare == NULL)
Hye-Shik Chang19cb1932003-12-10 07:31:08 +00002044 return NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002045 } else
2046 Py_XINCREF(compare);
2047
Tim Petersb9099c32002-11-12 22:08:10 +00002048 /* The list is temporarily made empty, so that mutations performed
2049 * by comparison functions can't affect the slice of memory we're
2050 * sorting (allowing mutations during sorting is a core-dump
2051 * factory, since ob_item may change).
2052 */
Christian Heimese93237d2007-12-19 02:37:44 +00002053 saved_ob_size = Py_SIZE(self);
Tim Petersb9099c32002-11-12 22:08:10 +00002054 saved_ob_item = self->ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002055 saved_allocated = self->allocated;
Christian Heimese93237d2007-12-19 02:37:44 +00002056 Py_SIZE(self) = 0;
Tim Peters51b4ade2004-07-29 04:07:15 +00002057 self->ob_item = NULL;
Armin Rigo93677f02004-07-29 12:40:23 +00002058 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00002059
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002060 if (keyfunc != NULL) {
2061 for (i=0 ; i < saved_ob_size ; i++) {
2062 value = saved_ob_item[i];
Tim Petersb38e2b62004-07-29 02:29:26 +00002063 key = PyObject_CallFunctionObjArgs(keyfunc, value,
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002064 NULL);
2065 if (key == NULL) {
2066 for (i=i-1 ; i>=0 ; i--) {
2067 kvpair = saved_ob_item[i];
2068 value = sortwrapper_getvalue(kvpair);
2069 saved_ob_item[i] = value;
2070 Py_DECREF(kvpair);
2071 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002072 goto dsu_fail;
2073 }
2074 kvpair = build_sortwrapper(key, value);
2075 if (kvpair == NULL)
2076 goto dsu_fail;
2077 saved_ob_item[i] = kvpair;
2078 }
2079 }
2080
2081 /* Reverse sort stability achieved by initially reversing the list,
2082 applying a stable forward sort, then reversing the final result. */
2083 if (reverse && saved_ob_size > 1)
2084 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2085
2086 merge_init(&ms, compare);
2087
Tim Petersb9099c32002-11-12 22:08:10 +00002088 nremaining = saved_ob_size;
Tim Petersa64dc242002-08-01 02:13:36 +00002089 if (nremaining < 2)
2090 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00002091
Tim Petersa64dc242002-08-01 02:13:36 +00002092 /* March over the array once, left to right, finding natural runs,
2093 * and extending short natural runs to minrun elements.
2094 */
Tim Petersb9099c32002-11-12 22:08:10 +00002095 lo = saved_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00002096 hi = lo + nremaining;
2097 minrun = merge_compute_minrun(nremaining);
2098 do {
2099 int descending;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002100 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00002101
Tim Petersa64dc242002-08-01 02:13:36 +00002102 /* Identify next run. */
2103 n = count_run(lo, hi, compare, &descending);
2104 if (n < 0)
2105 goto fail;
2106 if (descending)
2107 reverse_slice(lo, lo + n);
2108 /* If short, extend to min(minrun, nremaining). */
2109 if (n < minrun) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002110 const Py_ssize_t force = nremaining <= minrun ?
Tim Petersa64dc242002-08-01 02:13:36 +00002111 nremaining : minrun;
2112 if (binarysort(lo, lo + force, lo + n, compare) < 0)
2113 goto fail;
2114 n = force;
2115 }
2116 /* Push run onto pending-runs stack, and maybe merge. */
2117 assert(ms.n < MAX_MERGE_PENDING);
Tim Peterse05f65a2002-08-10 05:21:15 +00002118 ms.pending[ms.n].base = lo;
2119 ms.pending[ms.n].len = n;
Tim Petersa64dc242002-08-01 02:13:36 +00002120 ++ms.n;
2121 if (merge_collapse(&ms) < 0)
2122 goto fail;
2123 /* Advance to find next run. */
2124 lo += n;
2125 nremaining -= n;
2126 } while (nremaining);
2127 assert(lo == hi);
Tim Peters330f9e92002-07-19 07:05:44 +00002128
Tim Petersa64dc242002-08-01 02:13:36 +00002129 if (merge_force_collapse(&ms) < 0)
2130 goto fail;
2131 assert(ms.n == 1);
Tim Petersb9099c32002-11-12 22:08:10 +00002132 assert(ms.pending[0].base == saved_ob_item);
2133 assert(ms.pending[0].len == saved_ob_size);
Tim Petersa64dc242002-08-01 02:13:36 +00002134
2135succeed:
2136 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002137fail:
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002138 if (keyfunc != NULL) {
2139 for (i=0 ; i < saved_ob_size ; i++) {
2140 kvpair = saved_ob_item[i];
2141 value = sortwrapper_getvalue(kvpair);
2142 saved_ob_item[i] = value;
2143 Py_DECREF(kvpair);
2144 }
2145 }
2146
Armin Rigo93677f02004-07-29 12:40:23 +00002147 if (self->allocated != -1 && result != NULL) {
Tim Peters51b4ade2004-07-29 04:07:15 +00002148 /* The user mucked with the list during the sort,
2149 * and we don't already have another error to report.
2150 */
2151 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2152 result = NULL;
Tim Petersb9099c32002-11-12 22:08:10 +00002153 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002154
2155 if (reverse && saved_ob_size > 1)
2156 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2157
2158 merge_freemem(&ms);
2159
2160dsu_fail:
Armin Rigo93677f02004-07-29 12:40:23 +00002161 final_ob_item = self->ob_item;
Christian Heimese93237d2007-12-19 02:37:44 +00002162 i = Py_SIZE(self);
2163 Py_SIZE(self) = saved_ob_size;
Tim Petersb9099c32002-11-12 22:08:10 +00002164 self->ob_item = saved_ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002165 self->allocated = saved_allocated;
Armin Rigo93677f02004-07-29 12:40:23 +00002166 if (final_ob_item != NULL) {
2167 /* we cannot use list_clear() for this because it does not
2168 guarantee that the list is really empty when it returns */
2169 while (--i >= 0) {
2170 Py_XDECREF(final_ob_item[i]);
2171 }
2172 PyMem_FREE(final_ob_item);
2173 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002174 Py_XDECREF(compare);
Tim Petersa64dc242002-08-01 02:13:36 +00002175 Py_XINCREF(result);
2176 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002177}
Tim Peters330f9e92002-07-19 07:05:44 +00002178#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002179#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002180
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002181int
Fred Drakea2f55112000-07-09 15:16:51 +00002182PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002183{
2184 if (v == NULL || !PyList_Check(v)) {
2185 PyErr_BadInternalCall();
2186 return -1;
2187 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002188 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002189 if (v == NULL)
2190 return -1;
2191 Py_DECREF(v);
2192 return 0;
2193}
2194
Guido van Rossumb86c5492001-02-12 22:06:02 +00002195static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002196listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002197{
Christian Heimese93237d2007-12-19 02:37:44 +00002198 if (Py_SIZE(self) > 1)
2199 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002200 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002201}
2202
Guido van Rossum84c76f51990-10-30 13:32:20 +00002203int
Fred Drakea2f55112000-07-09 15:16:51 +00002204PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002205{
Tim Peters6063e262002-08-08 01:06:39 +00002206 PyListObject *self = (PyListObject *)v;
2207
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002208 if (v == NULL || !PyList_Check(v)) {
2209 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002210 return -1;
2211 }
Christian Heimese93237d2007-12-19 02:37:44 +00002212 if (Py_SIZE(self) > 1)
2213 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002214 return 0;
2215}
2216
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002217PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002218PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002219{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002220 PyObject *w;
Raymond Hettinger6c87af52007-12-15 00:07:25 +00002221 PyObject **p, **q;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002222 Py_ssize_t n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002223 if (v == NULL || !PyList_Check(v)) {
2224 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002225 return NULL;
2226 }
Christian Heimese93237d2007-12-19 02:37:44 +00002227 n = Py_SIZE(v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002228 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002229 if (w == NULL)
2230 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002231 p = ((PyTupleObject *)w)->ob_item;
Raymond Hettinger6c87af52007-12-15 00:07:25 +00002232 q = ((PyListObject *)v)->ob_item;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002233 while (--n >= 0) {
Raymond Hettinger6c87af52007-12-15 00:07:25 +00002234 Py_INCREF(*q);
2235 *p = *q;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002236 p++;
Raymond Hettinger6c87af52007-12-15 00:07:25 +00002237 q++;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002238 }
2239 return w;
2240}
2241
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002242static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002243listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002244{
Christian Heimese93237d2007-12-19 02:37:44 +00002245 Py_ssize_t i, start=0, stop=Py_SIZE(self);
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002246 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002247
Walter Dörwalde8049bef2003-06-17 19:27:39 +00002248 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2249 _PyEval_SliceIndex, &start,
2250 _PyEval_SliceIndex, &stop))
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002251 return NULL;
Guido van Rossum2743d872003-06-17 14:25:14 +00002252 if (start < 0) {
Christian Heimese93237d2007-12-19 02:37:44 +00002253 start += Py_SIZE(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002254 if (start < 0)
2255 start = 0;
2256 }
2257 if (stop < 0) {
Christian Heimese93237d2007-12-19 02:37:44 +00002258 stop += Py_SIZE(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002259 if (stop < 0)
2260 stop = 0;
2261 }
Christian Heimese93237d2007-12-19 02:37:44 +00002262 for (i = start; i < stop && i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002263 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2264 if (cmp > 0)
Martin v. Löwis18e16552006-02-15 17:27:45 +00002265 return PyInt_FromSsize_t(i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002266 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002267 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002268 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002269 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002270 return NULL;
2271}
2272
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002273static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002274listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002275{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002276 Py_ssize_t count = 0;
2277 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002278
Christian Heimese93237d2007-12-19 02:37:44 +00002279 for (i = 0; i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002280 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2281 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002282 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002283 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002284 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00002285 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002286 return PyInt_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002287}
2288
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002289static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002290listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002291{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002292 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002293
Christian Heimese93237d2007-12-19 02:37:44 +00002294 for (i = 0; i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002295 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2296 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002297 if (list_ass_slice(self, i, i+1,
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002298 (PyObject *)NULL) == 0)
2299 Py_RETURN_NONE;
2300 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002301 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002302 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002303 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002304 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002305 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002306 return NULL;
2307}
2308
Jeremy Hylton8caad492000-06-23 14:18:11 +00002309static int
2310list_traverse(PyListObject *o, visitproc visit, void *arg)
2311{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002312 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002313
Christian Heimese93237d2007-12-19 02:37:44 +00002314 for (i = Py_SIZE(o); --i >= 0; )
Thomas Woutersc6e55062006-04-15 21:47:09 +00002315 Py_VISIT(o->ob_item[i]);
Jeremy Hylton8caad492000-06-23 14:18:11 +00002316 return 0;
2317}
2318
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002319static PyObject *
2320list_richcompare(PyObject *v, PyObject *w, int op)
2321{
2322 PyListObject *vl, *wl;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002323 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002324
2325 if (!PyList_Check(v) || !PyList_Check(w)) {
2326 Py_INCREF(Py_NotImplemented);
2327 return Py_NotImplemented;
2328 }
2329
2330 vl = (PyListObject *)v;
2331 wl = (PyListObject *)w;
2332
Christian Heimese93237d2007-12-19 02:37:44 +00002333 if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002334 /* Shortcut: if the lengths differ, the lists differ */
2335 PyObject *res;
2336 if (op == Py_EQ)
2337 res = Py_False;
2338 else
2339 res = Py_True;
2340 Py_INCREF(res);
2341 return res;
2342 }
2343
2344 /* Search for the first index where items are different */
Christian Heimese93237d2007-12-19 02:37:44 +00002345 for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002346 int k = PyObject_RichCompareBool(vl->ob_item[i],
2347 wl->ob_item[i], Py_EQ);
2348 if (k < 0)
2349 return NULL;
2350 if (!k)
2351 break;
2352 }
2353
Christian Heimese93237d2007-12-19 02:37:44 +00002354 if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002355 /* No more items to compare -- compare sizes */
Christian Heimese93237d2007-12-19 02:37:44 +00002356 Py_ssize_t vs = Py_SIZE(vl);
2357 Py_ssize_t ws = Py_SIZE(wl);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002358 int cmp;
2359 PyObject *res;
2360 switch (op) {
2361 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00002362 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002363 case Py_EQ: cmp = vs == ws; break;
2364 case Py_NE: cmp = vs != ws; break;
2365 case Py_GT: cmp = vs > ws; break;
2366 case Py_GE: cmp = vs >= ws; break;
2367 default: return NULL; /* cannot happen */
2368 }
2369 if (cmp)
2370 res = Py_True;
2371 else
2372 res = Py_False;
2373 Py_INCREF(res);
2374 return res;
2375 }
2376
2377 /* We have an item that differs -- shortcuts for EQ/NE */
2378 if (op == Py_EQ) {
2379 Py_INCREF(Py_False);
2380 return Py_False;
2381 }
2382 if (op == Py_NE) {
2383 Py_INCREF(Py_True);
2384 return Py_True;
2385 }
2386
2387 /* Compare the final item again using the proper operator */
2388 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
2389}
2390
Tim Peters6d6c1a32001-08-02 04:15:00 +00002391static int
2392list_init(PyListObject *self, PyObject *args, PyObject *kw)
2393{
2394 PyObject *arg = NULL;
Martin v. Löwis15e62742006-02-27 16:46:16 +00002395 static char *kwlist[] = {"sequence", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002396
2397 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2398 return -1;
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002399
2400 /* Verify list invariants established by PyType_GenericAlloc() */
Christian Heimese93237d2007-12-19 02:37:44 +00002401 assert(0 <= Py_SIZE(self));
2402 assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
Armin Rigoa37bbf22004-07-30 11:20:18 +00002403 assert(self->ob_item != NULL ||
2404 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002405
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002406 /* Empty previous contents */
Armin Rigo93677f02004-07-29 12:40:23 +00002407 if (self->ob_item != NULL) {
2408 (void)list_clear(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002409 }
2410 if (arg != NULL) {
2411 PyObject *rv = listextend(self, arg);
2412 if (rv == NULL)
2413 return -1;
2414 Py_DECREF(rv);
2415 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002416 return 0;
2417}
2418
Raymond Hettinger1021c442003-11-07 15:38:09 +00002419static PyObject *list_iter(PyObject *seq);
2420static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2421
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002422PyDoc_STRVAR(getitem_doc,
2423"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002424PyDoc_STRVAR(reversed_doc,
2425"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002426PyDoc_STRVAR(append_doc,
2427"L.append(object) -- append object to end");
2428PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002429"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002430PyDoc_STRVAR(insert_doc,
2431"L.insert(index, object) -- insert object before index");
2432PyDoc_STRVAR(pop_doc,
2433"L.pop([index]) -> item -- remove and return item at index (default last)");
2434PyDoc_STRVAR(remove_doc,
2435"L.remove(value) -- remove first occurrence of value");
2436PyDoc_STRVAR(index_doc,
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002437"L.index(value, [start, [stop]]) -> integer -- return first index of value");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002438PyDoc_STRVAR(count_doc,
2439"L.count(value) -> integer -- return number of occurrences of value");
2440PyDoc_STRVAR(reverse_doc,
2441"L.reverse() -- reverse *IN PLACE*");
2442PyDoc_STRVAR(sort_doc,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002443"L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n\
2444cmp(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002445
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002446static PyObject *list_subscript(PyListObject*, PyObject*);
2447
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002448static PyMethodDef list_methods[] = {
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002449 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
Raymond Hettinger1021c442003-11-07 15:38:09 +00002450 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002451 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002452 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002453 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002454 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002455 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002456 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002457 {"count", (PyCFunction)listcount, METH_O, count_doc},
2458 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002459 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
Tim Petersa64dc242002-08-01 02:13:36 +00002460 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002461};
2462
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002463static PySequenceMethods list_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002464 (lenfunc)list_length, /* sq_length */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002465 (binaryfunc)list_concat, /* sq_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002466 (ssizeargfunc)list_repeat, /* sq_repeat */
2467 (ssizeargfunc)list_item, /* sq_item */
2468 (ssizessizeargfunc)list_slice, /* sq_slice */
2469 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
2470 (ssizessizeobjargproc)list_ass_slice, /* sq_ass_slice */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002471 (objobjproc)list_contains, /* sq_contains */
2472 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002473 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002474};
2475
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002476PyDoc_STRVAR(list_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002477"list() -> new list\n"
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002478"list(sequence) -> new list initialized from sequence's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002479
Guido van Rossum38fff8c2006-03-07 18:50:55 +00002480
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002481static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002482list_subscript(PyListObject* self, PyObject* item)
2483{
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00002484 if (PyIndex_Check(item)) {
2485 Py_ssize_t i;
2486 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002487 if (i == -1 && PyErr_Occurred())
2488 return NULL;
2489 if (i < 0)
2490 i += PyList_GET_SIZE(self);
2491 return list_item(self, i);
2492 }
2493 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002494 Py_ssize_t start, stop, step, slicelength, cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002495 PyObject* result;
2496 PyObject* it;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002497 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002498
Christian Heimese93237d2007-12-19 02:37:44 +00002499 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002500 &start, &stop, &step, &slicelength) < 0) {
2501 return NULL;
2502 }
2503
2504 if (slicelength <= 0) {
2505 return PyList_New(0);
2506 }
Thomas Wouters3ccec682007-08-28 15:28:19 +00002507 else if (step == 1) {
2508 return list_slice(self, start, stop);
2509 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002510 else {
2511 result = PyList_New(slicelength);
2512 if (!result) return NULL;
2513
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002514 src = self->ob_item;
2515 dest = ((PyListObject *)result)->ob_item;
Tim Peters3b01a122002-07-19 02:35:45 +00002516 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002517 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002518 it = src[cur];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002519 Py_INCREF(it);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002520 dest[i] = it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002521 }
Tim Peters3b01a122002-07-19 02:35:45 +00002522
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002523 return result;
2524 }
2525 }
2526 else {
Georg Brandl283a1352006-11-19 08:48:30 +00002527 PyErr_Format(PyExc_TypeError,
2528 "list indices must be integers, not %.200s",
2529 item->ob_type->tp_name);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002530 return NULL;
2531 }
2532}
2533
Tim Peters3b01a122002-07-19 02:35:45 +00002534static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002535list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2536{
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00002537 if (PyIndex_Check(item)) {
2538 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002539 if (i == -1 && PyErr_Occurred())
2540 return -1;
2541 if (i < 0)
2542 i += PyList_GET_SIZE(self);
2543 return list_ass_item(self, i, value);
2544 }
2545 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002546 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002547
Christian Heimese93237d2007-12-19 02:37:44 +00002548 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002549 &start, &stop, &step, &slicelength) < 0) {
2550 return -1;
2551 }
2552
Thomas Wouters3ccec682007-08-28 15:28:19 +00002553 if (step == 1)
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002554 return list_ass_slice(self, start, stop, value);
2555
Thomas Wouters3ccec682007-08-28 15:28:19 +00002556 /* Make sure s[5:2] = [..] inserts at the right place:
2557 before 5, not before 2. */
2558 if ((step < 0 && start < stop) ||
2559 (step > 0 && start > stop))
2560 stop = start;
2561
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002562 if (value == NULL) {
2563 /* delete slice */
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002564 PyObject **garbage;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002565 Py_ssize_t cur, i;
Tim Peters3b01a122002-07-19 02:35:45 +00002566
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002567 if (slicelength <= 0)
2568 return 0;
2569
2570 if (step < 0) {
2571 stop = start + 1;
2572 start = stop + step*(slicelength - 1) - 1;
2573 step = -step;
2574 }
2575
2576 garbage = (PyObject**)
2577 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Neal Norwitzb88cfad2006-08-12 03:16:54 +00002578 if (!garbage) {
2579 PyErr_NoMemory();
2580 return -1;
2581 }
Tim Peters3b01a122002-07-19 02:35:45 +00002582
Thomas Wouters3ccec682007-08-28 15:28:19 +00002583 /* drawing pictures might help understand these for
2584 loops. Basically, we memmove the parts of the
2585 list that are *not* part of the slice: step-1
2586 items for each item that is part of the slice,
2587 and then tail end of the list that was not
2588 covered by the slice */
Guido van Rossum75a20b12002-06-11 12:22:28 +00002589 for (cur = start, i = 0;
2590 cur < stop;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002591 cur += step, i++) {
Thomas Wouters3ccec682007-08-28 15:28:19 +00002592 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002593
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002594 garbage[i] = PyList_GET_ITEM(self, cur);
2595
Christian Heimese93237d2007-12-19 02:37:44 +00002596 if (cur + step >= Py_SIZE(self)) {
2597 lim = Py_SIZE(self) - cur - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002598 }
2599
Tim Petersb38e2b62004-07-29 02:29:26 +00002600 memmove(self->ob_item + cur - i,
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002601 self->ob_item + cur + 1,
2602 lim * sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002603 }
Thomas Wouters3ccec682007-08-28 15:28:19 +00002604 cur = start + slicelength*step;
Christian Heimese93237d2007-12-19 02:37:44 +00002605 if (cur < Py_SIZE(self)) {
Thomas Wouters3ccec682007-08-28 15:28:19 +00002606 memmove(self->ob_item + cur - slicelength,
2607 self->ob_item + cur,
Christian Heimese93237d2007-12-19 02:37:44 +00002608 (Py_SIZE(self) - cur) *
Thomas Wouters3ccec682007-08-28 15:28:19 +00002609 sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002610 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002611
Christian Heimese93237d2007-12-19 02:37:44 +00002612 Py_SIZE(self) -= slicelength;
2613 list_resize(self, Py_SIZE(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002614
2615 for (i = 0; i < slicelength; i++) {
2616 Py_DECREF(garbage[i]);
2617 }
2618 PyMem_FREE(garbage);
2619
2620 return 0;
2621 }
2622 else {
2623 /* assign slice */
Thomas Wouters3ccec682007-08-28 15:28:19 +00002624 PyObject *ins, *seq;
2625 PyObject **garbage, **seqitems, **selfitems;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002626 Py_ssize_t cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002627
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002628 /* protect against a[::-1] = a */
Tim Peters3b01a122002-07-19 02:35:45 +00002629 if (self == (PyListObject*)value) {
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002630 seq = list_slice((PyListObject*)value, 0,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002631 PyList_GET_SIZE(value));
Tim Peters3b01a122002-07-19 02:35:45 +00002632 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002633 else {
Tim Petersb38e2b62004-07-29 02:29:26 +00002634 seq = PySequence_Fast(value,
Thomas Wouters3ccec682007-08-28 15:28:19 +00002635 "must assign iterable "
2636 "to extended slice");
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002637 }
Neal Norwitzb88cfad2006-08-12 03:16:54 +00002638 if (!seq)
2639 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002640
2641 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2642 PyErr_Format(PyExc_ValueError,
Thomas Wouters3ccec682007-08-28 15:28:19 +00002643 "attempt to assign sequence of "
2644 "size %zd to extended slice of "
2645 "size %zd",
Martin v. Löwise0e89f72006-02-16 06:59:22 +00002646 PySequence_Fast_GET_SIZE(seq),
2647 slicelength);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002648 Py_DECREF(seq);
2649 return -1;
2650 }
2651
2652 if (!slicelength) {
2653 Py_DECREF(seq);
2654 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002655 }
2656
2657 garbage = (PyObject**)
2658 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Neal Norwitze7e4e2d2006-10-28 21:20:12 +00002659 if (!garbage) {
2660 Py_DECREF(seq);
2661 PyErr_NoMemory();
2662 return -1;
2663 }
Tim Peters3b01a122002-07-19 02:35:45 +00002664
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002665 selfitems = self->ob_item;
Raymond Hettinger42bec932004-03-12 16:38:17 +00002666 seqitems = PySequence_Fast_ITEMS(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002667 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002668 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002669 garbage[i] = selfitems[cur];
2670 ins = seqitems[i];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002671 Py_INCREF(ins);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002672 selfitems[cur] = ins;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002673 }
2674
2675 for (i = 0; i < slicelength; i++) {
2676 Py_DECREF(garbage[i]);
2677 }
Tim Peters3b01a122002-07-19 02:35:45 +00002678
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002679 PyMem_FREE(garbage);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002680 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002681
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002682 return 0;
2683 }
Tim Peters3b01a122002-07-19 02:35:45 +00002684 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002685 else {
Georg Brandl283a1352006-11-19 08:48:30 +00002686 PyErr_Format(PyExc_TypeError,
2687 "list indices must be integers, not %.200s",
2688 item->ob_type->tp_name);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002689 return -1;
2690 }
2691}
2692
2693static PyMappingMethods list_as_mapping = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002694 (lenfunc)list_length,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002695 (binaryfunc)list_subscript,
2696 (objobjargproc)list_ass_subscript
2697};
2698
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002699PyTypeObject PyList_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002700 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002701 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002702 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002703 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002704 (destructor)list_dealloc, /* tp_dealloc */
2705 (printfunc)list_print, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002706 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002707 0, /* tp_setattr */
2708 0, /* tp_compare */
2709 (reprfunc)list_repr, /* tp_repr */
2710 0, /* tp_as_number */
2711 &list_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002712 &list_as_mapping, /* tp_as_mapping */
Guido van Rossum64c06e32007-11-22 00:55:51 +00002713 0, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002714 0, /* tp_call */
2715 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002716 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002717 0, /* tp_setattro */
2718 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002719 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Neal Norwitzee3a1b52007-02-25 19:44:48 +00002720 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002721 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002722 (traverseproc)list_traverse, /* tp_traverse */
2723 (inquiry)list_clear, /* tp_clear */
2724 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002725 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002726 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002727 0, /* tp_iternext */
2728 list_methods, /* tp_methods */
2729 0, /* tp_members */
2730 0, /* tp_getset */
2731 0, /* tp_base */
2732 0, /* tp_dict */
2733 0, /* tp_descr_get */
2734 0, /* tp_descr_set */
2735 0, /* tp_dictoffset */
2736 (initproc)list_init, /* tp_init */
2737 PyType_GenericAlloc, /* tp_alloc */
2738 PyType_GenericNew, /* tp_new */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002739 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002740};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002741
2742
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002743/*********************** List Iterator **************************/
2744
2745typedef struct {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002746 PyObject_HEAD
2747 long it_index;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002748 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002749} listiterobject;
2750
Anthony Baxter377be112006-04-11 06:54:30 +00002751static PyObject *list_iter(PyObject *);
2752static void listiter_dealloc(listiterobject *);
2753static int listiter_traverse(listiterobject *, visitproc, void *);
2754static PyObject *listiter_next(listiterobject *);
2755static PyObject *listiter_len(listiterobject *);
2756
2757PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
2758
2759static PyMethodDef listiter_methods[] = {
2760 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
2761 {NULL, NULL} /* sentinel */
2762};
2763
2764PyTypeObject PyListIter_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002765 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Anthony Baxter377be112006-04-11 06:54:30 +00002766 "listiterator", /* tp_name */
2767 sizeof(listiterobject), /* tp_basicsize */
2768 0, /* tp_itemsize */
2769 /* methods */
2770 (destructor)listiter_dealloc, /* tp_dealloc */
2771 0, /* tp_print */
2772 0, /* tp_getattr */
2773 0, /* tp_setattr */
2774 0, /* tp_compare */
2775 0, /* tp_repr */
2776 0, /* tp_as_number */
2777 0, /* tp_as_sequence */
2778 0, /* tp_as_mapping */
2779 0, /* tp_hash */
2780 0, /* tp_call */
2781 0, /* tp_str */
2782 PyObject_GenericGetAttr, /* tp_getattro */
2783 0, /* tp_setattro */
2784 0, /* tp_as_buffer */
2785 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2786 0, /* tp_doc */
2787 (traverseproc)listiter_traverse, /* tp_traverse */
2788 0, /* tp_clear */
2789 0, /* tp_richcompare */
2790 0, /* tp_weaklistoffset */
2791 PyObject_SelfIter, /* tp_iter */
2792 (iternextfunc)listiter_next, /* tp_iternext */
2793 listiter_methods, /* tp_methods */
2794 0, /* tp_members */
2795};
2796
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002797
Guido van Rossum5086e492002-07-16 15:56:52 +00002798static PyObject *
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002799list_iter(PyObject *seq)
2800{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002801 listiterobject *it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002802
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002803 if (!PyList_Check(seq)) {
2804 PyErr_BadInternalCall();
2805 return NULL;
2806 }
2807 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2808 if (it == NULL)
2809 return NULL;
2810 it->it_index = 0;
2811 Py_INCREF(seq);
2812 it->it_seq = (PyListObject *)seq;
2813 _PyObject_GC_TRACK(it);
2814 return (PyObject *)it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002815}
2816
2817static void
2818listiter_dealloc(listiterobject *it)
2819{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002820 _PyObject_GC_UNTRACK(it);
Guido van Rossum86103ae2002-07-16 20:07:32 +00002821 Py_XDECREF(it->it_seq);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002822 PyObject_GC_Del(it);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002823}
2824
2825static int
2826listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2827{
Thomas Woutersc6e55062006-04-15 21:47:09 +00002828 Py_VISIT(it->it_seq);
2829 return 0;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002830}
2831
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002832static PyObject *
Tim Peters93b2cc42002-06-01 05:22:55 +00002833listiter_next(listiterobject *it)
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002834{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002835 PyListObject *seq;
2836 PyObject *item;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002837
Tim Peters93b2cc42002-06-01 05:22:55 +00002838 assert(it != NULL);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002839 seq = it->it_seq;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002840 if (seq == NULL)
2841 return NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002842 assert(PyList_Check(seq));
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002843
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002844 if (it->it_index < PyList_GET_SIZE(seq)) {
Tim Peters93b2cc42002-06-01 05:22:55 +00002845 item = PyList_GET_ITEM(seq, it->it_index);
2846 ++it->it_index;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002847 Py_INCREF(item);
2848 return item;
2849 }
Guido van Rossum86103ae2002-07-16 20:07:32 +00002850
2851 Py_DECREF(seq);
2852 it->it_seq = NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002853 return NULL;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002854}
2855
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002856static PyObject *
Raymond Hettinger435bf582004-03-18 22:43:10 +00002857listiter_len(listiterobject *it)
2858{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002859 Py_ssize_t len;
Raymond Hettinger40a03822004-04-12 13:05:09 +00002860 if (it->it_seq) {
2861 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2862 if (len >= 0)
Martin v. Löwis18e16552006-02-15 17:27:45 +00002863 return PyInt_FromSsize_t(len);
Raymond Hettinger40a03822004-04-12 13:05:09 +00002864 }
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002865 return PyInt_FromLong(0);
Raymond Hettinger435bf582004-03-18 22:43:10 +00002866}
Anthony Baxter377be112006-04-11 06:54:30 +00002867/*********************** List Reverse Iterator **************************/
Raymond Hettinger435bf582004-03-18 22:43:10 +00002868
Anthony Baxter377be112006-04-11 06:54:30 +00002869typedef struct {
2870 PyObject_HEAD
2871 Py_ssize_t it_index;
2872 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
2873} listreviterobject;
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002874
Anthony Baxter377be112006-04-11 06:54:30 +00002875static PyObject *list_reversed(PyListObject *, PyObject *);
2876static void listreviter_dealloc(listreviterobject *);
2877static int listreviter_traverse(listreviterobject *, visitproc, void *);
2878static PyObject *listreviter_next(listreviterobject *);
2879static Py_ssize_t listreviter_len(listreviterobject *);
2880
2881static PySequenceMethods listreviter_as_sequence = {
2882 (lenfunc)listreviter_len, /* sq_length */
2883 0, /* sq_concat */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002884};
2885
Anthony Baxter377be112006-04-11 06:54:30 +00002886PyTypeObject PyListRevIter_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002887 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Anthony Baxter377be112006-04-11 06:54:30 +00002888 "listreverseiterator", /* tp_name */
2889 sizeof(listreviterobject), /* tp_basicsize */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002890 0, /* tp_itemsize */
2891 /* methods */
Anthony Baxter377be112006-04-11 06:54:30 +00002892 (destructor)listreviter_dealloc, /* tp_dealloc */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002893 0, /* tp_print */
2894 0, /* tp_getattr */
2895 0, /* tp_setattr */
2896 0, /* tp_compare */
2897 0, /* tp_repr */
2898 0, /* tp_as_number */
Anthony Baxter377be112006-04-11 06:54:30 +00002899 &listreviter_as_sequence, /* tp_as_sequence */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002900 0, /* tp_as_mapping */
2901 0, /* tp_hash */
2902 0, /* tp_call */
2903 0, /* tp_str */
2904 PyObject_GenericGetAttr, /* tp_getattro */
2905 0, /* tp_setattro */
2906 0, /* tp_as_buffer */
2907 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2908 0, /* tp_doc */
Anthony Baxter377be112006-04-11 06:54:30 +00002909 (traverseproc)listreviter_traverse, /* tp_traverse */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002910 0, /* tp_clear */
2911 0, /* tp_richcompare */
2912 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00002913 PyObject_SelfIter, /* tp_iter */
Anthony Baxter377be112006-04-11 06:54:30 +00002914 (iternextfunc)listreviter_next, /* tp_iternext */
2915 0,
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002916};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002917
Raymond Hettinger1021c442003-11-07 15:38:09 +00002918static PyObject *
2919list_reversed(PyListObject *seq, PyObject *unused)
2920{
2921 listreviterobject *it;
2922
2923 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2924 if (it == NULL)
2925 return NULL;
2926 assert(PyList_Check(seq));
2927 it->it_index = PyList_GET_SIZE(seq) - 1;
2928 Py_INCREF(seq);
2929 it->it_seq = seq;
2930 PyObject_GC_Track(it);
2931 return (PyObject *)it;
2932}
2933
2934static void
2935listreviter_dealloc(listreviterobject *it)
2936{
2937 PyObject_GC_UnTrack(it);
2938 Py_XDECREF(it->it_seq);
2939 PyObject_GC_Del(it);
2940}
2941
2942static int
2943listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2944{
Thomas Woutersc6e55062006-04-15 21:47:09 +00002945 Py_VISIT(it->it_seq);
2946 return 0;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002947}
2948
2949static PyObject *
2950listreviter_next(listreviterobject *it)
2951{
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002952 PyObject *item;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002953 Py_ssize_t index = it->it_index;
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002954 PyListObject *seq = it->it_seq;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002955
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002956 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2957 item = PyList_GET_ITEM(seq, index);
Raymond Hettinger1021c442003-11-07 15:38:09 +00002958 it->it_index--;
2959 Py_INCREF(item);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002960 return item;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002961 }
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002962 it->it_index = -1;
2963 if (seq != NULL) {
2964 it->it_seq = NULL;
2965 Py_DECREF(seq);
2966 }
2967 return NULL;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002968}
2969
Martin v. Löwis18e16552006-02-15 17:27:45 +00002970static Py_ssize_t
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002971listreviter_len(listreviterobject *it)
2972{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002973 Py_ssize_t len = it->it_index + 1;
Raymond Hettinger40a03822004-04-12 13:05:09 +00002974 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
2975 return 0;
2976 return len;
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002977}