blob: cb0609ac4d7c2fad4f1dad1b67891ddf1e155099 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* List object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
4
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00005#ifdef STDC_HEADERS
6#include <stddef.h>
7#else
8#include <sys/types.h> /* For size_t */
9#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000010
Tim Peters8d9eb102004-07-31 02:24:20 +000011/* Ensure ob_item has room for at least newsize elements, and set
12 * ob_size to newsize. If newsize > ob_size on entry, the content
13 * of the new slots at exit is undefined heap trash; it's the caller's
14 * responsiblity to overwrite them with sane values.
15 * The number of allocated elements may grow, shrink, or stay the same.
16 * Failure is impossible if newsize <= self.allocated on entry, although
17 * that partly relies on an assumption that the system realloc() never
18 * fails when passed a number of bytes <= the number of bytes last
19 * allocated (the C standard doesn't guarantee this, but it's hard to
20 * imagine a realloc implementation where it wouldn't be true).
21 * Note that self->ob_item may change, and even if newsize is less
22 * than ob_size on entry.
23 */
Guido van Rossuma46d51d1995-01-26 22:59:43 +000024static int
Martin v. Löwis18e16552006-02-15 17:27:45 +000025list_resize(PyListObject *self, Py_ssize_t newsize)
Guido van Rossuma46d51d1995-01-26 22:59:43 +000026{
Raymond Hettinger4bb95402004-02-13 11:36:39 +000027 PyObject **items;
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000028 size_t new_allocated;
Martin v. Löwis18e16552006-02-15 17:27:45 +000029 Py_ssize_t allocated = self->allocated;
Tim Peters65b8b842001-05-26 05:28:40 +000030
Raymond Hettinger4bb95402004-02-13 11:36:39 +000031 /* Bypass realloc() when a previous overallocation is large enough
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000032 to accommodate the newsize. If the newsize falls lower than half
33 the allocated size, then proceed with the realloc() to shrink the list.
Raymond Hettinger4bb95402004-02-13 11:36:39 +000034 */
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000035 if (allocated >= newsize && newsize >= (allocated >> 1)) {
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +000036 assert(self->ob_item != NULL || newsize == 0);
Christian Heimes90aa7642007-12-19 02:45:37 +000037 Py_SIZE(self) = newsize;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000038 return 0;
39 }
40
41 /* This over-allocates proportional to the list size, making room
Tim Peters65b8b842001-05-26 05:28:40 +000042 * for additional growth. The over-allocation is mild, but is
43 * enough to give linear-time amortized behavior over a long
44 * sequence of appends() in the presence of a poorly-performing
Raymond Hettingerab517d22004-02-14 18:34:46 +000045 * system realloc().
46 * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
Tim Peters65b8b842001-05-26 05:28:40 +000047 */
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 Heimes90aa7642007-12-19 02:45:37 +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 Heimes2202f872008-02-06 14:31:34 +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 Heimes2202f872008-02-06 14:31:34 +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 Heimes2202f872008-02-06 14:31:34 +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);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000113 if (op->ob_item == NULL) {
114 Py_DECREF(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000115 return PyErr_NoMemory();
Thomas Wouters0e3f5912006-08-11 14:57:12 +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 Heimes90aa7642007-12-19 02:45:37 +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 Heimes90aa7642007-12-19 02:45:37 +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 Heimes90aa7642007-12-19 02:45:37 +0000145 if (i < 0 || i >= Py_SIZE(op)) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000146 if (indexerr == NULL)
Neal Norwitz53cbdaa2007-08-23 21:42:55 +0000147 indexerr = PyUnicode_FromString(
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000148 "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 Heimes90aa7642007-12-19 02:45:37 +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 Heimes90aa7642007-12-19 02:45:37 +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 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +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);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +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 Heimes90aa7642007-12-19 02:45:37 +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 Heimes2202f872008-02-06 14:31:34 +0000270 if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op))
271 free_list[numfree++] = op;
Tim Petersb38e2b62004-07-29 02:29:26 +0000272 else
Christian Heimes90aa7642007-12-19 02:45:37 +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 Rossumc0b618a1997-05-02 03:12:38 +0000277static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000278list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000279{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000280 Py_ssize_t i;
Tim Petersa7259592001-06-16 05:11:17 +0000281 PyObject *s, *temp;
282 PyObject *pieces = NULL, *result = NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000283
284 i = Py_ReprEnter((PyObject*)v);
285 if (i != 0) {
Walter Dörwald1ab83302007-05-18 17:15:44 +0000286 return i > 0 ? PyUnicode_FromString("[...]") : NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000287 }
Tim Petersa7259592001-06-16 05:11:17 +0000288
Christian Heimes90aa7642007-12-19 02:45:37 +0000289 if (Py_SIZE(v) == 0) {
Walter Dörwald1ab83302007-05-18 17:15:44 +0000290 result = PyUnicode_FromString("[]");
Tim Petersa7259592001-06-16 05:11:17 +0000291 goto Done;
292 }
293
294 pieces = PyList_New(0);
295 if (pieces == NULL)
296 goto Done;
297
298 /* Do repr() on each element. Note that this may mutate the list,
299 so must refetch the list size on each iteration. */
Christian Heimes90aa7642007-12-19 02:45:37 +0000300 for (i = 0; i < Py_SIZE(v); ++i) {
Tim Petersa7259592001-06-16 05:11:17 +0000301 int status;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000302 if (Py_EnterRecursiveCall(" while getting the repr of a list"))
303 goto Done;
Tim Petersa7259592001-06-16 05:11:17 +0000304 s = PyObject_Repr(v->ob_item[i]);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000305 Py_LeaveRecursiveCall();
Tim Petersa7259592001-06-16 05:11:17 +0000306 if (s == NULL)
307 goto Done;
308 status = PyList_Append(pieces, s);
309 Py_DECREF(s); /* append created a new ref */
310 if (status < 0)
311 goto Done;
312 }
313
314 /* Add "[]" decorations to the first and last items. */
315 assert(PyList_GET_SIZE(pieces) > 0);
Walter Dörwald1ab83302007-05-18 17:15:44 +0000316 s = PyUnicode_FromString("[");
Tim Petersa7259592001-06-16 05:11:17 +0000317 if (s == NULL)
318 goto Done;
319 temp = PyList_GET_ITEM(pieces, 0);
Walter Dörwald1ab83302007-05-18 17:15:44 +0000320 PyUnicode_AppendAndDel(&s, temp);
Tim Petersa7259592001-06-16 05:11:17 +0000321 PyList_SET_ITEM(pieces, 0, s);
322 if (s == NULL)
323 goto Done;
324
Walter Dörwald1ab83302007-05-18 17:15:44 +0000325 s = PyUnicode_FromString("]");
Tim Petersa7259592001-06-16 05:11:17 +0000326 if (s == NULL)
327 goto Done;
328 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
Walter Dörwald1ab83302007-05-18 17:15:44 +0000329 PyUnicode_AppendAndDel(&temp, s);
Tim Petersa7259592001-06-16 05:11:17 +0000330 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
331 if (temp == NULL)
332 goto Done;
333
334 /* Paste them all together with ", " between. */
Walter Dörwald1ab83302007-05-18 17:15:44 +0000335 s = PyUnicode_FromString(", ");
Tim Petersa7259592001-06-16 05:11:17 +0000336 if (s == NULL)
337 goto Done;
Walter Dörwald1ab83302007-05-18 17:15:44 +0000338 result = PyUnicode_Join(s, pieces);
Tim Peters3b01a122002-07-19 02:35:45 +0000339 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +0000340
341Done:
342 Py_XDECREF(pieces);
Guido van Rossumfb376de1998-04-10 22:47:27 +0000343 Py_ReprLeave((PyObject *)v);
Tim Petersa7259592001-06-16 05:11:17 +0000344 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000345}
346
Martin v. Löwis18e16552006-02-15 17:27:45 +0000347static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000348list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000349{
Christian Heimes90aa7642007-12-19 02:45:37 +0000350 return Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000351}
352
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000353static int
Fred Drakea2f55112000-07-09 15:16:51 +0000354list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000355{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000356 Py_ssize_t i;
357 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000358
Christian Heimes90aa7642007-12-19 02:45:37 +0000359 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
Raymond Hettingeraae59992002-09-05 14:23:49 +0000360 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000361 Py_EQ);
Neal Norwitzbb9c5f52002-09-05 21:32:55 +0000362 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000363}
364
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000365static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000366list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000367{
Christian Heimes90aa7642007-12-19 02:45:37 +0000368 if (i < 0 || i >= Py_SIZE(a)) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000369 if (indexerr == NULL)
Neal Norwitz53cbdaa2007-08-23 21:42:55 +0000370 indexerr = PyUnicode_FromString(
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000371 "list index out of range");
372 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000373 return NULL;
374 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000375 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000376 return a->ob_item[i];
377}
378
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000379static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000380list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000381{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000382 PyListObject *np;
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000383 PyObject **src, **dest;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000384 Py_ssize_t i, len;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000385 if (ilow < 0)
386 ilow = 0;
Christian Heimes90aa7642007-12-19 02:45:37 +0000387 else if (ilow > Py_SIZE(a))
388 ilow = Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000389 if (ihigh < ilow)
390 ihigh = ilow;
Christian Heimes90aa7642007-12-19 02:45:37 +0000391 else if (ihigh > Py_SIZE(a))
392 ihigh = Py_SIZE(a);
Raymond Hettinger99842b62004-03-08 05:56:15 +0000393 len = ihigh - ilow;
394 np = (PyListObject *) PyList_New(len);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000395 if (np == NULL)
396 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000397
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000398 src = a->ob_item + ilow;
399 dest = np->ob_item;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000400 for (i = 0; i < len; i++) {
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000401 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000402 Py_INCREF(v);
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000403 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000404 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000405 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000406}
407
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000408PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000409PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000410{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000411 if (!PyList_Check(a)) {
412 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000413 return NULL;
414 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000415 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000416}
417
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000418static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000419list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000420{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000421 Py_ssize_t size;
422 Py_ssize_t i;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000423 PyObject **src, **dest;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000424 PyListObject *np;
425 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000426 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000427 "can only concatenate list (not \"%.200s\") to list",
428 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000429 return NULL;
430 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000431#define b ((PyListObject *)bb)
Christian Heimes90aa7642007-12-19 02:45:37 +0000432 size = Py_SIZE(a) + Py_SIZE(b);
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000433 if (size < 0)
434 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000435 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000436 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000437 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000438 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000439 src = a->ob_item;
440 dest = np->ob_item;
Christian Heimes90aa7642007-12-19 02:45:37 +0000441 for (i = 0; i < Py_SIZE(a); i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000442 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000443 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000444 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000445 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000446 src = b->ob_item;
Christian Heimes90aa7642007-12-19 02:45:37 +0000447 dest = np->ob_item + Py_SIZE(a);
448 for (i = 0; i < Py_SIZE(b); i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000449 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000450 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000451 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000452 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000453 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000454#undef b
455}
456
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000457static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000458list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000459{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000460 Py_ssize_t i, j;
461 Py_ssize_t size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000462 PyListObject *np;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000463 PyObject **p, **items;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000464 PyObject *elem;
Guido van Rossumed98d481991-03-06 13:07:53 +0000465 if (n < 0)
466 n = 0;
Christian Heimes90aa7642007-12-19 02:45:37 +0000467 size = Py_SIZE(a) * n;
468 if (n && size/n != Py_SIZE(a))
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000469 return PyErr_NoMemory();
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000470 if (size == 0)
Christian Heimesaf98da12008-01-27 15:18:18 +0000471 return PyList_New(0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000472 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000473 if (np == NULL)
474 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000475
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000476 items = np->ob_item;
Christian Heimes90aa7642007-12-19 02:45:37 +0000477 if (Py_SIZE(a) == 1) {
Raymond Hettinger6624e682003-05-21 05:58:46 +0000478 elem = a->ob_item[0];
479 for (i = 0; i < n; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000480 items[i] = elem;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000481 Py_INCREF(elem);
482 }
483 return (PyObject *) np;
484 }
Guido van Rossumed98d481991-03-06 13:07:53 +0000485 p = np->ob_item;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000486 items = a->ob_item;
Guido van Rossumed98d481991-03-06 13:07:53 +0000487 for (i = 0; i < n; i++) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000488 for (j = 0; j < Py_SIZE(a); j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000489 *p = items[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000490 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000491 p++;
492 }
493 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000494 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000495}
496
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000497static int
Armin Rigo93677f02004-07-29 12:40:23 +0000498list_clear(PyListObject *a)
499{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000500 Py_ssize_t i;
Armin Rigo93677f02004-07-29 12:40:23 +0000501 PyObject **item = a->ob_item;
502 if (item != NULL) {
503 /* Because XDECREF can recursively invoke operations on
504 this list, we make it empty first. */
Christian Heimes90aa7642007-12-19 02:45:37 +0000505 i = Py_SIZE(a);
506 Py_SIZE(a) = 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000507 a->ob_item = NULL;
508 a->allocated = 0;
509 while (--i >= 0) {
510 Py_XDECREF(item[i]);
511 }
512 PyMem_FREE(item);
513 }
514 /* Never fails; the return value can be ignored.
515 Note that there is no guarantee that the list is actually empty
516 at this point, because XDECREF may have populated it again! */
517 return 0;
518}
519
Tim Peters8fc4a912004-07-31 21:53:19 +0000520/* a[ilow:ihigh] = v if v != NULL.
521 * del a[ilow:ihigh] if v == NULL.
522 *
523 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
524 * guaranteed the call cannot fail.
525 */
Armin Rigo93677f02004-07-29 12:40:23 +0000526static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000527list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000528{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000529 /* Because [X]DECREF can recursively invoke list operations on
530 this list, we must postpone all [X]DECREF activity until
531 after the list is back in its canonical shape. Therefore
532 we must allocate an additional array, 'recycle', into which
533 we temporarily copy the items that are deleted from the
534 list. :-( */
Tim Peters73572222004-07-31 02:54:42 +0000535 PyObject *recycle_on_stack[8];
536 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000537 PyObject **item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000538 PyObject **vitem = NULL;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000539 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000540 Py_ssize_t n; /* # of elements in replacement list */
541 Py_ssize_t norig; /* # of elements in list getting replaced */
542 Py_ssize_t d; /* Change in size */
543 Py_ssize_t k;
Tim Peters8d9eb102004-07-31 02:24:20 +0000544 size_t s;
545 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000546#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000547 if (v == NULL)
548 n = 0;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000549 else {
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000550 if (a == b) {
551 /* Special case "a[i:j] = a" -- copy b first */
Christian Heimes90aa7642007-12-19 02:45:37 +0000552 v = list_slice(b, 0, Py_SIZE(b));
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000553 if (v == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000554 return result;
555 result = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000556 Py_DECREF(v);
Tim Peters8d9eb102004-07-31 02:24:20 +0000557 return result;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000558 }
Raymond Hettingerf889e102004-03-09 08:04:33 +0000559 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000560 if(v_as_SF == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000561 goto Error;
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000562 n = PySequence_Fast_GET_SIZE(v_as_SF);
Raymond Hettinger42bec932004-03-12 16:38:17 +0000563 vitem = PySequence_Fast_ITEMS(v_as_SF);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000564 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000565 if (ilow < 0)
566 ilow = 0;
Christian Heimes90aa7642007-12-19 02:45:37 +0000567 else if (ilow > Py_SIZE(a))
568 ilow = Py_SIZE(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000569
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000570 if (ihigh < ilow)
571 ihigh = ilow;
Christian Heimes90aa7642007-12-19 02:45:37 +0000572 else if (ihigh > Py_SIZE(a))
573 ihigh = Py_SIZE(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000574
Tim Peters8d9eb102004-07-31 02:24:20 +0000575 norig = ihigh - ilow;
576 assert(norig >= 0);
577 d = n - norig;
Christian Heimes90aa7642007-12-19 02:45:37 +0000578 if (Py_SIZE(a) + d == 0) {
Armin Rigo93677f02004-07-29 12:40:23 +0000579 Py_XDECREF(v_as_SF);
580 return list_clear(a);
581 }
582 item = a->ob_item;
Tim Peters8d9eb102004-07-31 02:24:20 +0000583 /* recycle the items that we are about to remove */
584 s = norig * sizeof(PyObject *);
Tim Peters73572222004-07-31 02:54:42 +0000585 if (s > sizeof(recycle_on_stack)) {
Armin Rigo1dd04a02004-07-30 11:38:22 +0000586 recycle = (PyObject **)PyMem_MALLOC(s);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000587 if (recycle == NULL) {
588 PyErr_NoMemory();
Tim Peters8d9eb102004-07-31 02:24:20 +0000589 goto Error;
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000590 }
591 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000592 memcpy(recycle, &item[ilow], s);
Tim Peters8d9eb102004-07-31 02:24:20 +0000593
Armin Rigo1dd04a02004-07-30 11:38:22 +0000594 if (d < 0) { /* Delete -d items */
595 memmove(&item[ihigh+d], &item[ihigh],
Christian Heimes90aa7642007-12-19 02:45:37 +0000596 (Py_SIZE(a) - ihigh)*sizeof(PyObject *));
597 list_resize(a, Py_SIZE(a) + d);
Armin Rigo1dd04a02004-07-30 11:38:22 +0000598 item = a->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000599 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000600 else if (d > 0) { /* Insert d items */
Christian Heimes90aa7642007-12-19 02:45:37 +0000601 k = Py_SIZE(a);
Tim Peters73572222004-07-31 02:54:42 +0000602 if (list_resize(a, k+d) < 0)
Tim Peters8d9eb102004-07-31 02:24:20 +0000603 goto Error;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000604 item = a->ob_item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000605 memmove(&item[ihigh+d], &item[ihigh],
Tim Peters73572222004-07-31 02:54:42 +0000606 (k - ihigh)*sizeof(PyObject *));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000607 }
608 for (k = 0; k < n; k++, ilow++) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000609 PyObject *w = vitem[k];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000610 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000611 item[ilow] = w;
612 }
Tim Peters73572222004-07-31 02:54:42 +0000613 for (k = norig - 1; k >= 0; --k)
614 Py_XDECREF(recycle[k]);
Tim Peters8d9eb102004-07-31 02:24:20 +0000615 result = 0;
616 Error:
Tim Peters73572222004-07-31 02:54:42 +0000617 if (recycle != recycle_on_stack)
Armin Rigo1dd04a02004-07-30 11:38:22 +0000618 PyMem_FREE(recycle);
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000619 Py_XDECREF(v_as_SF);
Tim Peters8d9eb102004-07-31 02:24:20 +0000620 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000621#undef b
622}
623
Guido van Rossum234f9421993-06-17 12:35:49 +0000624int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000625PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000626{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000627 if (!PyList_Check(a)) {
628 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000629 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000630 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000631 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000632}
633
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000634static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000635list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000636{
637 PyObject **items;
Christian Heimesaf98da12008-01-27 15:18:18 +0000638 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000639
640
641 size = PyList_GET_SIZE(self);
Christian Heimesaf98da12008-01-27 15:18:18 +0000642 if (size == 0 || n == 1) {
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000643 Py_INCREF(self);
644 return (PyObject *)self;
645 }
646
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000647 if (n < 1) {
Armin Rigo93677f02004-07-29 12:40:23 +0000648 (void)list_clear(self);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000649 Py_INCREF(self);
650 return (PyObject *)self;
651 }
652
Christian Heimesaf98da12008-01-27 15:18:18 +0000653 if (size > PY_SSIZE_T_MAX / n) {
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000654 return PyErr_NoMemory();
Christian Heimesaf98da12008-01-27 15:18:18 +0000655 }
656
657 if (list_resize(self, size*n) == -1)
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000658 return NULL;
659
660 p = size;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000661 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000662 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
663 for (j = 0; j < size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000664 PyObject *o = items[j];
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000665 Py_INCREF(o);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000666 items[p++] = o;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000667 }
668 }
669 Py_INCREF(self);
670 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000671}
672
Guido van Rossum4a450d01991-04-03 19:05:18 +0000673static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000674list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000675{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000676 PyObject *old_value;
Christian Heimes90aa7642007-12-19 02:45:37 +0000677 if (i < 0 || i >= Py_SIZE(a)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000678 PyErr_SetString(PyExc_IndexError,
679 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000680 return -1;
681 }
682 if (v == NULL)
683 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000684 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000685 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000686 a->ob_item[i] = v;
Tim Peters3b01a122002-07-19 02:35:45 +0000687 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000688 return 0;
689}
690
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000691static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000692listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000693{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000694 Py_ssize_t i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000695 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000696 if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000697 return NULL;
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000698 if (ins1(self, i, v) == 0)
699 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000700 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000701}
702
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000703static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000704listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000705{
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000706 if (app1(self, v) == 0)
707 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000708 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000709}
710
Barry Warsawdedf6d61998-10-09 16:37:25 +0000711static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000712listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000713{
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000714 PyObject *it; /* iter(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000715 Py_ssize_t m; /* size of self */
716 Py_ssize_t n; /* guess for size of b */
717 Py_ssize_t mn; /* m + n */
718 Py_ssize_t i;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000719 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000720
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000721 /* Special cases:
Tim Petersb38e2b62004-07-29 02:29:26 +0000722 1) lists and tuples which can use PySequence_Fast ops
723 2) extending self to self requires making a copy first
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000724 */
725 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
Armin Rigo70d172d2004-03-20 22:19:23 +0000726 PyObject **src, **dest;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000727 b = PySequence_Fast(b, "argument must be iterable");
728 if (!b)
729 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000730 n = PySequence_Fast_GET_SIZE(b);
731 if (n == 0) {
732 /* short circuit when b is empty */
733 Py_DECREF(b);
734 Py_RETURN_NONE;
735 }
Christian Heimes90aa7642007-12-19 02:45:37 +0000736 m = Py_SIZE(self);
Armin Rigo70d172d2004-03-20 22:19:23 +0000737 if (list_resize(self, m + n) == -1) {
738 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000739 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000740 }
741 /* note that we may still have self == b here for the
742 * situation a.extend(a), but the following code works
743 * in that case too. Just make sure to resize self
744 * before calling PySequence_Fast_ITEMS.
745 */
746 /* populate the end of self with b's items */
747 src = PySequence_Fast_ITEMS(b);
748 dest = self->ob_item + m;
749 for (i = 0; i < n; i++) {
750 PyObject *o = src[i];
751 Py_INCREF(o);
752 dest[i] = o;
753 }
754 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000755 Py_RETURN_NONE;
756 }
757
758 it = PyObject_GetIter(b);
759 if (it == NULL)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000760 return NULL;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000761 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000762
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000763 /* Guess a result list size. */
Christian Heimes255f53b2007-12-08 15:33:56 +0000764 n = _PyObject_LengthHint(b, 8);
Christian Heimes90aa7642007-12-19 02:45:37 +0000765 m = Py_SIZE(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000766 mn = m + n;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000767 if (mn >= m) {
768 /* Make room. */
769 if (list_resize(self, mn) == -1)
770 goto error;
771 /* Make the list sane again. */
Christian Heimes90aa7642007-12-19 02:45:37 +0000772 Py_SIZE(self) = m;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000773 }
774 /* Else m + n overflowed; on the chance that n lied, and there really
775 * is enough room, ignore it. If n was telling the truth, we'll
776 * eventually run out of memory during the loop.
777 */
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000778
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000779 /* Run iterator to exhaustion. */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000780 for (;;) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000781 PyObject *item = iternext(it);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000782 if (item == NULL) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000783 if (PyErr_Occurred()) {
784 if (PyErr_ExceptionMatches(PyExc_StopIteration))
785 PyErr_Clear();
786 else
787 goto error;
788 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000789 break;
790 }
Christian Heimes90aa7642007-12-19 02:45:37 +0000791 if (Py_SIZE(self) < self->allocated) {
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000792 /* steals ref */
Christian Heimes90aa7642007-12-19 02:45:37 +0000793 PyList_SET_ITEM(self, Py_SIZE(self), item);
794 ++Py_SIZE(self);
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000795 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000796 else {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000797 int status = app1(self, item);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000798 Py_DECREF(item); /* append creates a new ref */
799 if (status < 0)
800 goto error;
801 }
802 }
803
804 /* Cut back result list if initial guess was too large. */
Christian Heimes90aa7642007-12-19 02:45:37 +0000805 if (Py_SIZE(self) < self->allocated)
806 list_resize(self, Py_SIZE(self)); /* shrinking can't fail */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000807
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000808 Py_DECREF(it);
809 Py_RETURN_NONE;
810
811 error:
812 Py_DECREF(it);
813 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000814}
815
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000816PyObject *
817_PyList_Extend(PyListObject *self, PyObject *b)
818{
819 return listextend(self, b);
820}
821
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000822static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000823list_inplace_concat(PyListObject *self, PyObject *other)
824{
825 PyObject *result;
826
827 result = listextend(self, other);
828 if (result == NULL)
829 return result;
830 Py_DECREF(result);
831 Py_INCREF(self);
832 return (PyObject *)self;
833}
834
835static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000836listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000837{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000838 Py_ssize_t i = -1;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000839 PyObject *v;
Tim Peters8fc4a912004-07-31 21:53:19 +0000840 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000841
Thomas Wouters89f507f2006-12-13 04:49:30 +0000842 if (!PyArg_ParseTuple(args, "|n:pop", &i))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000843 return NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000844
Christian Heimes90aa7642007-12-19 02:45:37 +0000845 if (Py_SIZE(self) == 0) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000846 /* Special-case most common failure cause */
847 PyErr_SetString(PyExc_IndexError, "pop from empty list");
848 return NULL;
849 }
850 if (i < 0)
Christian Heimes90aa7642007-12-19 02:45:37 +0000851 i += Py_SIZE(self);
852 if (i < 0 || i >= Py_SIZE(self)) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000853 PyErr_SetString(PyExc_IndexError, "pop index out of range");
854 return NULL;
855 }
856 v = self->ob_item[i];
Christian Heimes90aa7642007-12-19 02:45:37 +0000857 if (i == Py_SIZE(self) - 1) {
858 status = list_resize(self, Py_SIZE(self) - 1);
Tim Peters8fc4a912004-07-31 21:53:19 +0000859 assert(status >= 0);
860 return v; /* and v now owns the reference the list had */
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000861 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000862 Py_INCREF(v);
Tim Peters8fc4a912004-07-31 21:53:19 +0000863 status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
864 assert(status >= 0);
865 /* Use status, so that in a release build compilers don't
866 * complain about the unused name.
867 */
Brett Cannon651dd522004-08-08 21:21:18 +0000868 (void) status;
869
870 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000871}
872
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000873/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
874static void
875reverse_slice(PyObject **lo, PyObject **hi)
876{
877 assert(lo && hi);
878
879 --hi;
880 while (lo < hi) {
881 PyObject *t = *lo;
882 *lo = *hi;
883 *hi = t;
884 ++lo;
885 --hi;
886 }
887}
888
Tim Petersa64dc242002-08-01 02:13:36 +0000889/* Lots of code for an adaptive, stable, natural mergesort. There are many
890 * pieces to this algorithm; read listsort.txt for overviews and details.
891 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000892
Raymond Hettinger70b64fc2008-01-30 20:15:17 +0000893/* Comparison function: PyObject_RichCompareBool with Py_LT.
Tim Petersa64dc242002-08-01 02:13:36 +0000894 * Returns -1 on error, 1 if x < y, 0 if x >= y.
895 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000896
Raymond Hettinger70b64fc2008-01-30 20:15:17 +0000897#define ISLT(X, Y) (PyObject_RichCompareBool(X, Y, Py_LT))
Tim Peters66860f62002-08-04 17:47:26 +0000898
899/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +0000900 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
901 started. It makes more sense in context <wink>. X and Y are PyObject*s.
902*/
Raymond Hettinger70b64fc2008-01-30 20:15:17 +0000903#define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail; \
Tim Petersa8c974c2002-07-19 03:30:57 +0000904 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000905
906/* binarysort is the best method for sorting small arrays: it does
907 few compares, but can do data movement quadratic in the number of
908 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000909 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +0000910 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000911 On entry, must have lo <= start <= hi, and that [lo, start) is already
912 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +0000913 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000914 Even in case of error, the output slice will be some permutation of
915 the input (nothing is lost or duplicated).
916*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000917static int
Raymond Hettinger70b64fc2008-01-30 20:15:17 +0000918binarysort(PyObject **lo, PyObject **hi, PyObject **start)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000919{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000920 register Py_ssize_t k;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000921 register PyObject **l, **p, **r;
922 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000923
Tim Petersa8c974c2002-07-19 03:30:57 +0000924 assert(lo <= start && start <= hi);
925 /* assert [lo, start) is sorted */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000926 if (lo == start)
927 ++start;
928 for (; start < hi; ++start) {
929 /* set l to where *start belongs */
930 l = lo;
931 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000932 pivot = *r;
Tim Peters0fe977c2002-07-19 06:12:32 +0000933 /* Invariants:
934 * pivot >= all in [lo, l).
935 * pivot < all in [r, start).
936 * The second is vacuously true at the start.
937 */
938 assert(l < r);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000939 do {
940 p = l + ((r - l) >> 1);
Tim Petersa8c974c2002-07-19 03:30:57 +0000941 IFLT(pivot, *p)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000942 r = p;
943 else
Tim Peters0fe977c2002-07-19 06:12:32 +0000944 l = p+1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000945 } while (l < r);
Tim Peters0fe977c2002-07-19 06:12:32 +0000946 assert(l == r);
947 /* The invariants still hold, so pivot >= all in [lo, l) and
948 pivot < all in [l, start), so pivot belongs at l. Note
949 that if there are elements equal to pivot, l points to the
950 first slot after them -- that's why this sort is stable.
951 Slide over to make room.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000952 Caution: using memmove is much slower under MSVC 5;
953 we're not usually moving many slots. */
954 for (p = start; p > l; --p)
955 *p = *(p-1);
956 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000957 }
Guido van Rossum3f236de1996-12-10 23:55:39 +0000958 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000959
960 fail:
961 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000962}
963
Tim Petersa64dc242002-08-01 02:13:36 +0000964/*
965Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
966is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000967
Tim Petersa64dc242002-08-01 02:13:36 +0000968 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000969
Tim Petersa64dc242002-08-01 02:13:36 +0000970or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000971
Tim Petersa64dc242002-08-01 02:13:36 +0000972 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +0000973
Tim Petersa64dc242002-08-01 02:13:36 +0000974Boolean *descending is set to 0 in the former case, or to 1 in the latter.
975For its intended use in a stable mergesort, the strictness of the defn of
976"descending" is needed so that the caller can safely reverse a descending
977sequence without violating stability (strict > ensures there are no equal
978elements to get out of order).
979
980Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000981*/
Martin v. Löwis18e16552006-02-15 17:27:45 +0000982static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +0000983count_run(PyObject **lo, PyObject **hi, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000984{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000985 Py_ssize_t k;
986 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000987
Tim Petersa64dc242002-08-01 02:13:36 +0000988 assert(lo < hi);
989 *descending = 0;
990 ++lo;
991 if (lo == hi)
992 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000993
Tim Petersa64dc242002-08-01 02:13:36 +0000994 n = 2;
995 IFLT(*lo, *(lo-1)) {
996 *descending = 1;
997 for (lo = lo+1; lo < hi; ++lo, ++n) {
998 IFLT(*lo, *(lo-1))
999 ;
1000 else
1001 break;
1002 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001003 }
Tim Petersa64dc242002-08-01 02:13:36 +00001004 else {
1005 for (lo = lo+1; lo < hi; ++lo, ++n) {
1006 IFLT(*lo, *(lo-1))
1007 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001008 }
1009 }
1010
Tim Petersa64dc242002-08-01 02:13:36 +00001011 return n;
1012fail:
1013 return -1;
1014}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001015
Tim Petersa64dc242002-08-01 02:13:36 +00001016/*
1017Locate the proper position of key in a sorted vector; if the vector contains
1018an element equal to key, return the position immediately to the left of
1019the leftmost equal element. [gallop_right() does the same except returns
1020the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001021
Tim Petersa64dc242002-08-01 02:13:36 +00001022"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001023
Tim Petersa64dc242002-08-01 02:13:36 +00001024"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1025hint is to the final result, the faster this runs.
1026
1027The return value is the int k in 0..n such that
1028
1029 a[k-1] < key <= a[k]
1030
1031pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1032key belongs at index k; or, IOW, the first k elements of a should precede
1033key, and the last n-k should follow key.
1034
1035Returns -1 on error. See listsort.txt for info on the method.
1036*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001037static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001038gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001039{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001040 Py_ssize_t ofs;
1041 Py_ssize_t lastofs;
1042 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001043
1044 assert(key && a && n > 0 && hint >= 0 && hint < n);
1045
1046 a += hint;
1047 lastofs = 0;
1048 ofs = 1;
1049 IFLT(*a, key) {
1050 /* a[hint] < key -- gallop right, until
1051 * a[hint + lastofs] < key <= a[hint + ofs]
1052 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001053 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001054 while (ofs < maxofs) {
1055 IFLT(a[ofs], key) {
1056 lastofs = ofs;
1057 ofs = (ofs << 1) + 1;
1058 if (ofs <= 0) /* int overflow */
1059 ofs = maxofs;
1060 }
1061 else /* key <= a[hint + ofs] */
1062 break;
1063 }
1064 if (ofs > maxofs)
1065 ofs = maxofs;
1066 /* Translate back to offsets relative to &a[0]. */
1067 lastofs += hint;
1068 ofs += hint;
1069 }
1070 else {
1071 /* key <= a[hint] -- gallop left, until
1072 * a[hint - ofs] < key <= a[hint - lastofs]
1073 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001074 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001075 while (ofs < maxofs) {
1076 IFLT(*(a-ofs), key)
1077 break;
1078 /* key <= a[hint - ofs] */
1079 lastofs = ofs;
1080 ofs = (ofs << 1) + 1;
1081 if (ofs <= 0) /* int overflow */
1082 ofs = maxofs;
1083 }
1084 if (ofs > maxofs)
1085 ofs = maxofs;
1086 /* Translate back to positive offsets relative to &a[0]. */
1087 k = lastofs;
1088 lastofs = hint - ofs;
1089 ofs = hint - k;
1090 }
1091 a -= hint;
1092
1093 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1094 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1095 * right of lastofs but no farther right than ofs. Do a binary
1096 * search, with invariant a[lastofs-1] < key <= a[ofs].
1097 */
1098 ++lastofs;
1099 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001100 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001101
1102 IFLT(a[m], key)
1103 lastofs = m+1; /* a[m] < key */
1104 else
1105 ofs = m; /* key <= a[m] */
1106 }
1107 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1108 return ofs;
1109
1110fail:
1111 return -1;
1112}
1113
1114/*
1115Exactly like gallop_left(), except that if key already exists in a[0:n],
1116finds the position immediately to the right of the rightmost equal value.
1117
1118The return value is the int k in 0..n such that
1119
1120 a[k-1] <= key < a[k]
1121
1122or -1 if error.
1123
1124The code duplication is massive, but this is enough different given that
1125we're sticking to "<" comparisons that it's much harder to follow if
1126written as one routine with yet another "left or right?" flag.
1127*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001128static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001129gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001130{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001131 Py_ssize_t ofs;
1132 Py_ssize_t lastofs;
1133 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001134
1135 assert(key && a && n > 0 && hint >= 0 && hint < n);
1136
1137 a += hint;
1138 lastofs = 0;
1139 ofs = 1;
1140 IFLT(key, *a) {
1141 /* key < a[hint] -- gallop left, until
1142 * a[hint - ofs] <= key < a[hint - lastofs]
1143 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001144 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001145 while (ofs < maxofs) {
1146 IFLT(key, *(a-ofs)) {
1147 lastofs = ofs;
1148 ofs = (ofs << 1) + 1;
1149 if (ofs <= 0) /* int overflow */
1150 ofs = maxofs;
1151 }
1152 else /* a[hint - ofs] <= key */
1153 break;
1154 }
1155 if (ofs > maxofs)
1156 ofs = maxofs;
1157 /* Translate back to positive offsets relative to &a[0]. */
1158 k = lastofs;
1159 lastofs = hint - ofs;
1160 ofs = hint - k;
1161 }
1162 else {
1163 /* a[hint] <= key -- gallop right, until
1164 * a[hint + lastofs] <= key < a[hint + ofs]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001165 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001166 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001167 while (ofs < maxofs) {
1168 IFLT(key, a[ofs])
1169 break;
1170 /* a[hint + ofs] <= key */
1171 lastofs = ofs;
1172 ofs = (ofs << 1) + 1;
1173 if (ofs <= 0) /* int overflow */
1174 ofs = maxofs;
1175 }
1176 if (ofs > maxofs)
1177 ofs = maxofs;
1178 /* Translate back to offsets relative to &a[0]. */
1179 lastofs += hint;
1180 ofs += hint;
1181 }
1182 a -= hint;
1183
1184 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1185 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1186 * right of lastofs but no farther right than ofs. Do a binary
1187 * search, with invariant a[lastofs-1] <= key < a[ofs].
1188 */
1189 ++lastofs;
1190 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001191 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001192
1193 IFLT(key, a[m])
1194 ofs = m; /* key < a[m] */
1195 else
1196 lastofs = m+1; /* a[m] <= key */
1197 }
1198 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1199 return ofs;
1200
1201fail:
1202 return -1;
1203}
1204
1205/* The maximum number of entries in a MergeState's pending-runs stack.
1206 * This is enough to sort arrays of size up to about
1207 * 32 * phi ** MAX_MERGE_PENDING
1208 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1209 * with 2**64 elements.
1210 */
1211#define MAX_MERGE_PENDING 85
1212
Tim Peterse05f65a2002-08-10 05:21:15 +00001213/* When we get into galloping mode, we stay there until both runs win less
1214 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001215 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001216#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001217
1218/* Avoid malloc for small temp arrays. */
1219#define MERGESTATE_TEMP_SIZE 256
1220
1221/* One MergeState exists on the stack per invocation of mergesort. It's just
1222 * a convenient way to pass state around among the helper functions.
1223 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001224struct s_slice {
1225 PyObject **base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001226 Py_ssize_t len;
Tim Peterse05f65a2002-08-10 05:21:15 +00001227};
1228
Tim Petersa64dc242002-08-01 02:13:36 +00001229typedef struct s_MergeState {
Tim Peterse05f65a2002-08-10 05:21:15 +00001230 /* This controls when we get *into* galloping mode. It's initialized
1231 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1232 * random data, and lower for highly structured data.
1233 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001234 Py_ssize_t min_gallop;
Tim Peterse05f65a2002-08-10 05:21:15 +00001235
Tim Petersa64dc242002-08-01 02:13:36 +00001236 /* 'a' is temp storage to help with merges. It contains room for
1237 * alloced entries.
1238 */
1239 PyObject **a; /* may point to temparray below */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001240 Py_ssize_t alloced;
Tim Petersa64dc242002-08-01 02:13:36 +00001241
1242 /* A stack of n pending runs yet to be merged. Run #i starts at
1243 * address base[i] and extends for len[i] elements. It's always
1244 * true (so long as the indices are in bounds) that
1245 *
Tim Peterse05f65a2002-08-10 05:21:15 +00001246 * pending[i].base + pending[i].len == pending[i+1].base
Tim Petersa64dc242002-08-01 02:13:36 +00001247 *
1248 * so we could cut the storage for this, but it's a minor amount,
1249 * and keeping all the info explicit simplifies the code.
1250 */
1251 int n;
Tim Peterse05f65a2002-08-10 05:21:15 +00001252 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001253
1254 /* 'a' points to this when possible, rather than muck with malloc. */
1255 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1256} MergeState;
1257
1258/* Conceptually a MergeState's constructor. */
1259static void
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001260merge_init(MergeState *ms)
Tim Petersa64dc242002-08-01 02:13:36 +00001261{
1262 assert(ms != NULL);
Tim Petersa64dc242002-08-01 02:13:36 +00001263 ms->a = ms->temparray;
1264 ms->alloced = MERGESTATE_TEMP_SIZE;
1265 ms->n = 0;
Tim Peterse05f65a2002-08-10 05:21:15 +00001266 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001267}
1268
1269/* Free all the temp memory owned by the MergeState. This must be called
1270 * when you're done with a MergeState, and may be called before then if
1271 * you want to free the temp memory early.
1272 */
1273static void
1274merge_freemem(MergeState *ms)
1275{
1276 assert(ms != NULL);
1277 if (ms->a != ms->temparray)
1278 PyMem_Free(ms->a);
1279 ms->a = ms->temparray;
1280 ms->alloced = MERGESTATE_TEMP_SIZE;
1281}
1282
1283/* Ensure enough temp memory for 'need' array slots is available.
1284 * Returns 0 on success and -1 if the memory can't be gotten.
1285 */
1286static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001287merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001288{
1289 assert(ms != NULL);
1290 if (need <= ms->alloced)
1291 return 0;
1292 /* Don't realloc! That can cost cycles to copy the old data, but
1293 * we don't care what's in the block.
1294 */
1295 merge_freemem(ms);
1296 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1297 if (ms->a) {
1298 ms->alloced = need;
1299 return 0;
1300 }
1301 PyErr_NoMemory();
1302 merge_freemem(ms); /* reset to sane state */
1303 return -1;
1304}
1305#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1306 merge_getmem(MS, NEED))
1307
1308/* Merge the na elements starting at pa with the nb elements starting at pb
1309 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1310 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1311 * merge, and should have na <= nb. See listsort.txt for more info.
1312 * Return 0 if successful, -1 if error.
1313 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001314static Py_ssize_t
1315merge_lo(MergeState *ms, PyObject **pa, Py_ssize_t na,
1316 PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001317{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001318 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001319 PyObject **dest;
1320 int result = -1; /* guilty until proved innocent */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001321 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001322
1323 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1324 if (MERGE_GETMEM(ms, na) < 0)
1325 return -1;
1326 memcpy(ms->a, pa, na * sizeof(PyObject*));
1327 dest = pa;
1328 pa = ms->a;
1329
1330 *dest++ = *pb++;
1331 --nb;
1332 if (nb == 0)
1333 goto Succeed;
1334 if (na == 1)
1335 goto CopyB;
1336
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001337 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001338 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001339 Py_ssize_t acount = 0; /* # of times A won in a row */
1340 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001341
1342 /* Do the straightforward thing until (if ever) one run
1343 * appears to win consistently.
1344 */
1345 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001346 assert(na > 1 && nb > 0);
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001347 k = ISLT(*pb, *pa);
Tim Petersa64dc242002-08-01 02:13:36 +00001348 if (k) {
1349 if (k < 0)
1350 goto Fail;
1351 *dest++ = *pb++;
1352 ++bcount;
1353 acount = 0;
1354 --nb;
1355 if (nb == 0)
1356 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001357 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001358 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001359 }
1360 else {
Tim Petersa64dc242002-08-01 02:13:36 +00001361 *dest++ = *pa++;
1362 ++acount;
1363 bcount = 0;
1364 --na;
1365 if (na == 1)
1366 goto CopyB;
Tim Peterse05f65a2002-08-10 05:21:15 +00001367 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001368 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001369 }
Tim Petersa64dc242002-08-01 02:13:36 +00001370 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001371
Tim Petersa64dc242002-08-01 02:13:36 +00001372 /* One run is winning so consistently that galloping may
1373 * be a huge win. So try that, and continue galloping until
1374 * (if ever) neither run appears to be winning consistently
1375 * anymore.
1376 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001377 ++min_gallop;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001378 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001379 assert(na > 1 && nb > 0);
1380 min_gallop -= min_gallop > 1;
1381 ms->min_gallop = min_gallop;
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001382 k = gallop_right(*pb, pa, na, 0);
Tim Petersa64dc242002-08-01 02:13:36 +00001383 acount = k;
1384 if (k) {
1385 if (k < 0)
1386 goto Fail;
1387 memcpy(dest, pa, k * sizeof(PyObject *));
1388 dest += k;
1389 pa += k;
1390 na -= k;
1391 if (na == 1)
1392 goto CopyB;
1393 /* na==0 is impossible now if the comparison
1394 * function is consistent, but we can't assume
1395 * that it is.
1396 */
1397 if (na == 0)
1398 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001399 }
Tim Petersa64dc242002-08-01 02:13:36 +00001400 *dest++ = *pb++;
1401 --nb;
1402 if (nb == 0)
1403 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001404
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001405 k = gallop_left(*pa, pb, nb, 0);
Tim Petersa64dc242002-08-01 02:13:36 +00001406 bcount = k;
1407 if (k) {
1408 if (k < 0)
1409 goto Fail;
1410 memmove(dest, pb, k * sizeof(PyObject *));
1411 dest += k;
1412 pb += k;
1413 nb -= k;
1414 if (nb == 0)
1415 goto Succeed;
1416 }
1417 *dest++ = *pa++;
1418 --na;
1419 if (na == 1)
1420 goto CopyB;
1421 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001422 ++min_gallop; /* penalize it for leaving galloping mode */
1423 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001424 }
1425Succeed:
1426 result = 0;
1427Fail:
1428 if (na)
1429 memcpy(dest, pa, na * sizeof(PyObject*));
1430 return result;
1431CopyB:
1432 assert(na == 1 && nb > 0);
1433 /* The last element of pa belongs at the end of the merge. */
1434 memmove(dest, pb, nb * sizeof(PyObject *));
1435 dest[nb] = *pa;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001436 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001437}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001438
Tim Petersa64dc242002-08-01 02:13:36 +00001439/* Merge the na elements starting at pa with the nb elements starting at pb
1440 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1441 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1442 * merge, and should have na >= nb. See listsort.txt for more info.
1443 * Return 0 if successful, -1 if error.
1444 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001445static Py_ssize_t
1446merge_hi(MergeState *ms, PyObject **pa, Py_ssize_t na, PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001447{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001448 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001449 PyObject **dest;
1450 int result = -1; /* guilty until proved innocent */
1451 PyObject **basea;
1452 PyObject **baseb;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001453 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001454
1455 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1456 if (MERGE_GETMEM(ms, nb) < 0)
1457 return -1;
1458 dest = pb + nb - 1;
1459 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1460 basea = pa;
1461 baseb = ms->a;
1462 pb = ms->a + nb - 1;
1463 pa += na - 1;
1464
1465 *dest-- = *pa--;
1466 --na;
1467 if (na == 0)
1468 goto Succeed;
1469 if (nb == 1)
1470 goto CopyA;
1471
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001472 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001473 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001474 Py_ssize_t acount = 0; /* # of times A won in a row */
1475 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001476
1477 /* Do the straightforward thing until (if ever) one run
1478 * appears to win consistently.
1479 */
1480 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001481 assert(na > 0 && nb > 1);
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001482 k = ISLT(*pb, *pa);
Tim Petersa64dc242002-08-01 02:13:36 +00001483 if (k) {
1484 if (k < 0)
1485 goto Fail;
1486 *dest-- = *pa--;
1487 ++acount;
1488 bcount = 0;
1489 --na;
1490 if (na == 0)
1491 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001492 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001493 break;
1494 }
1495 else {
1496 *dest-- = *pb--;
1497 ++bcount;
1498 acount = 0;
1499 --nb;
1500 if (nb == 1)
1501 goto CopyA;
Tim Peterse05f65a2002-08-10 05:21:15 +00001502 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001503 break;
1504 }
1505 }
1506
1507 /* One run is winning so consistently that galloping may
1508 * be a huge win. So try that, and continue galloping until
1509 * (if ever) neither run appears to be winning consistently
1510 * anymore.
1511 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001512 ++min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001513 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001514 assert(na > 0 && nb > 1);
1515 min_gallop -= min_gallop > 1;
1516 ms->min_gallop = min_gallop;
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001517 k = gallop_right(*pb, basea, na, na-1);
Tim Petersa64dc242002-08-01 02:13:36 +00001518 if (k < 0)
1519 goto Fail;
1520 k = na - k;
1521 acount = k;
1522 if (k) {
1523 dest -= k;
1524 pa -= k;
1525 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1526 na -= k;
1527 if (na == 0)
1528 goto Succeed;
1529 }
1530 *dest-- = *pb--;
1531 --nb;
1532 if (nb == 1)
1533 goto CopyA;
1534
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001535 k = gallop_left(*pa, baseb, nb, nb-1);
Tim Petersa64dc242002-08-01 02:13:36 +00001536 if (k < 0)
1537 goto Fail;
1538 k = nb - k;
1539 bcount = k;
1540 if (k) {
1541 dest -= k;
1542 pb -= k;
1543 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1544 nb -= k;
1545 if (nb == 1)
1546 goto CopyA;
1547 /* nb==0 is impossible now if the comparison
1548 * function is consistent, but we can't assume
1549 * that it is.
1550 */
1551 if (nb == 0)
1552 goto Succeed;
1553 }
1554 *dest-- = *pa--;
1555 --na;
1556 if (na == 0)
1557 goto Succeed;
1558 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001559 ++min_gallop; /* penalize it for leaving galloping mode */
1560 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001561 }
1562Succeed:
1563 result = 0;
1564Fail:
1565 if (nb)
1566 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1567 return result;
1568CopyA:
1569 assert(nb == 1 && na > 0);
1570 /* The first element of pb belongs at the front of the merge. */
1571 dest -= na;
1572 pa -= na;
1573 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1574 *dest = *pb;
1575 return 0;
1576}
1577
1578/* Merge the two runs at stack indices i and i+1.
1579 * Returns 0 on success, -1 on error.
1580 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001581static Py_ssize_t
1582merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001583{
1584 PyObject **pa, **pb;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001585 Py_ssize_t na, nb;
1586 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001587
1588 assert(ms != NULL);
1589 assert(ms->n >= 2);
1590 assert(i >= 0);
1591 assert(i == ms->n - 2 || i == ms->n - 3);
1592
Tim Peterse05f65a2002-08-10 05:21:15 +00001593 pa = ms->pending[i].base;
1594 na = ms->pending[i].len;
1595 pb = ms->pending[i+1].base;
1596 nb = ms->pending[i+1].len;
Tim Petersa64dc242002-08-01 02:13:36 +00001597 assert(na > 0 && nb > 0);
1598 assert(pa + na == pb);
1599
1600 /* Record the length of the combined runs; if i is the 3rd-last
1601 * run now, also slide over the last run (which isn't involved
1602 * in this merge). The current run i+1 goes away in any case.
1603 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001604 ms->pending[i].len = na + nb;
1605 if (i == ms->n - 3)
1606 ms->pending[i+1] = ms->pending[i+2];
Tim Petersa64dc242002-08-01 02:13:36 +00001607 --ms->n;
1608
1609 /* Where does b start in a? Elements in a before that can be
1610 * ignored (already in place).
1611 */
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001612 k = gallop_right(*pb, pa, na, 0);
Tim Petersa64dc242002-08-01 02:13:36 +00001613 if (k < 0)
1614 return -1;
1615 pa += k;
1616 na -= k;
1617 if (na == 0)
1618 return 0;
1619
1620 /* Where does a end in b? Elements in b after that can be
1621 * ignored (already in place).
1622 */
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001623 nb = gallop_left(pa[na-1], pb, nb, nb-1);
Tim Petersa64dc242002-08-01 02:13:36 +00001624 if (nb <= 0)
1625 return nb;
1626
1627 /* Merge what remains of the runs, using a temp array with
1628 * min(na, nb) elements.
1629 */
1630 if (na <= nb)
1631 return merge_lo(ms, pa, na, pb, nb);
1632 else
1633 return merge_hi(ms, pa, na, pb, nb);
1634}
1635
1636/* Examine the stack of runs waiting to be merged, merging adjacent runs
1637 * until the stack invariants are re-established:
1638 *
1639 * 1. len[-3] > len[-2] + len[-1]
1640 * 2. len[-2] > len[-1]
1641 *
1642 * See listsort.txt for more info.
1643 *
1644 * Returns 0 on success, -1 on error.
1645 */
1646static int
1647merge_collapse(MergeState *ms)
1648{
Tim Peterse05f65a2002-08-10 05:21:15 +00001649 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001650
1651 assert(ms);
1652 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001653 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001654 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1655 if (p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001656 --n;
1657 if (merge_at(ms, n) < 0)
1658 return -1;
1659 }
Tim Peterse05f65a2002-08-10 05:21:15 +00001660 else if (p[n].len <= p[n+1].len) {
Tim Petersa64dc242002-08-01 02:13:36 +00001661 if (merge_at(ms, n) < 0)
1662 return -1;
1663 }
1664 else
1665 break;
1666 }
1667 return 0;
1668}
1669
1670/* Regardless of invariants, merge all runs on the stack until only one
1671 * remains. This is used at the end of the mergesort.
1672 *
1673 * Returns 0 on success, -1 on error.
1674 */
1675static int
1676merge_force_collapse(MergeState *ms)
1677{
Tim Peterse05f65a2002-08-10 05:21:15 +00001678 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001679
1680 assert(ms);
1681 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001682 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001683 if (n > 0 && p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001684 --n;
1685 if (merge_at(ms, n) < 0)
1686 return -1;
1687 }
1688 return 0;
1689}
1690
1691/* Compute a good value for the minimum run length; natural runs shorter
1692 * than this are boosted artificially via binary insertion.
1693 *
1694 * If n < 64, return n (it's too small to bother with fancy stuff).
1695 * Else if n is an exact power of 2, return 32.
1696 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1697 * strictly less than, an exact power of 2.
1698 *
1699 * See listsort.txt for more info.
1700 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001701static Py_ssize_t
1702merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001703{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001704 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001705
1706 assert(n >= 0);
1707 while (n >= 64) {
1708 r |= n & 1;
1709 n >>= 1;
1710 }
1711 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001712}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001713
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001714/* Special wrapper to support stable sorting using the decorate-sort-undecorate
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001715 pattern. Holds a key which is used for comparisons and the original record
Tim Petersb38e2b62004-07-29 02:29:26 +00001716 which is returned during the undecorate phase. By exposing only the key
1717 during comparisons, the underlying sort stability characteristics are left
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001718 unchanged. Also, the comparison function will only see the key instead of
1719 a full record. */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001720
1721typedef struct {
1722 PyObject_HEAD
1723 PyObject *key;
1724 PyObject *value;
1725} sortwrapperobject;
1726
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001727PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001728static PyObject *
1729sortwrapper_richcompare(sortwrapperobject *, sortwrapperobject *, int);
1730static void
1731sortwrapper_dealloc(sortwrapperobject *);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001732
Christian Heimesa22e8bd2007-11-29 22:35:39 +00001733PyTypeObject PySortWrapper_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001734 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001735 "sortwrapper", /* tp_name */
1736 sizeof(sortwrapperobject), /* tp_basicsize */
1737 0, /* tp_itemsize */
1738 /* methods */
1739 (destructor)sortwrapper_dealloc, /* tp_dealloc */
1740 0, /* tp_print */
1741 0, /* tp_getattr */
1742 0, /* tp_setattr */
1743 0, /* tp_compare */
1744 0, /* tp_repr */
1745 0, /* tp_as_number */
1746 0, /* tp_as_sequence */
1747 0, /* tp_as_mapping */
1748 0, /* tp_hash */
1749 0, /* tp_call */
1750 0, /* tp_str */
1751 PyObject_GenericGetAttr, /* tp_getattro */
1752 0, /* tp_setattro */
1753 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001754 Py_TPFLAGS_DEFAULT, /* tp_flags */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001755 sortwrapper_doc, /* tp_doc */
1756 0, /* tp_traverse */
1757 0, /* tp_clear */
1758 (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
1759};
1760
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001761
1762static PyObject *
1763sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
1764{
Christian Heimesa22e8bd2007-11-29 22:35:39 +00001765 if (!PyObject_TypeCheck(b, &PySortWrapper_Type)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001766 PyErr_SetString(PyExc_TypeError,
1767 "expected a sortwrapperobject");
1768 return NULL;
1769 }
1770 return PyObject_RichCompare(a->key, b->key, op);
1771}
1772
1773static void
1774sortwrapper_dealloc(sortwrapperobject *so)
1775{
1776 Py_XDECREF(so->key);
1777 Py_XDECREF(so->value);
1778 PyObject_Del(so);
1779}
1780
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001781/* Returns a new reference to a sortwrapper.
1782 Consumes the references to the two underlying objects. */
1783
1784static PyObject *
1785build_sortwrapper(PyObject *key, PyObject *value)
1786{
1787 sortwrapperobject *so;
Tim Petersb38e2b62004-07-29 02:29:26 +00001788
Christian Heimesa22e8bd2007-11-29 22:35:39 +00001789 so = PyObject_New(sortwrapperobject, &PySortWrapper_Type);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001790 if (so == NULL)
1791 return NULL;
1792 so->key = key;
1793 so->value = value;
1794 return (PyObject *)so;
1795}
1796
1797/* Returns a new reference to the value underlying the wrapper. */
1798static PyObject *
1799sortwrapper_getvalue(PyObject *so)
1800{
1801 PyObject *value;
1802
Christian Heimesa22e8bd2007-11-29 22:35:39 +00001803 if (!PyObject_TypeCheck(so, &PySortWrapper_Type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001804 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001805 "expected a sortwrapperobject");
1806 return NULL;
1807 }
1808 value = ((sortwrapperobject *)so)->value;
1809 Py_INCREF(value);
1810 return value;
1811}
1812
Tim Petersa64dc242002-08-01 02:13:36 +00001813/* An adaptive, stable, natural mergesort. See listsort.txt.
1814 * Returns Py_None on success, NULL on error. Even in case of error, the
1815 * list will be some permutation of its input state (nothing is lost or
1816 * duplicated).
1817 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001818static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001819listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001820{
Tim Petersa64dc242002-08-01 02:13:36 +00001821 MergeState ms;
1822 PyObject **lo, **hi;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001823 Py_ssize_t nremaining;
1824 Py_ssize_t minrun;
1825 Py_ssize_t saved_ob_size, saved_allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00001826 PyObject **saved_ob_item;
Armin Rigo93677f02004-07-29 12:40:23 +00001827 PyObject **final_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001828 PyObject *result = NULL; /* guilty until proved innocent */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001829 int reverse = 0;
1830 PyObject *keyfunc = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001831 Py_ssize_t i;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001832 PyObject *key, *value, *kvpair;
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001833 static char *kwlist[] = {"key", "reverse", 0};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001834
Tim Petersa64dc242002-08-01 02:13:36 +00001835 assert(self != NULL);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001836 assert (PyList_Check(self));
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001837 if (args != NULL) {
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001838 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:sort",
1839 kwlist, &keyfunc, &reverse))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001840 return NULL;
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001841 if (Py_SIZE(args) > 0) {
1842 PyErr_SetString(PyExc_TypeError,
1843 "must use keyword argument for key function");
1844 return NULL;
1845 }
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001846 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001847 if (keyfunc == Py_None)
1848 keyfunc = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001849
Tim Petersb9099c32002-11-12 22:08:10 +00001850 /* The list is temporarily made empty, so that mutations performed
1851 * by comparison functions can't affect the slice of memory we're
1852 * sorting (allowing mutations during sorting is a core-dump
1853 * factory, since ob_item may change).
1854 */
Christian Heimes90aa7642007-12-19 02:45:37 +00001855 saved_ob_size = Py_SIZE(self);
Tim Petersb9099c32002-11-12 22:08:10 +00001856 saved_ob_item = self->ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001857 saved_allocated = self->allocated;
Christian Heimes90aa7642007-12-19 02:45:37 +00001858 Py_SIZE(self) = 0;
Tim Peters51b4ade2004-07-29 04:07:15 +00001859 self->ob_item = NULL;
Armin Rigo93677f02004-07-29 12:40:23 +00001860 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00001861
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001862 if (keyfunc != NULL) {
1863 for (i=0 ; i < saved_ob_size ; i++) {
1864 value = saved_ob_item[i];
Tim Petersb38e2b62004-07-29 02:29:26 +00001865 key = PyObject_CallFunctionObjArgs(keyfunc, value,
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001866 NULL);
1867 if (key == NULL) {
1868 for (i=i-1 ; i>=0 ; i--) {
1869 kvpair = saved_ob_item[i];
1870 value = sortwrapper_getvalue(kvpair);
1871 saved_ob_item[i] = value;
1872 Py_DECREF(kvpair);
1873 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001874 goto dsu_fail;
1875 }
1876 kvpair = build_sortwrapper(key, value);
1877 if (kvpair == NULL)
1878 goto dsu_fail;
1879 saved_ob_item[i] = kvpair;
1880 }
1881 }
1882
1883 /* Reverse sort stability achieved by initially reversing the list,
1884 applying a stable forward sort, then reversing the final result. */
1885 if (reverse && saved_ob_size > 1)
1886 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
1887
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001888 merge_init(&ms);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001889
Tim Petersb9099c32002-11-12 22:08:10 +00001890 nremaining = saved_ob_size;
Tim Petersa64dc242002-08-01 02:13:36 +00001891 if (nremaining < 2)
1892 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00001893
Tim Petersa64dc242002-08-01 02:13:36 +00001894 /* March over the array once, left to right, finding natural runs,
1895 * and extending short natural runs to minrun elements.
1896 */
Tim Petersb9099c32002-11-12 22:08:10 +00001897 lo = saved_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001898 hi = lo + nremaining;
1899 minrun = merge_compute_minrun(nremaining);
1900 do {
1901 int descending;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001902 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00001903
Tim Petersa64dc242002-08-01 02:13:36 +00001904 /* Identify next run. */
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001905 n = count_run(lo, hi, &descending);
Tim Petersa64dc242002-08-01 02:13:36 +00001906 if (n < 0)
1907 goto fail;
1908 if (descending)
1909 reverse_slice(lo, lo + n);
1910 /* If short, extend to min(minrun, nremaining). */
1911 if (n < minrun) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001912 const Py_ssize_t force = nremaining <= minrun ?
Tim Petersa64dc242002-08-01 02:13:36 +00001913 nremaining : minrun;
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001914 if (binarysort(lo, lo + force, lo + n) < 0)
Tim Petersa64dc242002-08-01 02:13:36 +00001915 goto fail;
1916 n = force;
1917 }
1918 /* Push run onto pending-runs stack, and maybe merge. */
1919 assert(ms.n < MAX_MERGE_PENDING);
Tim Peterse05f65a2002-08-10 05:21:15 +00001920 ms.pending[ms.n].base = lo;
1921 ms.pending[ms.n].len = n;
Tim Petersa64dc242002-08-01 02:13:36 +00001922 ++ms.n;
1923 if (merge_collapse(&ms) < 0)
1924 goto fail;
1925 /* Advance to find next run. */
1926 lo += n;
1927 nremaining -= n;
1928 } while (nremaining);
1929 assert(lo == hi);
Tim Peters330f9e92002-07-19 07:05:44 +00001930
Tim Petersa64dc242002-08-01 02:13:36 +00001931 if (merge_force_collapse(&ms) < 0)
1932 goto fail;
1933 assert(ms.n == 1);
Tim Petersb9099c32002-11-12 22:08:10 +00001934 assert(ms.pending[0].base == saved_ob_item);
1935 assert(ms.pending[0].len == saved_ob_size);
Tim Petersa64dc242002-08-01 02:13:36 +00001936
1937succeed:
1938 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00001939fail:
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001940 if (keyfunc != NULL) {
1941 for (i=0 ; i < saved_ob_size ; i++) {
1942 kvpair = saved_ob_item[i];
1943 value = sortwrapper_getvalue(kvpair);
1944 saved_ob_item[i] = value;
1945 Py_DECREF(kvpair);
1946 }
1947 }
1948
Armin Rigo93677f02004-07-29 12:40:23 +00001949 if (self->allocated != -1 && result != NULL) {
Tim Peters51b4ade2004-07-29 04:07:15 +00001950 /* The user mucked with the list during the sort,
1951 * and we don't already have another error to report.
1952 */
1953 PyErr_SetString(PyExc_ValueError, "list modified during sort");
1954 result = NULL;
Tim Petersb9099c32002-11-12 22:08:10 +00001955 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001956
1957 if (reverse && saved_ob_size > 1)
1958 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
1959
1960 merge_freemem(&ms);
1961
1962dsu_fail:
Armin Rigo93677f02004-07-29 12:40:23 +00001963 final_ob_item = self->ob_item;
Christian Heimes90aa7642007-12-19 02:45:37 +00001964 i = Py_SIZE(self);
1965 Py_SIZE(self) = saved_ob_size;
Tim Petersb9099c32002-11-12 22:08:10 +00001966 self->ob_item = saved_ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001967 self->allocated = saved_allocated;
Armin Rigo93677f02004-07-29 12:40:23 +00001968 if (final_ob_item != NULL) {
1969 /* we cannot use list_clear() for this because it does not
1970 guarantee that the list is really empty when it returns */
1971 while (--i >= 0) {
1972 Py_XDECREF(final_ob_item[i]);
1973 }
1974 PyMem_FREE(final_ob_item);
1975 }
Tim Petersa64dc242002-08-01 02:13:36 +00001976 Py_XINCREF(result);
1977 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001978}
Tim Peters330f9e92002-07-19 07:05:44 +00001979#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00001980#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00001981
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001982int
Fred Drakea2f55112000-07-09 15:16:51 +00001983PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001984{
1985 if (v == NULL || !PyList_Check(v)) {
1986 PyErr_BadInternalCall();
1987 return -1;
1988 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001989 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001990 if (v == NULL)
1991 return -1;
1992 Py_DECREF(v);
1993 return 0;
1994}
1995
Guido van Rossumb86c5492001-02-12 22:06:02 +00001996static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001997listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00001998{
Christian Heimes90aa7642007-12-19 02:45:37 +00001999 if (Py_SIZE(self) > 1)
2000 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002001 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002002}
2003
Guido van Rossum84c76f51990-10-30 13:32:20 +00002004int
Fred Drakea2f55112000-07-09 15:16:51 +00002005PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002006{
Tim Peters6063e262002-08-08 01:06:39 +00002007 PyListObject *self = (PyListObject *)v;
2008
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002009 if (v == NULL || !PyList_Check(v)) {
2010 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002011 return -1;
2012 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002013 if (Py_SIZE(self) > 1)
2014 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002015 return 0;
2016}
2017
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002018PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002019PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002020{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002021 PyObject *w;
Christian Heimes2c181612007-12-17 20:04:13 +00002022 PyObject **p, **q;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002023 Py_ssize_t n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002024 if (v == NULL || !PyList_Check(v)) {
2025 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002026 return NULL;
2027 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002028 n = Py_SIZE(v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002029 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002030 if (w == NULL)
2031 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002032 p = ((PyTupleObject *)w)->ob_item;
Christian Heimes2c181612007-12-17 20:04:13 +00002033 q = ((PyListObject *)v)->ob_item;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002034 while (--n >= 0) {
Christian Heimes2c181612007-12-17 20:04:13 +00002035 Py_INCREF(*q);
2036 *p = *q;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002037 p++;
Christian Heimes2c181612007-12-17 20:04:13 +00002038 q++;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002039 }
2040 return w;
2041}
2042
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002043static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002044listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002045{
Christian Heimes90aa7642007-12-19 02:45:37 +00002046 Py_ssize_t i, start=0, stop=Py_SIZE(self);
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002047 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002048
Walter Dörwalde8049bef2003-06-17 19:27:39 +00002049 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2050 _PyEval_SliceIndex, &start,
2051 _PyEval_SliceIndex, &stop))
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002052 return NULL;
Guido van Rossum2743d872003-06-17 14:25:14 +00002053 if (start < 0) {
Christian Heimes90aa7642007-12-19 02:45:37 +00002054 start += Py_SIZE(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002055 if (start < 0)
2056 start = 0;
2057 }
2058 if (stop < 0) {
Christian Heimes90aa7642007-12-19 02:45:37 +00002059 stop += Py_SIZE(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002060 if (stop < 0)
2061 stop = 0;
2062 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002063 for (i = start; i < stop && i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002064 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2065 if (cmp > 0)
Christian Heimes217cfd12007-12-02 14:31:20 +00002066 return PyLong_FromSsize_t(i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002067 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002068 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002069 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002070 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002071 return NULL;
2072}
2073
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002074static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002075listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002076{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002077 Py_ssize_t count = 0;
2078 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002079
Christian Heimes90aa7642007-12-19 02:45:37 +00002080 for (i = 0; i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002081 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2082 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002083 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002084 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002085 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00002086 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002087 return PyLong_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002088}
2089
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002090static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002091listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002092{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002093 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002094
Christian Heimes90aa7642007-12-19 02:45:37 +00002095 for (i = 0; i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002096 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2097 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002098 if (list_ass_slice(self, i, i+1,
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002099 (PyObject *)NULL) == 0)
2100 Py_RETURN_NONE;
2101 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002102 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002103 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002104 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002105 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002106 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002107 return NULL;
2108}
2109
Jeremy Hylton8caad492000-06-23 14:18:11 +00002110static int
2111list_traverse(PyListObject *o, visitproc visit, void *arg)
2112{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002113 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002114
Christian Heimes90aa7642007-12-19 02:45:37 +00002115 for (i = Py_SIZE(o); --i >= 0; )
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002116 Py_VISIT(o->ob_item[i]);
Jeremy Hylton8caad492000-06-23 14:18:11 +00002117 return 0;
2118}
2119
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002120static PyObject *
2121list_richcompare(PyObject *v, PyObject *w, int op)
2122{
2123 PyListObject *vl, *wl;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002124 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002125
2126 if (!PyList_Check(v) || !PyList_Check(w)) {
2127 Py_INCREF(Py_NotImplemented);
2128 return Py_NotImplemented;
2129 }
2130
2131 vl = (PyListObject *)v;
2132 wl = (PyListObject *)w;
2133
Christian Heimes90aa7642007-12-19 02:45:37 +00002134 if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002135 /* Shortcut: if the lengths differ, the lists differ */
2136 PyObject *res;
2137 if (op == Py_EQ)
2138 res = Py_False;
2139 else
2140 res = Py_True;
2141 Py_INCREF(res);
2142 return res;
2143 }
2144
2145 /* Search for the first index where items are different */
Christian Heimes90aa7642007-12-19 02:45:37 +00002146 for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002147 int k = PyObject_RichCompareBool(vl->ob_item[i],
2148 wl->ob_item[i], Py_EQ);
2149 if (k < 0)
2150 return NULL;
2151 if (!k)
2152 break;
2153 }
2154
Christian Heimes90aa7642007-12-19 02:45:37 +00002155 if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002156 /* No more items to compare -- compare sizes */
Christian Heimes90aa7642007-12-19 02:45:37 +00002157 Py_ssize_t vs = Py_SIZE(vl);
2158 Py_ssize_t ws = Py_SIZE(wl);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002159 int cmp;
2160 PyObject *res;
2161 switch (op) {
2162 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00002163 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002164 case Py_EQ: cmp = vs == ws; break;
2165 case Py_NE: cmp = vs != ws; break;
2166 case Py_GT: cmp = vs > ws; break;
2167 case Py_GE: cmp = vs >= ws; break;
2168 default: return NULL; /* cannot happen */
2169 }
2170 if (cmp)
2171 res = Py_True;
2172 else
2173 res = Py_False;
2174 Py_INCREF(res);
2175 return res;
2176 }
2177
2178 /* We have an item that differs -- shortcuts for EQ/NE */
2179 if (op == Py_EQ) {
2180 Py_INCREF(Py_False);
2181 return Py_False;
2182 }
2183 if (op == Py_NE) {
2184 Py_INCREF(Py_True);
2185 return Py_True;
2186 }
2187
2188 /* Compare the final item again using the proper operator */
2189 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
2190}
2191
Tim Peters6d6c1a32001-08-02 04:15:00 +00002192static int
2193list_init(PyListObject *self, PyObject *args, PyObject *kw)
2194{
2195 PyObject *arg = NULL;
Martin v. Löwis15e62742006-02-27 16:46:16 +00002196 static char *kwlist[] = {"sequence", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002197
2198 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2199 return -1;
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002200
2201 /* Verify list invariants established by PyType_GenericAlloc() */
Christian Heimes90aa7642007-12-19 02:45:37 +00002202 assert(0 <= Py_SIZE(self));
2203 assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
Armin Rigoa37bbf22004-07-30 11:20:18 +00002204 assert(self->ob_item != NULL ||
2205 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002206
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002207 /* Empty previous contents */
Armin Rigo93677f02004-07-29 12:40:23 +00002208 if (self->ob_item != NULL) {
2209 (void)list_clear(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002210 }
2211 if (arg != NULL) {
2212 PyObject *rv = listextend(self, arg);
2213 if (rv == NULL)
2214 return -1;
2215 Py_DECREF(rv);
2216 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002217 return 0;
2218}
2219
Raymond Hettinger1021c442003-11-07 15:38:09 +00002220static PyObject *list_iter(PyObject *seq);
2221static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2222
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002223PyDoc_STRVAR(getitem_doc,
2224"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002225PyDoc_STRVAR(reversed_doc,
2226"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002227PyDoc_STRVAR(append_doc,
2228"L.append(object) -- append object to end");
2229PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002230"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002231PyDoc_STRVAR(insert_doc,
2232"L.insert(index, object) -- insert object before index");
2233PyDoc_STRVAR(pop_doc,
2234"L.pop([index]) -> item -- remove and return item at index (default last)");
2235PyDoc_STRVAR(remove_doc,
2236"L.remove(value) -- remove first occurrence of value");
2237PyDoc_STRVAR(index_doc,
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002238"L.index(value, [start, [stop]]) -> integer -- return first index of value");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002239PyDoc_STRVAR(count_doc,
2240"L.count(value) -> integer -- return number of occurrences of value");
2241PyDoc_STRVAR(reverse_doc,
2242"L.reverse() -- reverse *IN PLACE*");
2243PyDoc_STRVAR(sort_doc,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002244"L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n\
2245cmp(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002246
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002247static PyObject *list_subscript(PyListObject*, PyObject*);
2248
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002249static PyMethodDef list_methods[] = {
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002250 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
Raymond Hettinger1021c442003-11-07 15:38:09 +00002251 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002252 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002253 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002254 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002255 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002256 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002257 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002258 {"count", (PyCFunction)listcount, METH_O, count_doc},
2259 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002260 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
Tim Petersa64dc242002-08-01 02:13:36 +00002261 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002262};
2263
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002264static PySequenceMethods list_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002265 (lenfunc)list_length, /* sq_length */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002266 (binaryfunc)list_concat, /* sq_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002267 (ssizeargfunc)list_repeat, /* sq_repeat */
2268 (ssizeargfunc)list_item, /* sq_item */
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002269 0, /* sq_slice */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002270 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002271 0, /* sq_ass_slice */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002272 (objobjproc)list_contains, /* sq_contains */
2273 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002274 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002275};
2276
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002277PyDoc_STRVAR(list_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002278"list() -> new list\n"
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002279"list(sequence) -> new list initialized from sequence's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002280
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002281static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002282list_subscript(PyListObject* self, PyObject* item)
2283{
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002284 if (PyIndex_Check(item)) {
2285 Py_ssize_t i;
2286 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002287 if (i == -1 && PyErr_Occurred())
2288 return NULL;
2289 if (i < 0)
2290 i += PyList_GET_SIZE(self);
2291 return list_item(self, i);
2292 }
2293 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002294 Py_ssize_t start, stop, step, slicelength, cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002295 PyObject* result;
2296 PyObject* it;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002297 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002298
Christian Heimes90aa7642007-12-19 02:45:37 +00002299 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002300 &start, &stop, &step, &slicelength) < 0) {
2301 return NULL;
2302 }
2303
2304 if (slicelength <= 0) {
2305 return PyList_New(0);
2306 }
Thomas Woutersed03b412007-08-28 21:37:11 +00002307 else if (step == 1) {
2308 return list_slice(self, start, stop);
2309 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002310 else {
2311 result = PyList_New(slicelength);
2312 if (!result) return NULL;
2313
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002314 src = self->ob_item;
2315 dest = ((PyListObject *)result)->ob_item;
Tim Peters3b01a122002-07-19 02:35:45 +00002316 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002317 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002318 it = src[cur];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002319 Py_INCREF(it);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002320 dest[i] = it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002321 }
Tim Peters3b01a122002-07-19 02:35:45 +00002322
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002323 return result;
2324 }
2325 }
2326 else {
Thomas Wouters89f507f2006-12-13 04:49:30 +00002327 PyErr_Format(PyExc_TypeError,
2328 "list indices must be integers, not %.200s",
2329 item->ob_type->tp_name);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002330 return NULL;
2331 }
2332}
2333
Tim Peters3b01a122002-07-19 02:35:45 +00002334static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002335list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2336{
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002337 if (PyIndex_Check(item)) {
2338 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002339 if (i == -1 && PyErr_Occurred())
2340 return -1;
2341 if (i < 0)
2342 i += PyList_GET_SIZE(self);
2343 return list_ass_item(self, i, value);
2344 }
2345 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002346 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002347
Christian Heimes90aa7642007-12-19 02:45:37 +00002348 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002349 &start, &stop, &step, &slicelength) < 0) {
2350 return -1;
2351 }
2352
Thomas Woutersed03b412007-08-28 21:37:11 +00002353 if (step == 1)
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002354 return list_ass_slice(self, start, stop, value);
2355
Thomas Woutersed03b412007-08-28 21:37:11 +00002356 /* Make sure s[5:2] = [..] inserts at the right place:
2357 before 5, not before 2. */
2358 if ((step < 0 && start < stop) ||
2359 (step > 0 && start > stop))
2360 stop = start;
2361
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002362 if (value == NULL) {
2363 /* delete slice */
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002364 PyObject **garbage;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002365 Py_ssize_t cur, i;
Tim Peters3b01a122002-07-19 02:35:45 +00002366
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002367 if (slicelength <= 0)
2368 return 0;
2369
2370 if (step < 0) {
2371 stop = start + 1;
2372 start = stop + step*(slicelength - 1) - 1;
2373 step = -step;
2374 }
2375
2376 garbage = (PyObject**)
2377 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002378 if (!garbage) {
2379 PyErr_NoMemory();
2380 return -1;
2381 }
Tim Peters3b01a122002-07-19 02:35:45 +00002382
Thomas Woutersed03b412007-08-28 21:37:11 +00002383 /* drawing pictures might help understand these for
2384 loops. Basically, we memmove the parts of the
2385 list that are *not* part of the slice: step-1
2386 items for each item that is part of the slice,
2387 and then tail end of the list that was not
2388 covered by the slice */
Guido van Rossum75a20b12002-06-11 12:22:28 +00002389 for (cur = start, i = 0;
2390 cur < stop;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002391 cur += step, i++) {
Thomas Woutersed03b412007-08-28 21:37:11 +00002392 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002393
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002394 garbage[i] = PyList_GET_ITEM(self, cur);
2395
Christian Heimes90aa7642007-12-19 02:45:37 +00002396 if (cur + step >= Py_SIZE(self)) {
2397 lim = Py_SIZE(self) - cur - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002398 }
2399
Tim Petersb38e2b62004-07-29 02:29:26 +00002400 memmove(self->ob_item + cur - i,
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002401 self->ob_item + cur + 1,
2402 lim * sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002403 }
Thomas Woutersed03b412007-08-28 21:37:11 +00002404 cur = start + slicelength*step;
Christian Heimes90aa7642007-12-19 02:45:37 +00002405 if (cur < Py_SIZE(self)) {
Thomas Woutersed03b412007-08-28 21:37:11 +00002406 memmove(self->ob_item + cur - slicelength,
2407 self->ob_item + cur,
Christian Heimes90aa7642007-12-19 02:45:37 +00002408 (Py_SIZE(self) - cur) *
Thomas Woutersed03b412007-08-28 21:37:11 +00002409 sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002410 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002411
Christian Heimes90aa7642007-12-19 02:45:37 +00002412 Py_SIZE(self) -= slicelength;
2413 list_resize(self, Py_SIZE(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002414
2415 for (i = 0; i < slicelength; i++) {
2416 Py_DECREF(garbage[i]);
2417 }
2418 PyMem_FREE(garbage);
2419
2420 return 0;
2421 }
2422 else {
2423 /* assign slice */
Thomas Woutersed03b412007-08-28 21:37:11 +00002424 PyObject *ins, *seq;
2425 PyObject **garbage, **seqitems, **selfitems;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002426 Py_ssize_t cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002427
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002428 /* protect against a[::-1] = a */
Tim Peters3b01a122002-07-19 02:35:45 +00002429 if (self == (PyListObject*)value) {
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002430 seq = list_slice((PyListObject*)value, 0,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002431 PyList_GET_SIZE(value));
Tim Peters3b01a122002-07-19 02:35:45 +00002432 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002433 else {
Tim Petersb38e2b62004-07-29 02:29:26 +00002434 seq = PySequence_Fast(value,
Thomas Woutersed03b412007-08-28 21:37:11 +00002435 "must assign iterable "
2436 "to extended slice");
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002437 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002438 if (!seq)
2439 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002440
2441 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2442 PyErr_Format(PyExc_ValueError,
Thomas Woutersed03b412007-08-28 21:37:11 +00002443 "attempt to assign sequence of "
2444 "size %zd to extended slice of "
2445 "size %zd",
Martin v. Löwise0e89f72006-02-16 06:59:22 +00002446 PySequence_Fast_GET_SIZE(seq),
2447 slicelength);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002448 Py_DECREF(seq);
2449 return -1;
2450 }
2451
2452 if (!slicelength) {
2453 Py_DECREF(seq);
2454 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002455 }
2456
2457 garbage = (PyObject**)
2458 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Thomas Wouters89f507f2006-12-13 04:49:30 +00002459 if (!garbage) {
2460 Py_DECREF(seq);
2461 PyErr_NoMemory();
2462 return -1;
2463 }
Tim Peters3b01a122002-07-19 02:35:45 +00002464
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002465 selfitems = self->ob_item;
Raymond Hettinger42bec932004-03-12 16:38:17 +00002466 seqitems = PySequence_Fast_ITEMS(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002467 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002468 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002469 garbage[i] = selfitems[cur];
2470 ins = seqitems[i];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002471 Py_INCREF(ins);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002472 selfitems[cur] = ins;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002473 }
2474
2475 for (i = 0; i < slicelength; i++) {
2476 Py_DECREF(garbage[i]);
2477 }
Tim Peters3b01a122002-07-19 02:35:45 +00002478
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002479 PyMem_FREE(garbage);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002480 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002481
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002482 return 0;
2483 }
Tim Peters3b01a122002-07-19 02:35:45 +00002484 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002485 else {
Thomas Wouters89f507f2006-12-13 04:49:30 +00002486 PyErr_Format(PyExc_TypeError,
2487 "list indices must be integers, not %.200s",
2488 item->ob_type->tp_name);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002489 return -1;
2490 }
2491}
2492
2493static PyMappingMethods list_as_mapping = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002494 (lenfunc)list_length,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002495 (binaryfunc)list_subscript,
2496 (objobjargproc)list_ass_subscript
2497};
2498
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002499PyTypeObject PyList_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002500 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002501 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002502 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002503 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002504 (destructor)list_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00002505 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002506 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002507 0, /* tp_setattr */
2508 0, /* tp_compare */
2509 (reprfunc)list_repr, /* tp_repr */
2510 0, /* tp_as_number */
2511 &list_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002512 &list_as_mapping, /* tp_as_mapping */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00002513 0, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002514 0, /* tp_call */
2515 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002516 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002517 0, /* tp_setattro */
2518 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002519 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Thomas Wouters27d517b2007-02-25 20:39:11 +00002520 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002521 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002522 (traverseproc)list_traverse, /* tp_traverse */
2523 (inquiry)list_clear, /* tp_clear */
2524 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002525 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002526 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002527 0, /* tp_iternext */
2528 list_methods, /* tp_methods */
2529 0, /* tp_members */
2530 0, /* tp_getset */
2531 0, /* tp_base */
2532 0, /* tp_dict */
2533 0, /* tp_descr_get */
2534 0, /* tp_descr_set */
2535 0, /* tp_dictoffset */
2536 (initproc)list_init, /* tp_init */
2537 PyType_GenericAlloc, /* tp_alloc */
2538 PyType_GenericNew, /* tp_new */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002539 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002540};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002541
2542
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002543/*********************** List Iterator **************************/
2544
2545typedef struct {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002546 PyObject_HEAD
2547 long it_index;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002548 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002549} listiterobject;
2550
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002551static PyObject *list_iter(PyObject *);
2552static void listiter_dealloc(listiterobject *);
2553static int listiter_traverse(listiterobject *, visitproc, void *);
2554static PyObject *listiter_next(listiterobject *);
2555static PyObject *listiter_len(listiterobject *);
Raymond Hettinger435bf582004-03-18 22:43:10 +00002556
Armin Rigof5b3e362006-02-11 21:32:43 +00002557PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002558
2559static PyMethodDef listiter_methods[] = {
Armin Rigof5b3e362006-02-11 21:32:43 +00002560 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002561 {NULL, NULL} /* sentinel */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002562};
2563
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002564PyTypeObject PyListIter_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002565 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Christian Heimesf83be4e2007-11-28 09:44:38 +00002566 "list_iterator", /* tp_name */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002567 sizeof(listiterobject), /* tp_basicsize */
2568 0, /* tp_itemsize */
2569 /* methods */
2570 (destructor)listiter_dealloc, /* tp_dealloc */
2571 0, /* tp_print */
2572 0, /* tp_getattr */
2573 0, /* tp_setattr */
2574 0, /* tp_compare */
2575 0, /* tp_repr */
2576 0, /* tp_as_number */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002577 0, /* tp_as_sequence */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002578 0, /* tp_as_mapping */
2579 0, /* tp_hash */
2580 0, /* tp_call */
2581 0, /* tp_str */
2582 PyObject_GenericGetAttr, /* tp_getattro */
2583 0, /* tp_setattro */
2584 0, /* tp_as_buffer */
2585 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2586 0, /* tp_doc */
2587 (traverseproc)listiter_traverse, /* tp_traverse */
2588 0, /* tp_clear */
2589 0, /* tp_richcompare */
2590 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00002591 PyObject_SelfIter, /* tp_iter */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002592 (iternextfunc)listiter_next, /* tp_iternext */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002593 listiter_methods, /* tp_methods */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002594 0, /* tp_members */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002595};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002596
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002597
2598static PyObject *
2599list_iter(PyObject *seq)
2600{
2601 listiterobject *it;
2602
2603 if (!PyList_Check(seq)) {
2604 PyErr_BadInternalCall();
2605 return NULL;
2606 }
2607 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2608 if (it == NULL)
2609 return NULL;
2610 it->it_index = 0;
2611 Py_INCREF(seq);
2612 it->it_seq = (PyListObject *)seq;
2613 _PyObject_GC_TRACK(it);
2614 return (PyObject *)it;
2615}
2616
2617static void
2618listiter_dealloc(listiterobject *it)
2619{
2620 _PyObject_GC_UNTRACK(it);
2621 Py_XDECREF(it->it_seq);
2622 PyObject_GC_Del(it);
2623}
2624
2625static int
2626listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2627{
2628 Py_VISIT(it->it_seq);
2629 return 0;
2630}
2631
2632static PyObject *
2633listiter_next(listiterobject *it)
2634{
2635 PyListObject *seq;
2636 PyObject *item;
2637
2638 assert(it != NULL);
2639 seq = it->it_seq;
2640 if (seq == NULL)
2641 return NULL;
2642 assert(PyList_Check(seq));
2643
2644 if (it->it_index < PyList_GET_SIZE(seq)) {
2645 item = PyList_GET_ITEM(seq, it->it_index);
2646 ++it->it_index;
2647 Py_INCREF(item);
2648 return item;
2649 }
2650
2651 Py_DECREF(seq);
2652 it->it_seq = NULL;
2653 return NULL;
2654}
2655
2656static PyObject *
2657listiter_len(listiterobject *it)
2658{
2659 Py_ssize_t len;
2660 if (it->it_seq) {
2661 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2662 if (len >= 0)
Christian Heimes217cfd12007-12-02 14:31:20 +00002663 return PyLong_FromSsize_t(len);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002664 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002665 return PyLong_FromLong(0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002666}
Raymond Hettinger1021c442003-11-07 15:38:09 +00002667/*********************** List Reverse Iterator **************************/
2668
2669typedef struct {
2670 PyObject_HEAD
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002671 Py_ssize_t it_index;
Raymond Hettinger001f2282003-11-08 11:58:44 +00002672 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002673} listreviterobject;
2674
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002675static PyObject *list_reversed(PyListObject *, PyObject *);
2676static void listreviter_dealloc(listreviterobject *);
2677static int listreviter_traverse(listreviterobject *, visitproc, void *);
2678static PyObject *listreviter_next(listreviterobject *);
2679static Py_ssize_t listreviter_len(listreviterobject *);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002680
2681static PySequenceMethods listreviter_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002682 (lenfunc)listreviter_len, /* sq_length */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002683 0, /* sq_concat */
2684};
2685
Raymond Hettinger1021c442003-11-07 15:38:09 +00002686PyTypeObject PyListRevIter_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002687 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Christian Heimesf83be4e2007-11-28 09:44:38 +00002688 "list_reverseiterator", /* tp_name */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002689 sizeof(listreviterobject), /* tp_basicsize */
2690 0, /* tp_itemsize */
2691 /* methods */
2692 (destructor)listreviter_dealloc, /* tp_dealloc */
2693 0, /* tp_print */
2694 0, /* tp_getattr */
2695 0, /* tp_setattr */
2696 0, /* tp_compare */
2697 0, /* tp_repr */
2698 0, /* tp_as_number */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002699 &listreviter_as_sequence, /* tp_as_sequence */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002700 0, /* tp_as_mapping */
2701 0, /* tp_hash */
2702 0, /* tp_call */
2703 0, /* tp_str */
2704 PyObject_GenericGetAttr, /* tp_getattro */
2705 0, /* tp_setattro */
2706 0, /* tp_as_buffer */
2707 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2708 0, /* tp_doc */
2709 (traverseproc)listreviter_traverse, /* tp_traverse */
2710 0, /* tp_clear */
2711 0, /* tp_richcompare */
2712 0, /* tp_weaklistoffset */
2713 PyObject_SelfIter, /* tp_iter */
2714 (iternextfunc)listreviter_next, /* tp_iternext */
2715 0,
2716};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002717
2718static PyObject *
2719list_reversed(PyListObject *seq, PyObject *unused)
2720{
2721 listreviterobject *it;
2722
2723 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2724 if (it == NULL)
2725 return NULL;
2726 assert(PyList_Check(seq));
2727 it->it_index = PyList_GET_SIZE(seq) - 1;
2728 Py_INCREF(seq);
2729 it->it_seq = seq;
2730 PyObject_GC_Track(it);
2731 return (PyObject *)it;
2732}
2733
2734static void
2735listreviter_dealloc(listreviterobject *it)
2736{
2737 PyObject_GC_UnTrack(it);
2738 Py_XDECREF(it->it_seq);
2739 PyObject_GC_Del(it);
2740}
2741
2742static int
2743listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2744{
2745 Py_VISIT(it->it_seq);
2746 return 0;
2747}
2748
2749static PyObject *
2750listreviter_next(listreviterobject *it)
2751{
2752 PyObject *item;
2753 Py_ssize_t index = it->it_index;
2754 PyListObject *seq = it->it_seq;
2755
2756 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2757 item = PyList_GET_ITEM(seq, index);
2758 it->it_index--;
2759 Py_INCREF(item);
2760 return item;
2761 }
2762 it->it_index = -1;
2763 if (seq != NULL) {
2764 it->it_seq = NULL;
2765 Py_DECREF(seq);
2766 }
2767 return NULL;
2768}
2769
2770static Py_ssize_t
2771listreviter_len(listreviterobject *it)
2772{
2773 Py_ssize_t len = it->it_index + 1;
2774 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
2775 return 0;
2776 return len;
2777}
2778