blob: 9e893662b350630245a9202647f5a7ad306e2028 [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
Raymond Hettinger0468e412004-05-05 05:37:53 +000066/* Empty list reuse scheme to save calls to malloc and free */
Christian Heimes5b970ad2008-02-06 13:33:44 +000067#ifndef PyList_MAXFREELIST
68#define PyList_MAXFREELIST 80
69#endif
70static PyListObject *free_list[PyList_MAXFREELIST];
71static int numfree = 0;
Raymond Hettinger0468e412004-05-05 05:37:53 +000072
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +000073void
74PyList_Fini(void)
75{
76 PyListObject *op;
77
Christian Heimes5b970ad2008-02-06 13:33:44 +000078 while (numfree) {
79 numfree--;
80 op = free_list[numfree];
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +000081 assert(PyList_CheckExact(op));
82 PyObject_GC_Del(op);
83 }
84}
85
Guido van Rossumc0b618a1997-05-02 03:12:38 +000086PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000087PyList_New(Py_ssize_t size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000088{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000089 PyListObject *op;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +000090 size_t nbytes;
Tim Peters3986d4e2004-07-29 02:28:42 +000091
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000092 if (size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000093 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000094 return NULL;
95 }
Tim Peters7049d812004-01-18 20:31:02 +000096 nbytes = size * sizeof(PyObject *);
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000097 /* Check for overflow */
Raymond Hettingerfdfe6182004-05-05 06:28:16 +000098 if (nbytes / sizeof(PyObject *) != (size_t)size)
Guido van Rossumc0b618a1997-05-02 03:12:38 +000099 return PyErr_NoMemory();
Christian Heimes5b970ad2008-02-06 13:33:44 +0000100 if (numfree) {
101 numfree--;
102 op = free_list[numfree];
Raymond Hettinger0468e412004-05-05 05:37:53 +0000103 _Py_NewReference((PyObject *)op);
104 } else {
105 op = PyObject_GC_New(PyListObject, &PyList_Type);
106 if (op == NULL)
107 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000108 }
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000109 if (size <= 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000110 op->ob_item = NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000111 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +0000112 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
Neal Norwitza00c0b92006-06-12 02:08:41 +0000113 if (op->ob_item == NULL) {
114 Py_DECREF(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000115 return PyErr_NoMemory();
Neal Norwitza00c0b92006-06-12 02:08:41 +0000116 }
Tim Peters3986d4e2004-07-29 02:28:42 +0000117 memset(op->ob_item, 0, nbytes);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000118 }
Christian Heimese93237d2007-12-19 02:37:44 +0000119 Py_SIZE(op) = size;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000120 op->allocated = size;
Neil Schemenauere83c00e2001-08-29 23:54:21 +0000121 _PyObject_GC_TRACK(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000122 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000123}
124
Martin v. Löwis18e16552006-02-15 17:27:45 +0000125Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000126PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000127{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000128 if (!PyList_Check(op)) {
129 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000130 return -1;
131 }
132 else
Christian Heimese93237d2007-12-19 02:37:44 +0000133 return Py_SIZE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000134}
135
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000136static PyObject *indexerr = NULL;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000137
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000138PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000139PyList_GetItem(PyObject *op, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000140{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000141 if (!PyList_Check(op)) {
142 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000143 return NULL;
144 }
Christian Heimese93237d2007-12-19 02:37:44 +0000145 if (i < 0 || i >= Py_SIZE(op)) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000146 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000147 indexerr = PyString_FromString(
148 "list index out of range");
149 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000150 return NULL;
151 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000152 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000153}
154
155int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000156PyList_SetItem(register PyObject *op, register Py_ssize_t i,
Fred Drakea2f55112000-07-09 15:16:51 +0000157 register PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000158{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000159 register PyObject *olditem;
160 register PyObject **p;
161 if (!PyList_Check(op)) {
162 Py_XDECREF(newitem);
163 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000164 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000165 }
Christian Heimese93237d2007-12-19 02:37:44 +0000166 if (i < 0 || i >= Py_SIZE(op)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000167 Py_XDECREF(newitem);
168 PyErr_SetString(PyExc_IndexError,
169 "list assignment index out of range");
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000170 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000171 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000172 p = ((PyListObject *)op) -> ob_item + i;
Guido van Rossum5fe60581995-03-09 12:12:50 +0000173 olditem = *p;
174 *p = newitem;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000175 Py_XDECREF(olditem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000176 return 0;
177}
178
179static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000180ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000181{
Christian Heimese93237d2007-12-19 02:37:44 +0000182 Py_ssize_t i, n = Py_SIZE(self);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000183 PyObject **items;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000184 if (v == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000185 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000186 return -1;
187 }
Martin v. Löwisb1ed7fa2006-04-13 07:52:27 +0000188 if (n == PY_SSIZE_T_MAX) {
Trent Micka5846642000-08-13 22:47:45 +0000189 PyErr_SetString(PyExc_OverflowError,
190 "cannot add more objects to list");
191 return -1;
192 }
Tim Petersb38e2b62004-07-29 02:29:26 +0000193
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000194 if (list_resize(self, n+1) == -1)
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000195 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000196
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000197 if (where < 0) {
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000198 where += n;
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000199 if (where < 0)
200 where = 0;
201 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000202 if (where > n)
203 where = n;
204 items = self->ob_item;
205 for (i = n; --i >= where; )
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000206 items[i+1] = items[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000207 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000208 items[where] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000209 return 0;
210}
211
212int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000213PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000214{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000215 if (!PyList_Check(op)) {
216 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000217 return -1;
218 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000219 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000220}
221
Raymond Hettinger40a03822004-04-12 13:05:09 +0000222static int
223app1(PyListObject *self, PyObject *v)
224{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000225 Py_ssize_t n = PyList_GET_SIZE(self);
Raymond Hettinger40a03822004-04-12 13:05:09 +0000226
227 assert (v != NULL);
Martin v. Löwisb1ed7fa2006-04-13 07:52:27 +0000228 if (n == PY_SSIZE_T_MAX) {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000229 PyErr_SetString(PyExc_OverflowError,
230 "cannot add more objects to list");
231 return -1;
232 }
233
234 if (list_resize(self, n+1) == -1)
235 return -1;
236
237 Py_INCREF(v);
238 PyList_SET_ITEM(self, n, v);
239 return 0;
240}
241
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000242int
Fred Drakea2f55112000-07-09 15:16:51 +0000243PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000244{
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000245 if (PyList_Check(op) && (newitem != NULL))
246 return app1((PyListObject *)op, newitem);
247 PyErr_BadInternalCall();
248 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000249}
250
251/* Methods */
252
253static void
Fred Drakea2f55112000-07-09 15:16:51 +0000254list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000255{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000256 Py_ssize_t i;
Guido van Rossumff413af2002-03-28 20:34:59 +0000257 PyObject_GC_UnTrack(op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000258 Py_TRASHCAN_SAFE_BEGIN(op)
Jack Jansen7874d1f1995-01-19 12:09:27 +0000259 if (op->ob_item != NULL) {
Guido van Rossumfa717011999-06-09 15:19:34 +0000260 /* Do it backwards, for Christian Tismer.
261 There's a simple test case where somehow this reduces
262 thrashing when a *very* large list is created and
263 immediately deleted. */
Christian Heimese93237d2007-12-19 02:37:44 +0000264 i = Py_SIZE(op);
Guido van Rossumfa717011999-06-09 15:19:34 +0000265 while (--i >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000266 Py_XDECREF(op->ob_item[i]);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000267 }
Guido van Rossumb18618d2000-05-03 23:44:39 +0000268 PyMem_FREE(op->ob_item);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000269 }
Christian Heimes5b970ad2008-02-06 13:33:44 +0000270 if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op))
271 free_list[numfree++] = op;
Tim Petersb38e2b62004-07-29 02:29:26 +0000272 else
Christian Heimese93237d2007-12-19 02:37:44 +0000273 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000274 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000275}
276
Guido van Rossum90933611991-06-07 16:10:43 +0000277static int
Fred Drakea2f55112000-07-09 15:16:51 +0000278list_print(PyListObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000279{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000280 int rc;
281 Py_ssize_t i;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000282
Martin v. Löwis18e16552006-02-15 17:27:45 +0000283 rc = Py_ReprEnter((PyObject*)op);
284 if (rc != 0) {
285 if (rc < 0)
286 return rc;
Brett Cannon01531592007-09-17 03:28:34 +0000287 Py_BEGIN_ALLOW_THREADS
Guido van Rossumfb376de1998-04-10 22:47:27 +0000288 fprintf(fp, "[...]");
Brett Cannon01531592007-09-17 03:28:34 +0000289 Py_END_ALLOW_THREADS
Guido van Rossumfb376de1998-04-10 22:47:27 +0000290 return 0;
291 }
Brett Cannon01531592007-09-17 03:28:34 +0000292 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000293 fprintf(fp, "[");
Brett Cannon01531592007-09-17 03:28:34 +0000294 Py_END_ALLOW_THREADS
Christian Heimese93237d2007-12-19 02:37:44 +0000295 for (i = 0; i < Py_SIZE(op); i++) {
Brett Cannon01531592007-09-17 03:28:34 +0000296 if (i > 0) {
297 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000298 fprintf(fp, ", ");
Brett Cannon01531592007-09-17 03:28:34 +0000299 Py_END_ALLOW_THREADS
300 }
Guido van Rossumfb376de1998-04-10 22:47:27 +0000301 if (PyObject_Print(op->ob_item[i], fp, 0) != 0) {
302 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000303 return -1;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000304 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000305 }
Brett Cannon01531592007-09-17 03:28:34 +0000306 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000307 fprintf(fp, "]");
Brett Cannon01531592007-09-17 03:28:34 +0000308 Py_END_ALLOW_THREADS
Guido van Rossumfb376de1998-04-10 22:47:27 +0000309 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000310 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000311}
312
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000313static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000314list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000315{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000316 Py_ssize_t i;
Tim Petersa7259592001-06-16 05:11:17 +0000317 PyObject *s, *temp;
318 PyObject *pieces = NULL, *result = NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000319
320 i = Py_ReprEnter((PyObject*)v);
321 if (i != 0) {
Tim Petersa7259592001-06-16 05:11:17 +0000322 return i > 0 ? PyString_FromString("[...]") : NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000323 }
Tim Petersa7259592001-06-16 05:11:17 +0000324
Christian Heimese93237d2007-12-19 02:37:44 +0000325 if (Py_SIZE(v) == 0) {
Tim Petersa7259592001-06-16 05:11:17 +0000326 result = PyString_FromString("[]");
327 goto Done;
328 }
329
330 pieces = PyList_New(0);
331 if (pieces == NULL)
332 goto Done;
333
334 /* Do repr() on each element. Note that this may mutate the list,
335 so must refetch the list size on each iteration. */
Christian Heimese93237d2007-12-19 02:37:44 +0000336 for (i = 0; i < Py_SIZE(v); ++i) {
Tim Petersa7259592001-06-16 05:11:17 +0000337 int status;
Brett Cannona0c05512007-09-10 21:38:27 +0000338 if (Py_EnterRecursiveCall(" while getting the repr of a list"))
339 goto Done;
Tim Petersa7259592001-06-16 05:11:17 +0000340 s = PyObject_Repr(v->ob_item[i]);
Brett Cannona0c05512007-09-10 21:38:27 +0000341 Py_LeaveRecursiveCall();
Tim Petersa7259592001-06-16 05:11:17 +0000342 if (s == NULL)
343 goto Done;
344 status = PyList_Append(pieces, s);
345 Py_DECREF(s); /* append created a new ref */
346 if (status < 0)
347 goto Done;
348 }
349
350 /* Add "[]" decorations to the first and last items. */
351 assert(PyList_GET_SIZE(pieces) > 0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000352 s = PyString_FromString("[");
Tim Petersa7259592001-06-16 05:11:17 +0000353 if (s == NULL)
354 goto Done;
355 temp = PyList_GET_ITEM(pieces, 0);
356 PyString_ConcatAndDel(&s, temp);
357 PyList_SET_ITEM(pieces, 0, s);
358 if (s == NULL)
359 goto Done;
360
361 s = PyString_FromString("]");
362 if (s == NULL)
363 goto Done;
364 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
365 PyString_ConcatAndDel(&temp, s);
366 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
367 if (temp == NULL)
368 goto Done;
369
370 /* Paste them all together with ", " between. */
371 s = PyString_FromString(", ");
372 if (s == NULL)
373 goto Done;
374 result = _PyString_Join(s, pieces);
Tim Peters3b01a122002-07-19 02:35:45 +0000375 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +0000376
377Done:
378 Py_XDECREF(pieces);
Guido van Rossumfb376de1998-04-10 22:47:27 +0000379 Py_ReprLeave((PyObject *)v);
Tim Petersa7259592001-06-16 05:11:17 +0000380 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000381}
382
Martin v. Löwis18e16552006-02-15 17:27:45 +0000383static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000384list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000385{
Christian Heimese93237d2007-12-19 02:37:44 +0000386 return Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000387}
388
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000389static int
Fred Drakea2f55112000-07-09 15:16:51 +0000390list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000391{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000392 Py_ssize_t i;
393 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000394
Christian Heimese93237d2007-12-19 02:37:44 +0000395 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
Raymond Hettingeraae59992002-09-05 14:23:49 +0000396 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000397 Py_EQ);
Neal Norwitzbb9c5f52002-09-05 21:32:55 +0000398 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000399}
400
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000401static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000402list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000403{
Christian Heimese93237d2007-12-19 02:37:44 +0000404 if (i < 0 || i >= Py_SIZE(a)) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000405 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000406 indexerr = PyString_FromString(
407 "list index out of range");
408 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000409 return NULL;
410 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000411 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000412 return a->ob_item[i];
413}
414
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000415static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000416list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000417{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000418 PyListObject *np;
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000419 PyObject **src, **dest;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000420 Py_ssize_t i, len;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000421 if (ilow < 0)
422 ilow = 0;
Christian Heimese93237d2007-12-19 02:37:44 +0000423 else if (ilow > Py_SIZE(a))
424 ilow = Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000425 if (ihigh < ilow)
426 ihigh = ilow;
Christian Heimese93237d2007-12-19 02:37:44 +0000427 else if (ihigh > Py_SIZE(a))
428 ihigh = Py_SIZE(a);
Raymond Hettinger99842b62004-03-08 05:56:15 +0000429 len = ihigh - ilow;
430 np = (PyListObject *) PyList_New(len);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000431 if (np == NULL)
432 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000433
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000434 src = a->ob_item + ilow;
435 dest = np->ob_item;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000436 for (i = 0; i < len; i++) {
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000437 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000438 Py_INCREF(v);
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000439 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000440 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000441 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000442}
443
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000444PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000445PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000446{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000447 if (!PyList_Check(a)) {
448 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000449 return NULL;
450 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000451 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000452}
453
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000454static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000455list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000456{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000457 Py_ssize_t size;
458 Py_ssize_t i;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000459 PyObject **src, **dest;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000460 PyListObject *np;
461 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000462 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000463 "can only concatenate list (not \"%.200s\") to list",
464 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000465 return NULL;
466 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000467#define b ((PyListObject *)bb)
Christian Heimese93237d2007-12-19 02:37:44 +0000468 size = Py_SIZE(a) + Py_SIZE(b);
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000469 if (size < 0)
470 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000471 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000472 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000473 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000474 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000475 src = a->ob_item;
476 dest = np->ob_item;
Christian Heimese93237d2007-12-19 02:37:44 +0000477 for (i = 0; i < Py_SIZE(a); i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000478 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000479 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000480 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000481 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000482 src = b->ob_item;
Christian Heimese93237d2007-12-19 02:37:44 +0000483 dest = np->ob_item + Py_SIZE(a);
484 for (i = 0; i < Py_SIZE(b); i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000485 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000486 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000487 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000488 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000489 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000490#undef b
491}
492
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000493static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000494list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000495{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000496 Py_ssize_t i, j;
497 Py_ssize_t size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000498 PyListObject *np;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000499 PyObject **p, **items;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000500 PyObject *elem;
Guido van Rossumed98d481991-03-06 13:07:53 +0000501 if (n < 0)
502 n = 0;
Christian Heimese93237d2007-12-19 02:37:44 +0000503 size = Py_SIZE(a) * n;
504 if (n && size/n != Py_SIZE(a))
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000505 return PyErr_NoMemory();
Armin Rigoa1e42e12007-10-17 18:46:37 +0000506 if (size == 0)
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000507 return PyList_New(0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000508 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000509 if (np == NULL)
510 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000511
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000512 items = np->ob_item;
Christian Heimese93237d2007-12-19 02:37:44 +0000513 if (Py_SIZE(a) == 1) {
Raymond Hettinger6624e682003-05-21 05:58:46 +0000514 elem = a->ob_item[0];
515 for (i = 0; i < n; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000516 items[i] = elem;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000517 Py_INCREF(elem);
518 }
519 return (PyObject *) np;
520 }
Guido van Rossumed98d481991-03-06 13:07:53 +0000521 p = np->ob_item;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000522 items = a->ob_item;
Guido van Rossumed98d481991-03-06 13:07:53 +0000523 for (i = 0; i < n; i++) {
Christian Heimese93237d2007-12-19 02:37:44 +0000524 for (j = 0; j < Py_SIZE(a); j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000525 *p = items[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000526 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000527 p++;
528 }
529 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000530 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000531}
532
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000533static int
Armin Rigo93677f02004-07-29 12:40:23 +0000534list_clear(PyListObject *a)
535{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000536 Py_ssize_t i;
Armin Rigo93677f02004-07-29 12:40:23 +0000537 PyObject **item = a->ob_item;
538 if (item != NULL) {
539 /* Because XDECREF can recursively invoke operations on
540 this list, we make it empty first. */
Christian Heimese93237d2007-12-19 02:37:44 +0000541 i = Py_SIZE(a);
542 Py_SIZE(a) = 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000543 a->ob_item = NULL;
544 a->allocated = 0;
545 while (--i >= 0) {
546 Py_XDECREF(item[i]);
547 }
548 PyMem_FREE(item);
549 }
550 /* Never fails; the return value can be ignored.
551 Note that there is no guarantee that the list is actually empty
552 at this point, because XDECREF may have populated it again! */
553 return 0;
554}
555
Tim Peters8fc4a912004-07-31 21:53:19 +0000556/* a[ilow:ihigh] = v if v != NULL.
557 * del a[ilow:ihigh] if v == NULL.
558 *
559 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
560 * guaranteed the call cannot fail.
561 */
Armin Rigo93677f02004-07-29 12:40:23 +0000562static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000563list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000564{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000565 /* Because [X]DECREF can recursively invoke list operations on
566 this list, we must postpone all [X]DECREF activity until
567 after the list is back in its canonical shape. Therefore
568 we must allocate an additional array, 'recycle', into which
569 we temporarily copy the items that are deleted from the
570 list. :-( */
Tim Peters73572222004-07-31 02:54:42 +0000571 PyObject *recycle_on_stack[8];
572 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000573 PyObject **item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000574 PyObject **vitem = NULL;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000575 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000576 Py_ssize_t n; /* # of elements in replacement list */
577 Py_ssize_t norig; /* # of elements in list getting replaced */
578 Py_ssize_t d; /* Change in size */
579 Py_ssize_t k;
Tim Peters8d9eb102004-07-31 02:24:20 +0000580 size_t s;
581 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000582#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000583 if (v == NULL)
584 n = 0;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000585 else {
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000586 if (a == b) {
587 /* Special case "a[i:j] = a" -- copy b first */
Christian Heimese93237d2007-12-19 02:37:44 +0000588 v = list_slice(b, 0, Py_SIZE(b));
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000589 if (v == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000590 return result;
591 result = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000592 Py_DECREF(v);
Tim Peters8d9eb102004-07-31 02:24:20 +0000593 return result;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000594 }
Raymond Hettingerf889e102004-03-09 08:04:33 +0000595 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000596 if(v_as_SF == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000597 goto Error;
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000598 n = PySequence_Fast_GET_SIZE(v_as_SF);
Raymond Hettinger42bec932004-03-12 16:38:17 +0000599 vitem = PySequence_Fast_ITEMS(v_as_SF);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000600 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000601 if (ilow < 0)
602 ilow = 0;
Christian Heimese93237d2007-12-19 02:37:44 +0000603 else if (ilow > Py_SIZE(a))
604 ilow = Py_SIZE(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000605
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000606 if (ihigh < ilow)
607 ihigh = ilow;
Christian Heimese93237d2007-12-19 02:37:44 +0000608 else if (ihigh > Py_SIZE(a))
609 ihigh = Py_SIZE(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000610
Tim Peters8d9eb102004-07-31 02:24:20 +0000611 norig = ihigh - ilow;
612 assert(norig >= 0);
613 d = n - norig;
Christian Heimese93237d2007-12-19 02:37:44 +0000614 if (Py_SIZE(a) + d == 0) {
Armin Rigo93677f02004-07-29 12:40:23 +0000615 Py_XDECREF(v_as_SF);
616 return list_clear(a);
617 }
618 item = a->ob_item;
Tim Peters8d9eb102004-07-31 02:24:20 +0000619 /* recycle the items that we are about to remove */
620 s = norig * sizeof(PyObject *);
Tim Peters73572222004-07-31 02:54:42 +0000621 if (s > sizeof(recycle_on_stack)) {
Armin Rigo1dd04a02004-07-30 11:38:22 +0000622 recycle = (PyObject **)PyMem_MALLOC(s);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000623 if (recycle == NULL) {
624 PyErr_NoMemory();
Tim Peters8d9eb102004-07-31 02:24:20 +0000625 goto Error;
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000626 }
627 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000628 memcpy(recycle, &item[ilow], s);
Tim Peters8d9eb102004-07-31 02:24:20 +0000629
Armin Rigo1dd04a02004-07-30 11:38:22 +0000630 if (d < 0) { /* Delete -d items */
631 memmove(&item[ihigh+d], &item[ihigh],
Christian Heimese93237d2007-12-19 02:37:44 +0000632 (Py_SIZE(a) - ihigh)*sizeof(PyObject *));
633 list_resize(a, Py_SIZE(a) + d);
Armin Rigo1dd04a02004-07-30 11:38:22 +0000634 item = a->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000635 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000636 else if (d > 0) { /* Insert d items */
Christian Heimese93237d2007-12-19 02:37:44 +0000637 k = Py_SIZE(a);
Tim Peters73572222004-07-31 02:54:42 +0000638 if (list_resize(a, k+d) < 0)
Tim Peters8d9eb102004-07-31 02:24:20 +0000639 goto Error;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000640 item = a->ob_item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000641 memmove(&item[ihigh+d], &item[ihigh],
Tim Peters73572222004-07-31 02:54:42 +0000642 (k - ihigh)*sizeof(PyObject *));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000643 }
644 for (k = 0; k < n; k++, ilow++) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000645 PyObject *w = vitem[k];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000646 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000647 item[ilow] = w;
648 }
Tim Peters73572222004-07-31 02:54:42 +0000649 for (k = norig - 1; k >= 0; --k)
650 Py_XDECREF(recycle[k]);
Tim Peters8d9eb102004-07-31 02:24:20 +0000651 result = 0;
652 Error:
Tim Peters73572222004-07-31 02:54:42 +0000653 if (recycle != recycle_on_stack)
Armin Rigo1dd04a02004-07-30 11:38:22 +0000654 PyMem_FREE(recycle);
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000655 Py_XDECREF(v_as_SF);
Tim Peters8d9eb102004-07-31 02:24:20 +0000656 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000657#undef b
658}
659
Guido van Rossum234f9421993-06-17 12:35:49 +0000660int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000661PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000662{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000663 if (!PyList_Check(a)) {
664 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000665 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000666 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000667 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000668}
669
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000670static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000671list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000672{
673 PyObject **items;
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000674 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000675
676
677 size = PyList_GET_SIZE(self);
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000678 if (size == 0 || n == 1) {
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000679 Py_INCREF(self);
680 return (PyObject *)self;
681 }
682
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000683 if (n < 1) {
Armin Rigo93677f02004-07-29 12:40:23 +0000684 (void)list_clear(self);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000685 Py_INCREF(self);
686 return (PyObject *)self;
687 }
688
Thomas Woutersa97744c2008-01-25 21:09:34 +0000689 if (size > PY_SSIZE_T_MAX / n) {
Armin Rigoa1e42e12007-10-17 18:46:37 +0000690 return PyErr_NoMemory();
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000691 }
692
693 if (list_resize(self, size*n) == -1)
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000694 return NULL;
695
696 p = size;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000697 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000698 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
699 for (j = 0; j < size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000700 PyObject *o = items[j];
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000701 Py_INCREF(o);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000702 items[p++] = o;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000703 }
704 }
705 Py_INCREF(self);
706 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000707}
708
Guido van Rossum4a450d01991-04-03 19:05:18 +0000709static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000710list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000711{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000712 PyObject *old_value;
Christian Heimese93237d2007-12-19 02:37:44 +0000713 if (i < 0 || i >= Py_SIZE(a)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000714 PyErr_SetString(PyExc_IndexError,
715 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000716 return -1;
717 }
718 if (v == NULL)
719 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000720 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000721 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000722 a->ob_item[i] = v;
Tim Peters3b01a122002-07-19 02:35:45 +0000723 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000724 return 0;
725}
726
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000727static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000728listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000729{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000730 Py_ssize_t i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000731 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000732 if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000733 return NULL;
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000734 if (ins1(self, i, v) == 0)
735 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000736 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000737}
738
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000739static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000740listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000741{
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000742 if (app1(self, v) == 0)
743 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000744 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000745}
746
Barry Warsawdedf6d61998-10-09 16:37:25 +0000747static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000748listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000749{
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000750 PyObject *it; /* iter(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000751 Py_ssize_t m; /* size of self */
752 Py_ssize_t n; /* guess for size of b */
753 Py_ssize_t mn; /* m + n */
754 Py_ssize_t i;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000755 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000756
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000757 /* Special cases:
Tim Petersb38e2b62004-07-29 02:29:26 +0000758 1) lists and tuples which can use PySequence_Fast ops
759 2) extending self to self requires making a copy first
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000760 */
761 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
Armin Rigo70d172d2004-03-20 22:19:23 +0000762 PyObject **src, **dest;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000763 b = PySequence_Fast(b, "argument must be iterable");
764 if (!b)
765 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000766 n = PySequence_Fast_GET_SIZE(b);
767 if (n == 0) {
768 /* short circuit when b is empty */
769 Py_DECREF(b);
770 Py_RETURN_NONE;
771 }
Christian Heimese93237d2007-12-19 02:37:44 +0000772 m = Py_SIZE(self);
Armin Rigo70d172d2004-03-20 22:19:23 +0000773 if (list_resize(self, m + n) == -1) {
774 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000775 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000776 }
777 /* note that we may still have self == b here for the
778 * situation a.extend(a), but the following code works
779 * in that case too. Just make sure to resize self
780 * before calling PySequence_Fast_ITEMS.
781 */
782 /* populate the end of self with b's items */
783 src = PySequence_Fast_ITEMS(b);
784 dest = self->ob_item + m;
785 for (i = 0; i < n; i++) {
786 PyObject *o = src[i];
787 Py_INCREF(o);
788 dest[i] = o;
789 }
790 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000791 Py_RETURN_NONE;
792 }
793
794 it = PyObject_GetIter(b);
795 if (it == NULL)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000796 return NULL;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000797 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000798
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000799 /* Guess a result list size. */
Raymond Hettinger4e2f7142007-12-06 00:56:53 +0000800 n = _PyObject_LengthHint(b, 8);
Christian Heimese93237d2007-12-19 02:37:44 +0000801 m = Py_SIZE(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000802 mn = m + n;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000803 if (mn >= m) {
804 /* Make room. */
805 if (list_resize(self, mn) == -1)
806 goto error;
807 /* Make the list sane again. */
Christian Heimese93237d2007-12-19 02:37:44 +0000808 Py_SIZE(self) = m;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000809 }
810 /* Else m + n overflowed; on the chance that n lied, and there really
811 * is enough room, ignore it. If n was telling the truth, we'll
812 * eventually run out of memory during the loop.
813 */
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000814
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000815 /* Run iterator to exhaustion. */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000816 for (;;) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000817 PyObject *item = iternext(it);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000818 if (item == NULL) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000819 if (PyErr_Occurred()) {
820 if (PyErr_ExceptionMatches(PyExc_StopIteration))
821 PyErr_Clear();
822 else
823 goto error;
824 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000825 break;
826 }
Christian Heimese93237d2007-12-19 02:37:44 +0000827 if (Py_SIZE(self) < self->allocated) {
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000828 /* steals ref */
Christian Heimese93237d2007-12-19 02:37:44 +0000829 PyList_SET_ITEM(self, Py_SIZE(self), item);
830 ++Py_SIZE(self);
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000831 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000832 else {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000833 int status = app1(self, item);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000834 Py_DECREF(item); /* append creates a new ref */
835 if (status < 0)
836 goto error;
837 }
838 }
839
840 /* Cut back result list if initial guess was too large. */
Christian Heimese93237d2007-12-19 02:37:44 +0000841 if (Py_SIZE(self) < self->allocated)
842 list_resize(self, Py_SIZE(self)); /* shrinking can't fail */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000843
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000844 Py_DECREF(it);
845 Py_RETURN_NONE;
846
847 error:
848 Py_DECREF(it);
849 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000850}
851
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000852PyObject *
853_PyList_Extend(PyListObject *self, PyObject *b)
854{
855 return listextend(self, b);
856}
857
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000858static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000859list_inplace_concat(PyListObject *self, PyObject *other)
860{
861 PyObject *result;
862
863 result = listextend(self, other);
864 if (result == NULL)
865 return result;
866 Py_DECREF(result);
867 Py_INCREF(self);
868 return (PyObject *)self;
869}
870
871static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000872listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000873{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000874 Py_ssize_t i = -1;
Armin Rigo7ccbca92006-10-04 12:17:45 +0000875 PyObject *v;
Tim Peters8fc4a912004-07-31 21:53:19 +0000876 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000877
Armin Rigo7ccbca92006-10-04 12:17:45 +0000878 if (!PyArg_ParseTuple(args, "|n:pop", &i))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000879 return NULL;
Armin Rigo7ccbca92006-10-04 12:17:45 +0000880
Christian Heimese93237d2007-12-19 02:37:44 +0000881 if (Py_SIZE(self) == 0) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000882 /* Special-case most common failure cause */
883 PyErr_SetString(PyExc_IndexError, "pop from empty list");
884 return NULL;
885 }
886 if (i < 0)
Christian Heimese93237d2007-12-19 02:37:44 +0000887 i += Py_SIZE(self);
888 if (i < 0 || i >= Py_SIZE(self)) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000889 PyErr_SetString(PyExc_IndexError, "pop index out of range");
890 return NULL;
891 }
892 v = self->ob_item[i];
Christian Heimese93237d2007-12-19 02:37:44 +0000893 if (i == Py_SIZE(self) - 1) {
894 status = list_resize(self, Py_SIZE(self) - 1);
Tim Peters8fc4a912004-07-31 21:53:19 +0000895 assert(status >= 0);
896 return v; /* and v now owns the reference the list had */
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000897 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000898 Py_INCREF(v);
Tim Peters8fc4a912004-07-31 21:53:19 +0000899 status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
900 assert(status >= 0);
901 /* Use status, so that in a release build compilers don't
902 * complain about the unused name.
903 */
Brett Cannon651dd522004-08-08 21:21:18 +0000904 (void) status;
905
906 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000907}
908
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000909/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
910static void
911reverse_slice(PyObject **lo, PyObject **hi)
912{
913 assert(lo && hi);
914
915 --hi;
916 while (lo < hi) {
917 PyObject *t = *lo;
918 *lo = *hi;
919 *hi = t;
920 ++lo;
921 --hi;
922 }
923}
924
Tim Petersa64dc242002-08-01 02:13:36 +0000925/* Lots of code for an adaptive, stable, natural mergesort. There are many
926 * pieces to this algorithm; read listsort.txt for overviews and details.
927 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000928
Guido van Rossum3f236de1996-12-10 23:55:39 +0000929/* Comparison function. Takes care of calling a user-supplied
Tim Peters66860f62002-08-04 17:47:26 +0000930 * comparison function (any callable Python object), which must not be
931 * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool
932 * with Py_LT if you know it's NULL).
Tim Petersa64dc242002-08-01 02:13:36 +0000933 * Returns -1 on error, 1 if x < y, 0 if x >= y.
934 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000935static int
Tim Petersa8c974c2002-07-19 03:30:57 +0000936islt(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000937{
Tim Petersf2a04732002-07-11 21:46:16 +0000938 PyObject *res;
939 PyObject *args;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000940 Py_ssize_t i;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000941
Tim Peters66860f62002-08-04 17:47:26 +0000942 assert(compare != NULL);
Tim Petersa8c974c2002-07-19 03:30:57 +0000943 /* Call the user's comparison function and translate the 3-way
944 * result into true or false (or error).
945 */
Tim Petersf2a04732002-07-11 21:46:16 +0000946 args = PyTuple_New(2);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000947 if (args == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000948 return -1;
Tim Petersf2a04732002-07-11 21:46:16 +0000949 Py_INCREF(x);
950 Py_INCREF(y);
951 PyTuple_SET_ITEM(args, 0, x);
952 PyTuple_SET_ITEM(args, 1, y);
Tim Peters58cf3612002-07-15 05:16:13 +0000953 res = PyObject_Call(compare, args, NULL);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000954 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000955 if (res == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000956 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000957 if (!PyInt_Check(res)) {
Georg Brandl283a1352006-11-19 08:48:30 +0000958 PyErr_Format(PyExc_TypeError,
959 "comparison function must return int, not %.200s",
960 res->ob_type->tp_name);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000961 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +0000962 return -1;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000963 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000964 i = PyInt_AsLong(res);
965 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +0000966 return i < 0;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000967}
968
Tim Peters66860f62002-08-04 17:47:26 +0000969/* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
970 * islt. This avoids a layer of function call in the usual case, and
971 * sorting does many comparisons.
972 * Returns -1 on error, 1 if x < y, 0 if x >= y.
973 */
974#define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
975 PyObject_RichCompareBool(X, Y, Py_LT) : \
976 islt(X, Y, COMPARE))
977
978/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +0000979 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
980 started. It makes more sense in context <wink>. X and Y are PyObject*s.
981*/
Tim Peters66860f62002-08-04 17:47:26 +0000982#define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
Tim Petersa8c974c2002-07-19 03:30:57 +0000983 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000984
985/* binarysort is the best method for sorting small arrays: it does
986 few compares, but can do data movement quadratic in the number of
987 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000988 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +0000989 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000990 On entry, must have lo <= start <= hi, and that [lo, start) is already
991 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +0000992 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000993 Even in case of error, the output slice will be some permutation of
994 the input (nothing is lost or duplicated).
995*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000996static int
Fred Drakea2f55112000-07-09 15:16:51 +0000997binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
998 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000999{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001000 register Py_ssize_t k;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001001 register PyObject **l, **p, **r;
1002 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001003
Tim Petersa8c974c2002-07-19 03:30:57 +00001004 assert(lo <= start && start <= hi);
1005 /* assert [lo, start) is sorted */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001006 if (lo == start)
1007 ++start;
1008 for (; start < hi; ++start) {
1009 /* set l to where *start belongs */
1010 l = lo;
1011 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001012 pivot = *r;
Tim Peters0fe977c2002-07-19 06:12:32 +00001013 /* Invariants:
1014 * pivot >= all in [lo, l).
1015 * pivot < all in [r, start).
1016 * The second is vacuously true at the start.
1017 */
1018 assert(l < r);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001019 do {
1020 p = l + ((r - l) >> 1);
Tim Petersa8c974c2002-07-19 03:30:57 +00001021 IFLT(pivot, *p)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001022 r = p;
1023 else
Tim Peters0fe977c2002-07-19 06:12:32 +00001024 l = p+1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001025 } while (l < r);
Tim Peters0fe977c2002-07-19 06:12:32 +00001026 assert(l == r);
1027 /* The invariants still hold, so pivot >= all in [lo, l) and
1028 pivot < all in [l, start), so pivot belongs at l. Note
1029 that if there are elements equal to pivot, l points to the
1030 first slot after them -- that's why this sort is stable.
1031 Slide over to make room.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001032 Caution: using memmove is much slower under MSVC 5;
1033 we're not usually moving many slots. */
1034 for (p = start; p > l; --p)
1035 *p = *(p-1);
1036 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001037 }
Guido van Rossum3f236de1996-12-10 23:55:39 +00001038 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001039
1040 fail:
1041 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001042}
1043
Tim Petersa64dc242002-08-01 02:13:36 +00001044/*
1045Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1046is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001047
Tim Petersa64dc242002-08-01 02:13:36 +00001048 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001049
Tim Petersa64dc242002-08-01 02:13:36 +00001050or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001051
Tim Petersa64dc242002-08-01 02:13:36 +00001052 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001053
Tim Petersa64dc242002-08-01 02:13:36 +00001054Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1055For its intended use in a stable mergesort, the strictness of the defn of
1056"descending" is needed so that the caller can safely reverse a descending
1057sequence without violating stability (strict > ensures there are no equal
1058elements to get out of order).
1059
1060Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001061*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001062static Py_ssize_t
Tim Petersa64dc242002-08-01 02:13:36 +00001063count_run(PyObject **lo, PyObject **hi, PyObject *compare, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001064{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001065 Py_ssize_t k;
1066 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001067
Tim Petersa64dc242002-08-01 02:13:36 +00001068 assert(lo < hi);
1069 *descending = 0;
1070 ++lo;
1071 if (lo == hi)
1072 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001073
Tim Petersa64dc242002-08-01 02:13:36 +00001074 n = 2;
1075 IFLT(*lo, *(lo-1)) {
1076 *descending = 1;
1077 for (lo = lo+1; lo < hi; ++lo, ++n) {
1078 IFLT(*lo, *(lo-1))
1079 ;
1080 else
1081 break;
1082 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001083 }
Tim Petersa64dc242002-08-01 02:13:36 +00001084 else {
1085 for (lo = lo+1; lo < hi; ++lo, ++n) {
1086 IFLT(*lo, *(lo-1))
1087 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001088 }
1089 }
1090
Tim Petersa64dc242002-08-01 02:13:36 +00001091 return n;
1092fail:
1093 return -1;
1094}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001095
Tim Petersa64dc242002-08-01 02:13:36 +00001096/*
1097Locate the proper position of key in a sorted vector; if the vector contains
1098an element equal to key, return the position immediately to the left of
1099the leftmost equal element. [gallop_right() does the same except returns
1100the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001101
Tim Petersa64dc242002-08-01 02:13:36 +00001102"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001103
Tim Petersa64dc242002-08-01 02:13:36 +00001104"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1105hint is to the final result, the faster this runs.
1106
1107The return value is the int k in 0..n such that
1108
1109 a[k-1] < key <= a[k]
1110
1111pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1112key belongs at index k; or, IOW, the first k elements of a should precede
1113key, and the last n-k should follow key.
1114
1115Returns -1 on error. See listsort.txt for info on the method.
1116*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001117static Py_ssize_t
1118gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
Tim Petersa64dc242002-08-01 02:13:36 +00001119{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001120 Py_ssize_t ofs;
1121 Py_ssize_t lastofs;
1122 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001123
1124 assert(key && a && n > 0 && hint >= 0 && hint < n);
1125
1126 a += hint;
1127 lastofs = 0;
1128 ofs = 1;
1129 IFLT(*a, key) {
1130 /* a[hint] < key -- gallop right, until
1131 * a[hint + lastofs] < key <= a[hint + ofs]
1132 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001133 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001134 while (ofs < maxofs) {
1135 IFLT(a[ofs], key) {
1136 lastofs = ofs;
1137 ofs = (ofs << 1) + 1;
1138 if (ofs <= 0) /* int overflow */
1139 ofs = maxofs;
1140 }
1141 else /* key <= a[hint + ofs] */
1142 break;
1143 }
1144 if (ofs > maxofs)
1145 ofs = maxofs;
1146 /* Translate back to offsets relative to &a[0]. */
1147 lastofs += hint;
1148 ofs += hint;
1149 }
1150 else {
1151 /* key <= a[hint] -- gallop left, until
1152 * a[hint - ofs] < key <= a[hint - lastofs]
1153 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001154 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001155 while (ofs < maxofs) {
1156 IFLT(*(a-ofs), key)
1157 break;
1158 /* key <= a[hint - ofs] */
1159 lastofs = ofs;
1160 ofs = (ofs << 1) + 1;
1161 if (ofs <= 0) /* int overflow */
1162 ofs = maxofs;
1163 }
1164 if (ofs > maxofs)
1165 ofs = maxofs;
1166 /* Translate back to positive offsets relative to &a[0]. */
1167 k = lastofs;
1168 lastofs = hint - ofs;
1169 ofs = hint - k;
1170 }
1171 a -= hint;
1172
1173 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1174 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1175 * right of lastofs but no farther right than ofs. Do a binary
1176 * search, with invariant a[lastofs-1] < key <= a[ofs].
1177 */
1178 ++lastofs;
1179 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001180 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001181
1182 IFLT(a[m], key)
1183 lastofs = m+1; /* a[m] < key */
1184 else
1185 ofs = m; /* key <= a[m] */
1186 }
1187 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1188 return ofs;
1189
1190fail:
1191 return -1;
1192}
1193
1194/*
1195Exactly like gallop_left(), except that if key already exists in a[0:n],
1196finds the position immediately to the right of the rightmost equal value.
1197
1198The return value is the int k in 0..n such that
1199
1200 a[k-1] <= key < a[k]
1201
1202or -1 if error.
1203
1204The code duplication is massive, but this is enough different given that
1205we're sticking to "<" comparisons that it's much harder to follow if
1206written as one routine with yet another "left or right?" flag.
1207*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001208static Py_ssize_t
1209gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
Tim Petersa64dc242002-08-01 02:13:36 +00001210{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001211 Py_ssize_t ofs;
1212 Py_ssize_t lastofs;
1213 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001214
1215 assert(key && a && n > 0 && hint >= 0 && hint < n);
1216
1217 a += hint;
1218 lastofs = 0;
1219 ofs = 1;
1220 IFLT(key, *a) {
1221 /* key < a[hint] -- gallop left, until
1222 * a[hint - ofs] <= key < a[hint - lastofs]
1223 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001224 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001225 while (ofs < maxofs) {
1226 IFLT(key, *(a-ofs)) {
1227 lastofs = ofs;
1228 ofs = (ofs << 1) + 1;
1229 if (ofs <= 0) /* int overflow */
1230 ofs = maxofs;
1231 }
1232 else /* a[hint - ofs] <= key */
1233 break;
1234 }
1235 if (ofs > maxofs)
1236 ofs = maxofs;
1237 /* Translate back to positive offsets relative to &a[0]. */
1238 k = lastofs;
1239 lastofs = hint - ofs;
1240 ofs = hint - k;
1241 }
1242 else {
1243 /* a[hint] <= key -- gallop right, until
1244 * a[hint + lastofs] <= key < a[hint + ofs]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001245 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001246 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001247 while (ofs < maxofs) {
1248 IFLT(key, a[ofs])
1249 break;
1250 /* a[hint + ofs] <= key */
1251 lastofs = ofs;
1252 ofs = (ofs << 1) + 1;
1253 if (ofs <= 0) /* int overflow */
1254 ofs = maxofs;
1255 }
1256 if (ofs > maxofs)
1257 ofs = maxofs;
1258 /* Translate back to offsets relative to &a[0]. */
1259 lastofs += hint;
1260 ofs += hint;
1261 }
1262 a -= hint;
1263
1264 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1265 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1266 * right of lastofs but no farther right than ofs. Do a binary
1267 * search, with invariant a[lastofs-1] <= key < a[ofs].
1268 */
1269 ++lastofs;
1270 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001271 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001272
1273 IFLT(key, a[m])
1274 ofs = m; /* key < a[m] */
1275 else
1276 lastofs = m+1; /* a[m] <= key */
1277 }
1278 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1279 return ofs;
1280
1281fail:
1282 return -1;
1283}
1284
1285/* The maximum number of entries in a MergeState's pending-runs stack.
1286 * This is enough to sort arrays of size up to about
1287 * 32 * phi ** MAX_MERGE_PENDING
1288 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1289 * with 2**64 elements.
1290 */
1291#define MAX_MERGE_PENDING 85
1292
Tim Peterse05f65a2002-08-10 05:21:15 +00001293/* When we get into galloping mode, we stay there until both runs win less
1294 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001295 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001296#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001297
1298/* Avoid malloc for small temp arrays. */
1299#define MERGESTATE_TEMP_SIZE 256
1300
1301/* One MergeState exists on the stack per invocation of mergesort. It's just
1302 * a convenient way to pass state around among the helper functions.
1303 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001304struct s_slice {
1305 PyObject **base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001306 Py_ssize_t len;
Tim Peterse05f65a2002-08-10 05:21:15 +00001307};
1308
Tim Petersa64dc242002-08-01 02:13:36 +00001309typedef struct s_MergeState {
1310 /* The user-supplied comparison function. or NULL if none given. */
1311 PyObject *compare;
1312
Tim Peterse05f65a2002-08-10 05:21:15 +00001313 /* This controls when we get *into* galloping mode. It's initialized
1314 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1315 * random data, and lower for highly structured data.
1316 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001317 Py_ssize_t min_gallop;
Tim Peterse05f65a2002-08-10 05:21:15 +00001318
Tim Petersa64dc242002-08-01 02:13:36 +00001319 /* 'a' is temp storage to help with merges. It contains room for
1320 * alloced entries.
1321 */
1322 PyObject **a; /* may point to temparray below */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001323 Py_ssize_t alloced;
Tim Petersa64dc242002-08-01 02:13:36 +00001324
1325 /* A stack of n pending runs yet to be merged. Run #i starts at
1326 * address base[i] and extends for len[i] elements. It's always
1327 * true (so long as the indices are in bounds) that
1328 *
Tim Peterse05f65a2002-08-10 05:21:15 +00001329 * pending[i].base + pending[i].len == pending[i+1].base
Tim Petersa64dc242002-08-01 02:13:36 +00001330 *
1331 * so we could cut the storage for this, but it's a minor amount,
1332 * and keeping all the info explicit simplifies the code.
1333 */
1334 int n;
Tim Peterse05f65a2002-08-10 05:21:15 +00001335 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001336
1337 /* 'a' points to this when possible, rather than muck with malloc. */
1338 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1339} MergeState;
1340
1341/* Conceptually a MergeState's constructor. */
1342static void
1343merge_init(MergeState *ms, PyObject *compare)
1344{
1345 assert(ms != NULL);
1346 ms->compare = compare;
1347 ms->a = ms->temparray;
1348 ms->alloced = MERGESTATE_TEMP_SIZE;
1349 ms->n = 0;
Tim Peterse05f65a2002-08-10 05:21:15 +00001350 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001351}
1352
1353/* Free all the temp memory owned by the MergeState. This must be called
1354 * when you're done with a MergeState, and may be called before then if
1355 * you want to free the temp memory early.
1356 */
1357static void
1358merge_freemem(MergeState *ms)
1359{
1360 assert(ms != NULL);
1361 if (ms->a != ms->temparray)
1362 PyMem_Free(ms->a);
1363 ms->a = ms->temparray;
1364 ms->alloced = MERGESTATE_TEMP_SIZE;
1365}
1366
1367/* Ensure enough temp memory for 'need' array slots is available.
1368 * Returns 0 on success and -1 if the memory can't be gotten.
1369 */
1370static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001371merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001372{
1373 assert(ms != NULL);
1374 if (need <= ms->alloced)
1375 return 0;
1376 /* Don't realloc! That can cost cycles to copy the old data, but
1377 * we don't care what's in the block.
1378 */
1379 merge_freemem(ms);
1380 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1381 if (ms->a) {
1382 ms->alloced = need;
1383 return 0;
1384 }
1385 PyErr_NoMemory();
1386 merge_freemem(ms); /* reset to sane state */
1387 return -1;
1388}
1389#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1390 merge_getmem(MS, NEED))
1391
1392/* Merge the na elements starting at pa with the nb elements starting at pb
1393 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1394 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1395 * merge, and should have na <= nb. See listsort.txt for more info.
1396 * Return 0 if successful, -1 if error.
1397 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001398static Py_ssize_t
1399merge_lo(MergeState *ms, PyObject **pa, Py_ssize_t na,
1400 PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001401{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001402 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001403 PyObject *compare;
1404 PyObject **dest;
1405 int result = -1; /* guilty until proved innocent */
Neal Norwitz7fd96072006-08-19 04:28:55 +00001406 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001407
1408 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1409 if (MERGE_GETMEM(ms, na) < 0)
1410 return -1;
1411 memcpy(ms->a, pa, na * sizeof(PyObject*));
1412 dest = pa;
1413 pa = ms->a;
1414
1415 *dest++ = *pb++;
1416 --nb;
1417 if (nb == 0)
1418 goto Succeed;
1419 if (na == 1)
1420 goto CopyB;
1421
Neal Norwitz7fd96072006-08-19 04:28:55 +00001422 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001423 compare = ms->compare;
1424 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001425 Py_ssize_t acount = 0; /* # of times A won in a row */
1426 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001427
1428 /* Do the straightforward thing until (if ever) one run
1429 * appears to win consistently.
1430 */
1431 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001432 assert(na > 1 && nb > 0);
Tim Peters66860f62002-08-04 17:47:26 +00001433 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001434 if (k) {
1435 if (k < 0)
1436 goto Fail;
1437 *dest++ = *pb++;
1438 ++bcount;
1439 acount = 0;
1440 --nb;
1441 if (nb == 0)
1442 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001443 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001444 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001445 }
1446 else {
Tim Petersa64dc242002-08-01 02:13:36 +00001447 *dest++ = *pa++;
1448 ++acount;
1449 bcount = 0;
1450 --na;
1451 if (na == 1)
1452 goto CopyB;
Tim Peterse05f65a2002-08-10 05:21:15 +00001453 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001454 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001455 }
Tim Petersa64dc242002-08-01 02:13:36 +00001456 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001457
Tim Petersa64dc242002-08-01 02:13:36 +00001458 /* One run is winning so consistently that galloping may
1459 * be a huge win. So try that, and continue galloping until
1460 * (if ever) neither run appears to be winning consistently
1461 * anymore.
1462 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001463 ++min_gallop;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001464 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001465 assert(na > 1 && nb > 0);
1466 min_gallop -= min_gallop > 1;
1467 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001468 k = gallop_right(*pb, pa, na, 0, compare);
1469 acount = k;
1470 if (k) {
1471 if (k < 0)
1472 goto Fail;
1473 memcpy(dest, pa, k * sizeof(PyObject *));
1474 dest += k;
1475 pa += k;
1476 na -= k;
1477 if (na == 1)
1478 goto CopyB;
1479 /* na==0 is impossible now if the comparison
1480 * function is consistent, but we can't assume
1481 * that it is.
1482 */
1483 if (na == 0)
1484 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001485 }
Tim Petersa64dc242002-08-01 02:13:36 +00001486 *dest++ = *pb++;
1487 --nb;
1488 if (nb == 0)
1489 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001490
Tim Petersa64dc242002-08-01 02:13:36 +00001491 k = gallop_left(*pa, pb, nb, 0, compare);
1492 bcount = k;
1493 if (k) {
1494 if (k < 0)
1495 goto Fail;
1496 memmove(dest, pb, k * sizeof(PyObject *));
1497 dest += k;
1498 pb += k;
1499 nb -= k;
1500 if (nb == 0)
1501 goto Succeed;
1502 }
1503 *dest++ = *pa++;
1504 --na;
1505 if (na == 1)
1506 goto CopyB;
1507 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001508 ++min_gallop; /* penalize it for leaving galloping mode */
1509 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001510 }
1511Succeed:
1512 result = 0;
1513Fail:
1514 if (na)
1515 memcpy(dest, pa, na * sizeof(PyObject*));
1516 return result;
1517CopyB:
1518 assert(na == 1 && nb > 0);
1519 /* The last element of pa belongs at the end of the merge. */
1520 memmove(dest, pb, nb * sizeof(PyObject *));
1521 dest[nb] = *pa;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001522 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001523}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001524
Tim Petersa64dc242002-08-01 02:13:36 +00001525/* Merge the na elements starting at pa with the nb elements starting at pb
1526 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1527 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1528 * merge, and should have na >= nb. See listsort.txt for more info.
1529 * Return 0 if successful, -1 if error.
1530 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001531static Py_ssize_t
1532merge_hi(MergeState *ms, PyObject **pa, Py_ssize_t na, PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001533{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001534 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001535 PyObject *compare;
1536 PyObject **dest;
1537 int result = -1; /* guilty until proved innocent */
1538 PyObject **basea;
1539 PyObject **baseb;
Neal Norwitz7fd96072006-08-19 04:28:55 +00001540 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001541
1542 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1543 if (MERGE_GETMEM(ms, nb) < 0)
1544 return -1;
1545 dest = pb + nb - 1;
1546 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1547 basea = pa;
1548 baseb = ms->a;
1549 pb = ms->a + nb - 1;
1550 pa += na - 1;
1551
1552 *dest-- = *pa--;
1553 --na;
1554 if (na == 0)
1555 goto Succeed;
1556 if (nb == 1)
1557 goto CopyA;
1558
Neal Norwitz7fd96072006-08-19 04:28:55 +00001559 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001560 compare = ms->compare;
1561 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001562 Py_ssize_t acount = 0; /* # of times A won in a row */
1563 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001564
1565 /* Do the straightforward thing until (if ever) one run
1566 * appears to win consistently.
1567 */
1568 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001569 assert(na > 0 && nb > 1);
Tim Peters66860f62002-08-04 17:47:26 +00001570 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001571 if (k) {
1572 if (k < 0)
1573 goto Fail;
1574 *dest-- = *pa--;
1575 ++acount;
1576 bcount = 0;
1577 --na;
1578 if (na == 0)
1579 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001580 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001581 break;
1582 }
1583 else {
1584 *dest-- = *pb--;
1585 ++bcount;
1586 acount = 0;
1587 --nb;
1588 if (nb == 1)
1589 goto CopyA;
Tim Peterse05f65a2002-08-10 05:21:15 +00001590 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001591 break;
1592 }
1593 }
1594
1595 /* One run is winning so consistently that galloping may
1596 * be a huge win. So try that, and continue galloping until
1597 * (if ever) neither run appears to be winning consistently
1598 * anymore.
1599 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001600 ++min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001601 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001602 assert(na > 0 && nb > 1);
1603 min_gallop -= min_gallop > 1;
1604 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001605 k = gallop_right(*pb, basea, na, na-1, compare);
1606 if (k < 0)
1607 goto Fail;
1608 k = na - k;
1609 acount = k;
1610 if (k) {
1611 dest -= k;
1612 pa -= k;
1613 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1614 na -= k;
1615 if (na == 0)
1616 goto Succeed;
1617 }
1618 *dest-- = *pb--;
1619 --nb;
1620 if (nb == 1)
1621 goto CopyA;
1622
1623 k = gallop_left(*pa, baseb, nb, nb-1, compare);
1624 if (k < 0)
1625 goto Fail;
1626 k = nb - k;
1627 bcount = k;
1628 if (k) {
1629 dest -= k;
1630 pb -= k;
1631 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1632 nb -= k;
1633 if (nb == 1)
1634 goto CopyA;
1635 /* nb==0 is impossible now if the comparison
1636 * function is consistent, but we can't assume
1637 * that it is.
1638 */
1639 if (nb == 0)
1640 goto Succeed;
1641 }
1642 *dest-- = *pa--;
1643 --na;
1644 if (na == 0)
1645 goto Succeed;
1646 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001647 ++min_gallop; /* penalize it for leaving galloping mode */
1648 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001649 }
1650Succeed:
1651 result = 0;
1652Fail:
1653 if (nb)
1654 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1655 return result;
1656CopyA:
1657 assert(nb == 1 && na > 0);
1658 /* The first element of pb belongs at the front of the merge. */
1659 dest -= na;
1660 pa -= na;
1661 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1662 *dest = *pb;
1663 return 0;
1664}
1665
1666/* Merge the two runs at stack indices i and i+1.
1667 * Returns 0 on success, -1 on error.
1668 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001669static Py_ssize_t
1670merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001671{
1672 PyObject **pa, **pb;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001673 Py_ssize_t na, nb;
1674 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001675 PyObject *compare;
1676
1677 assert(ms != NULL);
1678 assert(ms->n >= 2);
1679 assert(i >= 0);
1680 assert(i == ms->n - 2 || i == ms->n - 3);
1681
Tim Peterse05f65a2002-08-10 05:21:15 +00001682 pa = ms->pending[i].base;
1683 na = ms->pending[i].len;
1684 pb = ms->pending[i+1].base;
1685 nb = ms->pending[i+1].len;
Tim Petersa64dc242002-08-01 02:13:36 +00001686 assert(na > 0 && nb > 0);
1687 assert(pa + na == pb);
1688
1689 /* Record the length of the combined runs; if i is the 3rd-last
1690 * run now, also slide over the last run (which isn't involved
1691 * in this merge). The current run i+1 goes away in any case.
1692 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001693 ms->pending[i].len = na + nb;
1694 if (i == ms->n - 3)
1695 ms->pending[i+1] = ms->pending[i+2];
Tim Petersa64dc242002-08-01 02:13:36 +00001696 --ms->n;
1697
1698 /* Where does b start in a? Elements in a before that can be
1699 * ignored (already in place).
1700 */
1701 compare = ms->compare;
1702 k = gallop_right(*pb, pa, na, 0, compare);
1703 if (k < 0)
1704 return -1;
1705 pa += k;
1706 na -= k;
1707 if (na == 0)
1708 return 0;
1709
1710 /* Where does a end in b? Elements in b after that can be
1711 * ignored (already in place).
1712 */
1713 nb = gallop_left(pa[na-1], pb, nb, nb-1, compare);
1714 if (nb <= 0)
1715 return nb;
1716
1717 /* Merge what remains of the runs, using a temp array with
1718 * min(na, nb) elements.
1719 */
1720 if (na <= nb)
1721 return merge_lo(ms, pa, na, pb, nb);
1722 else
1723 return merge_hi(ms, pa, na, pb, nb);
1724}
1725
1726/* Examine the stack of runs waiting to be merged, merging adjacent runs
1727 * until the stack invariants are re-established:
1728 *
1729 * 1. len[-3] > len[-2] + len[-1]
1730 * 2. len[-2] > len[-1]
1731 *
1732 * See listsort.txt for more info.
1733 *
1734 * Returns 0 on success, -1 on error.
1735 */
1736static int
1737merge_collapse(MergeState *ms)
1738{
Tim Peterse05f65a2002-08-10 05:21:15 +00001739 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001740
1741 assert(ms);
1742 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001743 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001744 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1745 if (p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001746 --n;
1747 if (merge_at(ms, n) < 0)
1748 return -1;
1749 }
Tim Peterse05f65a2002-08-10 05:21:15 +00001750 else if (p[n].len <= p[n+1].len) {
Tim Petersa64dc242002-08-01 02:13:36 +00001751 if (merge_at(ms, n) < 0)
1752 return -1;
1753 }
1754 else
1755 break;
1756 }
1757 return 0;
1758}
1759
1760/* Regardless of invariants, merge all runs on the stack until only one
1761 * remains. This is used at the end of the mergesort.
1762 *
1763 * Returns 0 on success, -1 on error.
1764 */
1765static int
1766merge_force_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+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001774 --n;
1775 if (merge_at(ms, n) < 0)
1776 return -1;
1777 }
1778 return 0;
1779}
1780
1781/* Compute a good value for the minimum run length; natural runs shorter
1782 * than this are boosted artificially via binary insertion.
1783 *
1784 * If n < 64, return n (it's too small to bother with fancy stuff).
1785 * Else if n is an exact power of 2, return 32.
1786 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1787 * strictly less than, an exact power of 2.
1788 *
1789 * See listsort.txt for more info.
1790 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001791static Py_ssize_t
1792merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001793{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001794 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001795
1796 assert(n >= 0);
1797 while (n >= 64) {
1798 r |= n & 1;
1799 n >>= 1;
1800 }
1801 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001802}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001803
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001804/* Special wrapper to support stable sorting using the decorate-sort-undecorate
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001805 pattern. Holds a key which is used for comparisons and the original record
Tim Petersb38e2b62004-07-29 02:29:26 +00001806 which is returned during the undecorate phase. By exposing only the key
1807 during comparisons, the underlying sort stability characteristics are left
1808 unchanged. Also, if a custom comparison function is used, it will only see
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001809 the key instead of a full record. */
1810
1811typedef struct {
1812 PyObject_HEAD
1813 PyObject *key;
1814 PyObject *value;
1815} sortwrapperobject;
1816
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001817PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
Anthony Baxter377be112006-04-11 06:54:30 +00001818static PyObject *
1819sortwrapper_richcompare(sortwrapperobject *, sortwrapperobject *, int);
1820static void
1821sortwrapper_dealloc(sortwrapperobject *);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001822
1823static PyTypeObject sortwrapper_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001824 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001825 "sortwrapper", /* tp_name */
1826 sizeof(sortwrapperobject), /* tp_basicsize */
1827 0, /* tp_itemsize */
1828 /* methods */
1829 (destructor)sortwrapper_dealloc, /* tp_dealloc */
1830 0, /* tp_print */
1831 0, /* tp_getattr */
1832 0, /* tp_setattr */
1833 0, /* tp_compare */
1834 0, /* tp_repr */
1835 0, /* tp_as_number */
1836 0, /* tp_as_sequence */
1837 0, /* tp_as_mapping */
1838 0, /* tp_hash */
1839 0, /* tp_call */
1840 0, /* tp_str */
1841 PyObject_GenericGetAttr, /* tp_getattro */
1842 0, /* tp_setattro */
1843 0, /* tp_as_buffer */
Tim Petersb38e2b62004-07-29 02:29:26 +00001844 Py_TPFLAGS_DEFAULT |
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001845 Py_TPFLAGS_HAVE_RICHCOMPARE, /* tp_flags */
1846 sortwrapper_doc, /* tp_doc */
1847 0, /* tp_traverse */
1848 0, /* tp_clear */
1849 (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
1850};
1851
Anthony Baxter377be112006-04-11 06:54:30 +00001852
1853static PyObject *
1854sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
1855{
1856 if (!PyObject_TypeCheck(b, &sortwrapper_type)) {
1857 PyErr_SetString(PyExc_TypeError,
1858 "expected a sortwrapperobject");
1859 return NULL;
1860 }
1861 return PyObject_RichCompare(a->key, b->key, op);
1862}
1863
1864static void
1865sortwrapper_dealloc(sortwrapperobject *so)
1866{
1867 Py_XDECREF(so->key);
1868 Py_XDECREF(so->value);
1869 PyObject_Del(so);
1870}
1871
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001872/* Returns a new reference to a sortwrapper.
1873 Consumes the references to the two underlying objects. */
1874
1875static PyObject *
1876build_sortwrapper(PyObject *key, PyObject *value)
1877{
1878 sortwrapperobject *so;
Tim Petersb38e2b62004-07-29 02:29:26 +00001879
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001880 so = PyObject_New(sortwrapperobject, &sortwrapper_type);
1881 if (so == NULL)
1882 return NULL;
1883 so->key = key;
1884 so->value = value;
1885 return (PyObject *)so;
1886}
1887
1888/* Returns a new reference to the value underlying the wrapper. */
1889static PyObject *
1890sortwrapper_getvalue(PyObject *so)
1891{
1892 PyObject *value;
1893
1894 if (!PyObject_TypeCheck(so, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001895 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001896 "expected a sortwrapperobject");
1897 return NULL;
1898 }
1899 value = ((sortwrapperobject *)so)->value;
1900 Py_INCREF(value);
1901 return value;
1902}
1903
1904/* Wrapper for user specified cmp functions in combination with a
1905 specified key function. Makes sure the cmp function is presented
1906 with the actual key instead of the sortwrapper */
1907
1908typedef struct {
1909 PyObject_HEAD
1910 PyObject *func;
1911} cmpwrapperobject;
1912
1913static void
1914cmpwrapper_dealloc(cmpwrapperobject *co)
1915{
1916 Py_XDECREF(co->func);
1917 PyObject_Del(co);
1918}
1919
1920static PyObject *
1921cmpwrapper_call(cmpwrapperobject *co, PyObject *args, PyObject *kwds)
1922{
1923 PyObject *x, *y, *xx, *yy;
1924
1925 if (!PyArg_UnpackTuple(args, "", 2, 2, &x, &y))
1926 return NULL;
1927 if (!PyObject_TypeCheck(x, &sortwrapper_type) ||
Raymond Hettingerae4a2992003-10-16 17:16:30 +00001928 !PyObject_TypeCheck(y, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001929 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001930 "expected a sortwrapperobject");
1931 return NULL;
1932 }
1933 xx = ((sortwrapperobject *)x)->key;
1934 yy = ((sortwrapperobject *)y)->key;
1935 return PyObject_CallFunctionObjArgs(co->func, xx, yy, NULL);
1936}
1937
1938PyDoc_STRVAR(cmpwrapper_doc, "cmp() wrapper for sort with custom keys.");
1939
1940static PyTypeObject cmpwrapper_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001941 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001942 "cmpwrapper", /* tp_name */
1943 sizeof(cmpwrapperobject), /* tp_basicsize */
1944 0, /* tp_itemsize */
1945 /* methods */
1946 (destructor)cmpwrapper_dealloc, /* tp_dealloc */
1947 0, /* tp_print */
1948 0, /* tp_getattr */
1949 0, /* tp_setattr */
1950 0, /* tp_compare */
1951 0, /* tp_repr */
1952 0, /* tp_as_number */
1953 0, /* tp_as_sequence */
1954 0, /* tp_as_mapping */
1955 0, /* tp_hash */
1956 (ternaryfunc)cmpwrapper_call, /* tp_call */
1957 0, /* tp_str */
1958 PyObject_GenericGetAttr, /* tp_getattro */
1959 0, /* tp_setattro */
1960 0, /* tp_as_buffer */
1961 Py_TPFLAGS_DEFAULT, /* tp_flags */
1962 cmpwrapper_doc, /* tp_doc */
1963};
1964
1965static PyObject *
1966build_cmpwrapper(PyObject *cmpfunc)
1967{
1968 cmpwrapperobject *co;
Tim Petersb38e2b62004-07-29 02:29:26 +00001969
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001970 co = PyObject_New(cmpwrapperobject, &cmpwrapper_type);
1971 if (co == NULL)
1972 return NULL;
1973 Py_INCREF(cmpfunc);
1974 co->func = cmpfunc;
1975 return (PyObject *)co;
1976}
1977
Tim Petersa64dc242002-08-01 02:13:36 +00001978/* An adaptive, stable, natural mergesort. See listsort.txt.
1979 * Returns Py_None on success, NULL on error. Even in case of error, the
1980 * list will be some permutation of its input state (nothing is lost or
1981 * duplicated).
1982 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001983static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001984listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001985{
Tim Petersa64dc242002-08-01 02:13:36 +00001986 MergeState ms;
1987 PyObject **lo, **hi;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001988 Py_ssize_t nremaining;
1989 Py_ssize_t minrun;
1990 Py_ssize_t saved_ob_size, saved_allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00001991 PyObject **saved_ob_item;
Armin Rigo93677f02004-07-29 12:40:23 +00001992 PyObject **final_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001993 PyObject *compare = NULL;
1994 PyObject *result = NULL; /* guilty until proved innocent */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001995 int reverse = 0;
1996 PyObject *keyfunc = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001997 Py_ssize_t i;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001998 PyObject *key, *value, *kvpair;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001999 static char *kwlist[] = {"cmp", "key", "reverse", 0};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002000
Tim Petersa64dc242002-08-01 02:13:36 +00002001 assert(self != NULL);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002002 assert (PyList_Check(self));
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002003 if (args != NULL) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002004 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:sort",
2005 kwlist, &compare, &keyfunc, &reverse))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002006 return NULL;
2007 }
Skip Montanaro4abd5f02003-01-02 20:51:08 +00002008 if (compare == Py_None)
2009 compare = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002010 if (keyfunc == Py_None)
2011 keyfunc = NULL;
2012 if (compare != NULL && keyfunc != NULL) {
2013 compare = build_cmpwrapper(compare);
2014 if (compare == NULL)
Hye-Shik Chang19cb1932003-12-10 07:31:08 +00002015 return NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002016 } else
2017 Py_XINCREF(compare);
2018
Tim Petersb9099c32002-11-12 22:08:10 +00002019 /* The list is temporarily made empty, so that mutations performed
2020 * by comparison functions can't affect the slice of memory we're
2021 * sorting (allowing mutations during sorting is a core-dump
2022 * factory, since ob_item may change).
2023 */
Christian Heimese93237d2007-12-19 02:37:44 +00002024 saved_ob_size = Py_SIZE(self);
Tim Petersb9099c32002-11-12 22:08:10 +00002025 saved_ob_item = self->ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002026 saved_allocated = self->allocated;
Christian Heimese93237d2007-12-19 02:37:44 +00002027 Py_SIZE(self) = 0;
Tim Peters51b4ade2004-07-29 04:07:15 +00002028 self->ob_item = NULL;
Armin Rigo93677f02004-07-29 12:40:23 +00002029 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00002030
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002031 if (keyfunc != NULL) {
2032 for (i=0 ; i < saved_ob_size ; i++) {
2033 value = saved_ob_item[i];
Tim Petersb38e2b62004-07-29 02:29:26 +00002034 key = PyObject_CallFunctionObjArgs(keyfunc, value,
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002035 NULL);
2036 if (key == NULL) {
2037 for (i=i-1 ; i>=0 ; i--) {
2038 kvpair = saved_ob_item[i];
2039 value = sortwrapper_getvalue(kvpair);
2040 saved_ob_item[i] = value;
2041 Py_DECREF(kvpair);
2042 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002043 goto dsu_fail;
2044 }
2045 kvpair = build_sortwrapper(key, value);
2046 if (kvpair == NULL)
2047 goto dsu_fail;
2048 saved_ob_item[i] = kvpair;
2049 }
2050 }
2051
2052 /* Reverse sort stability achieved by initially reversing the list,
2053 applying a stable forward sort, then reversing the final result. */
2054 if (reverse && saved_ob_size > 1)
2055 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2056
2057 merge_init(&ms, compare);
2058
Tim Petersb9099c32002-11-12 22:08:10 +00002059 nremaining = saved_ob_size;
Tim Petersa64dc242002-08-01 02:13:36 +00002060 if (nremaining < 2)
2061 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00002062
Tim Petersa64dc242002-08-01 02:13:36 +00002063 /* March over the array once, left to right, finding natural runs,
2064 * and extending short natural runs to minrun elements.
2065 */
Tim Petersb9099c32002-11-12 22:08:10 +00002066 lo = saved_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00002067 hi = lo + nremaining;
2068 minrun = merge_compute_minrun(nremaining);
2069 do {
2070 int descending;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002071 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00002072
Tim Petersa64dc242002-08-01 02:13:36 +00002073 /* Identify next run. */
2074 n = count_run(lo, hi, compare, &descending);
2075 if (n < 0)
2076 goto fail;
2077 if (descending)
2078 reverse_slice(lo, lo + n);
2079 /* If short, extend to min(minrun, nremaining). */
2080 if (n < minrun) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002081 const Py_ssize_t force = nremaining <= minrun ?
Tim Petersa64dc242002-08-01 02:13:36 +00002082 nremaining : minrun;
2083 if (binarysort(lo, lo + force, lo + n, compare) < 0)
2084 goto fail;
2085 n = force;
2086 }
2087 /* Push run onto pending-runs stack, and maybe merge. */
2088 assert(ms.n < MAX_MERGE_PENDING);
Tim Peterse05f65a2002-08-10 05:21:15 +00002089 ms.pending[ms.n].base = lo;
2090 ms.pending[ms.n].len = n;
Tim Petersa64dc242002-08-01 02:13:36 +00002091 ++ms.n;
2092 if (merge_collapse(&ms) < 0)
2093 goto fail;
2094 /* Advance to find next run. */
2095 lo += n;
2096 nremaining -= n;
2097 } while (nremaining);
2098 assert(lo == hi);
Tim Peters330f9e92002-07-19 07:05:44 +00002099
Tim Petersa64dc242002-08-01 02:13:36 +00002100 if (merge_force_collapse(&ms) < 0)
2101 goto fail;
2102 assert(ms.n == 1);
Tim Petersb9099c32002-11-12 22:08:10 +00002103 assert(ms.pending[0].base == saved_ob_item);
2104 assert(ms.pending[0].len == saved_ob_size);
Tim Petersa64dc242002-08-01 02:13:36 +00002105
2106succeed:
2107 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002108fail:
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002109 if (keyfunc != NULL) {
2110 for (i=0 ; i < saved_ob_size ; i++) {
2111 kvpair = saved_ob_item[i];
2112 value = sortwrapper_getvalue(kvpair);
2113 saved_ob_item[i] = value;
2114 Py_DECREF(kvpair);
2115 }
2116 }
2117
Armin Rigo93677f02004-07-29 12:40:23 +00002118 if (self->allocated != -1 && result != NULL) {
Tim Peters51b4ade2004-07-29 04:07:15 +00002119 /* The user mucked with the list during the sort,
2120 * and we don't already have another error to report.
2121 */
2122 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2123 result = NULL;
Tim Petersb9099c32002-11-12 22:08:10 +00002124 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002125
2126 if (reverse && saved_ob_size > 1)
2127 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2128
2129 merge_freemem(&ms);
2130
2131dsu_fail:
Armin Rigo93677f02004-07-29 12:40:23 +00002132 final_ob_item = self->ob_item;
Christian Heimese93237d2007-12-19 02:37:44 +00002133 i = Py_SIZE(self);
2134 Py_SIZE(self) = saved_ob_size;
Tim Petersb9099c32002-11-12 22:08:10 +00002135 self->ob_item = saved_ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002136 self->allocated = saved_allocated;
Armin Rigo93677f02004-07-29 12:40:23 +00002137 if (final_ob_item != NULL) {
2138 /* we cannot use list_clear() for this because it does not
2139 guarantee that the list is really empty when it returns */
2140 while (--i >= 0) {
2141 Py_XDECREF(final_ob_item[i]);
2142 }
2143 PyMem_FREE(final_ob_item);
2144 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002145 Py_XDECREF(compare);
Tim Petersa64dc242002-08-01 02:13:36 +00002146 Py_XINCREF(result);
2147 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002148}
Tim Peters330f9e92002-07-19 07:05:44 +00002149#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002150#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002151
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002152int
Fred Drakea2f55112000-07-09 15:16:51 +00002153PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002154{
2155 if (v == NULL || !PyList_Check(v)) {
2156 PyErr_BadInternalCall();
2157 return -1;
2158 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002159 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002160 if (v == NULL)
2161 return -1;
2162 Py_DECREF(v);
2163 return 0;
2164}
2165
Guido van Rossumb86c5492001-02-12 22:06:02 +00002166static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002167listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002168{
Christian Heimese93237d2007-12-19 02:37:44 +00002169 if (Py_SIZE(self) > 1)
2170 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002171 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002172}
2173
Guido van Rossum84c76f51990-10-30 13:32:20 +00002174int
Fred Drakea2f55112000-07-09 15:16:51 +00002175PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002176{
Tim Peters6063e262002-08-08 01:06:39 +00002177 PyListObject *self = (PyListObject *)v;
2178
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002179 if (v == NULL || !PyList_Check(v)) {
2180 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002181 return -1;
2182 }
Christian Heimese93237d2007-12-19 02:37:44 +00002183 if (Py_SIZE(self) > 1)
2184 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002185 return 0;
2186}
2187
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002188PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002189PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002190{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002191 PyObject *w;
Raymond Hettinger6c87af52007-12-15 00:07:25 +00002192 PyObject **p, **q;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002193 Py_ssize_t n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002194 if (v == NULL || !PyList_Check(v)) {
2195 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002196 return NULL;
2197 }
Christian Heimese93237d2007-12-19 02:37:44 +00002198 n = Py_SIZE(v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002199 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002200 if (w == NULL)
2201 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002202 p = ((PyTupleObject *)w)->ob_item;
Raymond Hettinger6c87af52007-12-15 00:07:25 +00002203 q = ((PyListObject *)v)->ob_item;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002204 while (--n >= 0) {
Raymond Hettinger6c87af52007-12-15 00:07:25 +00002205 Py_INCREF(*q);
2206 *p = *q;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002207 p++;
Raymond Hettinger6c87af52007-12-15 00:07:25 +00002208 q++;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002209 }
2210 return w;
2211}
2212
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002213static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002214listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002215{
Christian Heimese93237d2007-12-19 02:37:44 +00002216 Py_ssize_t i, start=0, stop=Py_SIZE(self);
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002217 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002218
Walter Dörwalde8049bef2003-06-17 19:27:39 +00002219 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2220 _PyEval_SliceIndex, &start,
2221 _PyEval_SliceIndex, &stop))
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002222 return NULL;
Guido van Rossum2743d872003-06-17 14:25:14 +00002223 if (start < 0) {
Christian Heimese93237d2007-12-19 02:37:44 +00002224 start += Py_SIZE(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002225 if (start < 0)
2226 start = 0;
2227 }
2228 if (stop < 0) {
Christian Heimese93237d2007-12-19 02:37:44 +00002229 stop += Py_SIZE(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002230 if (stop < 0)
2231 stop = 0;
2232 }
Christian Heimese93237d2007-12-19 02:37:44 +00002233 for (i = start; i < stop && i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002234 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2235 if (cmp > 0)
Martin v. Löwis18e16552006-02-15 17:27:45 +00002236 return PyInt_FromSsize_t(i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002237 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002238 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002239 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002240 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002241 return NULL;
2242}
2243
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002244static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002245listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002246{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002247 Py_ssize_t count = 0;
2248 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002249
Christian Heimese93237d2007-12-19 02:37:44 +00002250 for (i = 0; i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002251 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2252 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002253 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002254 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002255 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00002256 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002257 return PyInt_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002258}
2259
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002260static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002261listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002262{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002263 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002264
Christian Heimese93237d2007-12-19 02:37:44 +00002265 for (i = 0; i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002266 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2267 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002268 if (list_ass_slice(self, i, i+1,
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002269 (PyObject *)NULL) == 0)
2270 Py_RETURN_NONE;
2271 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002272 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002273 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002274 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002275 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002276 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002277 return NULL;
2278}
2279
Jeremy Hylton8caad492000-06-23 14:18:11 +00002280static int
2281list_traverse(PyListObject *o, visitproc visit, void *arg)
2282{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002283 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002284
Christian Heimese93237d2007-12-19 02:37:44 +00002285 for (i = Py_SIZE(o); --i >= 0; )
Thomas Woutersc6e55062006-04-15 21:47:09 +00002286 Py_VISIT(o->ob_item[i]);
Jeremy Hylton8caad492000-06-23 14:18:11 +00002287 return 0;
2288}
2289
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002290static PyObject *
2291list_richcompare(PyObject *v, PyObject *w, int op)
2292{
2293 PyListObject *vl, *wl;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002294 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002295
2296 if (!PyList_Check(v) || !PyList_Check(w)) {
2297 Py_INCREF(Py_NotImplemented);
2298 return Py_NotImplemented;
2299 }
2300
2301 vl = (PyListObject *)v;
2302 wl = (PyListObject *)w;
2303
Christian Heimese93237d2007-12-19 02:37:44 +00002304 if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002305 /* Shortcut: if the lengths differ, the lists differ */
2306 PyObject *res;
2307 if (op == Py_EQ)
2308 res = Py_False;
2309 else
2310 res = Py_True;
2311 Py_INCREF(res);
2312 return res;
2313 }
2314
2315 /* Search for the first index where items are different */
Christian Heimese93237d2007-12-19 02:37:44 +00002316 for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002317 int k = PyObject_RichCompareBool(vl->ob_item[i],
2318 wl->ob_item[i], Py_EQ);
2319 if (k < 0)
2320 return NULL;
2321 if (!k)
2322 break;
2323 }
2324
Christian Heimese93237d2007-12-19 02:37:44 +00002325 if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002326 /* No more items to compare -- compare sizes */
Christian Heimese93237d2007-12-19 02:37:44 +00002327 Py_ssize_t vs = Py_SIZE(vl);
2328 Py_ssize_t ws = Py_SIZE(wl);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002329 int cmp;
2330 PyObject *res;
2331 switch (op) {
2332 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00002333 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002334 case Py_EQ: cmp = vs == ws; break;
2335 case Py_NE: cmp = vs != ws; break;
2336 case Py_GT: cmp = vs > ws; break;
2337 case Py_GE: cmp = vs >= ws; break;
2338 default: return NULL; /* cannot happen */
2339 }
2340 if (cmp)
2341 res = Py_True;
2342 else
2343 res = Py_False;
2344 Py_INCREF(res);
2345 return res;
2346 }
2347
2348 /* We have an item that differs -- shortcuts for EQ/NE */
2349 if (op == Py_EQ) {
2350 Py_INCREF(Py_False);
2351 return Py_False;
2352 }
2353 if (op == Py_NE) {
2354 Py_INCREF(Py_True);
2355 return Py_True;
2356 }
2357
2358 /* Compare the final item again using the proper operator */
2359 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
2360}
2361
Tim Peters6d6c1a32001-08-02 04:15:00 +00002362static int
2363list_init(PyListObject *self, PyObject *args, PyObject *kw)
2364{
2365 PyObject *arg = NULL;
Martin v. Löwis15e62742006-02-27 16:46:16 +00002366 static char *kwlist[] = {"sequence", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002367
2368 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2369 return -1;
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002370
2371 /* Verify list invariants established by PyType_GenericAlloc() */
Christian Heimese93237d2007-12-19 02:37:44 +00002372 assert(0 <= Py_SIZE(self));
2373 assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
Armin Rigoa37bbf22004-07-30 11:20:18 +00002374 assert(self->ob_item != NULL ||
2375 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002376
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002377 /* Empty previous contents */
Armin Rigo93677f02004-07-29 12:40:23 +00002378 if (self->ob_item != NULL) {
2379 (void)list_clear(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002380 }
2381 if (arg != NULL) {
2382 PyObject *rv = listextend(self, arg);
2383 if (rv == NULL)
2384 return -1;
2385 Py_DECREF(rv);
2386 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002387 return 0;
2388}
2389
Raymond Hettinger1021c442003-11-07 15:38:09 +00002390static PyObject *list_iter(PyObject *seq);
2391static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2392
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002393PyDoc_STRVAR(getitem_doc,
2394"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002395PyDoc_STRVAR(reversed_doc,
2396"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002397PyDoc_STRVAR(append_doc,
2398"L.append(object) -- append object to end");
2399PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002400"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002401PyDoc_STRVAR(insert_doc,
2402"L.insert(index, object) -- insert object before index");
2403PyDoc_STRVAR(pop_doc,
2404"L.pop([index]) -> item -- remove and return item at index (default last)");
2405PyDoc_STRVAR(remove_doc,
2406"L.remove(value) -- remove first occurrence of value");
2407PyDoc_STRVAR(index_doc,
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002408"L.index(value, [start, [stop]]) -> integer -- return first index of value");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002409PyDoc_STRVAR(count_doc,
2410"L.count(value) -> integer -- return number of occurrences of value");
2411PyDoc_STRVAR(reverse_doc,
2412"L.reverse() -- reverse *IN PLACE*");
2413PyDoc_STRVAR(sort_doc,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002414"L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n\
2415cmp(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002416
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002417static PyObject *list_subscript(PyListObject*, PyObject*);
2418
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002419static PyMethodDef list_methods[] = {
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002420 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
Raymond Hettinger1021c442003-11-07 15:38:09 +00002421 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002422 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002423 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002424 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002425 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002426 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002427 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002428 {"count", (PyCFunction)listcount, METH_O, count_doc},
2429 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002430 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
Tim Petersa64dc242002-08-01 02:13:36 +00002431 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002432};
2433
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002434static PySequenceMethods list_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002435 (lenfunc)list_length, /* sq_length */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002436 (binaryfunc)list_concat, /* sq_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002437 (ssizeargfunc)list_repeat, /* sq_repeat */
2438 (ssizeargfunc)list_item, /* sq_item */
2439 (ssizessizeargfunc)list_slice, /* sq_slice */
2440 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
2441 (ssizessizeobjargproc)list_ass_slice, /* sq_ass_slice */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002442 (objobjproc)list_contains, /* sq_contains */
2443 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002444 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002445};
2446
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002447PyDoc_STRVAR(list_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002448"list() -> new list\n"
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002449"list(sequence) -> new list initialized from sequence's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002450
Guido van Rossum38fff8c2006-03-07 18:50:55 +00002451
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002452static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002453list_subscript(PyListObject* self, PyObject* item)
2454{
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00002455 if (PyIndex_Check(item)) {
2456 Py_ssize_t i;
2457 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002458 if (i == -1 && PyErr_Occurred())
2459 return NULL;
2460 if (i < 0)
2461 i += PyList_GET_SIZE(self);
2462 return list_item(self, i);
2463 }
2464 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002465 Py_ssize_t start, stop, step, slicelength, cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002466 PyObject* result;
2467 PyObject* it;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002468 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002469
Christian Heimese93237d2007-12-19 02:37:44 +00002470 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002471 &start, &stop, &step, &slicelength) < 0) {
2472 return NULL;
2473 }
2474
2475 if (slicelength <= 0) {
2476 return PyList_New(0);
2477 }
Thomas Wouters3ccec682007-08-28 15:28:19 +00002478 else if (step == 1) {
2479 return list_slice(self, start, stop);
2480 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002481 else {
2482 result = PyList_New(slicelength);
2483 if (!result) return NULL;
2484
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002485 src = self->ob_item;
2486 dest = ((PyListObject *)result)->ob_item;
Tim Peters3b01a122002-07-19 02:35:45 +00002487 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002488 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002489 it = src[cur];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002490 Py_INCREF(it);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002491 dest[i] = it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002492 }
Tim Peters3b01a122002-07-19 02:35:45 +00002493
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002494 return result;
2495 }
2496 }
2497 else {
Georg Brandl283a1352006-11-19 08:48:30 +00002498 PyErr_Format(PyExc_TypeError,
2499 "list indices must be integers, not %.200s",
2500 item->ob_type->tp_name);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002501 return NULL;
2502 }
2503}
2504
Tim Peters3b01a122002-07-19 02:35:45 +00002505static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002506list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2507{
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00002508 if (PyIndex_Check(item)) {
2509 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002510 if (i == -1 && PyErr_Occurred())
2511 return -1;
2512 if (i < 0)
2513 i += PyList_GET_SIZE(self);
2514 return list_ass_item(self, i, value);
2515 }
2516 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002517 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002518
Christian Heimese93237d2007-12-19 02:37:44 +00002519 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002520 &start, &stop, &step, &slicelength) < 0) {
2521 return -1;
2522 }
2523
Thomas Wouters3ccec682007-08-28 15:28:19 +00002524 if (step == 1)
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002525 return list_ass_slice(self, start, stop, value);
2526
Thomas Wouters3ccec682007-08-28 15:28:19 +00002527 /* Make sure s[5:2] = [..] inserts at the right place:
2528 before 5, not before 2. */
2529 if ((step < 0 && start < stop) ||
2530 (step > 0 && start > stop))
2531 stop = start;
2532
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002533 if (value == NULL) {
2534 /* delete slice */
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002535 PyObject **garbage;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002536 Py_ssize_t cur, i;
Tim Peters3b01a122002-07-19 02:35:45 +00002537
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002538 if (slicelength <= 0)
2539 return 0;
2540
2541 if (step < 0) {
2542 stop = start + 1;
2543 start = stop + step*(slicelength - 1) - 1;
2544 step = -step;
2545 }
2546
2547 garbage = (PyObject**)
2548 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Neal Norwitzb88cfad2006-08-12 03:16:54 +00002549 if (!garbage) {
2550 PyErr_NoMemory();
2551 return -1;
2552 }
Tim Peters3b01a122002-07-19 02:35:45 +00002553
Thomas Wouters3ccec682007-08-28 15:28:19 +00002554 /* drawing pictures might help understand these for
2555 loops. Basically, we memmove the parts of the
2556 list that are *not* part of the slice: step-1
2557 items for each item that is part of the slice,
2558 and then tail end of the list that was not
2559 covered by the slice */
Guido van Rossum75a20b12002-06-11 12:22:28 +00002560 for (cur = start, i = 0;
2561 cur < stop;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002562 cur += step, i++) {
Thomas Wouters3ccec682007-08-28 15:28:19 +00002563 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002564
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002565 garbage[i] = PyList_GET_ITEM(self, cur);
2566
Christian Heimese93237d2007-12-19 02:37:44 +00002567 if (cur + step >= Py_SIZE(self)) {
2568 lim = Py_SIZE(self) - cur - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002569 }
2570
Tim Petersb38e2b62004-07-29 02:29:26 +00002571 memmove(self->ob_item + cur - i,
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002572 self->ob_item + cur + 1,
2573 lim * sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002574 }
Thomas Wouters3ccec682007-08-28 15:28:19 +00002575 cur = start + slicelength*step;
Christian Heimese93237d2007-12-19 02:37:44 +00002576 if (cur < Py_SIZE(self)) {
Thomas Wouters3ccec682007-08-28 15:28:19 +00002577 memmove(self->ob_item + cur - slicelength,
2578 self->ob_item + cur,
Christian Heimese93237d2007-12-19 02:37:44 +00002579 (Py_SIZE(self) - cur) *
Thomas Wouters3ccec682007-08-28 15:28:19 +00002580 sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002581 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002582
Christian Heimese93237d2007-12-19 02:37:44 +00002583 Py_SIZE(self) -= slicelength;
2584 list_resize(self, Py_SIZE(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002585
2586 for (i = 0; i < slicelength; i++) {
2587 Py_DECREF(garbage[i]);
2588 }
2589 PyMem_FREE(garbage);
2590
2591 return 0;
2592 }
2593 else {
2594 /* assign slice */
Thomas Wouters3ccec682007-08-28 15:28:19 +00002595 PyObject *ins, *seq;
2596 PyObject **garbage, **seqitems, **selfitems;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002597 Py_ssize_t cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002598
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002599 /* protect against a[::-1] = a */
Tim Peters3b01a122002-07-19 02:35:45 +00002600 if (self == (PyListObject*)value) {
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002601 seq = list_slice((PyListObject*)value, 0,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002602 PyList_GET_SIZE(value));
Tim Peters3b01a122002-07-19 02:35:45 +00002603 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002604 else {
Tim Petersb38e2b62004-07-29 02:29:26 +00002605 seq = PySequence_Fast(value,
Thomas Wouters3ccec682007-08-28 15:28:19 +00002606 "must assign iterable "
2607 "to extended slice");
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002608 }
Neal Norwitzb88cfad2006-08-12 03:16:54 +00002609 if (!seq)
2610 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002611
2612 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2613 PyErr_Format(PyExc_ValueError,
Thomas Wouters3ccec682007-08-28 15:28:19 +00002614 "attempt to assign sequence of "
2615 "size %zd to extended slice of "
2616 "size %zd",
Martin v. Löwise0e89f72006-02-16 06:59:22 +00002617 PySequence_Fast_GET_SIZE(seq),
2618 slicelength);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002619 Py_DECREF(seq);
2620 return -1;
2621 }
2622
2623 if (!slicelength) {
2624 Py_DECREF(seq);
2625 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002626 }
2627
2628 garbage = (PyObject**)
2629 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Neal Norwitze7e4e2d2006-10-28 21:20:12 +00002630 if (!garbage) {
2631 Py_DECREF(seq);
2632 PyErr_NoMemory();
2633 return -1;
2634 }
Tim Peters3b01a122002-07-19 02:35:45 +00002635
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002636 selfitems = self->ob_item;
Raymond Hettinger42bec932004-03-12 16:38:17 +00002637 seqitems = PySequence_Fast_ITEMS(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002638 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002639 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002640 garbage[i] = selfitems[cur];
2641 ins = seqitems[i];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002642 Py_INCREF(ins);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002643 selfitems[cur] = ins;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002644 }
2645
2646 for (i = 0; i < slicelength; i++) {
2647 Py_DECREF(garbage[i]);
2648 }
Tim Peters3b01a122002-07-19 02:35:45 +00002649
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002650 PyMem_FREE(garbage);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002651 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002652
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002653 return 0;
2654 }
Tim Peters3b01a122002-07-19 02:35:45 +00002655 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002656 else {
Georg Brandl283a1352006-11-19 08:48:30 +00002657 PyErr_Format(PyExc_TypeError,
2658 "list indices must be integers, not %.200s",
2659 item->ob_type->tp_name);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002660 return -1;
2661 }
2662}
2663
2664static PyMappingMethods list_as_mapping = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002665 (lenfunc)list_length,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002666 (binaryfunc)list_subscript,
2667 (objobjargproc)list_ass_subscript
2668};
2669
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002670PyTypeObject PyList_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002671 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002672 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002673 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002674 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002675 (destructor)list_dealloc, /* tp_dealloc */
2676 (printfunc)list_print, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002677 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002678 0, /* tp_setattr */
2679 0, /* tp_compare */
2680 (reprfunc)list_repr, /* tp_repr */
2681 0, /* tp_as_number */
2682 &list_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002683 &list_as_mapping, /* tp_as_mapping */
Guido van Rossum64c06e32007-11-22 00:55:51 +00002684 0, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002685 0, /* tp_call */
2686 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002687 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002688 0, /* tp_setattro */
2689 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002690 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Neal Norwitzee3a1b52007-02-25 19:44:48 +00002691 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002692 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002693 (traverseproc)list_traverse, /* tp_traverse */
2694 (inquiry)list_clear, /* tp_clear */
2695 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002696 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002697 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002698 0, /* tp_iternext */
2699 list_methods, /* tp_methods */
2700 0, /* tp_members */
2701 0, /* tp_getset */
2702 0, /* tp_base */
2703 0, /* tp_dict */
2704 0, /* tp_descr_get */
2705 0, /* tp_descr_set */
2706 0, /* tp_dictoffset */
2707 (initproc)list_init, /* tp_init */
2708 PyType_GenericAlloc, /* tp_alloc */
2709 PyType_GenericNew, /* tp_new */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002710 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002711};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002712
2713
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002714/*********************** List Iterator **************************/
2715
2716typedef struct {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002717 PyObject_HEAD
2718 long it_index;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002719 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002720} listiterobject;
2721
Anthony Baxter377be112006-04-11 06:54:30 +00002722static PyObject *list_iter(PyObject *);
2723static void listiter_dealloc(listiterobject *);
2724static int listiter_traverse(listiterobject *, visitproc, void *);
2725static PyObject *listiter_next(listiterobject *);
2726static PyObject *listiter_len(listiterobject *);
2727
2728PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
2729
2730static PyMethodDef listiter_methods[] = {
2731 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
2732 {NULL, NULL} /* sentinel */
2733};
2734
2735PyTypeObject PyListIter_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002736 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Anthony Baxter377be112006-04-11 06:54:30 +00002737 "listiterator", /* tp_name */
2738 sizeof(listiterobject), /* tp_basicsize */
2739 0, /* tp_itemsize */
2740 /* methods */
2741 (destructor)listiter_dealloc, /* tp_dealloc */
2742 0, /* tp_print */
2743 0, /* tp_getattr */
2744 0, /* tp_setattr */
2745 0, /* tp_compare */
2746 0, /* tp_repr */
2747 0, /* tp_as_number */
2748 0, /* tp_as_sequence */
2749 0, /* tp_as_mapping */
2750 0, /* tp_hash */
2751 0, /* tp_call */
2752 0, /* tp_str */
2753 PyObject_GenericGetAttr, /* tp_getattro */
2754 0, /* tp_setattro */
2755 0, /* tp_as_buffer */
2756 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2757 0, /* tp_doc */
2758 (traverseproc)listiter_traverse, /* tp_traverse */
2759 0, /* tp_clear */
2760 0, /* tp_richcompare */
2761 0, /* tp_weaklistoffset */
2762 PyObject_SelfIter, /* tp_iter */
2763 (iternextfunc)listiter_next, /* tp_iternext */
2764 listiter_methods, /* tp_methods */
2765 0, /* tp_members */
2766};
2767
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002768
Guido van Rossum5086e492002-07-16 15:56:52 +00002769static PyObject *
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002770list_iter(PyObject *seq)
2771{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002772 listiterobject *it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002773
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002774 if (!PyList_Check(seq)) {
2775 PyErr_BadInternalCall();
2776 return NULL;
2777 }
2778 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2779 if (it == NULL)
2780 return NULL;
2781 it->it_index = 0;
2782 Py_INCREF(seq);
2783 it->it_seq = (PyListObject *)seq;
2784 _PyObject_GC_TRACK(it);
2785 return (PyObject *)it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002786}
2787
2788static void
2789listiter_dealloc(listiterobject *it)
2790{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002791 _PyObject_GC_UNTRACK(it);
Guido van Rossum86103ae2002-07-16 20:07:32 +00002792 Py_XDECREF(it->it_seq);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002793 PyObject_GC_Del(it);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002794}
2795
2796static int
2797listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2798{
Thomas Woutersc6e55062006-04-15 21:47:09 +00002799 Py_VISIT(it->it_seq);
2800 return 0;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002801}
2802
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002803static PyObject *
Tim Peters93b2cc42002-06-01 05:22:55 +00002804listiter_next(listiterobject *it)
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002805{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002806 PyListObject *seq;
2807 PyObject *item;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002808
Tim Peters93b2cc42002-06-01 05:22:55 +00002809 assert(it != NULL);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002810 seq = it->it_seq;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002811 if (seq == NULL)
2812 return NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002813 assert(PyList_Check(seq));
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002814
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002815 if (it->it_index < PyList_GET_SIZE(seq)) {
Tim Peters93b2cc42002-06-01 05:22:55 +00002816 item = PyList_GET_ITEM(seq, it->it_index);
2817 ++it->it_index;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002818 Py_INCREF(item);
2819 return item;
2820 }
Guido van Rossum86103ae2002-07-16 20:07:32 +00002821
2822 Py_DECREF(seq);
2823 it->it_seq = NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002824 return NULL;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002825}
2826
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002827static PyObject *
Raymond Hettinger435bf582004-03-18 22:43:10 +00002828listiter_len(listiterobject *it)
2829{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002830 Py_ssize_t len;
Raymond Hettinger40a03822004-04-12 13:05:09 +00002831 if (it->it_seq) {
2832 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2833 if (len >= 0)
Martin v. Löwis18e16552006-02-15 17:27:45 +00002834 return PyInt_FromSsize_t(len);
Raymond Hettinger40a03822004-04-12 13:05:09 +00002835 }
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002836 return PyInt_FromLong(0);
Raymond Hettinger435bf582004-03-18 22:43:10 +00002837}
Anthony Baxter377be112006-04-11 06:54:30 +00002838/*********************** List Reverse Iterator **************************/
Raymond Hettinger435bf582004-03-18 22:43:10 +00002839
Anthony Baxter377be112006-04-11 06:54:30 +00002840typedef struct {
2841 PyObject_HEAD
2842 Py_ssize_t it_index;
2843 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
2844} listreviterobject;
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002845
Anthony Baxter377be112006-04-11 06:54:30 +00002846static PyObject *list_reversed(PyListObject *, PyObject *);
2847static void listreviter_dealloc(listreviterobject *);
2848static int listreviter_traverse(listreviterobject *, visitproc, void *);
2849static PyObject *listreviter_next(listreviterobject *);
2850static Py_ssize_t listreviter_len(listreviterobject *);
2851
2852static PySequenceMethods listreviter_as_sequence = {
2853 (lenfunc)listreviter_len, /* sq_length */
2854 0, /* sq_concat */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002855};
2856
Anthony Baxter377be112006-04-11 06:54:30 +00002857PyTypeObject PyListRevIter_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002858 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Anthony Baxter377be112006-04-11 06:54:30 +00002859 "listreverseiterator", /* tp_name */
2860 sizeof(listreviterobject), /* tp_basicsize */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002861 0, /* tp_itemsize */
2862 /* methods */
Anthony Baxter377be112006-04-11 06:54:30 +00002863 (destructor)listreviter_dealloc, /* tp_dealloc */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002864 0, /* tp_print */
2865 0, /* tp_getattr */
2866 0, /* tp_setattr */
2867 0, /* tp_compare */
2868 0, /* tp_repr */
2869 0, /* tp_as_number */
Anthony Baxter377be112006-04-11 06:54:30 +00002870 &listreviter_as_sequence, /* tp_as_sequence */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002871 0, /* tp_as_mapping */
2872 0, /* tp_hash */
2873 0, /* tp_call */
2874 0, /* tp_str */
2875 PyObject_GenericGetAttr, /* tp_getattro */
2876 0, /* tp_setattro */
2877 0, /* tp_as_buffer */
2878 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2879 0, /* tp_doc */
Anthony Baxter377be112006-04-11 06:54:30 +00002880 (traverseproc)listreviter_traverse, /* tp_traverse */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002881 0, /* tp_clear */
2882 0, /* tp_richcompare */
2883 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00002884 PyObject_SelfIter, /* tp_iter */
Anthony Baxter377be112006-04-11 06:54:30 +00002885 (iternextfunc)listreviter_next, /* tp_iternext */
2886 0,
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002887};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002888
Raymond Hettinger1021c442003-11-07 15:38:09 +00002889static PyObject *
2890list_reversed(PyListObject *seq, PyObject *unused)
2891{
2892 listreviterobject *it;
2893
2894 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2895 if (it == NULL)
2896 return NULL;
2897 assert(PyList_Check(seq));
2898 it->it_index = PyList_GET_SIZE(seq) - 1;
2899 Py_INCREF(seq);
2900 it->it_seq = seq;
2901 PyObject_GC_Track(it);
2902 return (PyObject *)it;
2903}
2904
2905static void
2906listreviter_dealloc(listreviterobject *it)
2907{
2908 PyObject_GC_UnTrack(it);
2909 Py_XDECREF(it->it_seq);
2910 PyObject_GC_Del(it);
2911}
2912
2913static int
2914listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2915{
Thomas Woutersc6e55062006-04-15 21:47:09 +00002916 Py_VISIT(it->it_seq);
2917 return 0;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002918}
2919
2920static PyObject *
2921listreviter_next(listreviterobject *it)
2922{
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002923 PyObject *item;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002924 Py_ssize_t index = it->it_index;
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002925 PyListObject *seq = it->it_seq;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002926
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002927 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2928 item = PyList_GET_ITEM(seq, index);
Raymond Hettinger1021c442003-11-07 15:38:09 +00002929 it->it_index--;
2930 Py_INCREF(item);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002931 return item;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002932 }
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002933 it->it_index = -1;
2934 if (seq != NULL) {
2935 it->it_seq = NULL;
2936 Py_DECREF(seq);
2937 }
2938 return NULL;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002939}
2940
Martin v. Löwis18e16552006-02-15 17:27:45 +00002941static Py_ssize_t
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002942listreviter_len(listreviterobject *it)
2943{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002944 Py_ssize_t len = it->it_index + 1;
Raymond Hettinger40a03822004-04-12 13:05:09 +00002945 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
2946 return 0;
2947 return len;
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002948}