blob: c5a4287ec18cf8c565139d2767e8288811de0b3e [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);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +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;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +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 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +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
Martin v. Löwis9f2e3462007-07-21 17:22:18 +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 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +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 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +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{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +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. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +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
Martin v. Löwis9f2e3462007-07-21 17:22:18 +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
Martin v. Löwis9f2e3462007-07-21 17:22:18 +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. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000298 for (i = 0; i < Py_Size(v); ++i) {
Tim Petersa7259592001-06-16 05:11:17 +0000299 int status;
300 s = PyObject_Repr(v->ob_item[i]);
301 if (s == NULL)
302 goto Done;
303 status = PyList_Append(pieces, s);
304 Py_DECREF(s); /* append created a new ref */
305 if (status < 0)
306 goto Done;
307 }
308
309 /* Add "[]" decorations to the first and last items. */
310 assert(PyList_GET_SIZE(pieces) > 0);
Walter Dörwald1ab83302007-05-18 17:15:44 +0000311 s = PyUnicode_FromString("[");
Tim Petersa7259592001-06-16 05:11:17 +0000312 if (s == NULL)
313 goto Done;
314 temp = PyList_GET_ITEM(pieces, 0);
Walter Dörwald1ab83302007-05-18 17:15:44 +0000315 PyUnicode_AppendAndDel(&s, temp);
Tim Petersa7259592001-06-16 05:11:17 +0000316 PyList_SET_ITEM(pieces, 0, s);
317 if (s == NULL)
318 goto Done;
319
Walter Dörwald1ab83302007-05-18 17:15:44 +0000320 s = PyUnicode_FromString("]");
Tim Petersa7259592001-06-16 05:11:17 +0000321 if (s == NULL)
322 goto Done;
323 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
Walter Dörwald1ab83302007-05-18 17:15:44 +0000324 PyUnicode_AppendAndDel(&temp, s);
Tim Petersa7259592001-06-16 05:11:17 +0000325 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
326 if (temp == NULL)
327 goto Done;
328
329 /* Paste them all together with ", " between. */
Walter Dörwald1ab83302007-05-18 17:15:44 +0000330 s = PyUnicode_FromString(", ");
Tim Petersa7259592001-06-16 05:11:17 +0000331 if (s == NULL)
332 goto Done;
Walter Dörwald1ab83302007-05-18 17:15:44 +0000333 result = PyUnicode_Join(s, pieces);
Tim Peters3b01a122002-07-19 02:35:45 +0000334 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +0000335
336Done:
337 Py_XDECREF(pieces);
Guido van Rossumfb376de1998-04-10 22:47:27 +0000338 Py_ReprLeave((PyObject *)v);
Tim Petersa7259592001-06-16 05:11:17 +0000339 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000340}
341
Martin v. Löwis18e16552006-02-15 17:27:45 +0000342static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000343list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000344{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000345 return Py_Size(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000346}
347
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000348static int
Fred Drakea2f55112000-07-09 15:16:51 +0000349list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000350{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000351 Py_ssize_t i;
352 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000353
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000354 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_Size(a); ++i)
Raymond Hettingeraae59992002-09-05 14:23:49 +0000355 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000356 Py_EQ);
Neal Norwitzbb9c5f52002-09-05 21:32:55 +0000357 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000358}
359
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000360static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000361list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000362{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000363 if (i < 0 || i >= Py_Size(a)) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000364 if (indexerr == NULL)
Neal Norwitz53cbdaa2007-08-23 21:42:55 +0000365 indexerr = PyUnicode_FromString(
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000366 "list index out of range");
367 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000368 return NULL;
369 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000370 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000371 return a->ob_item[i];
372}
373
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000374static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000375list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000376{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000377 PyListObject *np;
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000378 PyObject **src, **dest;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000379 Py_ssize_t i, len;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000380 if (ilow < 0)
381 ilow = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000382 else if (ilow > Py_Size(a))
383 ilow = Py_Size(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000384 if (ihigh < ilow)
385 ihigh = ilow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000386 else if (ihigh > Py_Size(a))
387 ihigh = Py_Size(a);
Raymond Hettinger99842b62004-03-08 05:56:15 +0000388 len = ihigh - ilow;
389 np = (PyListObject *) PyList_New(len);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000390 if (np == NULL)
391 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000392
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000393 src = a->ob_item + ilow;
394 dest = np->ob_item;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000395 for (i = 0; i < len; i++) {
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000396 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000397 Py_INCREF(v);
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000398 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000399 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000400 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000401}
402
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000403PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000404PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000405{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000406 if (!PyList_Check(a)) {
407 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000408 return NULL;
409 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000410 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000411}
412
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000413static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000414list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000415{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000416 Py_ssize_t size;
417 Py_ssize_t i;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000418 PyObject **src, **dest;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000419 PyListObject *np;
420 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000421 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000422 "can only concatenate list (not \"%.200s\") to list",
423 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000424 return NULL;
425 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000426#define b ((PyListObject *)bb)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000427 size = Py_Size(a) + Py_Size(b);
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000428 if (size < 0)
429 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000430 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000431 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000432 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000433 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000434 src = a->ob_item;
435 dest = np->ob_item;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000436 for (i = 0; i < Py_Size(a); i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000437 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000438 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000439 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000440 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000441 src = b->ob_item;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000442 dest = np->ob_item + Py_Size(a);
443 for (i = 0; i < Py_Size(b); i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000444 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000445 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000446 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000447 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000448 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000449#undef b
450}
451
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000452static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000453list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000454{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000455 Py_ssize_t i, j;
456 Py_ssize_t size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000457 PyListObject *np;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000458 PyObject **p, **items;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000459 PyObject *elem;
Guido van Rossumed98d481991-03-06 13:07:53 +0000460 if (n < 0)
461 n = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000462 size = Py_Size(a) * n;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000463 if (size == 0)
464 return PyList_New(0);
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000465 if (n && size/n != Py_Size(a))
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000466 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000467 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000468 if (np == NULL)
469 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000470
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000471 items = np->ob_item;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000472 if (Py_Size(a) == 1) {
Raymond Hettinger6624e682003-05-21 05:58:46 +0000473 elem = a->ob_item[0];
474 for (i = 0; i < n; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000475 items[i] = elem;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000476 Py_INCREF(elem);
477 }
478 return (PyObject *) np;
479 }
Guido van Rossumed98d481991-03-06 13:07:53 +0000480 p = np->ob_item;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000481 items = a->ob_item;
Guido van Rossumed98d481991-03-06 13:07:53 +0000482 for (i = 0; i < n; i++) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000483 for (j = 0; j < Py_Size(a); j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000484 *p = items[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000485 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000486 p++;
487 }
488 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000489 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000490}
491
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000492static int
Armin Rigo93677f02004-07-29 12:40:23 +0000493list_clear(PyListObject *a)
494{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000495 Py_ssize_t i;
Armin Rigo93677f02004-07-29 12:40:23 +0000496 PyObject **item = a->ob_item;
497 if (item != NULL) {
498 /* Because XDECREF can recursively invoke operations on
499 this list, we make it empty first. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000500 i = Py_Size(a);
501 Py_Size(a) = 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000502 a->ob_item = NULL;
503 a->allocated = 0;
504 while (--i >= 0) {
505 Py_XDECREF(item[i]);
506 }
507 PyMem_FREE(item);
508 }
509 /* Never fails; the return value can be ignored.
510 Note that there is no guarantee that the list is actually empty
511 at this point, because XDECREF may have populated it again! */
512 return 0;
513}
514
Tim Peters8fc4a912004-07-31 21:53:19 +0000515/* a[ilow:ihigh] = v if v != NULL.
516 * del a[ilow:ihigh] if v == NULL.
517 *
518 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
519 * guaranteed the call cannot fail.
520 */
Armin Rigo93677f02004-07-29 12:40:23 +0000521static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000522list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000523{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000524 /* Because [X]DECREF can recursively invoke list operations on
525 this list, we must postpone all [X]DECREF activity until
526 after the list is back in its canonical shape. Therefore
527 we must allocate an additional array, 'recycle', into which
528 we temporarily copy the items that are deleted from the
529 list. :-( */
Tim Peters73572222004-07-31 02:54:42 +0000530 PyObject *recycle_on_stack[8];
531 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000532 PyObject **item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000533 PyObject **vitem = NULL;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000534 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000535 Py_ssize_t n; /* # of elements in replacement list */
536 Py_ssize_t norig; /* # of elements in list getting replaced */
537 Py_ssize_t d; /* Change in size */
538 Py_ssize_t k;
Tim Peters8d9eb102004-07-31 02:24:20 +0000539 size_t s;
540 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000541#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000542 if (v == NULL)
543 n = 0;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000544 else {
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000545 if (a == b) {
546 /* Special case "a[i:j] = a" -- copy b first */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000547 v = list_slice(b, 0, Py_Size(b));
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000548 if (v == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000549 return result;
550 result = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000551 Py_DECREF(v);
Tim Peters8d9eb102004-07-31 02:24:20 +0000552 return result;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000553 }
Raymond Hettingerf889e102004-03-09 08:04:33 +0000554 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000555 if(v_as_SF == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000556 goto Error;
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000557 n = PySequence_Fast_GET_SIZE(v_as_SF);
Raymond Hettinger42bec932004-03-12 16:38:17 +0000558 vitem = PySequence_Fast_ITEMS(v_as_SF);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000559 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000560 if (ilow < 0)
561 ilow = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000562 else if (ilow > Py_Size(a))
563 ilow = Py_Size(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000564
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000565 if (ihigh < ilow)
566 ihigh = ilow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000567 else if (ihigh > Py_Size(a))
568 ihigh = Py_Size(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000569
Tim Peters8d9eb102004-07-31 02:24:20 +0000570 norig = ihigh - ilow;
571 assert(norig >= 0);
572 d = n - norig;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000573 if (Py_Size(a) + d == 0) {
Armin Rigo93677f02004-07-29 12:40:23 +0000574 Py_XDECREF(v_as_SF);
575 return list_clear(a);
576 }
577 item = a->ob_item;
Tim Peters8d9eb102004-07-31 02:24:20 +0000578 /* recycle the items that we are about to remove */
579 s = norig * sizeof(PyObject *);
Tim Peters73572222004-07-31 02:54:42 +0000580 if (s > sizeof(recycle_on_stack)) {
Armin Rigo1dd04a02004-07-30 11:38:22 +0000581 recycle = (PyObject **)PyMem_MALLOC(s);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000582 if (recycle == NULL) {
583 PyErr_NoMemory();
Tim Peters8d9eb102004-07-31 02:24:20 +0000584 goto Error;
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000585 }
586 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000587 memcpy(recycle, &item[ilow], s);
Tim Peters8d9eb102004-07-31 02:24:20 +0000588
Armin Rigo1dd04a02004-07-30 11:38:22 +0000589 if (d < 0) { /* Delete -d items */
590 memmove(&item[ihigh+d], &item[ihigh],
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000591 (Py_Size(a) - ihigh)*sizeof(PyObject *));
592 list_resize(a, Py_Size(a) + d);
Armin Rigo1dd04a02004-07-30 11:38:22 +0000593 item = a->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000594 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000595 else if (d > 0) { /* Insert d items */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000596 k = Py_Size(a);
Tim Peters73572222004-07-31 02:54:42 +0000597 if (list_resize(a, k+d) < 0)
Tim Peters8d9eb102004-07-31 02:24:20 +0000598 goto Error;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000599 item = a->ob_item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000600 memmove(&item[ihigh+d], &item[ihigh],
Tim Peters73572222004-07-31 02:54:42 +0000601 (k - ihigh)*sizeof(PyObject *));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000602 }
603 for (k = 0; k < n; k++, ilow++) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000604 PyObject *w = vitem[k];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000605 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000606 item[ilow] = w;
607 }
Tim Peters73572222004-07-31 02:54:42 +0000608 for (k = norig - 1; k >= 0; --k)
609 Py_XDECREF(recycle[k]);
Tim Peters8d9eb102004-07-31 02:24:20 +0000610 result = 0;
611 Error:
Tim Peters73572222004-07-31 02:54:42 +0000612 if (recycle != recycle_on_stack)
Armin Rigo1dd04a02004-07-30 11:38:22 +0000613 PyMem_FREE(recycle);
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000614 Py_XDECREF(v_as_SF);
Tim Peters8d9eb102004-07-31 02:24:20 +0000615 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000616#undef b
617}
618
Guido van Rossum234f9421993-06-17 12:35:49 +0000619int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000620PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000621{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000622 if (!PyList_Check(a)) {
623 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000624 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000625 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000626 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000627}
628
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000629static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000630list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000631{
632 PyObject **items;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000633 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000634
635
636 size = PyList_GET_SIZE(self);
637 if (size == 0) {
638 Py_INCREF(self);
639 return (PyObject *)self;
640 }
641
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000642 if (n < 1) {
Armin Rigo93677f02004-07-29 12:40:23 +0000643 (void)list_clear(self);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000644 Py_INCREF(self);
645 return (PyObject *)self;
646 }
647
Tim Petersb38e2b62004-07-29 02:29:26 +0000648 if (list_resize(self, size*n) == -1)
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000649 return NULL;
650
651 p = size;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000652 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000653 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
654 for (j = 0; j < size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000655 PyObject *o = items[j];
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000656 Py_INCREF(o);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000657 items[p++] = o;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000658 }
659 }
660 Py_INCREF(self);
661 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000662}
663
Guido van Rossum4a450d01991-04-03 19:05:18 +0000664static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000665list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000666{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000667 PyObject *old_value;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000668 if (i < 0 || i >= Py_Size(a)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000669 PyErr_SetString(PyExc_IndexError,
670 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000671 return -1;
672 }
673 if (v == NULL)
674 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000675 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000676 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000677 a->ob_item[i] = v;
Tim Peters3b01a122002-07-19 02:35:45 +0000678 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000679 return 0;
680}
681
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000682static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000683listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000684{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000685 Py_ssize_t i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000686 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000687 if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000688 return NULL;
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000689 if (ins1(self, i, v) == 0)
690 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000691 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000692}
693
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000694static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000695listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000696{
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000697 if (app1(self, v) == 0)
698 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000699 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000700}
701
Barry Warsawdedf6d61998-10-09 16:37:25 +0000702static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000703listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000704{
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000705 PyObject *it; /* iter(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000706 Py_ssize_t m; /* size of self */
707 Py_ssize_t n; /* guess for size of b */
708 Py_ssize_t mn; /* m + n */
709 Py_ssize_t i;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000710 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000711
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000712 /* Special cases:
Tim Petersb38e2b62004-07-29 02:29:26 +0000713 1) lists and tuples which can use PySequence_Fast ops
714 2) extending self to self requires making a copy first
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000715 */
716 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
Armin Rigo70d172d2004-03-20 22:19:23 +0000717 PyObject **src, **dest;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000718 b = PySequence_Fast(b, "argument must be iterable");
719 if (!b)
720 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000721 n = PySequence_Fast_GET_SIZE(b);
722 if (n == 0) {
723 /* short circuit when b is empty */
724 Py_DECREF(b);
725 Py_RETURN_NONE;
726 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000727 m = Py_Size(self);
Armin Rigo70d172d2004-03-20 22:19:23 +0000728 if (list_resize(self, m + n) == -1) {
729 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000730 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000731 }
732 /* note that we may still have self == b here for the
733 * situation a.extend(a), but the following code works
734 * in that case too. Just make sure to resize self
735 * before calling PySequence_Fast_ITEMS.
736 */
737 /* populate the end of self with b's items */
738 src = PySequence_Fast_ITEMS(b);
739 dest = self->ob_item + m;
740 for (i = 0; i < n; i++) {
741 PyObject *o = src[i];
742 Py_INCREF(o);
743 dest[i] = o;
744 }
745 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000746 Py_RETURN_NONE;
747 }
748
749 it = PyObject_GetIter(b);
750 if (it == NULL)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000751 return NULL;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000752 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000753
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000754 /* Guess a result list size. */
Armin Rigof5b3e362006-02-11 21:32:43 +0000755 n = _PyObject_LengthHint(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000756 if (n < 0) {
Raymond Hettingera710b332005-08-21 11:03:59 +0000757 if (!PyErr_ExceptionMatches(PyExc_TypeError) &&
758 !PyErr_ExceptionMatches(PyExc_AttributeError)) {
759 Py_DECREF(it);
760 return NULL;
761 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000762 PyErr_Clear();
763 n = 8; /* arbitrary */
764 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000765 m = Py_Size(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000766 mn = m + n;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000767 if (mn >= m) {
768 /* Make room. */
769 if (list_resize(self, mn) == -1)
770 goto error;
771 /* Make the list sane again. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000772 Py_Size(self) = m;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000773 }
774 /* Else m + n overflowed; on the chance that n lied, and there really
775 * is enough room, ignore it. If n was telling the truth, we'll
776 * eventually run out of memory during the loop.
777 */
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000778
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000779 /* Run iterator to exhaustion. */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000780 for (;;) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000781 PyObject *item = iternext(it);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000782 if (item == NULL) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000783 if (PyErr_Occurred()) {
784 if (PyErr_ExceptionMatches(PyExc_StopIteration))
785 PyErr_Clear();
786 else
787 goto error;
788 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000789 break;
790 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000791 if (Py_Size(self) < self->allocated) {
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000792 /* steals ref */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000793 PyList_SET_ITEM(self, Py_Size(self), item);
794 ++Py_Size(self);
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000795 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000796 else {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000797 int status = app1(self, item);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000798 Py_DECREF(item); /* append creates a new ref */
799 if (status < 0)
800 goto error;
801 }
802 }
803
804 /* Cut back result list if initial guess was too large. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000805 if (Py_Size(self) < self->allocated)
806 list_resize(self, Py_Size(self)); /* shrinking can't fail */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000807
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000808 Py_DECREF(it);
809 Py_RETURN_NONE;
810
811 error:
812 Py_DECREF(it);
813 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000814}
815
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000816PyObject *
817_PyList_Extend(PyListObject *self, PyObject *b)
818{
819 return listextend(self, b);
820}
821
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000822static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000823list_inplace_concat(PyListObject *self, PyObject *other)
824{
825 PyObject *result;
826
827 result = listextend(self, other);
828 if (result == NULL)
829 return result;
830 Py_DECREF(result);
831 Py_INCREF(self);
832 return (PyObject *)self;
833}
834
835static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000836listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000837{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000838 Py_ssize_t i = -1;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000839 PyObject *v;
Tim Peters8fc4a912004-07-31 21:53:19 +0000840 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000841
Thomas Wouters89f507f2006-12-13 04:49:30 +0000842 if (!PyArg_ParseTuple(args, "|n:pop", &i))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000843 return NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000844
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000845 if (Py_Size(self) == 0) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000846 /* Special-case most common failure cause */
847 PyErr_SetString(PyExc_IndexError, "pop from empty list");
848 return NULL;
849 }
850 if (i < 0)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000851 i += Py_Size(self);
852 if (i < 0 || i >= Py_Size(self)) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000853 PyErr_SetString(PyExc_IndexError, "pop index out of range");
854 return NULL;
855 }
856 v = self->ob_item[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000857 if (i == Py_Size(self) - 1) {
858 status = list_resize(self, Py_Size(self) - 1);
Tim Peters8fc4a912004-07-31 21:53:19 +0000859 assert(status >= 0);
860 return v; /* and v now owns the reference the list had */
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000861 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000862 Py_INCREF(v);
Tim Peters8fc4a912004-07-31 21:53:19 +0000863 status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
864 assert(status >= 0);
865 /* Use status, so that in a release build compilers don't
866 * complain about the unused name.
867 */
Brett Cannon651dd522004-08-08 21:21:18 +0000868 (void) status;
869
870 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000871}
872
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000873/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
874static void
875reverse_slice(PyObject **lo, PyObject **hi)
876{
877 assert(lo && hi);
878
879 --hi;
880 while (lo < hi) {
881 PyObject *t = *lo;
882 *lo = *hi;
883 *hi = t;
884 ++lo;
885 --hi;
886 }
887}
888
Tim Petersa64dc242002-08-01 02:13:36 +0000889/* Lots of code for an adaptive, stable, natural mergesort. There are many
890 * pieces to this algorithm; read listsort.txt for overviews and details.
891 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000892
Guido van Rossum3f236de1996-12-10 23:55:39 +0000893/* Comparison function. Takes care of calling a user-supplied
Tim Peters66860f62002-08-04 17:47:26 +0000894 * comparison function (any callable Python object), which must not be
895 * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool
896 * with Py_LT if you know it's NULL).
Tim Petersa64dc242002-08-01 02:13:36 +0000897 * Returns -1 on error, 1 if x < y, 0 if x >= y.
898 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000899static int
Tim Petersa8c974c2002-07-19 03:30:57 +0000900islt(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000901{
Tim Petersf2a04732002-07-11 21:46:16 +0000902 PyObject *res;
903 PyObject *args;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000904 Py_ssize_t i;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000905
Tim Peters66860f62002-08-04 17:47:26 +0000906 assert(compare != NULL);
Tim Petersa8c974c2002-07-19 03:30:57 +0000907 /* Call the user's comparison function and translate the 3-way
908 * result into true or false (or error).
909 */
Tim Petersf2a04732002-07-11 21:46:16 +0000910 args = PyTuple_New(2);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000911 if (args == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000912 return -1;
Tim Petersf2a04732002-07-11 21:46:16 +0000913 Py_INCREF(x);
914 Py_INCREF(y);
915 PyTuple_SET_ITEM(args, 0, x);
916 PyTuple_SET_ITEM(args, 1, y);
Tim Peters58cf3612002-07-15 05:16:13 +0000917 res = PyObject_Call(compare, args, NULL);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000918 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000919 if (res == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000920 return -1;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000921 if (!PyInt_CheckExact(res)) {
Thomas Wouters89f507f2006-12-13 04:49:30 +0000922 PyErr_Format(PyExc_TypeError,
923 "comparison function must return int, not %.200s",
924 res->ob_type->tp_name);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000925 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +0000926 return -1;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000927 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000928 i = PyInt_AsLong(res);
929 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +0000930 return i < 0;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000931}
932
Tim Peters66860f62002-08-04 17:47:26 +0000933/* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
934 * islt. This avoids a layer of function call in the usual case, and
935 * sorting does many comparisons.
936 * Returns -1 on error, 1 if x < y, 0 if x >= y.
937 */
938#define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
939 PyObject_RichCompareBool(X, Y, Py_LT) : \
940 islt(X, Y, COMPARE))
941
942/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +0000943 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
944 started. It makes more sense in context <wink>. X and Y are PyObject*s.
945*/
Tim Peters66860f62002-08-04 17:47:26 +0000946#define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
Tim Petersa8c974c2002-07-19 03:30:57 +0000947 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000948
949/* binarysort is the best method for sorting small arrays: it does
950 few compares, but can do data movement quadratic in the number of
951 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000952 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +0000953 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000954 On entry, must have lo <= start <= hi, and that [lo, start) is already
955 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +0000956 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000957 Even in case of error, the output slice will be some permutation of
958 the input (nothing is lost or duplicated).
959*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000960static int
Fred Drakea2f55112000-07-09 15:16:51 +0000961binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
962 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000963{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000964 register Py_ssize_t k;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000965 register PyObject **l, **p, **r;
966 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000967
Tim Petersa8c974c2002-07-19 03:30:57 +0000968 assert(lo <= start && start <= hi);
969 /* assert [lo, start) is sorted */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000970 if (lo == start)
971 ++start;
972 for (; start < hi; ++start) {
973 /* set l to where *start belongs */
974 l = lo;
975 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000976 pivot = *r;
Tim Peters0fe977c2002-07-19 06:12:32 +0000977 /* Invariants:
978 * pivot >= all in [lo, l).
979 * pivot < all in [r, start).
980 * The second is vacuously true at the start.
981 */
982 assert(l < r);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000983 do {
984 p = l + ((r - l) >> 1);
Tim Petersa8c974c2002-07-19 03:30:57 +0000985 IFLT(pivot, *p)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000986 r = p;
987 else
Tim Peters0fe977c2002-07-19 06:12:32 +0000988 l = p+1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000989 } while (l < r);
Tim Peters0fe977c2002-07-19 06:12:32 +0000990 assert(l == r);
991 /* The invariants still hold, so pivot >= all in [lo, l) and
992 pivot < all in [l, start), so pivot belongs at l. Note
993 that if there are elements equal to pivot, l points to the
994 first slot after them -- that's why this sort is stable.
995 Slide over to make room.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000996 Caution: using memmove is much slower under MSVC 5;
997 we're not usually moving many slots. */
998 for (p = start; p > l; --p)
999 *p = *(p-1);
1000 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001001 }
Guido van Rossum3f236de1996-12-10 23:55:39 +00001002 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001003
1004 fail:
1005 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001006}
1007
Tim Petersa64dc242002-08-01 02:13:36 +00001008/*
1009Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1010is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001011
Tim Petersa64dc242002-08-01 02:13:36 +00001012 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001013
Tim Petersa64dc242002-08-01 02:13:36 +00001014or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001015
Tim Petersa64dc242002-08-01 02:13:36 +00001016 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001017
Tim Petersa64dc242002-08-01 02:13:36 +00001018Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1019For its intended use in a stable mergesort, the strictness of the defn of
1020"descending" is needed so that the caller can safely reverse a descending
1021sequence without violating stability (strict > ensures there are no equal
1022elements to get out of order).
1023
1024Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001025*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001026static Py_ssize_t
Tim Petersa64dc242002-08-01 02:13:36 +00001027count_run(PyObject **lo, PyObject **hi, PyObject *compare, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001028{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001029 Py_ssize_t k;
1030 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001031
Tim Petersa64dc242002-08-01 02:13:36 +00001032 assert(lo < hi);
1033 *descending = 0;
1034 ++lo;
1035 if (lo == hi)
1036 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001037
Tim Petersa64dc242002-08-01 02:13:36 +00001038 n = 2;
1039 IFLT(*lo, *(lo-1)) {
1040 *descending = 1;
1041 for (lo = lo+1; lo < hi; ++lo, ++n) {
1042 IFLT(*lo, *(lo-1))
1043 ;
1044 else
1045 break;
1046 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001047 }
Tim Petersa64dc242002-08-01 02:13:36 +00001048 else {
1049 for (lo = lo+1; lo < hi; ++lo, ++n) {
1050 IFLT(*lo, *(lo-1))
1051 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001052 }
1053 }
1054
Tim Petersa64dc242002-08-01 02:13:36 +00001055 return n;
1056fail:
1057 return -1;
1058}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001059
Tim Petersa64dc242002-08-01 02:13:36 +00001060/*
1061Locate the proper position of key in a sorted vector; if the vector contains
1062an element equal to key, return the position immediately to the left of
1063the leftmost equal element. [gallop_right() does the same except returns
1064the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001065
Tim Petersa64dc242002-08-01 02:13:36 +00001066"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001067
Tim Petersa64dc242002-08-01 02:13:36 +00001068"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1069hint is to the final result, the faster this runs.
1070
1071The return value is the int k in 0..n such that
1072
1073 a[k-1] < key <= a[k]
1074
1075pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1076key belongs at index k; or, IOW, the first k elements of a should precede
1077key, and the last n-k should follow key.
1078
1079Returns -1 on error. See listsort.txt for info on the method.
1080*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001081static Py_ssize_t
1082gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
Tim Petersa64dc242002-08-01 02:13:36 +00001083{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001084 Py_ssize_t ofs;
1085 Py_ssize_t lastofs;
1086 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001087
1088 assert(key && a && n > 0 && hint >= 0 && hint < n);
1089
1090 a += hint;
1091 lastofs = 0;
1092 ofs = 1;
1093 IFLT(*a, key) {
1094 /* a[hint] < key -- gallop right, until
1095 * a[hint + lastofs] < key <= a[hint + ofs]
1096 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001097 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001098 while (ofs < maxofs) {
1099 IFLT(a[ofs], key) {
1100 lastofs = ofs;
1101 ofs = (ofs << 1) + 1;
1102 if (ofs <= 0) /* int overflow */
1103 ofs = maxofs;
1104 }
1105 else /* key <= a[hint + ofs] */
1106 break;
1107 }
1108 if (ofs > maxofs)
1109 ofs = maxofs;
1110 /* Translate back to offsets relative to &a[0]. */
1111 lastofs += hint;
1112 ofs += hint;
1113 }
1114 else {
1115 /* key <= a[hint] -- gallop left, until
1116 * a[hint - ofs] < key <= a[hint - lastofs]
1117 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001118 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001119 while (ofs < maxofs) {
1120 IFLT(*(a-ofs), key)
1121 break;
1122 /* key <= a[hint - ofs] */
1123 lastofs = ofs;
1124 ofs = (ofs << 1) + 1;
1125 if (ofs <= 0) /* int overflow */
1126 ofs = maxofs;
1127 }
1128 if (ofs > maxofs)
1129 ofs = maxofs;
1130 /* Translate back to positive offsets relative to &a[0]. */
1131 k = lastofs;
1132 lastofs = hint - ofs;
1133 ofs = hint - k;
1134 }
1135 a -= hint;
1136
1137 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1138 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1139 * right of lastofs but no farther right than ofs. Do a binary
1140 * search, with invariant a[lastofs-1] < key <= a[ofs].
1141 */
1142 ++lastofs;
1143 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001144 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001145
1146 IFLT(a[m], key)
1147 lastofs = m+1; /* a[m] < key */
1148 else
1149 ofs = m; /* key <= a[m] */
1150 }
1151 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1152 return ofs;
1153
1154fail:
1155 return -1;
1156}
1157
1158/*
1159Exactly like gallop_left(), except that if key already exists in a[0:n],
1160finds the position immediately to the right of the rightmost equal value.
1161
1162The return value is the int k in 0..n such that
1163
1164 a[k-1] <= key < a[k]
1165
1166or -1 if error.
1167
1168The code duplication is massive, but this is enough different given that
1169we're sticking to "<" comparisons that it's much harder to follow if
1170written as one routine with yet another "left or right?" flag.
1171*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001172static Py_ssize_t
1173gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
Tim Petersa64dc242002-08-01 02:13:36 +00001174{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001175 Py_ssize_t ofs;
1176 Py_ssize_t lastofs;
1177 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001178
1179 assert(key && a && n > 0 && hint >= 0 && hint < n);
1180
1181 a += hint;
1182 lastofs = 0;
1183 ofs = 1;
1184 IFLT(key, *a) {
1185 /* key < a[hint] -- gallop left, until
1186 * a[hint - ofs] <= key < a[hint - lastofs]
1187 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001188 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001189 while (ofs < maxofs) {
1190 IFLT(key, *(a-ofs)) {
1191 lastofs = ofs;
1192 ofs = (ofs << 1) + 1;
1193 if (ofs <= 0) /* int overflow */
1194 ofs = maxofs;
1195 }
1196 else /* a[hint - ofs] <= key */
1197 break;
1198 }
1199 if (ofs > maxofs)
1200 ofs = maxofs;
1201 /* Translate back to positive offsets relative to &a[0]. */
1202 k = lastofs;
1203 lastofs = hint - ofs;
1204 ofs = hint - k;
1205 }
1206 else {
1207 /* a[hint] <= key -- gallop right, until
1208 * a[hint + lastofs] <= key < a[hint + ofs]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001209 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001210 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001211 while (ofs < maxofs) {
1212 IFLT(key, a[ofs])
1213 break;
1214 /* a[hint + ofs] <= key */
1215 lastofs = ofs;
1216 ofs = (ofs << 1) + 1;
1217 if (ofs <= 0) /* int overflow */
1218 ofs = maxofs;
1219 }
1220 if (ofs > maxofs)
1221 ofs = maxofs;
1222 /* Translate back to offsets relative to &a[0]. */
1223 lastofs += hint;
1224 ofs += hint;
1225 }
1226 a -= hint;
1227
1228 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1229 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1230 * right of lastofs but no farther right than ofs. Do a binary
1231 * search, with invariant a[lastofs-1] <= key < a[ofs].
1232 */
1233 ++lastofs;
1234 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001235 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001236
1237 IFLT(key, a[m])
1238 ofs = m; /* key < a[m] */
1239 else
1240 lastofs = m+1; /* a[m] <= key */
1241 }
1242 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1243 return ofs;
1244
1245fail:
1246 return -1;
1247}
1248
1249/* The maximum number of entries in a MergeState's pending-runs stack.
1250 * This is enough to sort arrays of size up to about
1251 * 32 * phi ** MAX_MERGE_PENDING
1252 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1253 * with 2**64 elements.
1254 */
1255#define MAX_MERGE_PENDING 85
1256
Tim Peterse05f65a2002-08-10 05:21:15 +00001257/* When we get into galloping mode, we stay there until both runs win less
1258 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001259 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001260#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001261
1262/* Avoid malloc for small temp arrays. */
1263#define MERGESTATE_TEMP_SIZE 256
1264
1265/* One MergeState exists on the stack per invocation of mergesort. It's just
1266 * a convenient way to pass state around among the helper functions.
1267 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001268struct s_slice {
1269 PyObject **base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001270 Py_ssize_t len;
Tim Peterse05f65a2002-08-10 05:21:15 +00001271};
1272
Tim Petersa64dc242002-08-01 02:13:36 +00001273typedef struct s_MergeState {
1274 /* The user-supplied comparison function. or NULL if none given. */
1275 PyObject *compare;
1276
Tim Peterse05f65a2002-08-10 05:21:15 +00001277 /* This controls when we get *into* galloping mode. It's initialized
1278 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1279 * random data, and lower for highly structured data.
1280 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001281 Py_ssize_t min_gallop;
Tim Peterse05f65a2002-08-10 05:21:15 +00001282
Tim Petersa64dc242002-08-01 02:13:36 +00001283 /* 'a' is temp storage to help with merges. It contains room for
1284 * alloced entries.
1285 */
1286 PyObject **a; /* may point to temparray below */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001287 Py_ssize_t alloced;
Tim Petersa64dc242002-08-01 02:13:36 +00001288
1289 /* A stack of n pending runs yet to be merged. Run #i starts at
1290 * address base[i] and extends for len[i] elements. It's always
1291 * true (so long as the indices are in bounds) that
1292 *
Tim Peterse05f65a2002-08-10 05:21:15 +00001293 * pending[i].base + pending[i].len == pending[i+1].base
Tim Petersa64dc242002-08-01 02:13:36 +00001294 *
1295 * so we could cut the storage for this, but it's a minor amount,
1296 * and keeping all the info explicit simplifies the code.
1297 */
1298 int n;
Tim Peterse05f65a2002-08-10 05:21:15 +00001299 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001300
1301 /* 'a' points to this when possible, rather than muck with malloc. */
1302 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1303} MergeState;
1304
1305/* Conceptually a MergeState's constructor. */
1306static void
1307merge_init(MergeState *ms, PyObject *compare)
1308{
1309 assert(ms != NULL);
1310 ms->compare = compare;
1311 ms->a = ms->temparray;
1312 ms->alloced = MERGESTATE_TEMP_SIZE;
1313 ms->n = 0;
Tim Peterse05f65a2002-08-10 05:21:15 +00001314 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001315}
1316
1317/* Free all the temp memory owned by the MergeState. This must be called
1318 * when you're done with a MergeState, and may be called before then if
1319 * you want to free the temp memory early.
1320 */
1321static void
1322merge_freemem(MergeState *ms)
1323{
1324 assert(ms != NULL);
1325 if (ms->a != ms->temparray)
1326 PyMem_Free(ms->a);
1327 ms->a = ms->temparray;
1328 ms->alloced = MERGESTATE_TEMP_SIZE;
1329}
1330
1331/* Ensure enough temp memory for 'need' array slots is available.
1332 * Returns 0 on success and -1 if the memory can't be gotten.
1333 */
1334static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001335merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001336{
1337 assert(ms != NULL);
1338 if (need <= ms->alloced)
1339 return 0;
1340 /* Don't realloc! That can cost cycles to copy the old data, but
1341 * we don't care what's in the block.
1342 */
1343 merge_freemem(ms);
1344 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1345 if (ms->a) {
1346 ms->alloced = need;
1347 return 0;
1348 }
1349 PyErr_NoMemory();
1350 merge_freemem(ms); /* reset to sane state */
1351 return -1;
1352}
1353#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1354 merge_getmem(MS, NEED))
1355
1356/* Merge the na elements starting at pa with the nb elements starting at pb
1357 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1358 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1359 * merge, and should have na <= nb. See listsort.txt for more info.
1360 * Return 0 if successful, -1 if error.
1361 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001362static Py_ssize_t
1363merge_lo(MergeState *ms, PyObject **pa, Py_ssize_t na,
1364 PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001365{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001366 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001367 PyObject *compare;
1368 PyObject **dest;
1369 int result = -1; /* guilty until proved innocent */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001370 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001371
1372 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1373 if (MERGE_GETMEM(ms, na) < 0)
1374 return -1;
1375 memcpy(ms->a, pa, na * sizeof(PyObject*));
1376 dest = pa;
1377 pa = ms->a;
1378
1379 *dest++ = *pb++;
1380 --nb;
1381 if (nb == 0)
1382 goto Succeed;
1383 if (na == 1)
1384 goto CopyB;
1385
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001386 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001387 compare = ms->compare;
1388 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001389 Py_ssize_t acount = 0; /* # of times A won in a row */
1390 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001391
1392 /* Do the straightforward thing until (if ever) one run
1393 * appears to win consistently.
1394 */
1395 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001396 assert(na > 1 && nb > 0);
Tim Peters66860f62002-08-04 17:47:26 +00001397 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001398 if (k) {
1399 if (k < 0)
1400 goto Fail;
1401 *dest++ = *pb++;
1402 ++bcount;
1403 acount = 0;
1404 --nb;
1405 if (nb == 0)
1406 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001407 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001408 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001409 }
1410 else {
Tim Petersa64dc242002-08-01 02:13:36 +00001411 *dest++ = *pa++;
1412 ++acount;
1413 bcount = 0;
1414 --na;
1415 if (na == 1)
1416 goto CopyB;
Tim Peterse05f65a2002-08-10 05:21:15 +00001417 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001418 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001419 }
Tim Petersa64dc242002-08-01 02:13:36 +00001420 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001421
Tim Petersa64dc242002-08-01 02:13:36 +00001422 /* One run is winning so consistently that galloping may
1423 * be a huge win. So try that, and continue galloping until
1424 * (if ever) neither run appears to be winning consistently
1425 * anymore.
1426 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001427 ++min_gallop;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001428 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001429 assert(na > 1 && nb > 0);
1430 min_gallop -= min_gallop > 1;
1431 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001432 k = gallop_right(*pb, pa, na, 0, compare);
1433 acount = k;
1434 if (k) {
1435 if (k < 0)
1436 goto Fail;
1437 memcpy(dest, pa, k * sizeof(PyObject *));
1438 dest += k;
1439 pa += k;
1440 na -= k;
1441 if (na == 1)
1442 goto CopyB;
1443 /* na==0 is impossible now if the comparison
1444 * function is consistent, but we can't assume
1445 * that it is.
1446 */
1447 if (na == 0)
1448 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001449 }
Tim Petersa64dc242002-08-01 02:13:36 +00001450 *dest++ = *pb++;
1451 --nb;
1452 if (nb == 0)
1453 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001454
Tim Petersa64dc242002-08-01 02:13:36 +00001455 k = gallop_left(*pa, pb, nb, 0, compare);
1456 bcount = k;
1457 if (k) {
1458 if (k < 0)
1459 goto Fail;
1460 memmove(dest, pb, k * sizeof(PyObject *));
1461 dest += k;
1462 pb += k;
1463 nb -= k;
1464 if (nb == 0)
1465 goto Succeed;
1466 }
1467 *dest++ = *pa++;
1468 --na;
1469 if (na == 1)
1470 goto CopyB;
1471 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001472 ++min_gallop; /* penalize it for leaving galloping mode */
1473 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001474 }
1475Succeed:
1476 result = 0;
1477Fail:
1478 if (na)
1479 memcpy(dest, pa, na * sizeof(PyObject*));
1480 return result;
1481CopyB:
1482 assert(na == 1 && nb > 0);
1483 /* The last element of pa belongs at the end of the merge. */
1484 memmove(dest, pb, nb * sizeof(PyObject *));
1485 dest[nb] = *pa;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001486 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001487}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001488
Tim Petersa64dc242002-08-01 02:13:36 +00001489/* Merge the na elements starting at pa with the nb elements starting at pb
1490 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1491 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1492 * merge, and should have na >= nb. See listsort.txt for more info.
1493 * Return 0 if successful, -1 if error.
1494 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001495static Py_ssize_t
1496merge_hi(MergeState *ms, PyObject **pa, Py_ssize_t na, PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001497{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001498 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001499 PyObject *compare;
1500 PyObject **dest;
1501 int result = -1; /* guilty until proved innocent */
1502 PyObject **basea;
1503 PyObject **baseb;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001504 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001505
1506 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1507 if (MERGE_GETMEM(ms, nb) < 0)
1508 return -1;
1509 dest = pb + nb - 1;
1510 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1511 basea = pa;
1512 baseb = ms->a;
1513 pb = ms->a + nb - 1;
1514 pa += na - 1;
1515
1516 *dest-- = *pa--;
1517 --na;
1518 if (na == 0)
1519 goto Succeed;
1520 if (nb == 1)
1521 goto CopyA;
1522
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001523 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001524 compare = ms->compare;
1525 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001526 Py_ssize_t acount = 0; /* # of times A won in a row */
1527 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001528
1529 /* Do the straightforward thing until (if ever) one run
1530 * appears to win consistently.
1531 */
1532 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001533 assert(na > 0 && nb > 1);
Tim Peters66860f62002-08-04 17:47:26 +00001534 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001535 if (k) {
1536 if (k < 0)
1537 goto Fail;
1538 *dest-- = *pa--;
1539 ++acount;
1540 bcount = 0;
1541 --na;
1542 if (na == 0)
1543 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001544 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001545 break;
1546 }
1547 else {
1548 *dest-- = *pb--;
1549 ++bcount;
1550 acount = 0;
1551 --nb;
1552 if (nb == 1)
1553 goto CopyA;
Tim Peterse05f65a2002-08-10 05:21:15 +00001554 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001555 break;
1556 }
1557 }
1558
1559 /* One run is winning so consistently that galloping may
1560 * be a huge win. So try that, and continue galloping until
1561 * (if ever) neither run appears to be winning consistently
1562 * anymore.
1563 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001564 ++min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001565 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001566 assert(na > 0 && nb > 1);
1567 min_gallop -= min_gallop > 1;
1568 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001569 k = gallop_right(*pb, basea, na, na-1, compare);
1570 if (k < 0)
1571 goto Fail;
1572 k = na - k;
1573 acount = k;
1574 if (k) {
1575 dest -= k;
1576 pa -= k;
1577 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1578 na -= k;
1579 if (na == 0)
1580 goto Succeed;
1581 }
1582 *dest-- = *pb--;
1583 --nb;
1584 if (nb == 1)
1585 goto CopyA;
1586
1587 k = gallop_left(*pa, baseb, nb, nb-1, compare);
1588 if (k < 0)
1589 goto Fail;
1590 k = nb - k;
1591 bcount = k;
1592 if (k) {
1593 dest -= k;
1594 pb -= k;
1595 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1596 nb -= k;
1597 if (nb == 1)
1598 goto CopyA;
1599 /* nb==0 is impossible now if the comparison
1600 * function is consistent, but we can't assume
1601 * that it is.
1602 */
1603 if (nb == 0)
1604 goto Succeed;
1605 }
1606 *dest-- = *pa--;
1607 --na;
1608 if (na == 0)
1609 goto Succeed;
1610 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001611 ++min_gallop; /* penalize it for leaving galloping mode */
1612 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001613 }
1614Succeed:
1615 result = 0;
1616Fail:
1617 if (nb)
1618 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1619 return result;
1620CopyA:
1621 assert(nb == 1 && na > 0);
1622 /* The first element of pb belongs at the front of the merge. */
1623 dest -= na;
1624 pa -= na;
1625 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1626 *dest = *pb;
1627 return 0;
1628}
1629
1630/* Merge the two runs at stack indices i and i+1.
1631 * Returns 0 on success, -1 on error.
1632 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001633static Py_ssize_t
1634merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001635{
1636 PyObject **pa, **pb;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001637 Py_ssize_t na, nb;
1638 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001639 PyObject *compare;
1640
1641 assert(ms != NULL);
1642 assert(ms->n >= 2);
1643 assert(i >= 0);
1644 assert(i == ms->n - 2 || i == ms->n - 3);
1645
Tim Peterse05f65a2002-08-10 05:21:15 +00001646 pa = ms->pending[i].base;
1647 na = ms->pending[i].len;
1648 pb = ms->pending[i+1].base;
1649 nb = ms->pending[i+1].len;
Tim Petersa64dc242002-08-01 02:13:36 +00001650 assert(na > 0 && nb > 0);
1651 assert(pa + na == pb);
1652
1653 /* Record the length of the combined runs; if i is the 3rd-last
1654 * run now, also slide over the last run (which isn't involved
1655 * in this merge). The current run i+1 goes away in any case.
1656 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001657 ms->pending[i].len = na + nb;
1658 if (i == ms->n - 3)
1659 ms->pending[i+1] = ms->pending[i+2];
Tim Petersa64dc242002-08-01 02:13:36 +00001660 --ms->n;
1661
1662 /* Where does b start in a? Elements in a before that can be
1663 * ignored (already in place).
1664 */
1665 compare = ms->compare;
1666 k = gallop_right(*pb, pa, na, 0, compare);
1667 if (k < 0)
1668 return -1;
1669 pa += k;
1670 na -= k;
1671 if (na == 0)
1672 return 0;
1673
1674 /* Where does a end in b? Elements in b after that can be
1675 * ignored (already in place).
1676 */
1677 nb = gallop_left(pa[na-1], pb, nb, nb-1, compare);
1678 if (nb <= 0)
1679 return nb;
1680
1681 /* Merge what remains of the runs, using a temp array with
1682 * min(na, nb) elements.
1683 */
1684 if (na <= nb)
1685 return merge_lo(ms, pa, na, pb, nb);
1686 else
1687 return merge_hi(ms, pa, na, pb, nb);
1688}
1689
1690/* Examine the stack of runs waiting to be merged, merging adjacent runs
1691 * until the stack invariants are re-established:
1692 *
1693 * 1. len[-3] > len[-2] + len[-1]
1694 * 2. len[-2] > len[-1]
1695 *
1696 * See listsort.txt for more info.
1697 *
1698 * Returns 0 on success, -1 on error.
1699 */
1700static int
1701merge_collapse(MergeState *ms)
1702{
Tim Peterse05f65a2002-08-10 05:21:15 +00001703 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001704
1705 assert(ms);
1706 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001707 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001708 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1709 if (p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001710 --n;
1711 if (merge_at(ms, n) < 0)
1712 return -1;
1713 }
Tim Peterse05f65a2002-08-10 05:21:15 +00001714 else if (p[n].len <= p[n+1].len) {
Tim Petersa64dc242002-08-01 02:13:36 +00001715 if (merge_at(ms, n) < 0)
1716 return -1;
1717 }
1718 else
1719 break;
1720 }
1721 return 0;
1722}
1723
1724/* Regardless of invariants, merge all runs on the stack until only one
1725 * remains. This is used at the end of the mergesort.
1726 *
1727 * Returns 0 on success, -1 on error.
1728 */
1729static int
1730merge_force_collapse(MergeState *ms)
1731{
Tim Peterse05f65a2002-08-10 05:21:15 +00001732 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001733
1734 assert(ms);
1735 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001736 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001737 if (n > 0 && p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001738 --n;
1739 if (merge_at(ms, n) < 0)
1740 return -1;
1741 }
1742 return 0;
1743}
1744
1745/* Compute a good value for the minimum run length; natural runs shorter
1746 * than this are boosted artificially via binary insertion.
1747 *
1748 * If n < 64, return n (it's too small to bother with fancy stuff).
1749 * Else if n is an exact power of 2, return 32.
1750 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1751 * strictly less than, an exact power of 2.
1752 *
1753 * See listsort.txt for more info.
1754 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001755static Py_ssize_t
1756merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001757{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001758 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001759
1760 assert(n >= 0);
1761 while (n >= 64) {
1762 r |= n & 1;
1763 n >>= 1;
1764 }
1765 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001766}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001767
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001768/* Special wrapper to support stable sorting using the decorate-sort-undecorate
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001769 pattern. Holds a key which is used for comparisons and the original record
Tim Petersb38e2b62004-07-29 02:29:26 +00001770 which is returned during the undecorate phase. By exposing only the key
1771 during comparisons, the underlying sort stability characteristics are left
1772 unchanged. Also, if a custom comparison function is used, it will only see
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001773 the key instead of a full record. */
1774
1775typedef struct {
1776 PyObject_HEAD
1777 PyObject *key;
1778 PyObject *value;
1779} sortwrapperobject;
1780
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001781PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001782static PyObject *
1783sortwrapper_richcompare(sortwrapperobject *, sortwrapperobject *, int);
1784static void
1785sortwrapper_dealloc(sortwrapperobject *);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001786
1787static PyTypeObject sortwrapper_type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001788 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001789 "sortwrapper", /* tp_name */
1790 sizeof(sortwrapperobject), /* tp_basicsize */
1791 0, /* tp_itemsize */
1792 /* methods */
1793 (destructor)sortwrapper_dealloc, /* tp_dealloc */
1794 0, /* tp_print */
1795 0, /* tp_getattr */
1796 0, /* tp_setattr */
1797 0, /* tp_compare */
1798 0, /* tp_repr */
1799 0, /* tp_as_number */
1800 0, /* tp_as_sequence */
1801 0, /* tp_as_mapping */
1802 0, /* tp_hash */
1803 0, /* tp_call */
1804 0, /* tp_str */
1805 PyObject_GenericGetAttr, /* tp_getattro */
1806 0, /* tp_setattro */
1807 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001808 Py_TPFLAGS_DEFAULT, /* tp_flags */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001809 sortwrapper_doc, /* tp_doc */
1810 0, /* tp_traverse */
1811 0, /* tp_clear */
1812 (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
1813};
1814
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001815
1816static PyObject *
1817sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
1818{
1819 if (!PyObject_TypeCheck(b, &sortwrapper_type)) {
1820 PyErr_SetString(PyExc_TypeError,
1821 "expected a sortwrapperobject");
1822 return NULL;
1823 }
1824 return PyObject_RichCompare(a->key, b->key, op);
1825}
1826
1827static void
1828sortwrapper_dealloc(sortwrapperobject *so)
1829{
1830 Py_XDECREF(so->key);
1831 Py_XDECREF(so->value);
1832 PyObject_Del(so);
1833}
1834
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001835/* Returns a new reference to a sortwrapper.
1836 Consumes the references to the two underlying objects. */
1837
1838static PyObject *
1839build_sortwrapper(PyObject *key, PyObject *value)
1840{
1841 sortwrapperobject *so;
Tim Petersb38e2b62004-07-29 02:29:26 +00001842
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001843 so = PyObject_New(sortwrapperobject, &sortwrapper_type);
1844 if (so == NULL)
1845 return NULL;
1846 so->key = key;
1847 so->value = value;
1848 return (PyObject *)so;
1849}
1850
1851/* Returns a new reference to the value underlying the wrapper. */
1852static PyObject *
1853sortwrapper_getvalue(PyObject *so)
1854{
1855 PyObject *value;
1856
1857 if (!PyObject_TypeCheck(so, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001858 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001859 "expected a sortwrapperobject");
1860 return NULL;
1861 }
1862 value = ((sortwrapperobject *)so)->value;
1863 Py_INCREF(value);
1864 return value;
1865}
1866
1867/* Wrapper for user specified cmp functions in combination with a
1868 specified key function. Makes sure the cmp function is presented
1869 with the actual key instead of the sortwrapper */
1870
1871typedef struct {
1872 PyObject_HEAD
1873 PyObject *func;
1874} cmpwrapperobject;
1875
1876static void
1877cmpwrapper_dealloc(cmpwrapperobject *co)
1878{
1879 Py_XDECREF(co->func);
1880 PyObject_Del(co);
1881}
1882
1883static PyObject *
1884cmpwrapper_call(cmpwrapperobject *co, PyObject *args, PyObject *kwds)
1885{
1886 PyObject *x, *y, *xx, *yy;
1887
1888 if (!PyArg_UnpackTuple(args, "", 2, 2, &x, &y))
1889 return NULL;
1890 if (!PyObject_TypeCheck(x, &sortwrapper_type) ||
Raymond Hettingerae4a2992003-10-16 17:16:30 +00001891 !PyObject_TypeCheck(y, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001892 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001893 "expected a sortwrapperobject");
1894 return NULL;
1895 }
1896 xx = ((sortwrapperobject *)x)->key;
1897 yy = ((sortwrapperobject *)y)->key;
1898 return PyObject_CallFunctionObjArgs(co->func, xx, yy, NULL);
1899}
1900
1901PyDoc_STRVAR(cmpwrapper_doc, "cmp() wrapper for sort with custom keys.");
1902
1903static PyTypeObject cmpwrapper_type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001904 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001905 "cmpwrapper", /* tp_name */
1906 sizeof(cmpwrapperobject), /* tp_basicsize */
1907 0, /* tp_itemsize */
1908 /* methods */
1909 (destructor)cmpwrapper_dealloc, /* tp_dealloc */
1910 0, /* tp_print */
1911 0, /* tp_getattr */
1912 0, /* tp_setattr */
1913 0, /* tp_compare */
1914 0, /* tp_repr */
1915 0, /* tp_as_number */
1916 0, /* tp_as_sequence */
1917 0, /* tp_as_mapping */
1918 0, /* tp_hash */
1919 (ternaryfunc)cmpwrapper_call, /* tp_call */
1920 0, /* tp_str */
1921 PyObject_GenericGetAttr, /* tp_getattro */
1922 0, /* tp_setattro */
1923 0, /* tp_as_buffer */
1924 Py_TPFLAGS_DEFAULT, /* tp_flags */
1925 cmpwrapper_doc, /* tp_doc */
1926};
1927
1928static PyObject *
1929build_cmpwrapper(PyObject *cmpfunc)
1930{
1931 cmpwrapperobject *co;
Tim Petersb38e2b62004-07-29 02:29:26 +00001932
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001933 co = PyObject_New(cmpwrapperobject, &cmpwrapper_type);
1934 if (co == NULL)
1935 return NULL;
1936 Py_INCREF(cmpfunc);
1937 co->func = cmpfunc;
1938 return (PyObject *)co;
1939}
1940
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001941static int
1942is_default_cmp(PyObject *cmpfunc)
1943{
1944 PyCFunctionObject *f;
Neal Norwitzed2b7392007-08-26 04:51:10 +00001945 const char *module;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001946 if (cmpfunc == NULL || cmpfunc == Py_None)
1947 return 1;
1948 if (!PyCFunction_Check(cmpfunc))
1949 return 0;
Guido van Rossumf1624cd2006-08-24 23:43:52 +00001950 f = (PyCFunctionObject *)cmpfunc;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001951 if (f->m_self != NULL)
1952 return 0;
Neal Norwitzed2b7392007-08-26 04:51:10 +00001953 if (!PyUnicode_Check(f->m_module))
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001954 return 0;
Neal Norwitzed2b7392007-08-26 04:51:10 +00001955 module = PyUnicode_AsString(f->m_module);
1956 if (module == NULL)
1957 return 0;
1958 if (strcmp(module, "__builtin__") != 0)
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001959 return 0;
1960 if (strcmp(f->m_ml->ml_name, "cmp") != 0)
1961 return 0;
1962 return 1;
1963}
1964
Tim Petersa64dc242002-08-01 02:13:36 +00001965/* An adaptive, stable, natural mergesort. See listsort.txt.
1966 * Returns Py_None on success, NULL on error. Even in case of error, the
1967 * list will be some permutation of its input state (nothing is lost or
1968 * duplicated).
1969 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001970static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001971listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001972{
Tim Petersa64dc242002-08-01 02:13:36 +00001973 MergeState ms;
1974 PyObject **lo, **hi;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001975 Py_ssize_t nremaining;
1976 Py_ssize_t minrun;
1977 Py_ssize_t saved_ob_size, saved_allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00001978 PyObject **saved_ob_item;
Armin Rigo93677f02004-07-29 12:40:23 +00001979 PyObject **final_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001980 PyObject *compare = NULL;
1981 PyObject *result = NULL; /* guilty until proved innocent */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001982 int reverse = 0;
1983 PyObject *keyfunc = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001984 Py_ssize_t i;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001985 PyObject *key, *value, *kvpair;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001986 static char *kwlist[] = {"cmp", "key", "reverse", 0};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001987
Tim Petersa64dc242002-08-01 02:13:36 +00001988 assert(self != NULL);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001989 assert (PyList_Check(self));
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001990 if (args != NULL) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001991 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:sort",
1992 kwlist, &compare, &keyfunc, &reverse))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001993 return NULL;
1994 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001995 if (is_default_cmp(compare))
Skip Montanaro4abd5f02003-01-02 20:51:08 +00001996 compare = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001997 if (keyfunc == Py_None)
1998 keyfunc = NULL;
1999 if (compare != NULL && keyfunc != NULL) {
2000 compare = build_cmpwrapper(compare);
2001 if (compare == NULL)
Hye-Shik Chang19cb1932003-12-10 07:31:08 +00002002 return NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002003 } else
2004 Py_XINCREF(compare);
2005
Tim Petersb9099c32002-11-12 22:08:10 +00002006 /* The list is temporarily made empty, so that mutations performed
2007 * by comparison functions can't affect the slice of memory we're
2008 * sorting (allowing mutations during sorting is a core-dump
2009 * factory, since ob_item may change).
2010 */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002011 saved_ob_size = Py_Size(self);
Tim Petersb9099c32002-11-12 22:08:10 +00002012 saved_ob_item = self->ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002013 saved_allocated = self->allocated;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002014 Py_Size(self) = 0;
Tim Peters51b4ade2004-07-29 04:07:15 +00002015 self->ob_item = NULL;
Armin Rigo93677f02004-07-29 12:40:23 +00002016 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00002017
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002018 if (keyfunc != NULL) {
2019 for (i=0 ; i < saved_ob_size ; i++) {
2020 value = saved_ob_item[i];
Tim Petersb38e2b62004-07-29 02:29:26 +00002021 key = PyObject_CallFunctionObjArgs(keyfunc, value,
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002022 NULL);
2023 if (key == NULL) {
2024 for (i=i-1 ; i>=0 ; i--) {
2025 kvpair = saved_ob_item[i];
2026 value = sortwrapper_getvalue(kvpair);
2027 saved_ob_item[i] = value;
2028 Py_DECREF(kvpair);
2029 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002030 goto dsu_fail;
2031 }
2032 kvpair = build_sortwrapper(key, value);
2033 if (kvpair == NULL)
2034 goto dsu_fail;
2035 saved_ob_item[i] = kvpair;
2036 }
2037 }
2038
2039 /* Reverse sort stability achieved by initially reversing the list,
2040 applying a stable forward sort, then reversing the final result. */
2041 if (reverse && saved_ob_size > 1)
2042 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2043
2044 merge_init(&ms, compare);
2045
Tim Petersb9099c32002-11-12 22:08:10 +00002046 nremaining = saved_ob_size;
Tim Petersa64dc242002-08-01 02:13:36 +00002047 if (nremaining < 2)
2048 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00002049
Tim Petersa64dc242002-08-01 02:13:36 +00002050 /* March over the array once, left to right, finding natural runs,
2051 * and extending short natural runs to minrun elements.
2052 */
Tim Petersb9099c32002-11-12 22:08:10 +00002053 lo = saved_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00002054 hi = lo + nremaining;
2055 minrun = merge_compute_minrun(nremaining);
2056 do {
2057 int descending;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002058 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00002059
Tim Petersa64dc242002-08-01 02:13:36 +00002060 /* Identify next run. */
2061 n = count_run(lo, hi, compare, &descending);
2062 if (n < 0)
2063 goto fail;
2064 if (descending)
2065 reverse_slice(lo, lo + n);
2066 /* If short, extend to min(minrun, nremaining). */
2067 if (n < minrun) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002068 const Py_ssize_t force = nremaining <= minrun ?
Tim Petersa64dc242002-08-01 02:13:36 +00002069 nremaining : minrun;
2070 if (binarysort(lo, lo + force, lo + n, compare) < 0)
2071 goto fail;
2072 n = force;
2073 }
2074 /* Push run onto pending-runs stack, and maybe merge. */
2075 assert(ms.n < MAX_MERGE_PENDING);
Tim Peterse05f65a2002-08-10 05:21:15 +00002076 ms.pending[ms.n].base = lo;
2077 ms.pending[ms.n].len = n;
Tim Petersa64dc242002-08-01 02:13:36 +00002078 ++ms.n;
2079 if (merge_collapse(&ms) < 0)
2080 goto fail;
2081 /* Advance to find next run. */
2082 lo += n;
2083 nremaining -= n;
2084 } while (nremaining);
2085 assert(lo == hi);
Tim Peters330f9e92002-07-19 07:05:44 +00002086
Tim Petersa64dc242002-08-01 02:13:36 +00002087 if (merge_force_collapse(&ms) < 0)
2088 goto fail;
2089 assert(ms.n == 1);
Tim Petersb9099c32002-11-12 22:08:10 +00002090 assert(ms.pending[0].base == saved_ob_item);
2091 assert(ms.pending[0].len == saved_ob_size);
Tim Petersa64dc242002-08-01 02:13:36 +00002092
2093succeed:
2094 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002095fail:
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002096 if (keyfunc != NULL) {
2097 for (i=0 ; i < saved_ob_size ; i++) {
2098 kvpair = saved_ob_item[i];
2099 value = sortwrapper_getvalue(kvpair);
2100 saved_ob_item[i] = value;
2101 Py_DECREF(kvpair);
2102 }
2103 }
2104
Armin Rigo93677f02004-07-29 12:40:23 +00002105 if (self->allocated != -1 && result != NULL) {
Tim Peters51b4ade2004-07-29 04:07:15 +00002106 /* The user mucked with the list during the sort,
2107 * and we don't already have another error to report.
2108 */
2109 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2110 result = NULL;
Tim Petersb9099c32002-11-12 22:08:10 +00002111 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002112
2113 if (reverse && saved_ob_size > 1)
2114 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2115
2116 merge_freemem(&ms);
2117
2118dsu_fail:
Armin Rigo93677f02004-07-29 12:40:23 +00002119 final_ob_item = self->ob_item;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002120 i = Py_Size(self);
2121 Py_Size(self) = saved_ob_size;
Tim Petersb9099c32002-11-12 22:08:10 +00002122 self->ob_item = saved_ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002123 self->allocated = saved_allocated;
Armin Rigo93677f02004-07-29 12:40:23 +00002124 if (final_ob_item != NULL) {
2125 /* we cannot use list_clear() for this because it does not
2126 guarantee that the list is really empty when it returns */
2127 while (--i >= 0) {
2128 Py_XDECREF(final_ob_item[i]);
2129 }
2130 PyMem_FREE(final_ob_item);
2131 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002132 Py_XDECREF(compare);
Tim Petersa64dc242002-08-01 02:13:36 +00002133 Py_XINCREF(result);
2134 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002135}
Tim Peters330f9e92002-07-19 07:05:44 +00002136#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002137#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002138
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002139int
Fred Drakea2f55112000-07-09 15:16:51 +00002140PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002141{
2142 if (v == NULL || !PyList_Check(v)) {
2143 PyErr_BadInternalCall();
2144 return -1;
2145 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002146 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002147 if (v == NULL)
2148 return -1;
2149 Py_DECREF(v);
2150 return 0;
2151}
2152
Guido van Rossumb86c5492001-02-12 22:06:02 +00002153static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002154listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002155{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002156 if (Py_Size(self) > 1)
2157 reverse_slice(self->ob_item, self->ob_item + Py_Size(self));
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002158 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002159}
2160
Guido van Rossum84c76f51990-10-30 13:32:20 +00002161int
Fred Drakea2f55112000-07-09 15:16:51 +00002162PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002163{
Tim Peters6063e262002-08-08 01:06:39 +00002164 PyListObject *self = (PyListObject *)v;
2165
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002166 if (v == NULL || !PyList_Check(v)) {
2167 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002168 return -1;
2169 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002170 if (Py_Size(self) > 1)
2171 reverse_slice(self->ob_item, self->ob_item + Py_Size(self));
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002172 return 0;
2173}
2174
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002175PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002176PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002177{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002178 PyObject *w;
2179 PyObject **p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002180 Py_ssize_t n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002181 if (v == NULL || !PyList_Check(v)) {
2182 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002183 return NULL;
2184 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002185 n = Py_Size(v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002186 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002187 if (w == NULL)
2188 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002189 p = ((PyTupleObject *)w)->ob_item;
Thomas Wouters334fb892000-07-25 12:56:38 +00002190 memcpy((void *)p,
2191 (void *)((PyListObject *)v)->ob_item,
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002192 n*sizeof(PyObject *));
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002193 while (--n >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002194 Py_INCREF(*p);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002195 p++;
2196 }
2197 return w;
2198}
2199
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002200static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002201listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002202{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002203 Py_ssize_t i, start=0, stop=Py_Size(self);
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002204 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002205
Walter Dörwalde8049bef2003-06-17 19:27:39 +00002206 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2207 _PyEval_SliceIndex, &start,
2208 _PyEval_SliceIndex, &stop))
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002209 return NULL;
Guido van Rossum2743d872003-06-17 14:25:14 +00002210 if (start < 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002211 start += Py_Size(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002212 if (start < 0)
2213 start = 0;
2214 }
2215 if (stop < 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002216 stop += Py_Size(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002217 if (stop < 0)
2218 stop = 0;
2219 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002220 for (i = start; i < stop && i < Py_Size(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002221 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2222 if (cmp > 0)
Martin v. Löwis18e16552006-02-15 17:27:45 +00002223 return PyInt_FromSsize_t(i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002224 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002225 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002226 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002227 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002228 return NULL;
2229}
2230
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002231static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002232listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002233{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002234 Py_ssize_t count = 0;
2235 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002236
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002237 for (i = 0; i < Py_Size(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002238 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2239 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002240 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002241 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002242 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00002243 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002244 return PyInt_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002245}
2246
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002247static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002248listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002249{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002250 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002251
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002252 for (i = 0; i < Py_Size(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002253 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2254 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002255 if (list_ass_slice(self, i, i+1,
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002256 (PyObject *)NULL) == 0)
2257 Py_RETURN_NONE;
2258 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002259 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002260 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002261 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002262 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002263 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002264 return NULL;
2265}
2266
Jeremy Hylton8caad492000-06-23 14:18:11 +00002267static int
2268list_traverse(PyListObject *o, visitproc visit, void *arg)
2269{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002270 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002271
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002272 for (i = Py_Size(o); --i >= 0; )
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002273 Py_VISIT(o->ob_item[i]);
Jeremy Hylton8caad492000-06-23 14:18:11 +00002274 return 0;
2275}
2276
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002277static PyObject *
2278list_richcompare(PyObject *v, PyObject *w, int op)
2279{
2280 PyListObject *vl, *wl;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002281 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002282
2283 if (!PyList_Check(v) || !PyList_Check(w)) {
2284 Py_INCREF(Py_NotImplemented);
2285 return Py_NotImplemented;
2286 }
2287
2288 vl = (PyListObject *)v;
2289 wl = (PyListObject *)w;
2290
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002291 if (Py_Size(vl) != Py_Size(wl) && (op == Py_EQ || op == Py_NE)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002292 /* Shortcut: if the lengths differ, the lists differ */
2293 PyObject *res;
2294 if (op == Py_EQ)
2295 res = Py_False;
2296 else
2297 res = Py_True;
2298 Py_INCREF(res);
2299 return res;
2300 }
2301
2302 /* Search for the first index where items are different */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002303 for (i = 0; i < Py_Size(vl) && i < Py_Size(wl); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002304 int k = PyObject_RichCompareBool(vl->ob_item[i],
2305 wl->ob_item[i], Py_EQ);
2306 if (k < 0)
2307 return NULL;
2308 if (!k)
2309 break;
2310 }
2311
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002312 if (i >= Py_Size(vl) || i >= Py_Size(wl)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002313 /* No more items to compare -- compare sizes */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002314 Py_ssize_t vs = Py_Size(vl);
2315 Py_ssize_t ws = Py_Size(wl);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002316 int cmp;
2317 PyObject *res;
2318 switch (op) {
2319 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00002320 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002321 case Py_EQ: cmp = vs == ws; break;
2322 case Py_NE: cmp = vs != ws; break;
2323 case Py_GT: cmp = vs > ws; break;
2324 case Py_GE: cmp = vs >= ws; break;
2325 default: return NULL; /* cannot happen */
2326 }
2327 if (cmp)
2328 res = Py_True;
2329 else
2330 res = Py_False;
2331 Py_INCREF(res);
2332 return res;
2333 }
2334
2335 /* We have an item that differs -- shortcuts for EQ/NE */
2336 if (op == Py_EQ) {
2337 Py_INCREF(Py_False);
2338 return Py_False;
2339 }
2340 if (op == Py_NE) {
2341 Py_INCREF(Py_True);
2342 return Py_True;
2343 }
2344
2345 /* Compare the final item again using the proper operator */
2346 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
2347}
2348
Tim Peters6d6c1a32001-08-02 04:15:00 +00002349static int
2350list_init(PyListObject *self, PyObject *args, PyObject *kw)
2351{
2352 PyObject *arg = NULL;
Martin v. Löwis15e62742006-02-27 16:46:16 +00002353 static char *kwlist[] = {"sequence", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002354
2355 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2356 return -1;
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002357
2358 /* Verify list invariants established by PyType_GenericAlloc() */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002359 assert(0 <= Py_Size(self));
2360 assert(Py_Size(self) <= self->allocated || self->allocated == -1);
Armin Rigoa37bbf22004-07-30 11:20:18 +00002361 assert(self->ob_item != NULL ||
2362 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002363
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002364 /* Empty previous contents */
Armin Rigo93677f02004-07-29 12:40:23 +00002365 if (self->ob_item != NULL) {
2366 (void)list_clear(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002367 }
2368 if (arg != NULL) {
2369 PyObject *rv = listextend(self, arg);
2370 if (rv == NULL)
2371 return -1;
2372 Py_DECREF(rv);
2373 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002374 return 0;
2375}
2376
Raymond Hettinger1021c442003-11-07 15:38:09 +00002377static PyObject *list_iter(PyObject *seq);
2378static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2379
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002380PyDoc_STRVAR(getitem_doc,
2381"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002382PyDoc_STRVAR(reversed_doc,
2383"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002384PyDoc_STRVAR(append_doc,
2385"L.append(object) -- append object to end");
2386PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002387"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002388PyDoc_STRVAR(insert_doc,
2389"L.insert(index, object) -- insert object before index");
2390PyDoc_STRVAR(pop_doc,
2391"L.pop([index]) -> item -- remove and return item at index (default last)");
2392PyDoc_STRVAR(remove_doc,
2393"L.remove(value) -- remove first occurrence of value");
2394PyDoc_STRVAR(index_doc,
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002395"L.index(value, [start, [stop]]) -> integer -- return first index of value");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002396PyDoc_STRVAR(count_doc,
2397"L.count(value) -> integer -- return number of occurrences of value");
2398PyDoc_STRVAR(reverse_doc,
2399"L.reverse() -- reverse *IN PLACE*");
2400PyDoc_STRVAR(sort_doc,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002401"L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n\
2402cmp(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002403
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002404static PyObject *list_subscript(PyListObject*, PyObject*);
2405
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002406static PyMethodDef list_methods[] = {
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002407 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
Raymond Hettinger1021c442003-11-07 15:38:09 +00002408 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002409 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002410 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002411 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002412 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002413 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002414 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002415 {"count", (PyCFunction)listcount, METH_O, count_doc},
2416 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002417 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
Tim Petersa64dc242002-08-01 02:13:36 +00002418 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002419};
2420
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002421static PySequenceMethods list_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002422 (lenfunc)list_length, /* sq_length */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002423 (binaryfunc)list_concat, /* sq_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002424 (ssizeargfunc)list_repeat, /* sq_repeat */
2425 (ssizeargfunc)list_item, /* sq_item */
2426 (ssizessizeargfunc)list_slice, /* sq_slice */
2427 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
2428 (ssizessizeobjargproc)list_ass_slice, /* sq_ass_slice */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002429 (objobjproc)list_contains, /* sq_contains */
2430 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002431 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002432};
2433
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002434PyDoc_STRVAR(list_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002435"list() -> new list\n"
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002436"list(sequence) -> new list initialized from sequence's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002437
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002438static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002439list_subscript(PyListObject* self, PyObject* item)
2440{
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002441 if (PyIndex_Check(item)) {
2442 Py_ssize_t i;
2443 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002444 if (i == -1 && PyErr_Occurred())
2445 return NULL;
2446 if (i < 0)
2447 i += PyList_GET_SIZE(self);
2448 return list_item(self, i);
2449 }
2450 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002451 Py_ssize_t start, stop, step, slicelength, cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002452 PyObject* result;
2453 PyObject* it;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002454 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002455
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002456 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_Size(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002457 &start, &stop, &step, &slicelength) < 0) {
2458 return NULL;
2459 }
2460
2461 if (slicelength <= 0) {
2462 return PyList_New(0);
2463 }
Thomas Woutersed03b412007-08-28 21:37:11 +00002464 else if (step == 1) {
2465 return list_slice(self, start, stop);
2466 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002467 else {
2468 result = PyList_New(slicelength);
2469 if (!result) return NULL;
2470
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002471 src = self->ob_item;
2472 dest = ((PyListObject *)result)->ob_item;
Tim Peters3b01a122002-07-19 02:35:45 +00002473 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002474 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002475 it = src[cur];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002476 Py_INCREF(it);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002477 dest[i] = it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002478 }
Tim Peters3b01a122002-07-19 02:35:45 +00002479
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002480 return result;
2481 }
2482 }
2483 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 NULL;
2488 }
2489}
2490
Tim Peters3b01a122002-07-19 02:35:45 +00002491static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002492list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2493{
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002494 if (PyIndex_Check(item)) {
2495 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002496 if (i == -1 && PyErr_Occurred())
2497 return -1;
2498 if (i < 0)
2499 i += PyList_GET_SIZE(self);
2500 return list_ass_item(self, i, value);
2501 }
2502 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002503 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002504
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002505 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_Size(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002506 &start, &stop, &step, &slicelength) < 0) {
2507 return -1;
2508 }
2509
Thomas Woutersed03b412007-08-28 21:37:11 +00002510 if (step == 1)
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002511 return list_ass_slice(self, start, stop, value);
2512
Thomas Woutersed03b412007-08-28 21:37:11 +00002513 /* Make sure s[5:2] = [..] inserts at the right place:
2514 before 5, not before 2. */
2515 if ((step < 0 && start < stop) ||
2516 (step > 0 && start > stop))
2517 stop = start;
2518
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002519 if (value == NULL) {
2520 /* delete slice */
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002521 PyObject **garbage;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002522 Py_ssize_t cur, i;
Tim Peters3b01a122002-07-19 02:35:45 +00002523
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002524 if (slicelength <= 0)
2525 return 0;
2526
2527 if (step < 0) {
2528 stop = start + 1;
2529 start = stop + step*(slicelength - 1) - 1;
2530 step = -step;
2531 }
2532
2533 garbage = (PyObject**)
2534 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002535 if (!garbage) {
2536 PyErr_NoMemory();
2537 return -1;
2538 }
Tim Peters3b01a122002-07-19 02:35:45 +00002539
Thomas Woutersed03b412007-08-28 21:37:11 +00002540 /* drawing pictures might help understand these for
2541 loops. Basically, we memmove the parts of the
2542 list that are *not* part of the slice: step-1
2543 items for each item that is part of the slice,
2544 and then tail end of the list that was not
2545 covered by the slice */
Guido van Rossum75a20b12002-06-11 12:22:28 +00002546 for (cur = start, i = 0;
2547 cur < stop;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002548 cur += step, i++) {
Thomas Woutersed03b412007-08-28 21:37:11 +00002549 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002550
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002551 garbage[i] = PyList_GET_ITEM(self, cur);
2552
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002553 if (cur + step >= Py_Size(self)) {
2554 lim = Py_Size(self) - cur - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002555 }
2556
Tim Petersb38e2b62004-07-29 02:29:26 +00002557 memmove(self->ob_item + cur - i,
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002558 self->ob_item + cur + 1,
2559 lim * sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002560 }
Thomas Woutersed03b412007-08-28 21:37:11 +00002561 cur = start + slicelength*step;
2562 if (cur < Py_Size(self)) {
2563 memmove(self->ob_item + cur - slicelength,
2564 self->ob_item + cur,
2565 (Py_Size(self) - cur) *
2566 sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002567 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002568
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002569 Py_Size(self) -= slicelength;
2570 list_resize(self, Py_Size(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002571
2572 for (i = 0; i < slicelength; i++) {
2573 Py_DECREF(garbage[i]);
2574 }
2575 PyMem_FREE(garbage);
2576
2577 return 0;
2578 }
2579 else {
2580 /* assign slice */
Thomas Woutersed03b412007-08-28 21:37:11 +00002581 PyObject *ins, *seq;
2582 PyObject **garbage, **seqitems, **selfitems;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002583 Py_ssize_t cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002584
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002585 /* protect against a[::-1] = a */
Tim Peters3b01a122002-07-19 02:35:45 +00002586 if (self == (PyListObject*)value) {
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002587 seq = list_slice((PyListObject*)value, 0,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002588 PyList_GET_SIZE(value));
Tim Peters3b01a122002-07-19 02:35:45 +00002589 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002590 else {
Tim Petersb38e2b62004-07-29 02:29:26 +00002591 seq = PySequence_Fast(value,
Thomas Woutersed03b412007-08-28 21:37:11 +00002592 "must assign iterable "
2593 "to extended slice");
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002594 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002595 if (!seq)
2596 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002597
2598 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2599 PyErr_Format(PyExc_ValueError,
Thomas Woutersed03b412007-08-28 21:37:11 +00002600 "attempt to assign sequence of "
2601 "size %zd to extended slice of "
2602 "size %zd",
Martin v. Löwise0e89f72006-02-16 06:59:22 +00002603 PySequence_Fast_GET_SIZE(seq),
2604 slicelength);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002605 Py_DECREF(seq);
2606 return -1;
2607 }
2608
2609 if (!slicelength) {
2610 Py_DECREF(seq);
2611 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002612 }
2613
2614 garbage = (PyObject**)
2615 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Thomas Wouters89f507f2006-12-13 04:49:30 +00002616 if (!garbage) {
2617 Py_DECREF(seq);
2618 PyErr_NoMemory();
2619 return -1;
2620 }
Tim Peters3b01a122002-07-19 02:35:45 +00002621
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002622 selfitems = self->ob_item;
Raymond Hettinger42bec932004-03-12 16:38:17 +00002623 seqitems = PySequence_Fast_ITEMS(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002624 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002625 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002626 garbage[i] = selfitems[cur];
2627 ins = seqitems[i];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002628 Py_INCREF(ins);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002629 selfitems[cur] = ins;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002630 }
2631
2632 for (i = 0; i < slicelength; i++) {
2633 Py_DECREF(garbage[i]);
2634 }
Tim Peters3b01a122002-07-19 02:35:45 +00002635
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002636 PyMem_FREE(garbage);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002637 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002638
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002639 return 0;
2640 }
Tim Peters3b01a122002-07-19 02:35:45 +00002641 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002642 else {
Thomas Wouters89f507f2006-12-13 04:49:30 +00002643 PyErr_Format(PyExc_TypeError,
2644 "list indices must be integers, not %.200s",
2645 item->ob_type->tp_name);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002646 return -1;
2647 }
2648}
2649
2650static PyMappingMethods list_as_mapping = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002651 (lenfunc)list_length,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002652 (binaryfunc)list_subscript,
2653 (objobjargproc)list_ass_subscript
2654};
2655
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002656PyTypeObject PyList_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002657 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002658 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002659 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002660 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002661 (destructor)list_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00002662 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002663 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002664 0, /* tp_setattr */
2665 0, /* tp_compare */
2666 (reprfunc)list_repr, /* tp_repr */
2667 0, /* tp_as_number */
2668 &list_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002669 &list_as_mapping, /* tp_as_mapping */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00002670 0, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002671 0, /* tp_call */
2672 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002673 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002674 0, /* tp_setattro */
2675 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002676 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Thomas Wouters27d517b2007-02-25 20:39:11 +00002677 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002678 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002679 (traverseproc)list_traverse, /* tp_traverse */
2680 (inquiry)list_clear, /* tp_clear */
2681 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002682 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002683 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002684 0, /* tp_iternext */
2685 list_methods, /* tp_methods */
2686 0, /* tp_members */
2687 0, /* tp_getset */
2688 0, /* tp_base */
2689 0, /* tp_dict */
2690 0, /* tp_descr_get */
2691 0, /* tp_descr_set */
2692 0, /* tp_dictoffset */
2693 (initproc)list_init, /* tp_init */
2694 PyType_GenericAlloc, /* tp_alloc */
2695 PyType_GenericNew, /* tp_new */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002696 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002697};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002698
2699
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002700/*********************** List Iterator **************************/
2701
2702typedef struct {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002703 PyObject_HEAD
2704 long it_index;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002705 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002706} listiterobject;
2707
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002708static PyObject *list_iter(PyObject *);
2709static void listiter_dealloc(listiterobject *);
2710static int listiter_traverse(listiterobject *, visitproc, void *);
2711static PyObject *listiter_next(listiterobject *);
2712static PyObject *listiter_len(listiterobject *);
Raymond Hettinger435bf582004-03-18 22:43:10 +00002713
Armin Rigof5b3e362006-02-11 21:32:43 +00002714PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002715
2716static PyMethodDef listiter_methods[] = {
Armin Rigof5b3e362006-02-11 21:32:43 +00002717 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002718 {NULL, NULL} /* sentinel */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002719};
2720
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002721PyTypeObject PyListIter_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002722 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002723 "listiterator", /* tp_name */
2724 sizeof(listiterobject), /* tp_basicsize */
2725 0, /* tp_itemsize */
2726 /* methods */
2727 (destructor)listiter_dealloc, /* tp_dealloc */
2728 0, /* tp_print */
2729 0, /* tp_getattr */
2730 0, /* tp_setattr */
2731 0, /* tp_compare */
2732 0, /* tp_repr */
2733 0, /* tp_as_number */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002734 0, /* tp_as_sequence */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002735 0, /* tp_as_mapping */
2736 0, /* tp_hash */
2737 0, /* tp_call */
2738 0, /* tp_str */
2739 PyObject_GenericGetAttr, /* tp_getattro */
2740 0, /* tp_setattro */
2741 0, /* tp_as_buffer */
2742 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2743 0, /* tp_doc */
2744 (traverseproc)listiter_traverse, /* tp_traverse */
2745 0, /* tp_clear */
2746 0, /* tp_richcompare */
2747 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00002748 PyObject_SelfIter, /* tp_iter */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002749 (iternextfunc)listiter_next, /* tp_iternext */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002750 listiter_methods, /* tp_methods */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002751 0, /* tp_members */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002752};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002753
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002754
2755static PyObject *
2756list_iter(PyObject *seq)
2757{
2758 listiterobject *it;
2759
2760 if (!PyList_Check(seq)) {
2761 PyErr_BadInternalCall();
2762 return NULL;
2763 }
2764 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2765 if (it == NULL)
2766 return NULL;
2767 it->it_index = 0;
2768 Py_INCREF(seq);
2769 it->it_seq = (PyListObject *)seq;
2770 _PyObject_GC_TRACK(it);
2771 return (PyObject *)it;
2772}
2773
2774static void
2775listiter_dealloc(listiterobject *it)
2776{
2777 _PyObject_GC_UNTRACK(it);
2778 Py_XDECREF(it->it_seq);
2779 PyObject_GC_Del(it);
2780}
2781
2782static int
2783listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2784{
2785 Py_VISIT(it->it_seq);
2786 return 0;
2787}
2788
2789static PyObject *
2790listiter_next(listiterobject *it)
2791{
2792 PyListObject *seq;
2793 PyObject *item;
2794
2795 assert(it != NULL);
2796 seq = it->it_seq;
2797 if (seq == NULL)
2798 return NULL;
2799 assert(PyList_Check(seq));
2800
2801 if (it->it_index < PyList_GET_SIZE(seq)) {
2802 item = PyList_GET_ITEM(seq, it->it_index);
2803 ++it->it_index;
2804 Py_INCREF(item);
2805 return item;
2806 }
2807
2808 Py_DECREF(seq);
2809 it->it_seq = NULL;
2810 return NULL;
2811}
2812
2813static PyObject *
2814listiter_len(listiterobject *it)
2815{
2816 Py_ssize_t len;
2817 if (it->it_seq) {
2818 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2819 if (len >= 0)
2820 return PyInt_FromSsize_t(len);
2821 }
2822 return PyInt_FromLong(0);
2823}
Raymond Hettinger1021c442003-11-07 15:38:09 +00002824/*********************** List Reverse Iterator **************************/
2825
2826typedef struct {
2827 PyObject_HEAD
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002828 Py_ssize_t it_index;
Raymond Hettinger001f2282003-11-08 11:58:44 +00002829 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002830} listreviterobject;
2831
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002832static PyObject *list_reversed(PyListObject *, PyObject *);
2833static void listreviter_dealloc(listreviterobject *);
2834static int listreviter_traverse(listreviterobject *, visitproc, void *);
2835static PyObject *listreviter_next(listreviterobject *);
2836static Py_ssize_t listreviter_len(listreviterobject *);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002837
2838static PySequenceMethods listreviter_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002839 (lenfunc)listreviter_len, /* sq_length */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002840 0, /* sq_concat */
2841};
2842
Raymond Hettinger1021c442003-11-07 15:38:09 +00002843PyTypeObject PyListRevIter_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002844 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Raymond Hettinger1021c442003-11-07 15:38:09 +00002845 "listreverseiterator", /* tp_name */
2846 sizeof(listreviterobject), /* tp_basicsize */
2847 0, /* tp_itemsize */
2848 /* methods */
2849 (destructor)listreviter_dealloc, /* tp_dealloc */
2850 0, /* tp_print */
2851 0, /* tp_getattr */
2852 0, /* tp_setattr */
2853 0, /* tp_compare */
2854 0, /* tp_repr */
2855 0, /* tp_as_number */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002856 &listreviter_as_sequence, /* tp_as_sequence */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002857 0, /* tp_as_mapping */
2858 0, /* tp_hash */
2859 0, /* tp_call */
2860 0, /* tp_str */
2861 PyObject_GenericGetAttr, /* tp_getattro */
2862 0, /* tp_setattro */
2863 0, /* tp_as_buffer */
2864 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2865 0, /* tp_doc */
2866 (traverseproc)listreviter_traverse, /* tp_traverse */
2867 0, /* tp_clear */
2868 0, /* tp_richcompare */
2869 0, /* tp_weaklistoffset */
2870 PyObject_SelfIter, /* tp_iter */
2871 (iternextfunc)listreviter_next, /* tp_iternext */
2872 0,
2873};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002874
2875static PyObject *
2876list_reversed(PyListObject *seq, PyObject *unused)
2877{
2878 listreviterobject *it;
2879
2880 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2881 if (it == NULL)
2882 return NULL;
2883 assert(PyList_Check(seq));
2884 it->it_index = PyList_GET_SIZE(seq) - 1;
2885 Py_INCREF(seq);
2886 it->it_seq = seq;
2887 PyObject_GC_Track(it);
2888 return (PyObject *)it;
2889}
2890
2891static void
2892listreviter_dealloc(listreviterobject *it)
2893{
2894 PyObject_GC_UnTrack(it);
2895 Py_XDECREF(it->it_seq);
2896 PyObject_GC_Del(it);
2897}
2898
2899static int
2900listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2901{
2902 Py_VISIT(it->it_seq);
2903 return 0;
2904}
2905
2906static PyObject *
2907listreviter_next(listreviterobject *it)
2908{
2909 PyObject *item;
2910 Py_ssize_t index = it->it_index;
2911 PyListObject *seq = it->it_seq;
2912
2913 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2914 item = PyList_GET_ITEM(seq, index);
2915 it->it_index--;
2916 Py_INCREF(item);
2917 return item;
2918 }
2919 it->it_index = -1;
2920 if (seq != NULL) {
2921 it->it_seq = NULL;
2922 Py_DECREF(seq);
2923 }
2924 return NULL;
2925}
2926
2927static Py_ssize_t
2928listreviter_len(listreviterobject *it)
2929{
2930 Py_ssize_t len = it->it_index + 1;
2931 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
2932 return 0;
2933 return len;
2934}
2935