blob: a36a29e4e9064ee2b23da302e47d1105365f8f48 [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 */
67#define MAXFREELISTS 80
68static PyListObject *free_lists[MAXFREELISTS];
69static int num_free_lists = 0;
70
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +000071void
72PyList_Fini(void)
73{
74 PyListObject *op;
75
76 while (num_free_lists) {
77 num_free_lists--;
78 op = free_lists[num_free_lists];
79 assert(PyList_CheckExact(op));
80 PyObject_GC_Del(op);
81 }
82}
83
Guido van Rossumc0b618a1997-05-02 03:12:38 +000084PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000085PyList_New(Py_ssize_t size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000086{
Guido van Rossumc0b618a1997-05-02 03:12:38 +000087 PyListObject *op;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +000088 size_t nbytes;
Tim Peters3986d4e2004-07-29 02:28:42 +000089
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000090 if (size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +000091 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000092 return NULL;
93 }
Tim Peters7049d812004-01-18 20:31:02 +000094 nbytes = size * sizeof(PyObject *);
Guido van Rossum1e28e5e1992-08-19 16:46:30 +000095 /* Check for overflow */
Raymond Hettingerfdfe6182004-05-05 06:28:16 +000096 if (nbytes / sizeof(PyObject *) != (size_t)size)
Guido van Rossumc0b618a1997-05-02 03:12:38 +000097 return PyErr_NoMemory();
Raymond Hettinger0468e412004-05-05 05:37:53 +000098 if (num_free_lists) {
99 num_free_lists--;
100 op = free_lists[num_free_lists];
101 _Py_NewReference((PyObject *)op);
102 } else {
103 op = PyObject_GC_New(PyListObject, &PyList_Type);
104 if (op == NULL)
105 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000106 }
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000107 if (size <= 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000108 op->ob_item = NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000109 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +0000110 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000111 if (op->ob_item == NULL) {
112 Py_DECREF(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000113 return PyErr_NoMemory();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000114 }
Tim Peters3986d4e2004-07-29 02:28:42 +0000115 memset(op->ob_item, 0, nbytes);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000116 }
Christian Heimes90aa7642007-12-19 02:45:37 +0000117 Py_SIZE(op) = size;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000118 op->allocated = size;
Neil Schemenauere83c00e2001-08-29 23:54:21 +0000119 _PyObject_GC_TRACK(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000120 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000121}
122
Martin v. Löwis18e16552006-02-15 17:27:45 +0000123Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000124PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000125{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000126 if (!PyList_Check(op)) {
127 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000128 return -1;
129 }
130 else
Christian Heimes90aa7642007-12-19 02:45:37 +0000131 return Py_SIZE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000132}
133
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000134static PyObject *indexerr = NULL;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000135
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000136PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000137PyList_GetItem(PyObject *op, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000138{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000139 if (!PyList_Check(op)) {
140 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000141 return NULL;
142 }
Christian Heimes90aa7642007-12-19 02:45:37 +0000143 if (i < 0 || i >= Py_SIZE(op)) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000144 if (indexerr == NULL)
Neal Norwitz53cbdaa2007-08-23 21:42:55 +0000145 indexerr = PyUnicode_FromString(
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000146 "list index out of range");
147 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000148 return NULL;
149 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000150 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000151}
152
153int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000154PyList_SetItem(register PyObject *op, register Py_ssize_t i,
Fred Drakea2f55112000-07-09 15:16:51 +0000155 register PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000156{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000157 register PyObject *olditem;
158 register PyObject **p;
159 if (!PyList_Check(op)) {
160 Py_XDECREF(newitem);
161 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000162 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000163 }
Christian Heimes90aa7642007-12-19 02:45:37 +0000164 if (i < 0 || i >= Py_SIZE(op)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000165 Py_XDECREF(newitem);
166 PyErr_SetString(PyExc_IndexError,
167 "list assignment index out of range");
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000168 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000169 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000170 p = ((PyListObject *)op) -> ob_item + i;
Guido van Rossum5fe60581995-03-09 12:12:50 +0000171 olditem = *p;
172 *p = newitem;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000173 Py_XDECREF(olditem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000174 return 0;
175}
176
177static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000178ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000179{
Christian Heimes90aa7642007-12-19 02:45:37 +0000180 Py_ssize_t i, n = Py_SIZE(self);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000181 PyObject **items;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000182 if (v == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000183 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000184 return -1;
185 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000186 if (n == PY_SSIZE_T_MAX) {
Trent Micka5846642000-08-13 22:47:45 +0000187 PyErr_SetString(PyExc_OverflowError,
188 "cannot add more objects to list");
189 return -1;
190 }
Tim Petersb38e2b62004-07-29 02:29:26 +0000191
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000192 if (list_resize(self, n+1) == -1)
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000193 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000194
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000195 if (where < 0) {
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000196 where += n;
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000197 if (where < 0)
198 where = 0;
199 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000200 if (where > n)
201 where = n;
202 items = self->ob_item;
203 for (i = n; --i >= where; )
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000204 items[i+1] = items[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000205 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000206 items[where] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000207 return 0;
208}
209
210int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000211PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000212{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000213 if (!PyList_Check(op)) {
214 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000215 return -1;
216 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000217 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000218}
219
Raymond Hettinger40a03822004-04-12 13:05:09 +0000220static int
221app1(PyListObject *self, PyObject *v)
222{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000223 Py_ssize_t n = PyList_GET_SIZE(self);
Raymond Hettinger40a03822004-04-12 13:05:09 +0000224
225 assert (v != NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000226 if (n == PY_SSIZE_T_MAX) {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000227 PyErr_SetString(PyExc_OverflowError,
228 "cannot add more objects to list");
229 return -1;
230 }
231
232 if (list_resize(self, n+1) == -1)
233 return -1;
234
235 Py_INCREF(v);
236 PyList_SET_ITEM(self, n, v);
237 return 0;
238}
239
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000240int
Fred Drakea2f55112000-07-09 15:16:51 +0000241PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000242{
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000243 if (PyList_Check(op) && (newitem != NULL))
244 return app1((PyListObject *)op, newitem);
245 PyErr_BadInternalCall();
246 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000247}
248
249/* Methods */
250
251static void
Fred Drakea2f55112000-07-09 15:16:51 +0000252list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000253{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000254 Py_ssize_t i;
Guido van Rossumff413af2002-03-28 20:34:59 +0000255 PyObject_GC_UnTrack(op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000256 Py_TRASHCAN_SAFE_BEGIN(op)
Jack Jansen7874d1f1995-01-19 12:09:27 +0000257 if (op->ob_item != NULL) {
Guido van Rossumfa717011999-06-09 15:19:34 +0000258 /* Do it backwards, for Christian Tismer.
259 There's a simple test case where somehow this reduces
260 thrashing when a *very* large list is created and
261 immediately deleted. */
Christian Heimes90aa7642007-12-19 02:45:37 +0000262 i = Py_SIZE(op);
Guido van Rossumfa717011999-06-09 15:19:34 +0000263 while (--i >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000264 Py_XDECREF(op->ob_item[i]);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000265 }
Guido van Rossumb18618d2000-05-03 23:44:39 +0000266 PyMem_FREE(op->ob_item);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000267 }
Raymond Hettinger0468e412004-05-05 05:37:53 +0000268 if (num_free_lists < MAXFREELISTS && PyList_CheckExact(op))
269 free_lists[num_free_lists++] = op;
Tim Petersb38e2b62004-07-29 02:29:26 +0000270 else
Christian Heimes90aa7642007-12-19 02:45:37 +0000271 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000272 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000273}
274
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000275static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000276list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000277{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000278 Py_ssize_t i;
Tim Petersa7259592001-06-16 05:11:17 +0000279 PyObject *s, *temp;
280 PyObject *pieces = NULL, *result = NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000281
282 i = Py_ReprEnter((PyObject*)v);
283 if (i != 0) {
Walter Dörwald1ab83302007-05-18 17:15:44 +0000284 return i > 0 ? PyUnicode_FromString("[...]") : NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000285 }
Tim Petersa7259592001-06-16 05:11:17 +0000286
Christian Heimes90aa7642007-12-19 02:45:37 +0000287 if (Py_SIZE(v) == 0) {
Walter Dörwald1ab83302007-05-18 17:15:44 +0000288 result = PyUnicode_FromString("[]");
Tim Petersa7259592001-06-16 05:11:17 +0000289 goto Done;
290 }
291
292 pieces = PyList_New(0);
293 if (pieces == NULL)
294 goto Done;
295
296 /* Do repr() on each element. Note that this may mutate the list,
297 so must refetch the list size on each iteration. */
Christian Heimes90aa7642007-12-19 02:45:37 +0000298 for (i = 0; i < Py_SIZE(v); ++i) {
Tim Petersa7259592001-06-16 05:11:17 +0000299 int status;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000300 if (Py_EnterRecursiveCall(" while getting the repr of a list"))
301 goto Done;
Tim Petersa7259592001-06-16 05:11:17 +0000302 s = PyObject_Repr(v->ob_item[i]);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000303 Py_LeaveRecursiveCall();
Tim Petersa7259592001-06-16 05:11:17 +0000304 if (s == NULL)
305 goto Done;
306 status = PyList_Append(pieces, s);
307 Py_DECREF(s); /* append created a new ref */
308 if (status < 0)
309 goto Done;
310 }
311
312 /* Add "[]" decorations to the first and last items. */
313 assert(PyList_GET_SIZE(pieces) > 0);
Walter Dörwald1ab83302007-05-18 17:15:44 +0000314 s = PyUnicode_FromString("[");
Tim Petersa7259592001-06-16 05:11:17 +0000315 if (s == NULL)
316 goto Done;
317 temp = PyList_GET_ITEM(pieces, 0);
Walter Dörwald1ab83302007-05-18 17:15:44 +0000318 PyUnicode_AppendAndDel(&s, temp);
Tim Petersa7259592001-06-16 05:11:17 +0000319 PyList_SET_ITEM(pieces, 0, s);
320 if (s == NULL)
321 goto Done;
322
Walter Dörwald1ab83302007-05-18 17:15:44 +0000323 s = PyUnicode_FromString("]");
Tim Petersa7259592001-06-16 05:11:17 +0000324 if (s == NULL)
325 goto Done;
326 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
Walter Dörwald1ab83302007-05-18 17:15:44 +0000327 PyUnicode_AppendAndDel(&temp, s);
Tim Petersa7259592001-06-16 05:11:17 +0000328 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
329 if (temp == NULL)
330 goto Done;
331
332 /* Paste them all together with ", " between. */
Walter Dörwald1ab83302007-05-18 17:15:44 +0000333 s = PyUnicode_FromString(", ");
Tim Petersa7259592001-06-16 05:11:17 +0000334 if (s == NULL)
335 goto Done;
Walter Dörwald1ab83302007-05-18 17:15:44 +0000336 result = PyUnicode_Join(s, pieces);
Tim Peters3b01a122002-07-19 02:35:45 +0000337 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +0000338
339Done:
340 Py_XDECREF(pieces);
Guido van Rossumfb376de1998-04-10 22:47:27 +0000341 Py_ReprLeave((PyObject *)v);
Tim Petersa7259592001-06-16 05:11:17 +0000342 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000343}
344
Martin v. Löwis18e16552006-02-15 17:27:45 +0000345static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000346list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000347{
Christian Heimes90aa7642007-12-19 02:45:37 +0000348 return Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000349}
350
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000351static int
Fred Drakea2f55112000-07-09 15:16:51 +0000352list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000353{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000354 Py_ssize_t i;
355 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000356
Christian Heimes90aa7642007-12-19 02:45:37 +0000357 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
Raymond Hettingeraae59992002-09-05 14:23:49 +0000358 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000359 Py_EQ);
Neal Norwitzbb9c5f52002-09-05 21:32:55 +0000360 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000361}
362
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000363static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000364list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000365{
Christian Heimes90aa7642007-12-19 02:45:37 +0000366 if (i < 0 || i >= Py_SIZE(a)) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000367 if (indexerr == NULL)
Neal Norwitz53cbdaa2007-08-23 21:42:55 +0000368 indexerr = PyUnicode_FromString(
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000369 "list index out of range");
370 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000371 return NULL;
372 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000373 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000374 return a->ob_item[i];
375}
376
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000377static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000378list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000379{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000380 PyListObject *np;
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000381 PyObject **src, **dest;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000382 Py_ssize_t i, len;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000383 if (ilow < 0)
384 ilow = 0;
Christian Heimes90aa7642007-12-19 02:45:37 +0000385 else if (ilow > Py_SIZE(a))
386 ilow = Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000387 if (ihigh < ilow)
388 ihigh = ilow;
Christian Heimes90aa7642007-12-19 02:45:37 +0000389 else if (ihigh > Py_SIZE(a))
390 ihigh = Py_SIZE(a);
Raymond Hettinger99842b62004-03-08 05:56:15 +0000391 len = ihigh - ilow;
392 np = (PyListObject *) PyList_New(len);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000393 if (np == NULL)
394 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000395
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000396 src = a->ob_item + ilow;
397 dest = np->ob_item;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000398 for (i = 0; i < len; i++) {
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000399 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000400 Py_INCREF(v);
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000401 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000402 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000403 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000404}
405
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000406PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000407PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000408{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000409 if (!PyList_Check(a)) {
410 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000411 return NULL;
412 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000413 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000414}
415
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000416static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000417list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000418{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000419 Py_ssize_t size;
420 Py_ssize_t i;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000421 PyObject **src, **dest;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000422 PyListObject *np;
423 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000424 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000425 "can only concatenate list (not \"%.200s\") to list",
426 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000427 return NULL;
428 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000429#define b ((PyListObject *)bb)
Christian Heimes90aa7642007-12-19 02:45:37 +0000430 size = Py_SIZE(a) + Py_SIZE(b);
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000431 if (size < 0)
432 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000433 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000434 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000435 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000436 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000437 src = a->ob_item;
438 dest = np->ob_item;
Christian Heimes90aa7642007-12-19 02:45:37 +0000439 for (i = 0; i < Py_SIZE(a); i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000440 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000441 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000442 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000443 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000444 src = b->ob_item;
Christian Heimes90aa7642007-12-19 02:45:37 +0000445 dest = np->ob_item + Py_SIZE(a);
446 for (i = 0; i < Py_SIZE(b); i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000447 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000448 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000449 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000450 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000451 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000452#undef b
453}
454
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000455static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000456list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000457{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000458 Py_ssize_t i, j;
459 Py_ssize_t size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000460 PyListObject *np;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000461 PyObject **p, **items;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000462 PyObject *elem;
Guido van Rossumed98d481991-03-06 13:07:53 +0000463 if (n < 0)
464 n = 0;
Christian Heimes90aa7642007-12-19 02:45:37 +0000465 size = Py_SIZE(a) * n;
466 if (n && size/n != Py_SIZE(a))
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000467 return PyErr_NoMemory();
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000468 if (size == 0)
Christian Heimesaf98da12008-01-27 15:18:18 +0000469 return PyList_New(0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000470 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000471 if (np == NULL)
472 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000473
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000474 items = np->ob_item;
Christian Heimes90aa7642007-12-19 02:45:37 +0000475 if (Py_SIZE(a) == 1) {
Raymond Hettinger6624e682003-05-21 05:58:46 +0000476 elem = a->ob_item[0];
477 for (i = 0; i < n; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000478 items[i] = elem;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000479 Py_INCREF(elem);
480 }
481 return (PyObject *) np;
482 }
Guido van Rossumed98d481991-03-06 13:07:53 +0000483 p = np->ob_item;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000484 items = a->ob_item;
Guido van Rossumed98d481991-03-06 13:07:53 +0000485 for (i = 0; i < n; i++) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000486 for (j = 0; j < Py_SIZE(a); j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000487 *p = items[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000488 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000489 p++;
490 }
491 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000492 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000493}
494
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000495static int
Armin Rigo93677f02004-07-29 12:40:23 +0000496list_clear(PyListObject *a)
497{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000498 Py_ssize_t i;
Armin Rigo93677f02004-07-29 12:40:23 +0000499 PyObject **item = a->ob_item;
500 if (item != NULL) {
501 /* Because XDECREF can recursively invoke operations on
502 this list, we make it empty first. */
Christian Heimes90aa7642007-12-19 02:45:37 +0000503 i = Py_SIZE(a);
504 Py_SIZE(a) = 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000505 a->ob_item = NULL;
506 a->allocated = 0;
507 while (--i >= 0) {
508 Py_XDECREF(item[i]);
509 }
510 PyMem_FREE(item);
511 }
512 /* Never fails; the return value can be ignored.
513 Note that there is no guarantee that the list is actually empty
514 at this point, because XDECREF may have populated it again! */
515 return 0;
516}
517
Tim Peters8fc4a912004-07-31 21:53:19 +0000518/* a[ilow:ihigh] = v if v != NULL.
519 * del a[ilow:ihigh] if v == NULL.
520 *
521 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
522 * guaranteed the call cannot fail.
523 */
Armin Rigo93677f02004-07-29 12:40:23 +0000524static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000525list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000526{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000527 /* Because [X]DECREF can recursively invoke list operations on
528 this list, we must postpone all [X]DECREF activity until
529 after the list is back in its canonical shape. Therefore
530 we must allocate an additional array, 'recycle', into which
531 we temporarily copy the items that are deleted from the
532 list. :-( */
Tim Peters73572222004-07-31 02:54:42 +0000533 PyObject *recycle_on_stack[8];
534 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000535 PyObject **item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000536 PyObject **vitem = NULL;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000537 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000538 Py_ssize_t n; /* # of elements in replacement list */
539 Py_ssize_t norig; /* # of elements in list getting replaced */
540 Py_ssize_t d; /* Change in size */
541 Py_ssize_t k;
Tim Peters8d9eb102004-07-31 02:24:20 +0000542 size_t s;
543 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000544#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000545 if (v == NULL)
546 n = 0;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000547 else {
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000548 if (a == b) {
549 /* Special case "a[i:j] = a" -- copy b first */
Christian Heimes90aa7642007-12-19 02:45:37 +0000550 v = list_slice(b, 0, Py_SIZE(b));
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000551 if (v == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000552 return result;
553 result = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000554 Py_DECREF(v);
Tim Peters8d9eb102004-07-31 02:24:20 +0000555 return result;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000556 }
Raymond Hettingerf889e102004-03-09 08:04:33 +0000557 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000558 if(v_as_SF == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000559 goto Error;
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000560 n = PySequence_Fast_GET_SIZE(v_as_SF);
Raymond Hettinger42bec932004-03-12 16:38:17 +0000561 vitem = PySequence_Fast_ITEMS(v_as_SF);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000562 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000563 if (ilow < 0)
564 ilow = 0;
Christian Heimes90aa7642007-12-19 02:45:37 +0000565 else if (ilow > Py_SIZE(a))
566 ilow = Py_SIZE(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000567
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000568 if (ihigh < ilow)
569 ihigh = ilow;
Christian Heimes90aa7642007-12-19 02:45:37 +0000570 else if (ihigh > Py_SIZE(a))
571 ihigh = Py_SIZE(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000572
Tim Peters8d9eb102004-07-31 02:24:20 +0000573 norig = ihigh - ilow;
574 assert(norig >= 0);
575 d = n - norig;
Christian Heimes90aa7642007-12-19 02:45:37 +0000576 if (Py_SIZE(a) + d == 0) {
Armin Rigo93677f02004-07-29 12:40:23 +0000577 Py_XDECREF(v_as_SF);
578 return list_clear(a);
579 }
580 item = a->ob_item;
Tim Peters8d9eb102004-07-31 02:24:20 +0000581 /* recycle the items that we are about to remove */
582 s = norig * sizeof(PyObject *);
Tim Peters73572222004-07-31 02:54:42 +0000583 if (s > sizeof(recycle_on_stack)) {
Armin Rigo1dd04a02004-07-30 11:38:22 +0000584 recycle = (PyObject **)PyMem_MALLOC(s);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000585 if (recycle == NULL) {
586 PyErr_NoMemory();
Tim Peters8d9eb102004-07-31 02:24:20 +0000587 goto Error;
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000588 }
589 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000590 memcpy(recycle, &item[ilow], s);
Tim Peters8d9eb102004-07-31 02:24:20 +0000591
Armin Rigo1dd04a02004-07-30 11:38:22 +0000592 if (d < 0) { /* Delete -d items */
593 memmove(&item[ihigh+d], &item[ihigh],
Christian Heimes90aa7642007-12-19 02:45:37 +0000594 (Py_SIZE(a) - ihigh)*sizeof(PyObject *));
595 list_resize(a, Py_SIZE(a) + d);
Armin Rigo1dd04a02004-07-30 11:38:22 +0000596 item = a->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000597 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000598 else if (d > 0) { /* Insert d items */
Christian Heimes90aa7642007-12-19 02:45:37 +0000599 k = Py_SIZE(a);
Tim Peters73572222004-07-31 02:54:42 +0000600 if (list_resize(a, k+d) < 0)
Tim Peters8d9eb102004-07-31 02:24:20 +0000601 goto Error;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000602 item = a->ob_item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000603 memmove(&item[ihigh+d], &item[ihigh],
Tim Peters73572222004-07-31 02:54:42 +0000604 (k - ihigh)*sizeof(PyObject *));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000605 }
606 for (k = 0; k < n; k++, ilow++) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000607 PyObject *w = vitem[k];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000608 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000609 item[ilow] = w;
610 }
Tim Peters73572222004-07-31 02:54:42 +0000611 for (k = norig - 1; k >= 0; --k)
612 Py_XDECREF(recycle[k]);
Tim Peters8d9eb102004-07-31 02:24:20 +0000613 result = 0;
614 Error:
Tim Peters73572222004-07-31 02:54:42 +0000615 if (recycle != recycle_on_stack)
Armin Rigo1dd04a02004-07-30 11:38:22 +0000616 PyMem_FREE(recycle);
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000617 Py_XDECREF(v_as_SF);
Tim Peters8d9eb102004-07-31 02:24:20 +0000618 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000619#undef b
620}
621
Guido van Rossum234f9421993-06-17 12:35:49 +0000622int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000623PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000624{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000625 if (!PyList_Check(a)) {
626 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000627 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000628 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000629 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000630}
631
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000632static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000633list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000634{
635 PyObject **items;
Christian Heimesaf98da12008-01-27 15:18:18 +0000636 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000637
638
639 size = PyList_GET_SIZE(self);
Christian Heimesaf98da12008-01-27 15:18:18 +0000640 if (size == 0 || n == 1) {
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000641 Py_INCREF(self);
642 return (PyObject *)self;
643 }
644
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000645 if (n < 1) {
Armin Rigo93677f02004-07-29 12:40:23 +0000646 (void)list_clear(self);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000647 Py_INCREF(self);
648 return (PyObject *)self;
649 }
650
Christian Heimesaf98da12008-01-27 15:18:18 +0000651 if (size > PY_SSIZE_T_MAX / n) {
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000652 return PyErr_NoMemory();
Christian Heimesaf98da12008-01-27 15:18:18 +0000653 }
654
655 if (list_resize(self, size*n) == -1)
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000656 return NULL;
657
658 p = size;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000659 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000660 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
661 for (j = 0; j < size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000662 PyObject *o = items[j];
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000663 Py_INCREF(o);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000664 items[p++] = o;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000665 }
666 }
667 Py_INCREF(self);
668 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000669}
670
Guido van Rossum4a450d01991-04-03 19:05:18 +0000671static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000672list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000673{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000674 PyObject *old_value;
Christian Heimes90aa7642007-12-19 02:45:37 +0000675 if (i < 0 || i >= Py_SIZE(a)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000676 PyErr_SetString(PyExc_IndexError,
677 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000678 return -1;
679 }
680 if (v == NULL)
681 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000682 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000683 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000684 a->ob_item[i] = v;
Tim Peters3b01a122002-07-19 02:35:45 +0000685 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000686 return 0;
687}
688
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000689static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000690listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000691{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000692 Py_ssize_t i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000693 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000694 if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000695 return NULL;
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000696 if (ins1(self, i, v) == 0)
697 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000698 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000699}
700
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000701static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000702listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000703{
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000704 if (app1(self, v) == 0)
705 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000706 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000707}
708
Barry Warsawdedf6d61998-10-09 16:37:25 +0000709static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000710listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000711{
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000712 PyObject *it; /* iter(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000713 Py_ssize_t m; /* size of self */
714 Py_ssize_t n; /* guess for size of b */
715 Py_ssize_t mn; /* m + n */
716 Py_ssize_t i;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000717 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000718
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000719 /* Special cases:
Tim Petersb38e2b62004-07-29 02:29:26 +0000720 1) lists and tuples which can use PySequence_Fast ops
721 2) extending self to self requires making a copy first
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000722 */
723 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
Armin Rigo70d172d2004-03-20 22:19:23 +0000724 PyObject **src, **dest;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000725 b = PySequence_Fast(b, "argument must be iterable");
726 if (!b)
727 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000728 n = PySequence_Fast_GET_SIZE(b);
729 if (n == 0) {
730 /* short circuit when b is empty */
731 Py_DECREF(b);
732 Py_RETURN_NONE;
733 }
Christian Heimes90aa7642007-12-19 02:45:37 +0000734 m = Py_SIZE(self);
Armin Rigo70d172d2004-03-20 22:19:23 +0000735 if (list_resize(self, m + n) == -1) {
736 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000737 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000738 }
739 /* note that we may still have self == b here for the
740 * situation a.extend(a), but the following code works
741 * in that case too. Just make sure to resize self
742 * before calling PySequence_Fast_ITEMS.
743 */
744 /* populate the end of self with b's items */
745 src = PySequence_Fast_ITEMS(b);
746 dest = self->ob_item + m;
747 for (i = 0; i < n; i++) {
748 PyObject *o = src[i];
749 Py_INCREF(o);
750 dest[i] = o;
751 }
752 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000753 Py_RETURN_NONE;
754 }
755
756 it = PyObject_GetIter(b);
757 if (it == NULL)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000758 return NULL;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000759 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000760
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000761 /* Guess a result list size. */
Christian Heimes255f53b2007-12-08 15:33:56 +0000762 n = _PyObject_LengthHint(b, 8);
Christian Heimes90aa7642007-12-19 02:45:37 +0000763 m = Py_SIZE(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000764 mn = m + n;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000765 if (mn >= m) {
766 /* Make room. */
767 if (list_resize(self, mn) == -1)
768 goto error;
769 /* Make the list sane again. */
Christian Heimes90aa7642007-12-19 02:45:37 +0000770 Py_SIZE(self) = m;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000771 }
772 /* Else m + n overflowed; on the chance that n lied, and there really
773 * is enough room, ignore it. If n was telling the truth, we'll
774 * eventually run out of memory during the loop.
775 */
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000776
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000777 /* Run iterator to exhaustion. */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000778 for (;;) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000779 PyObject *item = iternext(it);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000780 if (item == NULL) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000781 if (PyErr_Occurred()) {
782 if (PyErr_ExceptionMatches(PyExc_StopIteration))
783 PyErr_Clear();
784 else
785 goto error;
786 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000787 break;
788 }
Christian Heimes90aa7642007-12-19 02:45:37 +0000789 if (Py_SIZE(self) < self->allocated) {
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000790 /* steals ref */
Christian Heimes90aa7642007-12-19 02:45:37 +0000791 PyList_SET_ITEM(self, Py_SIZE(self), item);
792 ++Py_SIZE(self);
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000793 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000794 else {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000795 int status = app1(self, item);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000796 Py_DECREF(item); /* append creates a new ref */
797 if (status < 0)
798 goto error;
799 }
800 }
801
802 /* Cut back result list if initial guess was too large. */
Christian Heimes90aa7642007-12-19 02:45:37 +0000803 if (Py_SIZE(self) < self->allocated)
804 list_resize(self, Py_SIZE(self)); /* shrinking can't fail */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000805
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000806 Py_DECREF(it);
807 Py_RETURN_NONE;
808
809 error:
810 Py_DECREF(it);
811 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000812}
813
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000814PyObject *
815_PyList_Extend(PyListObject *self, PyObject *b)
816{
817 return listextend(self, b);
818}
819
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000820static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000821list_inplace_concat(PyListObject *self, PyObject *other)
822{
823 PyObject *result;
824
825 result = listextend(self, other);
826 if (result == NULL)
827 return result;
828 Py_DECREF(result);
829 Py_INCREF(self);
830 return (PyObject *)self;
831}
832
833static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000834listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000835{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000836 Py_ssize_t i = -1;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000837 PyObject *v;
Tim Peters8fc4a912004-07-31 21:53:19 +0000838 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000839
Thomas Wouters89f507f2006-12-13 04:49:30 +0000840 if (!PyArg_ParseTuple(args, "|n:pop", &i))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000841 return NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000842
Christian Heimes90aa7642007-12-19 02:45:37 +0000843 if (Py_SIZE(self) == 0) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000844 /* Special-case most common failure cause */
845 PyErr_SetString(PyExc_IndexError, "pop from empty list");
846 return NULL;
847 }
848 if (i < 0)
Christian Heimes90aa7642007-12-19 02:45:37 +0000849 i += Py_SIZE(self);
850 if (i < 0 || i >= Py_SIZE(self)) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000851 PyErr_SetString(PyExc_IndexError, "pop index out of range");
852 return NULL;
853 }
854 v = self->ob_item[i];
Christian Heimes90aa7642007-12-19 02:45:37 +0000855 if (i == Py_SIZE(self) - 1) {
856 status = list_resize(self, Py_SIZE(self) - 1);
Tim Peters8fc4a912004-07-31 21:53:19 +0000857 assert(status >= 0);
858 return v; /* and v now owns the reference the list had */
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000859 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000860 Py_INCREF(v);
Tim Peters8fc4a912004-07-31 21:53:19 +0000861 status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
862 assert(status >= 0);
863 /* Use status, so that in a release build compilers don't
864 * complain about the unused name.
865 */
Brett Cannon651dd522004-08-08 21:21:18 +0000866 (void) status;
867
868 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000869}
870
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000871/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
872static void
873reverse_slice(PyObject **lo, PyObject **hi)
874{
875 assert(lo && hi);
876
877 --hi;
878 while (lo < hi) {
879 PyObject *t = *lo;
880 *lo = *hi;
881 *hi = t;
882 ++lo;
883 --hi;
884 }
885}
886
Tim Petersa64dc242002-08-01 02:13:36 +0000887/* Lots of code for an adaptive, stable, natural mergesort. There are many
888 * pieces to this algorithm; read listsort.txt for overviews and details.
889 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000890
Raymond Hettinger70b64fc2008-01-30 20:15:17 +0000891/* Comparison function: PyObject_RichCompareBool with Py_LT.
Tim Petersa64dc242002-08-01 02:13:36 +0000892 * Returns -1 on error, 1 if x < y, 0 if x >= y.
893 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000894
Raymond Hettinger70b64fc2008-01-30 20:15:17 +0000895#define ISLT(X, Y) (PyObject_RichCompareBool(X, Y, Py_LT))
Tim Peters66860f62002-08-04 17:47:26 +0000896
897/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +0000898 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
899 started. It makes more sense in context <wink>. X and Y are PyObject*s.
900*/
Raymond Hettinger70b64fc2008-01-30 20:15:17 +0000901#define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail; \
Tim Petersa8c974c2002-07-19 03:30:57 +0000902 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000903
904/* binarysort is the best method for sorting small arrays: it does
905 few compares, but can do data movement quadratic in the number of
906 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000907 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +0000908 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000909 On entry, must have lo <= start <= hi, and that [lo, start) is already
910 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +0000911 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000912 Even in case of error, the output slice will be some permutation of
913 the input (nothing is lost or duplicated).
914*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000915static int
Raymond Hettinger70b64fc2008-01-30 20:15:17 +0000916binarysort(PyObject **lo, PyObject **hi, PyObject **start)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000917{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000918 register Py_ssize_t k;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000919 register PyObject **l, **p, **r;
920 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000921
Tim Petersa8c974c2002-07-19 03:30:57 +0000922 assert(lo <= start && start <= hi);
923 /* assert [lo, start) is sorted */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000924 if (lo == start)
925 ++start;
926 for (; start < hi; ++start) {
927 /* set l to where *start belongs */
928 l = lo;
929 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000930 pivot = *r;
Tim Peters0fe977c2002-07-19 06:12:32 +0000931 /* Invariants:
932 * pivot >= all in [lo, l).
933 * pivot < all in [r, start).
934 * The second is vacuously true at the start.
935 */
936 assert(l < r);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000937 do {
938 p = l + ((r - l) >> 1);
Tim Petersa8c974c2002-07-19 03:30:57 +0000939 IFLT(pivot, *p)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000940 r = p;
941 else
Tim Peters0fe977c2002-07-19 06:12:32 +0000942 l = p+1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000943 } while (l < r);
Tim Peters0fe977c2002-07-19 06:12:32 +0000944 assert(l == r);
945 /* The invariants still hold, so pivot >= all in [lo, l) and
946 pivot < all in [l, start), so pivot belongs at l. Note
947 that if there are elements equal to pivot, l points to the
948 first slot after them -- that's why this sort is stable.
949 Slide over to make room.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000950 Caution: using memmove is much slower under MSVC 5;
951 we're not usually moving many slots. */
952 for (p = start; p > l; --p)
953 *p = *(p-1);
954 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000955 }
Guido van Rossum3f236de1996-12-10 23:55:39 +0000956 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000957
958 fail:
959 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000960}
961
Tim Petersa64dc242002-08-01 02:13:36 +0000962/*
963Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
964is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000965
Tim Petersa64dc242002-08-01 02:13:36 +0000966 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000967
Tim Petersa64dc242002-08-01 02:13:36 +0000968or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000969
Tim Petersa64dc242002-08-01 02:13:36 +0000970 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +0000971
Tim Petersa64dc242002-08-01 02:13:36 +0000972Boolean *descending is set to 0 in the former case, or to 1 in the latter.
973For its intended use in a stable mergesort, the strictness of the defn of
974"descending" is needed so that the caller can safely reverse a descending
975sequence without violating stability (strict > ensures there are no equal
976elements to get out of order).
977
978Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000979*/
Martin v. Löwis18e16552006-02-15 17:27:45 +0000980static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +0000981count_run(PyObject **lo, PyObject **hi, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000982{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000983 Py_ssize_t k;
984 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000985
Tim Petersa64dc242002-08-01 02:13:36 +0000986 assert(lo < hi);
987 *descending = 0;
988 ++lo;
989 if (lo == hi)
990 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000991
Tim Petersa64dc242002-08-01 02:13:36 +0000992 n = 2;
993 IFLT(*lo, *(lo-1)) {
994 *descending = 1;
995 for (lo = lo+1; lo < hi; ++lo, ++n) {
996 IFLT(*lo, *(lo-1))
997 ;
998 else
999 break;
1000 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001001 }
Tim Petersa64dc242002-08-01 02:13:36 +00001002 else {
1003 for (lo = lo+1; lo < hi; ++lo, ++n) {
1004 IFLT(*lo, *(lo-1))
1005 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001006 }
1007 }
1008
Tim Petersa64dc242002-08-01 02:13:36 +00001009 return n;
1010fail:
1011 return -1;
1012}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001013
Tim Petersa64dc242002-08-01 02:13:36 +00001014/*
1015Locate the proper position of key in a sorted vector; if the vector contains
1016an element equal to key, return the position immediately to the left of
1017the leftmost equal element. [gallop_right() does the same except returns
1018the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001019
Tim Petersa64dc242002-08-01 02:13:36 +00001020"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001021
Tim Petersa64dc242002-08-01 02:13:36 +00001022"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1023hint is to the final result, the faster this runs.
1024
1025The return value is the int k in 0..n such that
1026
1027 a[k-1] < key <= a[k]
1028
1029pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1030key belongs at index k; or, IOW, the first k elements of a should precede
1031key, and the last n-k should follow key.
1032
1033Returns -1 on error. See listsort.txt for info on the method.
1034*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001035static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001036gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001037{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001038 Py_ssize_t ofs;
1039 Py_ssize_t lastofs;
1040 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001041
1042 assert(key && a && n > 0 && hint >= 0 && hint < n);
1043
1044 a += hint;
1045 lastofs = 0;
1046 ofs = 1;
1047 IFLT(*a, key) {
1048 /* a[hint] < key -- gallop right, until
1049 * a[hint + lastofs] < key <= a[hint + ofs]
1050 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001051 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001052 while (ofs < maxofs) {
1053 IFLT(a[ofs], key) {
1054 lastofs = ofs;
1055 ofs = (ofs << 1) + 1;
1056 if (ofs <= 0) /* int overflow */
1057 ofs = maxofs;
1058 }
1059 else /* key <= a[hint + ofs] */
1060 break;
1061 }
1062 if (ofs > maxofs)
1063 ofs = maxofs;
1064 /* Translate back to offsets relative to &a[0]. */
1065 lastofs += hint;
1066 ofs += hint;
1067 }
1068 else {
1069 /* key <= a[hint] -- gallop left, until
1070 * a[hint - ofs] < key <= a[hint - lastofs]
1071 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001072 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001073 while (ofs < maxofs) {
1074 IFLT(*(a-ofs), key)
1075 break;
1076 /* key <= a[hint - ofs] */
1077 lastofs = ofs;
1078 ofs = (ofs << 1) + 1;
1079 if (ofs <= 0) /* int overflow */
1080 ofs = maxofs;
1081 }
1082 if (ofs > maxofs)
1083 ofs = maxofs;
1084 /* Translate back to positive offsets relative to &a[0]. */
1085 k = lastofs;
1086 lastofs = hint - ofs;
1087 ofs = hint - k;
1088 }
1089 a -= hint;
1090
1091 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1092 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1093 * right of lastofs but no farther right than ofs. Do a binary
1094 * search, with invariant a[lastofs-1] < key <= a[ofs].
1095 */
1096 ++lastofs;
1097 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001098 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001099
1100 IFLT(a[m], key)
1101 lastofs = m+1; /* a[m] < key */
1102 else
1103 ofs = m; /* key <= a[m] */
1104 }
1105 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1106 return ofs;
1107
1108fail:
1109 return -1;
1110}
1111
1112/*
1113Exactly like gallop_left(), except that if key already exists in a[0:n],
1114finds the position immediately to the right of the rightmost equal value.
1115
1116The return value is the int k in 0..n such that
1117
1118 a[k-1] <= key < a[k]
1119
1120or -1 if error.
1121
1122The code duplication is massive, but this is enough different given that
1123we're sticking to "<" comparisons that it's much harder to follow if
1124written as one routine with yet another "left or right?" flag.
1125*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001126static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001127gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001128{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001129 Py_ssize_t ofs;
1130 Py_ssize_t lastofs;
1131 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001132
1133 assert(key && a && n > 0 && hint >= 0 && hint < n);
1134
1135 a += hint;
1136 lastofs = 0;
1137 ofs = 1;
1138 IFLT(key, *a) {
1139 /* key < a[hint] -- gallop left, until
1140 * a[hint - ofs] <= key < a[hint - lastofs]
1141 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001142 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001143 while (ofs < maxofs) {
1144 IFLT(key, *(a-ofs)) {
1145 lastofs = ofs;
1146 ofs = (ofs << 1) + 1;
1147 if (ofs <= 0) /* int overflow */
1148 ofs = maxofs;
1149 }
1150 else /* a[hint - ofs] <= key */
1151 break;
1152 }
1153 if (ofs > maxofs)
1154 ofs = maxofs;
1155 /* Translate back to positive offsets relative to &a[0]. */
1156 k = lastofs;
1157 lastofs = hint - ofs;
1158 ofs = hint - k;
1159 }
1160 else {
1161 /* a[hint] <= key -- gallop right, until
1162 * a[hint + lastofs] <= key < a[hint + ofs]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001163 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001164 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001165 while (ofs < maxofs) {
1166 IFLT(key, a[ofs])
1167 break;
1168 /* a[hint + ofs] <= key */
1169 lastofs = ofs;
1170 ofs = (ofs << 1) + 1;
1171 if (ofs <= 0) /* int overflow */
1172 ofs = maxofs;
1173 }
1174 if (ofs > maxofs)
1175 ofs = maxofs;
1176 /* Translate back to offsets relative to &a[0]. */
1177 lastofs += hint;
1178 ofs += hint;
1179 }
1180 a -= hint;
1181
1182 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1183 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1184 * right of lastofs but no farther right than ofs. Do a binary
1185 * search, with invariant a[lastofs-1] <= key < a[ofs].
1186 */
1187 ++lastofs;
1188 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001189 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001190
1191 IFLT(key, a[m])
1192 ofs = m; /* key < a[m] */
1193 else
1194 lastofs = m+1; /* a[m] <= key */
1195 }
1196 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1197 return ofs;
1198
1199fail:
1200 return -1;
1201}
1202
1203/* The maximum number of entries in a MergeState's pending-runs stack.
1204 * This is enough to sort arrays of size up to about
1205 * 32 * phi ** MAX_MERGE_PENDING
1206 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1207 * with 2**64 elements.
1208 */
1209#define MAX_MERGE_PENDING 85
1210
Tim Peterse05f65a2002-08-10 05:21:15 +00001211/* When we get into galloping mode, we stay there until both runs win less
1212 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001213 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001214#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001215
1216/* Avoid malloc for small temp arrays. */
1217#define MERGESTATE_TEMP_SIZE 256
1218
1219/* One MergeState exists on the stack per invocation of mergesort. It's just
1220 * a convenient way to pass state around among the helper functions.
1221 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001222struct s_slice {
1223 PyObject **base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001224 Py_ssize_t len;
Tim Peterse05f65a2002-08-10 05:21:15 +00001225};
1226
Tim Petersa64dc242002-08-01 02:13:36 +00001227typedef struct s_MergeState {
Tim Peterse05f65a2002-08-10 05:21:15 +00001228 /* This controls when we get *into* galloping mode. It's initialized
1229 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1230 * random data, and lower for highly structured data.
1231 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001232 Py_ssize_t min_gallop;
Tim Peterse05f65a2002-08-10 05:21:15 +00001233
Tim Petersa64dc242002-08-01 02:13:36 +00001234 /* 'a' is temp storage to help with merges. It contains room for
1235 * alloced entries.
1236 */
1237 PyObject **a; /* may point to temparray below */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001238 Py_ssize_t alloced;
Tim Petersa64dc242002-08-01 02:13:36 +00001239
1240 /* A stack of n pending runs yet to be merged. Run #i starts at
1241 * address base[i] and extends for len[i] elements. It's always
1242 * true (so long as the indices are in bounds) that
1243 *
Tim Peterse05f65a2002-08-10 05:21:15 +00001244 * pending[i].base + pending[i].len == pending[i+1].base
Tim Petersa64dc242002-08-01 02:13:36 +00001245 *
1246 * so we could cut the storage for this, but it's a minor amount,
1247 * and keeping all the info explicit simplifies the code.
1248 */
1249 int n;
Tim Peterse05f65a2002-08-10 05:21:15 +00001250 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001251
1252 /* 'a' points to this when possible, rather than muck with malloc. */
1253 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1254} MergeState;
1255
1256/* Conceptually a MergeState's constructor. */
1257static void
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001258merge_init(MergeState *ms)
Tim Petersa64dc242002-08-01 02:13:36 +00001259{
1260 assert(ms != NULL);
Tim Petersa64dc242002-08-01 02:13:36 +00001261 ms->a = ms->temparray;
1262 ms->alloced = MERGESTATE_TEMP_SIZE;
1263 ms->n = 0;
Tim Peterse05f65a2002-08-10 05:21:15 +00001264 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001265}
1266
1267/* Free all the temp memory owned by the MergeState. This must be called
1268 * when you're done with a MergeState, and may be called before then if
1269 * you want to free the temp memory early.
1270 */
1271static void
1272merge_freemem(MergeState *ms)
1273{
1274 assert(ms != NULL);
1275 if (ms->a != ms->temparray)
1276 PyMem_Free(ms->a);
1277 ms->a = ms->temparray;
1278 ms->alloced = MERGESTATE_TEMP_SIZE;
1279}
1280
1281/* Ensure enough temp memory for 'need' array slots is available.
1282 * Returns 0 on success and -1 if the memory can't be gotten.
1283 */
1284static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001285merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001286{
1287 assert(ms != NULL);
1288 if (need <= ms->alloced)
1289 return 0;
1290 /* Don't realloc! That can cost cycles to copy the old data, but
1291 * we don't care what's in the block.
1292 */
1293 merge_freemem(ms);
1294 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1295 if (ms->a) {
1296 ms->alloced = need;
1297 return 0;
1298 }
1299 PyErr_NoMemory();
1300 merge_freemem(ms); /* reset to sane state */
1301 return -1;
1302}
1303#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1304 merge_getmem(MS, NEED))
1305
1306/* Merge the na elements starting at pa with the nb elements starting at pb
1307 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1308 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1309 * merge, and should have na <= nb. See listsort.txt for more info.
1310 * Return 0 if successful, -1 if error.
1311 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001312static Py_ssize_t
1313merge_lo(MergeState *ms, PyObject **pa, Py_ssize_t na,
1314 PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001315{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001316 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001317 PyObject **dest;
1318 int result = -1; /* guilty until proved innocent */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001319 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001320
1321 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1322 if (MERGE_GETMEM(ms, na) < 0)
1323 return -1;
1324 memcpy(ms->a, pa, na * sizeof(PyObject*));
1325 dest = pa;
1326 pa = ms->a;
1327
1328 *dest++ = *pb++;
1329 --nb;
1330 if (nb == 0)
1331 goto Succeed;
1332 if (na == 1)
1333 goto CopyB;
1334
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001335 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001336 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001337 Py_ssize_t acount = 0; /* # of times A won in a row */
1338 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001339
1340 /* Do the straightforward thing until (if ever) one run
1341 * appears to win consistently.
1342 */
1343 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001344 assert(na > 1 && nb > 0);
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001345 k = ISLT(*pb, *pa);
Tim Petersa64dc242002-08-01 02:13:36 +00001346 if (k) {
1347 if (k < 0)
1348 goto Fail;
1349 *dest++ = *pb++;
1350 ++bcount;
1351 acount = 0;
1352 --nb;
1353 if (nb == 0)
1354 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001355 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001356 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001357 }
1358 else {
Tim Petersa64dc242002-08-01 02:13:36 +00001359 *dest++ = *pa++;
1360 ++acount;
1361 bcount = 0;
1362 --na;
1363 if (na == 1)
1364 goto CopyB;
Tim Peterse05f65a2002-08-10 05:21:15 +00001365 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001366 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001367 }
Tim Petersa64dc242002-08-01 02:13:36 +00001368 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001369
Tim Petersa64dc242002-08-01 02:13:36 +00001370 /* One run is winning so consistently that galloping may
1371 * be a huge win. So try that, and continue galloping until
1372 * (if ever) neither run appears to be winning consistently
1373 * anymore.
1374 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001375 ++min_gallop;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001376 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001377 assert(na > 1 && nb > 0);
1378 min_gallop -= min_gallop > 1;
1379 ms->min_gallop = min_gallop;
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001380 k = gallop_right(*pb, pa, na, 0);
Tim Petersa64dc242002-08-01 02:13:36 +00001381 acount = k;
1382 if (k) {
1383 if (k < 0)
1384 goto Fail;
1385 memcpy(dest, pa, k * sizeof(PyObject *));
1386 dest += k;
1387 pa += k;
1388 na -= k;
1389 if (na == 1)
1390 goto CopyB;
1391 /* na==0 is impossible now if the comparison
1392 * function is consistent, but we can't assume
1393 * that it is.
1394 */
1395 if (na == 0)
1396 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001397 }
Tim Petersa64dc242002-08-01 02:13:36 +00001398 *dest++ = *pb++;
1399 --nb;
1400 if (nb == 0)
1401 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001402
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001403 k = gallop_left(*pa, pb, nb, 0);
Tim Petersa64dc242002-08-01 02:13:36 +00001404 bcount = k;
1405 if (k) {
1406 if (k < 0)
1407 goto Fail;
1408 memmove(dest, pb, k * sizeof(PyObject *));
1409 dest += k;
1410 pb += k;
1411 nb -= k;
1412 if (nb == 0)
1413 goto Succeed;
1414 }
1415 *dest++ = *pa++;
1416 --na;
1417 if (na == 1)
1418 goto CopyB;
1419 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001420 ++min_gallop; /* penalize it for leaving galloping mode */
1421 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001422 }
1423Succeed:
1424 result = 0;
1425Fail:
1426 if (na)
1427 memcpy(dest, pa, na * sizeof(PyObject*));
1428 return result;
1429CopyB:
1430 assert(na == 1 && nb > 0);
1431 /* The last element of pa belongs at the end of the merge. */
1432 memmove(dest, pb, nb * sizeof(PyObject *));
1433 dest[nb] = *pa;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001434 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001435}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001436
Tim Petersa64dc242002-08-01 02:13:36 +00001437/* Merge the na elements starting at pa with the nb elements starting at pb
1438 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1439 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1440 * merge, and should have na >= nb. See listsort.txt for more info.
1441 * Return 0 if successful, -1 if error.
1442 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001443static Py_ssize_t
1444merge_hi(MergeState *ms, PyObject **pa, Py_ssize_t na, PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001445{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001446 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001447 PyObject **dest;
1448 int result = -1; /* guilty until proved innocent */
1449 PyObject **basea;
1450 PyObject **baseb;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001451 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001452
1453 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1454 if (MERGE_GETMEM(ms, nb) < 0)
1455 return -1;
1456 dest = pb + nb - 1;
1457 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1458 basea = pa;
1459 baseb = ms->a;
1460 pb = ms->a + nb - 1;
1461 pa += na - 1;
1462
1463 *dest-- = *pa--;
1464 --na;
1465 if (na == 0)
1466 goto Succeed;
1467 if (nb == 1)
1468 goto CopyA;
1469
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001470 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001471 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001472 Py_ssize_t acount = 0; /* # of times A won in a row */
1473 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001474
1475 /* Do the straightforward thing until (if ever) one run
1476 * appears to win consistently.
1477 */
1478 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001479 assert(na > 0 && nb > 1);
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001480 k = ISLT(*pb, *pa);
Tim Petersa64dc242002-08-01 02:13:36 +00001481 if (k) {
1482 if (k < 0)
1483 goto Fail;
1484 *dest-- = *pa--;
1485 ++acount;
1486 bcount = 0;
1487 --na;
1488 if (na == 0)
1489 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001490 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001491 break;
1492 }
1493 else {
1494 *dest-- = *pb--;
1495 ++bcount;
1496 acount = 0;
1497 --nb;
1498 if (nb == 1)
1499 goto CopyA;
Tim Peterse05f65a2002-08-10 05:21:15 +00001500 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001501 break;
1502 }
1503 }
1504
1505 /* One run is winning so consistently that galloping may
1506 * be a huge win. So try that, and continue galloping until
1507 * (if ever) neither run appears to be winning consistently
1508 * anymore.
1509 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001510 ++min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001511 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001512 assert(na > 0 && nb > 1);
1513 min_gallop -= min_gallop > 1;
1514 ms->min_gallop = min_gallop;
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001515 k = gallop_right(*pb, basea, na, na-1);
Tim Petersa64dc242002-08-01 02:13:36 +00001516 if (k < 0)
1517 goto Fail;
1518 k = na - k;
1519 acount = k;
1520 if (k) {
1521 dest -= k;
1522 pa -= k;
1523 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1524 na -= k;
1525 if (na == 0)
1526 goto Succeed;
1527 }
1528 *dest-- = *pb--;
1529 --nb;
1530 if (nb == 1)
1531 goto CopyA;
1532
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001533 k = gallop_left(*pa, baseb, nb, nb-1);
Tim Petersa64dc242002-08-01 02:13:36 +00001534 if (k < 0)
1535 goto Fail;
1536 k = nb - k;
1537 bcount = k;
1538 if (k) {
1539 dest -= k;
1540 pb -= k;
1541 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1542 nb -= k;
1543 if (nb == 1)
1544 goto CopyA;
1545 /* nb==0 is impossible now if the comparison
1546 * function is consistent, but we can't assume
1547 * that it is.
1548 */
1549 if (nb == 0)
1550 goto Succeed;
1551 }
1552 *dest-- = *pa--;
1553 --na;
1554 if (na == 0)
1555 goto Succeed;
1556 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001557 ++min_gallop; /* penalize it for leaving galloping mode */
1558 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001559 }
1560Succeed:
1561 result = 0;
1562Fail:
1563 if (nb)
1564 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1565 return result;
1566CopyA:
1567 assert(nb == 1 && na > 0);
1568 /* The first element of pb belongs at the front of the merge. */
1569 dest -= na;
1570 pa -= na;
1571 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1572 *dest = *pb;
1573 return 0;
1574}
1575
1576/* Merge the two runs at stack indices i and i+1.
1577 * Returns 0 on success, -1 on error.
1578 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001579static Py_ssize_t
1580merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001581{
1582 PyObject **pa, **pb;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001583 Py_ssize_t na, nb;
1584 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001585
1586 assert(ms != NULL);
1587 assert(ms->n >= 2);
1588 assert(i >= 0);
1589 assert(i == ms->n - 2 || i == ms->n - 3);
1590
Tim Peterse05f65a2002-08-10 05:21:15 +00001591 pa = ms->pending[i].base;
1592 na = ms->pending[i].len;
1593 pb = ms->pending[i+1].base;
1594 nb = ms->pending[i+1].len;
Tim Petersa64dc242002-08-01 02:13:36 +00001595 assert(na > 0 && nb > 0);
1596 assert(pa + na == pb);
1597
1598 /* Record the length of the combined runs; if i is the 3rd-last
1599 * run now, also slide over the last run (which isn't involved
1600 * in this merge). The current run i+1 goes away in any case.
1601 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001602 ms->pending[i].len = na + nb;
1603 if (i == ms->n - 3)
1604 ms->pending[i+1] = ms->pending[i+2];
Tim Petersa64dc242002-08-01 02:13:36 +00001605 --ms->n;
1606
1607 /* Where does b start in a? Elements in a before that can be
1608 * ignored (already in place).
1609 */
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001610 k = gallop_right(*pb, pa, na, 0);
Tim Petersa64dc242002-08-01 02:13:36 +00001611 if (k < 0)
1612 return -1;
1613 pa += k;
1614 na -= k;
1615 if (na == 0)
1616 return 0;
1617
1618 /* Where does a end in b? Elements in b after that can be
1619 * ignored (already in place).
1620 */
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001621 nb = gallop_left(pa[na-1], pb, nb, nb-1);
Tim Petersa64dc242002-08-01 02:13:36 +00001622 if (nb <= 0)
1623 return nb;
1624
1625 /* Merge what remains of the runs, using a temp array with
1626 * min(na, nb) elements.
1627 */
1628 if (na <= nb)
1629 return merge_lo(ms, pa, na, pb, nb);
1630 else
1631 return merge_hi(ms, pa, na, pb, nb);
1632}
1633
1634/* Examine the stack of runs waiting to be merged, merging adjacent runs
1635 * until the stack invariants are re-established:
1636 *
1637 * 1. len[-3] > len[-2] + len[-1]
1638 * 2. len[-2] > len[-1]
1639 *
1640 * See listsort.txt for more info.
1641 *
1642 * Returns 0 on success, -1 on error.
1643 */
1644static int
1645merge_collapse(MergeState *ms)
1646{
Tim Peterse05f65a2002-08-10 05:21:15 +00001647 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001648
1649 assert(ms);
1650 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001651 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001652 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1653 if (p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001654 --n;
1655 if (merge_at(ms, n) < 0)
1656 return -1;
1657 }
Tim Peterse05f65a2002-08-10 05:21:15 +00001658 else if (p[n].len <= p[n+1].len) {
Tim Petersa64dc242002-08-01 02:13:36 +00001659 if (merge_at(ms, n) < 0)
1660 return -1;
1661 }
1662 else
1663 break;
1664 }
1665 return 0;
1666}
1667
1668/* Regardless of invariants, merge all runs on the stack until only one
1669 * remains. This is used at the end of the mergesort.
1670 *
1671 * Returns 0 on success, -1 on error.
1672 */
1673static int
1674merge_force_collapse(MergeState *ms)
1675{
Tim Peterse05f65a2002-08-10 05:21:15 +00001676 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001677
1678 assert(ms);
1679 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001680 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001681 if (n > 0 && p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001682 --n;
1683 if (merge_at(ms, n) < 0)
1684 return -1;
1685 }
1686 return 0;
1687}
1688
1689/* Compute a good value for the minimum run length; natural runs shorter
1690 * than this are boosted artificially via binary insertion.
1691 *
1692 * If n < 64, return n (it's too small to bother with fancy stuff).
1693 * Else if n is an exact power of 2, return 32.
1694 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1695 * strictly less than, an exact power of 2.
1696 *
1697 * See listsort.txt for more info.
1698 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001699static Py_ssize_t
1700merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001701{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001702 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001703
1704 assert(n >= 0);
1705 while (n >= 64) {
1706 r |= n & 1;
1707 n >>= 1;
1708 }
1709 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001710}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001711
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001712/* Special wrapper to support stable sorting using the decorate-sort-undecorate
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001713 pattern. Holds a key which is used for comparisons and the original record
Tim Petersb38e2b62004-07-29 02:29:26 +00001714 which is returned during the undecorate phase. By exposing only the key
1715 during comparisons, the underlying sort stability characteristics are left
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001716 unchanged. Also, the comparison function will only see the key instead of
1717 a full record. */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001718
1719typedef struct {
1720 PyObject_HEAD
1721 PyObject *key;
1722 PyObject *value;
1723} sortwrapperobject;
1724
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001725PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001726static PyObject *
1727sortwrapper_richcompare(sortwrapperobject *, sortwrapperobject *, int);
1728static void
1729sortwrapper_dealloc(sortwrapperobject *);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001730
Christian Heimesa22e8bd2007-11-29 22:35:39 +00001731PyTypeObject PySortWrapper_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001732 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001733 "sortwrapper", /* tp_name */
1734 sizeof(sortwrapperobject), /* tp_basicsize */
1735 0, /* tp_itemsize */
1736 /* methods */
1737 (destructor)sortwrapper_dealloc, /* tp_dealloc */
1738 0, /* tp_print */
1739 0, /* tp_getattr */
1740 0, /* tp_setattr */
1741 0, /* tp_compare */
1742 0, /* tp_repr */
1743 0, /* tp_as_number */
1744 0, /* tp_as_sequence */
1745 0, /* tp_as_mapping */
1746 0, /* tp_hash */
1747 0, /* tp_call */
1748 0, /* tp_str */
1749 PyObject_GenericGetAttr, /* tp_getattro */
1750 0, /* tp_setattro */
1751 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001752 Py_TPFLAGS_DEFAULT, /* tp_flags */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001753 sortwrapper_doc, /* tp_doc */
1754 0, /* tp_traverse */
1755 0, /* tp_clear */
1756 (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
1757};
1758
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001759
1760static PyObject *
1761sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
1762{
Christian Heimesa22e8bd2007-11-29 22:35:39 +00001763 if (!PyObject_TypeCheck(b, &PySortWrapper_Type)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001764 PyErr_SetString(PyExc_TypeError,
1765 "expected a sortwrapperobject");
1766 return NULL;
1767 }
1768 return PyObject_RichCompare(a->key, b->key, op);
1769}
1770
1771static void
1772sortwrapper_dealloc(sortwrapperobject *so)
1773{
1774 Py_XDECREF(so->key);
1775 Py_XDECREF(so->value);
1776 PyObject_Del(so);
1777}
1778
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001779/* Returns a new reference to a sortwrapper.
1780 Consumes the references to the two underlying objects. */
1781
1782static PyObject *
1783build_sortwrapper(PyObject *key, PyObject *value)
1784{
1785 sortwrapperobject *so;
Tim Petersb38e2b62004-07-29 02:29:26 +00001786
Christian Heimesa22e8bd2007-11-29 22:35:39 +00001787 so = PyObject_New(sortwrapperobject, &PySortWrapper_Type);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001788 if (so == NULL)
1789 return NULL;
1790 so->key = key;
1791 so->value = value;
1792 return (PyObject *)so;
1793}
1794
1795/* Returns a new reference to the value underlying the wrapper. */
1796static PyObject *
1797sortwrapper_getvalue(PyObject *so)
1798{
1799 PyObject *value;
1800
Christian Heimesa22e8bd2007-11-29 22:35:39 +00001801 if (!PyObject_TypeCheck(so, &PySortWrapper_Type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001802 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001803 "expected a sortwrapperobject");
1804 return NULL;
1805 }
1806 value = ((sortwrapperobject *)so)->value;
1807 Py_INCREF(value);
1808 return value;
1809}
1810
Tim Petersa64dc242002-08-01 02:13:36 +00001811/* An adaptive, stable, natural mergesort. See listsort.txt.
1812 * Returns Py_None on success, NULL on error. Even in case of error, the
1813 * list will be some permutation of its input state (nothing is lost or
1814 * duplicated).
1815 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001816static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001817listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001818{
Tim Petersa64dc242002-08-01 02:13:36 +00001819 MergeState ms;
1820 PyObject **lo, **hi;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001821 Py_ssize_t nremaining;
1822 Py_ssize_t minrun;
1823 Py_ssize_t saved_ob_size, saved_allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00001824 PyObject **saved_ob_item;
Armin Rigo93677f02004-07-29 12:40:23 +00001825 PyObject **final_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001826 PyObject *result = NULL; /* guilty until proved innocent */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001827 int reverse = 0;
1828 PyObject *keyfunc = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001829 Py_ssize_t i;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001830 PyObject *key, *value, *kvpair;
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001831 static char *kwlist[] = {"key", "reverse", 0};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001832
Tim Petersa64dc242002-08-01 02:13:36 +00001833 assert(self != NULL);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001834 assert (PyList_Check(self));
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001835 if (args != NULL) {
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001836 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:sort",
1837 kwlist, &keyfunc, &reverse))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001838 return NULL;
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001839 if (Py_SIZE(args) > 0) {
1840 PyErr_SetString(PyExc_TypeError,
1841 "must use keyword argument for key function");
1842 return NULL;
1843 }
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001844 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001845 if (keyfunc == Py_None)
1846 keyfunc = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001847
Tim Petersb9099c32002-11-12 22:08:10 +00001848 /* The list is temporarily made empty, so that mutations performed
1849 * by comparison functions can't affect the slice of memory we're
1850 * sorting (allowing mutations during sorting is a core-dump
1851 * factory, since ob_item may change).
1852 */
Christian Heimes90aa7642007-12-19 02:45:37 +00001853 saved_ob_size = Py_SIZE(self);
Tim Petersb9099c32002-11-12 22:08:10 +00001854 saved_ob_item = self->ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001855 saved_allocated = self->allocated;
Christian Heimes90aa7642007-12-19 02:45:37 +00001856 Py_SIZE(self) = 0;
Tim Peters51b4ade2004-07-29 04:07:15 +00001857 self->ob_item = NULL;
Armin Rigo93677f02004-07-29 12:40:23 +00001858 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00001859
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001860 if (keyfunc != NULL) {
1861 for (i=0 ; i < saved_ob_size ; i++) {
1862 value = saved_ob_item[i];
Tim Petersb38e2b62004-07-29 02:29:26 +00001863 key = PyObject_CallFunctionObjArgs(keyfunc, value,
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001864 NULL);
1865 if (key == NULL) {
1866 for (i=i-1 ; i>=0 ; i--) {
1867 kvpair = saved_ob_item[i];
1868 value = sortwrapper_getvalue(kvpair);
1869 saved_ob_item[i] = value;
1870 Py_DECREF(kvpair);
1871 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001872 goto dsu_fail;
1873 }
1874 kvpair = build_sortwrapper(key, value);
1875 if (kvpair == NULL)
1876 goto dsu_fail;
1877 saved_ob_item[i] = kvpair;
1878 }
1879 }
1880
1881 /* Reverse sort stability achieved by initially reversing the list,
1882 applying a stable forward sort, then reversing the final result. */
1883 if (reverse && saved_ob_size > 1)
1884 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
1885
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001886 merge_init(&ms);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001887
Tim Petersb9099c32002-11-12 22:08:10 +00001888 nremaining = saved_ob_size;
Tim Petersa64dc242002-08-01 02:13:36 +00001889 if (nremaining < 2)
1890 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00001891
Tim Petersa64dc242002-08-01 02:13:36 +00001892 /* March over the array once, left to right, finding natural runs,
1893 * and extending short natural runs to minrun elements.
1894 */
Tim Petersb9099c32002-11-12 22:08:10 +00001895 lo = saved_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001896 hi = lo + nremaining;
1897 minrun = merge_compute_minrun(nremaining);
1898 do {
1899 int descending;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001900 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00001901
Tim Petersa64dc242002-08-01 02:13:36 +00001902 /* Identify next run. */
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001903 n = count_run(lo, hi, &descending);
Tim Petersa64dc242002-08-01 02:13:36 +00001904 if (n < 0)
1905 goto fail;
1906 if (descending)
1907 reverse_slice(lo, lo + n);
1908 /* If short, extend to min(minrun, nremaining). */
1909 if (n < minrun) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001910 const Py_ssize_t force = nremaining <= minrun ?
Tim Petersa64dc242002-08-01 02:13:36 +00001911 nremaining : minrun;
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001912 if (binarysort(lo, lo + force, lo + n) < 0)
Tim Petersa64dc242002-08-01 02:13:36 +00001913 goto fail;
1914 n = force;
1915 }
1916 /* Push run onto pending-runs stack, and maybe merge. */
1917 assert(ms.n < MAX_MERGE_PENDING);
Tim Peterse05f65a2002-08-10 05:21:15 +00001918 ms.pending[ms.n].base = lo;
1919 ms.pending[ms.n].len = n;
Tim Petersa64dc242002-08-01 02:13:36 +00001920 ++ms.n;
1921 if (merge_collapse(&ms) < 0)
1922 goto fail;
1923 /* Advance to find next run. */
1924 lo += n;
1925 nremaining -= n;
1926 } while (nremaining);
1927 assert(lo == hi);
Tim Peters330f9e92002-07-19 07:05:44 +00001928
Tim Petersa64dc242002-08-01 02:13:36 +00001929 if (merge_force_collapse(&ms) < 0)
1930 goto fail;
1931 assert(ms.n == 1);
Tim Petersb9099c32002-11-12 22:08:10 +00001932 assert(ms.pending[0].base == saved_ob_item);
1933 assert(ms.pending[0].len == saved_ob_size);
Tim Petersa64dc242002-08-01 02:13:36 +00001934
1935succeed:
1936 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00001937fail:
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001938 if (keyfunc != NULL) {
1939 for (i=0 ; i < saved_ob_size ; i++) {
1940 kvpair = saved_ob_item[i];
1941 value = sortwrapper_getvalue(kvpair);
1942 saved_ob_item[i] = value;
1943 Py_DECREF(kvpair);
1944 }
1945 }
1946
Armin Rigo93677f02004-07-29 12:40:23 +00001947 if (self->allocated != -1 && result != NULL) {
Tim Peters51b4ade2004-07-29 04:07:15 +00001948 /* The user mucked with the list during the sort,
1949 * and we don't already have another error to report.
1950 */
1951 PyErr_SetString(PyExc_ValueError, "list modified during sort");
1952 result = NULL;
Tim Petersb9099c32002-11-12 22:08:10 +00001953 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001954
1955 if (reverse && saved_ob_size > 1)
1956 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
1957
1958 merge_freemem(&ms);
1959
1960dsu_fail:
Armin Rigo93677f02004-07-29 12:40:23 +00001961 final_ob_item = self->ob_item;
Christian Heimes90aa7642007-12-19 02:45:37 +00001962 i = Py_SIZE(self);
1963 Py_SIZE(self) = saved_ob_size;
Tim Petersb9099c32002-11-12 22:08:10 +00001964 self->ob_item = saved_ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001965 self->allocated = saved_allocated;
Armin Rigo93677f02004-07-29 12:40:23 +00001966 if (final_ob_item != NULL) {
1967 /* we cannot use list_clear() for this because it does not
1968 guarantee that the list is really empty when it returns */
1969 while (--i >= 0) {
1970 Py_XDECREF(final_ob_item[i]);
1971 }
1972 PyMem_FREE(final_ob_item);
1973 }
Tim Petersa64dc242002-08-01 02:13:36 +00001974 Py_XINCREF(result);
1975 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001976}
Tim Peters330f9e92002-07-19 07:05:44 +00001977#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00001978#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00001979
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001980int
Fred Drakea2f55112000-07-09 15:16:51 +00001981PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001982{
1983 if (v == NULL || !PyList_Check(v)) {
1984 PyErr_BadInternalCall();
1985 return -1;
1986 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001987 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001988 if (v == NULL)
1989 return -1;
1990 Py_DECREF(v);
1991 return 0;
1992}
1993
Guido van Rossumb86c5492001-02-12 22:06:02 +00001994static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001995listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00001996{
Christian Heimes90aa7642007-12-19 02:45:37 +00001997 if (Py_SIZE(self) > 1)
1998 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00001999 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002000}
2001
Guido van Rossum84c76f51990-10-30 13:32:20 +00002002int
Fred Drakea2f55112000-07-09 15:16:51 +00002003PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002004{
Tim Peters6063e262002-08-08 01:06:39 +00002005 PyListObject *self = (PyListObject *)v;
2006
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002007 if (v == NULL || !PyList_Check(v)) {
2008 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002009 return -1;
2010 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002011 if (Py_SIZE(self) > 1)
2012 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002013 return 0;
2014}
2015
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002016PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002017PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002018{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002019 PyObject *w;
Christian Heimes2c181612007-12-17 20:04:13 +00002020 PyObject **p, **q;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002021 Py_ssize_t n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002022 if (v == NULL || !PyList_Check(v)) {
2023 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002024 return NULL;
2025 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002026 n = Py_SIZE(v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002027 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002028 if (w == NULL)
2029 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002030 p = ((PyTupleObject *)w)->ob_item;
Christian Heimes2c181612007-12-17 20:04:13 +00002031 q = ((PyListObject *)v)->ob_item;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002032 while (--n >= 0) {
Christian Heimes2c181612007-12-17 20:04:13 +00002033 Py_INCREF(*q);
2034 *p = *q;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002035 p++;
Christian Heimes2c181612007-12-17 20:04:13 +00002036 q++;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002037 }
2038 return w;
2039}
2040
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002041static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002042listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002043{
Christian Heimes90aa7642007-12-19 02:45:37 +00002044 Py_ssize_t i, start=0, stop=Py_SIZE(self);
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002045 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002046
Walter Dörwalde8049bef2003-06-17 19:27:39 +00002047 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2048 _PyEval_SliceIndex, &start,
2049 _PyEval_SliceIndex, &stop))
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002050 return NULL;
Guido van Rossum2743d872003-06-17 14:25:14 +00002051 if (start < 0) {
Christian Heimes90aa7642007-12-19 02:45:37 +00002052 start += Py_SIZE(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002053 if (start < 0)
2054 start = 0;
2055 }
2056 if (stop < 0) {
Christian Heimes90aa7642007-12-19 02:45:37 +00002057 stop += Py_SIZE(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002058 if (stop < 0)
2059 stop = 0;
2060 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002061 for (i = start; i < stop && i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002062 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2063 if (cmp > 0)
Christian Heimes217cfd12007-12-02 14:31:20 +00002064 return PyLong_FromSsize_t(i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002065 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002066 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002067 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002068 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002069 return NULL;
2070}
2071
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002072static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002073listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002074{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002075 Py_ssize_t count = 0;
2076 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002077
Christian Heimes90aa7642007-12-19 02:45:37 +00002078 for (i = 0; i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002079 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2080 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002081 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002082 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002083 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00002084 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002085 return PyLong_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002086}
2087
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002088static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002089listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002090{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002091 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002092
Christian Heimes90aa7642007-12-19 02:45:37 +00002093 for (i = 0; i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002094 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2095 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002096 if (list_ass_slice(self, i, i+1,
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002097 (PyObject *)NULL) == 0)
2098 Py_RETURN_NONE;
2099 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002100 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002101 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002102 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002103 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002104 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002105 return NULL;
2106}
2107
Jeremy Hylton8caad492000-06-23 14:18:11 +00002108static int
2109list_traverse(PyListObject *o, visitproc visit, void *arg)
2110{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002111 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002112
Christian Heimes90aa7642007-12-19 02:45:37 +00002113 for (i = Py_SIZE(o); --i >= 0; )
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002114 Py_VISIT(o->ob_item[i]);
Jeremy Hylton8caad492000-06-23 14:18:11 +00002115 return 0;
2116}
2117
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002118static PyObject *
2119list_richcompare(PyObject *v, PyObject *w, int op)
2120{
2121 PyListObject *vl, *wl;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002122 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002123
2124 if (!PyList_Check(v) || !PyList_Check(w)) {
2125 Py_INCREF(Py_NotImplemented);
2126 return Py_NotImplemented;
2127 }
2128
2129 vl = (PyListObject *)v;
2130 wl = (PyListObject *)w;
2131
Christian Heimes90aa7642007-12-19 02:45:37 +00002132 if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002133 /* Shortcut: if the lengths differ, the lists differ */
2134 PyObject *res;
2135 if (op == Py_EQ)
2136 res = Py_False;
2137 else
2138 res = Py_True;
2139 Py_INCREF(res);
2140 return res;
2141 }
2142
2143 /* Search for the first index where items are different */
Christian Heimes90aa7642007-12-19 02:45:37 +00002144 for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002145 int k = PyObject_RichCompareBool(vl->ob_item[i],
2146 wl->ob_item[i], Py_EQ);
2147 if (k < 0)
2148 return NULL;
2149 if (!k)
2150 break;
2151 }
2152
Christian Heimes90aa7642007-12-19 02:45:37 +00002153 if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002154 /* No more items to compare -- compare sizes */
Christian Heimes90aa7642007-12-19 02:45:37 +00002155 Py_ssize_t vs = Py_SIZE(vl);
2156 Py_ssize_t ws = Py_SIZE(wl);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002157 int cmp;
2158 PyObject *res;
2159 switch (op) {
2160 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00002161 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002162 case Py_EQ: cmp = vs == ws; break;
2163 case Py_NE: cmp = vs != ws; break;
2164 case Py_GT: cmp = vs > ws; break;
2165 case Py_GE: cmp = vs >= ws; break;
2166 default: return NULL; /* cannot happen */
2167 }
2168 if (cmp)
2169 res = Py_True;
2170 else
2171 res = Py_False;
2172 Py_INCREF(res);
2173 return res;
2174 }
2175
2176 /* We have an item that differs -- shortcuts for EQ/NE */
2177 if (op == Py_EQ) {
2178 Py_INCREF(Py_False);
2179 return Py_False;
2180 }
2181 if (op == Py_NE) {
2182 Py_INCREF(Py_True);
2183 return Py_True;
2184 }
2185
2186 /* Compare the final item again using the proper operator */
2187 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
2188}
2189
Tim Peters6d6c1a32001-08-02 04:15:00 +00002190static int
2191list_init(PyListObject *self, PyObject *args, PyObject *kw)
2192{
2193 PyObject *arg = NULL;
Martin v. Löwis15e62742006-02-27 16:46:16 +00002194 static char *kwlist[] = {"sequence", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002195
2196 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2197 return -1;
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002198
2199 /* Verify list invariants established by PyType_GenericAlloc() */
Christian Heimes90aa7642007-12-19 02:45:37 +00002200 assert(0 <= Py_SIZE(self));
2201 assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
Armin Rigoa37bbf22004-07-30 11:20:18 +00002202 assert(self->ob_item != NULL ||
2203 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002204
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002205 /* Empty previous contents */
Armin Rigo93677f02004-07-29 12:40:23 +00002206 if (self->ob_item != NULL) {
2207 (void)list_clear(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002208 }
2209 if (arg != NULL) {
2210 PyObject *rv = listextend(self, arg);
2211 if (rv == NULL)
2212 return -1;
2213 Py_DECREF(rv);
2214 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002215 return 0;
2216}
2217
Raymond Hettinger1021c442003-11-07 15:38:09 +00002218static PyObject *list_iter(PyObject *seq);
2219static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2220
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002221PyDoc_STRVAR(getitem_doc,
2222"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002223PyDoc_STRVAR(reversed_doc,
2224"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002225PyDoc_STRVAR(append_doc,
2226"L.append(object) -- append object to end");
2227PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002228"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002229PyDoc_STRVAR(insert_doc,
2230"L.insert(index, object) -- insert object before index");
2231PyDoc_STRVAR(pop_doc,
2232"L.pop([index]) -> item -- remove and return item at index (default last)");
2233PyDoc_STRVAR(remove_doc,
2234"L.remove(value) -- remove first occurrence of value");
2235PyDoc_STRVAR(index_doc,
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002236"L.index(value, [start, [stop]]) -> integer -- return first index of value");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002237PyDoc_STRVAR(count_doc,
2238"L.count(value) -> integer -- return number of occurrences of value");
2239PyDoc_STRVAR(reverse_doc,
2240"L.reverse() -- reverse *IN PLACE*");
2241PyDoc_STRVAR(sort_doc,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002242"L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n\
2243cmp(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002244
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002245static PyObject *list_subscript(PyListObject*, PyObject*);
2246
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002247static PyMethodDef list_methods[] = {
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002248 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
Raymond Hettinger1021c442003-11-07 15:38:09 +00002249 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002250 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002251 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002252 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002253 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002254 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002255 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002256 {"count", (PyCFunction)listcount, METH_O, count_doc},
2257 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002258 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
Tim Petersa64dc242002-08-01 02:13:36 +00002259 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002260};
2261
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002262static PySequenceMethods list_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002263 (lenfunc)list_length, /* sq_length */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002264 (binaryfunc)list_concat, /* sq_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002265 (ssizeargfunc)list_repeat, /* sq_repeat */
2266 (ssizeargfunc)list_item, /* sq_item */
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002267 0, /* sq_slice */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002268 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002269 0, /* sq_ass_slice */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002270 (objobjproc)list_contains, /* sq_contains */
2271 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002272 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002273};
2274
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002275PyDoc_STRVAR(list_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002276"list() -> new list\n"
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002277"list(sequence) -> new list initialized from sequence's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002278
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002279static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002280list_subscript(PyListObject* self, PyObject* item)
2281{
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002282 if (PyIndex_Check(item)) {
2283 Py_ssize_t i;
2284 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002285 if (i == -1 && PyErr_Occurred())
2286 return NULL;
2287 if (i < 0)
2288 i += PyList_GET_SIZE(self);
2289 return list_item(self, i);
2290 }
2291 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002292 Py_ssize_t start, stop, step, slicelength, cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002293 PyObject* result;
2294 PyObject* it;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002295 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002296
Christian Heimes90aa7642007-12-19 02:45:37 +00002297 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002298 &start, &stop, &step, &slicelength) < 0) {
2299 return NULL;
2300 }
2301
2302 if (slicelength <= 0) {
2303 return PyList_New(0);
2304 }
Thomas Woutersed03b412007-08-28 21:37:11 +00002305 else if (step == 1) {
2306 return list_slice(self, start, stop);
2307 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002308 else {
2309 result = PyList_New(slicelength);
2310 if (!result) return NULL;
2311
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002312 src = self->ob_item;
2313 dest = ((PyListObject *)result)->ob_item;
Tim Peters3b01a122002-07-19 02:35:45 +00002314 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002315 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002316 it = src[cur];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002317 Py_INCREF(it);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002318 dest[i] = it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002319 }
Tim Peters3b01a122002-07-19 02:35:45 +00002320
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002321 return result;
2322 }
2323 }
2324 else {
Thomas Wouters89f507f2006-12-13 04:49:30 +00002325 PyErr_Format(PyExc_TypeError,
2326 "list indices must be integers, not %.200s",
2327 item->ob_type->tp_name);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002328 return NULL;
2329 }
2330}
2331
Tim Peters3b01a122002-07-19 02:35:45 +00002332static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002333list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2334{
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002335 if (PyIndex_Check(item)) {
2336 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002337 if (i == -1 && PyErr_Occurred())
2338 return -1;
2339 if (i < 0)
2340 i += PyList_GET_SIZE(self);
2341 return list_ass_item(self, i, value);
2342 }
2343 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002344 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002345
Christian Heimes90aa7642007-12-19 02:45:37 +00002346 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002347 &start, &stop, &step, &slicelength) < 0) {
2348 return -1;
2349 }
2350
Thomas Woutersed03b412007-08-28 21:37:11 +00002351 if (step == 1)
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002352 return list_ass_slice(self, start, stop, value);
2353
Thomas Woutersed03b412007-08-28 21:37:11 +00002354 /* Make sure s[5:2] = [..] inserts at the right place:
2355 before 5, not before 2. */
2356 if ((step < 0 && start < stop) ||
2357 (step > 0 && start > stop))
2358 stop = start;
2359
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002360 if (value == NULL) {
2361 /* delete slice */
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002362 PyObject **garbage;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002363 Py_ssize_t cur, i;
Tim Peters3b01a122002-07-19 02:35:45 +00002364
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002365 if (slicelength <= 0)
2366 return 0;
2367
2368 if (step < 0) {
2369 stop = start + 1;
2370 start = stop + step*(slicelength - 1) - 1;
2371 step = -step;
2372 }
2373
2374 garbage = (PyObject**)
2375 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002376 if (!garbage) {
2377 PyErr_NoMemory();
2378 return -1;
2379 }
Tim Peters3b01a122002-07-19 02:35:45 +00002380
Thomas Woutersed03b412007-08-28 21:37:11 +00002381 /* drawing pictures might help understand these for
2382 loops. Basically, we memmove the parts of the
2383 list that are *not* part of the slice: step-1
2384 items for each item that is part of the slice,
2385 and then tail end of the list that was not
2386 covered by the slice */
Guido van Rossum75a20b12002-06-11 12:22:28 +00002387 for (cur = start, i = 0;
2388 cur < stop;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002389 cur += step, i++) {
Thomas Woutersed03b412007-08-28 21:37:11 +00002390 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002391
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002392 garbage[i] = PyList_GET_ITEM(self, cur);
2393
Christian Heimes90aa7642007-12-19 02:45:37 +00002394 if (cur + step >= Py_SIZE(self)) {
2395 lim = Py_SIZE(self) - cur - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002396 }
2397
Tim Petersb38e2b62004-07-29 02:29:26 +00002398 memmove(self->ob_item + cur - i,
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002399 self->ob_item + cur + 1,
2400 lim * sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002401 }
Thomas Woutersed03b412007-08-28 21:37:11 +00002402 cur = start + slicelength*step;
Christian Heimes90aa7642007-12-19 02:45:37 +00002403 if (cur < Py_SIZE(self)) {
Thomas Woutersed03b412007-08-28 21:37:11 +00002404 memmove(self->ob_item + cur - slicelength,
2405 self->ob_item + cur,
Christian Heimes90aa7642007-12-19 02:45:37 +00002406 (Py_SIZE(self) - cur) *
Thomas Woutersed03b412007-08-28 21:37:11 +00002407 sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002408 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002409
Christian Heimes90aa7642007-12-19 02:45:37 +00002410 Py_SIZE(self) -= slicelength;
2411 list_resize(self, Py_SIZE(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002412
2413 for (i = 0; i < slicelength; i++) {
2414 Py_DECREF(garbage[i]);
2415 }
2416 PyMem_FREE(garbage);
2417
2418 return 0;
2419 }
2420 else {
2421 /* assign slice */
Thomas Woutersed03b412007-08-28 21:37:11 +00002422 PyObject *ins, *seq;
2423 PyObject **garbage, **seqitems, **selfitems;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002424 Py_ssize_t cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002425
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002426 /* protect against a[::-1] = a */
Tim Peters3b01a122002-07-19 02:35:45 +00002427 if (self == (PyListObject*)value) {
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002428 seq = list_slice((PyListObject*)value, 0,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002429 PyList_GET_SIZE(value));
Tim Peters3b01a122002-07-19 02:35:45 +00002430 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002431 else {
Tim Petersb38e2b62004-07-29 02:29:26 +00002432 seq = PySequence_Fast(value,
Thomas Woutersed03b412007-08-28 21:37:11 +00002433 "must assign iterable "
2434 "to extended slice");
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002435 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002436 if (!seq)
2437 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002438
2439 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2440 PyErr_Format(PyExc_ValueError,
Thomas Woutersed03b412007-08-28 21:37:11 +00002441 "attempt to assign sequence of "
2442 "size %zd to extended slice of "
2443 "size %zd",
Martin v. Löwise0e89f72006-02-16 06:59:22 +00002444 PySequence_Fast_GET_SIZE(seq),
2445 slicelength);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002446 Py_DECREF(seq);
2447 return -1;
2448 }
2449
2450 if (!slicelength) {
2451 Py_DECREF(seq);
2452 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002453 }
2454
2455 garbage = (PyObject**)
2456 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Thomas Wouters89f507f2006-12-13 04:49:30 +00002457 if (!garbage) {
2458 Py_DECREF(seq);
2459 PyErr_NoMemory();
2460 return -1;
2461 }
Tim Peters3b01a122002-07-19 02:35:45 +00002462
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002463 selfitems = self->ob_item;
Raymond Hettinger42bec932004-03-12 16:38:17 +00002464 seqitems = PySequence_Fast_ITEMS(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002465 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002466 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002467 garbage[i] = selfitems[cur];
2468 ins = seqitems[i];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002469 Py_INCREF(ins);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002470 selfitems[cur] = ins;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002471 }
2472
2473 for (i = 0; i < slicelength; i++) {
2474 Py_DECREF(garbage[i]);
2475 }
Tim Peters3b01a122002-07-19 02:35:45 +00002476
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002477 PyMem_FREE(garbage);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002478 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002479
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002480 return 0;
2481 }
Tim Peters3b01a122002-07-19 02:35:45 +00002482 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002483 else {
Thomas Wouters89f507f2006-12-13 04:49:30 +00002484 PyErr_Format(PyExc_TypeError,
2485 "list indices must be integers, not %.200s",
2486 item->ob_type->tp_name);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002487 return -1;
2488 }
2489}
2490
2491static PyMappingMethods list_as_mapping = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002492 (lenfunc)list_length,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002493 (binaryfunc)list_subscript,
2494 (objobjargproc)list_ass_subscript
2495};
2496
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002497PyTypeObject PyList_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002498 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002499 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002500 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002501 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002502 (destructor)list_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00002503 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002504 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002505 0, /* tp_setattr */
2506 0, /* tp_compare */
2507 (reprfunc)list_repr, /* tp_repr */
2508 0, /* tp_as_number */
2509 &list_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002510 &list_as_mapping, /* tp_as_mapping */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00002511 0, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002512 0, /* tp_call */
2513 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002514 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002515 0, /* tp_setattro */
2516 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002517 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Thomas Wouters27d517b2007-02-25 20:39:11 +00002518 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002519 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002520 (traverseproc)list_traverse, /* tp_traverse */
2521 (inquiry)list_clear, /* tp_clear */
2522 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002523 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002524 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002525 0, /* tp_iternext */
2526 list_methods, /* tp_methods */
2527 0, /* tp_members */
2528 0, /* tp_getset */
2529 0, /* tp_base */
2530 0, /* tp_dict */
2531 0, /* tp_descr_get */
2532 0, /* tp_descr_set */
2533 0, /* tp_dictoffset */
2534 (initproc)list_init, /* tp_init */
2535 PyType_GenericAlloc, /* tp_alloc */
2536 PyType_GenericNew, /* tp_new */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002537 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002538};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002539
2540
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002541/*********************** List Iterator **************************/
2542
2543typedef struct {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002544 PyObject_HEAD
2545 long it_index;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002546 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002547} listiterobject;
2548
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002549static PyObject *list_iter(PyObject *);
2550static void listiter_dealloc(listiterobject *);
2551static int listiter_traverse(listiterobject *, visitproc, void *);
2552static PyObject *listiter_next(listiterobject *);
2553static PyObject *listiter_len(listiterobject *);
Raymond Hettinger435bf582004-03-18 22:43:10 +00002554
Armin Rigof5b3e362006-02-11 21:32:43 +00002555PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002556
2557static PyMethodDef listiter_methods[] = {
Armin Rigof5b3e362006-02-11 21:32:43 +00002558 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002559 {NULL, NULL} /* sentinel */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002560};
2561
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002562PyTypeObject PyListIter_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002563 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Christian Heimesf83be4e2007-11-28 09:44:38 +00002564 "list_iterator", /* tp_name */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002565 sizeof(listiterobject), /* tp_basicsize */
2566 0, /* tp_itemsize */
2567 /* methods */
2568 (destructor)listiter_dealloc, /* tp_dealloc */
2569 0, /* tp_print */
2570 0, /* tp_getattr */
2571 0, /* tp_setattr */
2572 0, /* tp_compare */
2573 0, /* tp_repr */
2574 0, /* tp_as_number */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002575 0, /* tp_as_sequence */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002576 0, /* tp_as_mapping */
2577 0, /* tp_hash */
2578 0, /* tp_call */
2579 0, /* tp_str */
2580 PyObject_GenericGetAttr, /* tp_getattro */
2581 0, /* tp_setattro */
2582 0, /* tp_as_buffer */
2583 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2584 0, /* tp_doc */
2585 (traverseproc)listiter_traverse, /* tp_traverse */
2586 0, /* tp_clear */
2587 0, /* tp_richcompare */
2588 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00002589 PyObject_SelfIter, /* tp_iter */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002590 (iternextfunc)listiter_next, /* tp_iternext */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002591 listiter_methods, /* tp_methods */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002592 0, /* tp_members */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002593};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002594
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002595
2596static PyObject *
2597list_iter(PyObject *seq)
2598{
2599 listiterobject *it;
2600
2601 if (!PyList_Check(seq)) {
2602 PyErr_BadInternalCall();
2603 return NULL;
2604 }
2605 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2606 if (it == NULL)
2607 return NULL;
2608 it->it_index = 0;
2609 Py_INCREF(seq);
2610 it->it_seq = (PyListObject *)seq;
2611 _PyObject_GC_TRACK(it);
2612 return (PyObject *)it;
2613}
2614
2615static void
2616listiter_dealloc(listiterobject *it)
2617{
2618 _PyObject_GC_UNTRACK(it);
2619 Py_XDECREF(it->it_seq);
2620 PyObject_GC_Del(it);
2621}
2622
2623static int
2624listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2625{
2626 Py_VISIT(it->it_seq);
2627 return 0;
2628}
2629
2630static PyObject *
2631listiter_next(listiterobject *it)
2632{
2633 PyListObject *seq;
2634 PyObject *item;
2635
2636 assert(it != NULL);
2637 seq = it->it_seq;
2638 if (seq == NULL)
2639 return NULL;
2640 assert(PyList_Check(seq));
2641
2642 if (it->it_index < PyList_GET_SIZE(seq)) {
2643 item = PyList_GET_ITEM(seq, it->it_index);
2644 ++it->it_index;
2645 Py_INCREF(item);
2646 return item;
2647 }
2648
2649 Py_DECREF(seq);
2650 it->it_seq = NULL;
2651 return NULL;
2652}
2653
2654static PyObject *
2655listiter_len(listiterobject *it)
2656{
2657 Py_ssize_t len;
2658 if (it->it_seq) {
2659 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2660 if (len >= 0)
Christian Heimes217cfd12007-12-02 14:31:20 +00002661 return PyLong_FromSsize_t(len);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002662 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002663 return PyLong_FromLong(0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002664}
Raymond Hettinger1021c442003-11-07 15:38:09 +00002665/*********************** List Reverse Iterator **************************/
2666
2667typedef struct {
2668 PyObject_HEAD
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002669 Py_ssize_t it_index;
Raymond Hettinger001f2282003-11-08 11:58:44 +00002670 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002671} listreviterobject;
2672
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002673static PyObject *list_reversed(PyListObject *, PyObject *);
2674static void listreviter_dealloc(listreviterobject *);
2675static int listreviter_traverse(listreviterobject *, visitproc, void *);
2676static PyObject *listreviter_next(listreviterobject *);
2677static Py_ssize_t listreviter_len(listreviterobject *);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002678
2679static PySequenceMethods listreviter_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002680 (lenfunc)listreviter_len, /* sq_length */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002681 0, /* sq_concat */
2682};
2683
Raymond Hettinger1021c442003-11-07 15:38:09 +00002684PyTypeObject PyListRevIter_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002685 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Christian Heimesf83be4e2007-11-28 09:44:38 +00002686 "list_reverseiterator", /* tp_name */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002687 sizeof(listreviterobject), /* tp_basicsize */
2688 0, /* tp_itemsize */
2689 /* methods */
2690 (destructor)listreviter_dealloc, /* tp_dealloc */
2691 0, /* tp_print */
2692 0, /* tp_getattr */
2693 0, /* tp_setattr */
2694 0, /* tp_compare */
2695 0, /* tp_repr */
2696 0, /* tp_as_number */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002697 &listreviter_as_sequence, /* tp_as_sequence */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002698 0, /* tp_as_mapping */
2699 0, /* tp_hash */
2700 0, /* tp_call */
2701 0, /* tp_str */
2702 PyObject_GenericGetAttr, /* tp_getattro */
2703 0, /* tp_setattro */
2704 0, /* tp_as_buffer */
2705 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2706 0, /* tp_doc */
2707 (traverseproc)listreviter_traverse, /* tp_traverse */
2708 0, /* tp_clear */
2709 0, /* tp_richcompare */
2710 0, /* tp_weaklistoffset */
2711 PyObject_SelfIter, /* tp_iter */
2712 (iternextfunc)listreviter_next, /* tp_iternext */
2713 0,
2714};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002715
2716static PyObject *
2717list_reversed(PyListObject *seq, PyObject *unused)
2718{
2719 listreviterobject *it;
2720
2721 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2722 if (it == NULL)
2723 return NULL;
2724 assert(PyList_Check(seq));
2725 it->it_index = PyList_GET_SIZE(seq) - 1;
2726 Py_INCREF(seq);
2727 it->it_seq = seq;
2728 PyObject_GC_Track(it);
2729 return (PyObject *)it;
2730}
2731
2732static void
2733listreviter_dealloc(listreviterobject *it)
2734{
2735 PyObject_GC_UnTrack(it);
2736 Py_XDECREF(it->it_seq);
2737 PyObject_GC_Del(it);
2738}
2739
2740static int
2741listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2742{
2743 Py_VISIT(it->it_seq);
2744 return 0;
2745}
2746
2747static PyObject *
2748listreviter_next(listreviterobject *it)
2749{
2750 PyObject *item;
2751 Py_ssize_t index = it->it_index;
2752 PyListObject *seq = it->it_seq;
2753
2754 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2755 item = PyList_GET_ITEM(seq, index);
2756 it->it_index--;
2757 Py_INCREF(item);
2758 return item;
2759 }
2760 it->it_index = -1;
2761 if (seq != NULL) {
2762 it->it_seq = NULL;
2763 Py_DECREF(seq);
2764 }
2765 return NULL;
2766}
2767
2768static Py_ssize_t
2769listreviter_len(listreviterobject *it)
2770{
2771 Py_ssize_t len = it->it_index + 1;
2772 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
2773 return 0;
2774 return len;
2775}
2776