blob: 5df40fa9ee5db7c604fee38e322b9a4652aa5382 [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;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000300 if (Py_EnterRecursiveCall(" while getting the repr of a list"))
301 goto Done;
Tim Petersa7259592001-06-16 05:11:17 +0000302 s = PyObject_Repr(v->ob_item[i]);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000303 Py_LeaveRecursiveCall();
Tim Petersa7259592001-06-16 05:11:17 +0000304 if (s == NULL)
305 goto Done;
306 status = PyList_Append(pieces, s);
307 Py_DECREF(s); /* append created a new ref */
308 if (status < 0)
309 goto Done;
310 }
311
312 /* Add "[]" decorations to the first and last items. */
313 assert(PyList_GET_SIZE(pieces) > 0);
Walter Dörwald1ab83302007-05-18 17:15:44 +0000314 s = PyUnicode_FromString("[");
Tim Petersa7259592001-06-16 05:11:17 +0000315 if (s == NULL)
316 goto Done;
317 temp = PyList_GET_ITEM(pieces, 0);
Walter Dörwald1ab83302007-05-18 17:15:44 +0000318 PyUnicode_AppendAndDel(&s, temp);
Tim Petersa7259592001-06-16 05:11:17 +0000319 PyList_SET_ITEM(pieces, 0, s);
320 if (s == NULL)
321 goto Done;
322
Walter Dörwald1ab83302007-05-18 17:15:44 +0000323 s = PyUnicode_FromString("]");
Tim Petersa7259592001-06-16 05:11:17 +0000324 if (s == NULL)
325 goto Done;
326 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
Walter Dörwald1ab83302007-05-18 17:15:44 +0000327 PyUnicode_AppendAndDel(&temp, s);
Tim Petersa7259592001-06-16 05:11:17 +0000328 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
329 if (temp == NULL)
330 goto Done;
331
332 /* Paste them all together with ", " between. */
Walter Dörwald1ab83302007-05-18 17:15:44 +0000333 s = PyUnicode_FromString(", ");
Tim Petersa7259592001-06-16 05:11:17 +0000334 if (s == NULL)
335 goto Done;
Walter Dörwald1ab83302007-05-18 17:15:44 +0000336 result = PyUnicode_Join(s, pieces);
Tim Peters3b01a122002-07-19 02:35:45 +0000337 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +0000338
339Done:
340 Py_XDECREF(pieces);
Guido van Rossumfb376de1998-04-10 22:47:27 +0000341 Py_ReprLeave((PyObject *)v);
Tim Petersa7259592001-06-16 05:11:17 +0000342 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000343}
344
Martin v. Löwis18e16552006-02-15 17:27:45 +0000345static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000346list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000347{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000348 return Py_Size(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000349}
350
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000351static int
Fred Drakea2f55112000-07-09 15:16:51 +0000352list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000353{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000354 Py_ssize_t i;
355 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000356
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000357 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_Size(a); ++i)
Raymond Hettingeraae59992002-09-05 14:23:49 +0000358 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000359 Py_EQ);
Neal Norwitzbb9c5f52002-09-05 21:32:55 +0000360 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000361}
362
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000363static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000364list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000365{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000366 if (i < 0 || i >= Py_Size(a)) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000367 if (indexerr == NULL)
Neal Norwitz53cbdaa2007-08-23 21:42:55 +0000368 indexerr = PyUnicode_FromString(
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000369 "list index out of range");
370 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000371 return NULL;
372 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000373 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000374 return a->ob_item[i];
375}
376
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000377static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000378list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000379{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000380 PyListObject *np;
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000381 PyObject **src, **dest;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000382 Py_ssize_t i, len;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000383 if (ilow < 0)
384 ilow = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000385 else if (ilow > Py_Size(a))
386 ilow = Py_Size(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000387 if (ihigh < ilow)
388 ihigh = ilow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000389 else if (ihigh > Py_Size(a))
390 ihigh = Py_Size(a);
Raymond Hettinger99842b62004-03-08 05:56:15 +0000391 len = ihigh - ilow;
392 np = (PyListObject *) PyList_New(len);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000393 if (np == NULL)
394 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000395
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000396 src = a->ob_item + ilow;
397 dest = np->ob_item;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000398 for (i = 0; i < len; i++) {
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000399 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000400 Py_INCREF(v);
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000401 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000402 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000403 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000404}
405
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000406PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000407PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000408{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000409 if (!PyList_Check(a)) {
410 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000411 return NULL;
412 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000413 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000414}
415
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000416static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000417list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000418{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000419 Py_ssize_t size;
420 Py_ssize_t i;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000421 PyObject **src, **dest;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000422 PyListObject *np;
423 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000424 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000425 "can only concatenate list (not \"%.200s\") to list",
426 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000427 return NULL;
428 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000429#define b ((PyListObject *)bb)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000430 size = Py_Size(a) + Py_Size(b);
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000431 if (size < 0)
432 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000433 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000434 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000435 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000436 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000437 src = a->ob_item;
438 dest = np->ob_item;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000439 for (i = 0; i < Py_Size(a); i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000440 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000441 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000442 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000443 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000444 src = b->ob_item;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000445 dest = np->ob_item + Py_Size(a);
446 for (i = 0; i < Py_Size(b); i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000447 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000448 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000449 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000450 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000451 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000452#undef b
453}
454
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000455static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000456list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000457{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000458 Py_ssize_t i, j;
459 Py_ssize_t size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000460 PyListObject *np;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000461 PyObject **p, **items;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000462 PyObject *elem;
Guido van Rossumed98d481991-03-06 13:07:53 +0000463 if (n < 0)
464 n = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000465 size = Py_Size(a) * n;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000466 if (n && size/n != Py_Size(a))
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000467 return PyErr_NoMemory();
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000468 if (size == 0)
469 return PyList_New(0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000470 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000471 if (np == NULL)
472 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000473
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000474 items = np->ob_item;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000475 if (Py_Size(a) == 1) {
Raymond Hettinger6624e682003-05-21 05:58:46 +0000476 elem = a->ob_item[0];
477 for (i = 0; i < n; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000478 items[i] = elem;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000479 Py_INCREF(elem);
480 }
481 return (PyObject *) np;
482 }
Guido van Rossumed98d481991-03-06 13:07:53 +0000483 p = np->ob_item;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000484 items = a->ob_item;
Guido van Rossumed98d481991-03-06 13:07:53 +0000485 for (i = 0; i < n; i++) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000486 for (j = 0; j < Py_Size(a); j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000487 *p = items[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000488 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000489 p++;
490 }
491 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000492 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000493}
494
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000495static int
Armin Rigo93677f02004-07-29 12:40:23 +0000496list_clear(PyListObject *a)
497{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000498 Py_ssize_t i;
Armin Rigo93677f02004-07-29 12:40:23 +0000499 PyObject **item = a->ob_item;
500 if (item != NULL) {
501 /* Because XDECREF can recursively invoke operations on
502 this list, we make it empty first. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000503 i = Py_Size(a);
504 Py_Size(a) = 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000505 a->ob_item = NULL;
506 a->allocated = 0;
507 while (--i >= 0) {
508 Py_XDECREF(item[i]);
509 }
510 PyMem_FREE(item);
511 }
512 /* Never fails; the return value can be ignored.
513 Note that there is no guarantee that the list is actually empty
514 at this point, because XDECREF may have populated it again! */
515 return 0;
516}
517
Tim Peters8fc4a912004-07-31 21:53:19 +0000518/* a[ilow:ihigh] = v if v != NULL.
519 * del a[ilow:ihigh] if v == NULL.
520 *
521 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
522 * guaranteed the call cannot fail.
523 */
Armin Rigo93677f02004-07-29 12:40:23 +0000524static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000525list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000526{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000527 /* Because [X]DECREF can recursively invoke list operations on
528 this list, we must postpone all [X]DECREF activity until
529 after the list is back in its canonical shape. Therefore
530 we must allocate an additional array, 'recycle', into which
531 we temporarily copy the items that are deleted from the
532 list. :-( */
Tim Peters73572222004-07-31 02:54:42 +0000533 PyObject *recycle_on_stack[8];
534 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000535 PyObject **item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000536 PyObject **vitem = NULL;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000537 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000538 Py_ssize_t n; /* # of elements in replacement list */
539 Py_ssize_t norig; /* # of elements in list getting replaced */
540 Py_ssize_t d; /* Change in size */
541 Py_ssize_t k;
Tim Peters8d9eb102004-07-31 02:24:20 +0000542 size_t s;
543 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000544#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000545 if (v == NULL)
546 n = 0;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000547 else {
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000548 if (a == b) {
549 /* Special case "a[i:j] = a" -- copy b first */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000550 v = list_slice(b, 0, Py_Size(b));
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000551 if (v == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000552 return result;
553 result = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000554 Py_DECREF(v);
Tim Peters8d9eb102004-07-31 02:24:20 +0000555 return result;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000556 }
Raymond Hettingerf889e102004-03-09 08:04:33 +0000557 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000558 if(v_as_SF == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000559 goto Error;
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000560 n = PySequence_Fast_GET_SIZE(v_as_SF);
Raymond Hettinger42bec932004-03-12 16:38:17 +0000561 vitem = PySequence_Fast_ITEMS(v_as_SF);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000562 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000563 if (ilow < 0)
564 ilow = 0;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000565 else if (ilow > Py_Size(a))
566 ilow = Py_Size(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000567
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000568 if (ihigh < ilow)
569 ihigh = ilow;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000570 else if (ihigh > Py_Size(a))
571 ihigh = Py_Size(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000572
Tim Peters8d9eb102004-07-31 02:24:20 +0000573 norig = ihigh - ilow;
574 assert(norig >= 0);
575 d = n - norig;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000576 if (Py_Size(a) + d == 0) {
Armin Rigo93677f02004-07-29 12:40:23 +0000577 Py_XDECREF(v_as_SF);
578 return list_clear(a);
579 }
580 item = a->ob_item;
Tim Peters8d9eb102004-07-31 02:24:20 +0000581 /* recycle the items that we are about to remove */
582 s = norig * sizeof(PyObject *);
Tim Peters73572222004-07-31 02:54:42 +0000583 if (s > sizeof(recycle_on_stack)) {
Armin Rigo1dd04a02004-07-30 11:38:22 +0000584 recycle = (PyObject **)PyMem_MALLOC(s);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000585 if (recycle == NULL) {
586 PyErr_NoMemory();
Tim Peters8d9eb102004-07-31 02:24:20 +0000587 goto Error;
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000588 }
589 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000590 memcpy(recycle, &item[ilow], s);
Tim Peters8d9eb102004-07-31 02:24:20 +0000591
Armin Rigo1dd04a02004-07-30 11:38:22 +0000592 if (d < 0) { /* Delete -d items */
593 memmove(&item[ihigh+d], &item[ihigh],
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000594 (Py_Size(a) - ihigh)*sizeof(PyObject *));
595 list_resize(a, Py_Size(a) + d);
Armin Rigo1dd04a02004-07-30 11:38:22 +0000596 item = a->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000597 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000598 else if (d > 0) { /* Insert d items */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000599 k = Py_Size(a);
Tim Peters73572222004-07-31 02:54:42 +0000600 if (list_resize(a, k+d) < 0)
Tim Peters8d9eb102004-07-31 02:24:20 +0000601 goto Error;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000602 item = a->ob_item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000603 memmove(&item[ihigh+d], &item[ihigh],
Tim Peters73572222004-07-31 02:54:42 +0000604 (k - ihigh)*sizeof(PyObject *));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000605 }
606 for (k = 0; k < n; k++, ilow++) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000607 PyObject *w = vitem[k];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000608 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000609 item[ilow] = w;
610 }
Tim Peters73572222004-07-31 02:54:42 +0000611 for (k = norig - 1; k >= 0; --k)
612 Py_XDECREF(recycle[k]);
Tim Peters8d9eb102004-07-31 02:24:20 +0000613 result = 0;
614 Error:
Tim Peters73572222004-07-31 02:54:42 +0000615 if (recycle != recycle_on_stack)
Armin Rigo1dd04a02004-07-30 11:38:22 +0000616 PyMem_FREE(recycle);
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000617 Py_XDECREF(v_as_SF);
Tim Peters8d9eb102004-07-31 02:24:20 +0000618 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000619#undef b
620}
621
Guido van Rossum234f9421993-06-17 12:35:49 +0000622int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000623PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000624{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000625 if (!PyList_Check(a)) {
626 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000627 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000628 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000629 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000630}
631
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000632static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000633list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000634{
635 PyObject **items;
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000636 Py_ssize_t size, i, j, p, newsize;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000637
638
639 size = PyList_GET_SIZE(self);
640 if (size == 0) {
641 Py_INCREF(self);
642 return (PyObject *)self;
643 }
644
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000645 if (n < 1) {
Armin Rigo93677f02004-07-29 12:40:23 +0000646 (void)list_clear(self);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000647 Py_INCREF(self);
648 return (PyObject *)self;
649 }
650
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000651 newsize = size * n;
652 if (newsize/n != size)
653 return PyErr_NoMemory();
654 if (list_resize(self, newsize) == -1)
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000655 return NULL;
656
657 p = size;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000658 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000659 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
660 for (j = 0; j < size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000661 PyObject *o = items[j];
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000662 Py_INCREF(o);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000663 items[p++] = o;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000664 }
665 }
666 Py_INCREF(self);
667 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000668}
669
Guido van Rossum4a450d01991-04-03 19:05:18 +0000670static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000671list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000672{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000673 PyObject *old_value;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000674 if (i < 0 || i >= Py_Size(a)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000675 PyErr_SetString(PyExc_IndexError,
676 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000677 return -1;
678 }
679 if (v == NULL)
680 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000681 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000682 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000683 a->ob_item[i] = v;
Tim Peters3b01a122002-07-19 02:35:45 +0000684 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000685 return 0;
686}
687
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000688static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000689listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000690{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000691 Py_ssize_t i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000692 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000693 if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000694 return NULL;
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000695 if (ins1(self, i, v) == 0)
696 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000697 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000698}
699
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000700static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000701listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000702{
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000703 if (app1(self, v) == 0)
704 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000705 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000706}
707
Barry Warsawdedf6d61998-10-09 16:37:25 +0000708static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000709listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000710{
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000711 PyObject *it; /* iter(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000712 Py_ssize_t m; /* size of self */
713 Py_ssize_t n; /* guess for size of b */
714 Py_ssize_t mn; /* m + n */
715 Py_ssize_t i;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000716 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000717
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000718 /* Special cases:
Tim Petersb38e2b62004-07-29 02:29:26 +0000719 1) lists and tuples which can use PySequence_Fast ops
720 2) extending self to self requires making a copy first
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000721 */
722 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
Armin Rigo70d172d2004-03-20 22:19:23 +0000723 PyObject **src, **dest;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000724 b = PySequence_Fast(b, "argument must be iterable");
725 if (!b)
726 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000727 n = PySequence_Fast_GET_SIZE(b);
728 if (n == 0) {
729 /* short circuit when b is empty */
730 Py_DECREF(b);
731 Py_RETURN_NONE;
732 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000733 m = Py_Size(self);
Armin Rigo70d172d2004-03-20 22:19:23 +0000734 if (list_resize(self, m + n) == -1) {
735 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000736 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000737 }
738 /* note that we may still have self == b here for the
739 * situation a.extend(a), but the following code works
740 * in that case too. Just make sure to resize self
741 * before calling PySequence_Fast_ITEMS.
742 */
743 /* populate the end of self with b's items */
744 src = PySequence_Fast_ITEMS(b);
745 dest = self->ob_item + m;
746 for (i = 0; i < n; i++) {
747 PyObject *o = src[i];
748 Py_INCREF(o);
749 dest[i] = o;
750 }
751 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000752 Py_RETURN_NONE;
753 }
754
755 it = PyObject_GetIter(b);
756 if (it == NULL)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000757 return NULL;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000758 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000759
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000760 /* Guess a result list size. */
Armin Rigof5b3e362006-02-11 21:32:43 +0000761 n = _PyObject_LengthHint(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000762 if (n < 0) {
Raymond Hettingera710b332005-08-21 11:03:59 +0000763 if (!PyErr_ExceptionMatches(PyExc_TypeError) &&
764 !PyErr_ExceptionMatches(PyExc_AttributeError)) {
765 Py_DECREF(it);
766 return NULL;
767 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000768 PyErr_Clear();
769 n = 8; /* arbitrary */
770 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000771 m = Py_Size(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000772 mn = m + n;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000773 if (mn >= m) {
774 /* Make room. */
775 if (list_resize(self, mn) == -1)
776 goto error;
777 /* Make the list sane again. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000778 Py_Size(self) = m;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000779 }
780 /* Else m + n overflowed; on the chance that n lied, and there really
781 * is enough room, ignore it. If n was telling the truth, we'll
782 * eventually run out of memory during the loop.
783 */
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000784
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000785 /* Run iterator to exhaustion. */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000786 for (;;) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000787 PyObject *item = iternext(it);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000788 if (item == NULL) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000789 if (PyErr_Occurred()) {
790 if (PyErr_ExceptionMatches(PyExc_StopIteration))
791 PyErr_Clear();
792 else
793 goto error;
794 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000795 break;
796 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000797 if (Py_Size(self) < self->allocated) {
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000798 /* steals ref */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000799 PyList_SET_ITEM(self, Py_Size(self), item);
800 ++Py_Size(self);
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000801 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000802 else {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000803 int status = app1(self, item);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000804 Py_DECREF(item); /* append creates a new ref */
805 if (status < 0)
806 goto error;
807 }
808 }
809
810 /* Cut back result list if initial guess was too large. */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000811 if (Py_Size(self) < self->allocated)
812 list_resize(self, Py_Size(self)); /* shrinking can't fail */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000813
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000814 Py_DECREF(it);
815 Py_RETURN_NONE;
816
817 error:
818 Py_DECREF(it);
819 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000820}
821
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000822PyObject *
823_PyList_Extend(PyListObject *self, PyObject *b)
824{
825 return listextend(self, b);
826}
827
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000828static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000829list_inplace_concat(PyListObject *self, PyObject *other)
830{
831 PyObject *result;
832
833 result = listextend(self, other);
834 if (result == NULL)
835 return result;
836 Py_DECREF(result);
837 Py_INCREF(self);
838 return (PyObject *)self;
839}
840
841static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000842listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000843{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000844 Py_ssize_t i = -1;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000845 PyObject *v;
Tim Peters8fc4a912004-07-31 21:53:19 +0000846 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000847
Thomas Wouters89f507f2006-12-13 04:49:30 +0000848 if (!PyArg_ParseTuple(args, "|n:pop", &i))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000849 return NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000850
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000851 if (Py_Size(self) == 0) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000852 /* Special-case most common failure cause */
853 PyErr_SetString(PyExc_IndexError, "pop from empty list");
854 return NULL;
855 }
856 if (i < 0)
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000857 i += Py_Size(self);
858 if (i < 0 || i >= Py_Size(self)) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000859 PyErr_SetString(PyExc_IndexError, "pop index out of range");
860 return NULL;
861 }
862 v = self->ob_item[i];
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000863 if (i == Py_Size(self) - 1) {
864 status = list_resize(self, Py_Size(self) - 1);
Tim Peters8fc4a912004-07-31 21:53:19 +0000865 assert(status >= 0);
866 return v; /* and v now owns the reference the list had */
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000867 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000868 Py_INCREF(v);
Tim Peters8fc4a912004-07-31 21:53:19 +0000869 status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
870 assert(status >= 0);
871 /* Use status, so that in a release build compilers don't
872 * complain about the unused name.
873 */
Brett Cannon651dd522004-08-08 21:21:18 +0000874 (void) status;
875
876 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000877}
878
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000879/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
880static void
881reverse_slice(PyObject **lo, PyObject **hi)
882{
883 assert(lo && hi);
884
885 --hi;
886 while (lo < hi) {
887 PyObject *t = *lo;
888 *lo = *hi;
889 *hi = t;
890 ++lo;
891 --hi;
892 }
893}
894
Tim Petersa64dc242002-08-01 02:13:36 +0000895/* Lots of code for an adaptive, stable, natural mergesort. There are many
896 * pieces to this algorithm; read listsort.txt for overviews and details.
897 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000898
Guido van Rossum3f236de1996-12-10 23:55:39 +0000899/* Comparison function. Takes care of calling a user-supplied
Tim Peters66860f62002-08-04 17:47:26 +0000900 * comparison function (any callable Python object), which must not be
901 * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool
902 * with Py_LT if you know it's NULL).
Tim Petersa64dc242002-08-01 02:13:36 +0000903 * Returns -1 on error, 1 if x < y, 0 if x >= y.
904 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000905static int
Tim Petersa8c974c2002-07-19 03:30:57 +0000906islt(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000907{
Tim Petersf2a04732002-07-11 21:46:16 +0000908 PyObject *res;
909 PyObject *args;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000910 Py_ssize_t i;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000911
Tim Peters66860f62002-08-04 17:47:26 +0000912 assert(compare != NULL);
Tim Petersa8c974c2002-07-19 03:30:57 +0000913 /* Call the user's comparison function and translate the 3-way
914 * result into true or false (or error).
915 */
Tim Petersf2a04732002-07-11 21:46:16 +0000916 args = PyTuple_New(2);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000917 if (args == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000918 return -1;
Tim Petersf2a04732002-07-11 21:46:16 +0000919 Py_INCREF(x);
920 Py_INCREF(y);
921 PyTuple_SET_ITEM(args, 0, x);
922 PyTuple_SET_ITEM(args, 1, y);
Tim Peters58cf3612002-07-15 05:16:13 +0000923 res = PyObject_Call(compare, args, NULL);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000924 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000925 if (res == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000926 return -1;
Guido van Rossumddefaf32007-01-14 03:31:43 +0000927 if (!PyInt_CheckExact(res)) {
Thomas Wouters89f507f2006-12-13 04:49:30 +0000928 PyErr_Format(PyExc_TypeError,
929 "comparison function must return int, not %.200s",
930 res->ob_type->tp_name);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000931 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +0000932 return -1;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000933 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000934 i = PyInt_AsLong(res);
935 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +0000936 return i < 0;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000937}
938
Tim Peters66860f62002-08-04 17:47:26 +0000939/* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
940 * islt. This avoids a layer of function call in the usual case, and
941 * sorting does many comparisons.
942 * Returns -1 on error, 1 if x < y, 0 if x >= y.
943 */
944#define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
945 PyObject_RichCompareBool(X, Y, Py_LT) : \
946 islt(X, Y, COMPARE))
947
948/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +0000949 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
950 started. It makes more sense in context <wink>. X and Y are PyObject*s.
951*/
Tim Peters66860f62002-08-04 17:47:26 +0000952#define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
Tim Petersa8c974c2002-07-19 03:30:57 +0000953 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000954
955/* binarysort is the best method for sorting small arrays: it does
956 few compares, but can do data movement quadratic in the number of
957 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000958 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +0000959 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000960 On entry, must have lo <= start <= hi, and that [lo, start) is already
961 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +0000962 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000963 Even in case of error, the output slice will be some permutation of
964 the input (nothing is lost or duplicated).
965*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000966static int
Fred Drakea2f55112000-07-09 15:16:51 +0000967binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
968 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000969{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000970 register Py_ssize_t k;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000971 register PyObject **l, **p, **r;
972 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000973
Tim Petersa8c974c2002-07-19 03:30:57 +0000974 assert(lo <= start && start <= hi);
975 /* assert [lo, start) is sorted */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000976 if (lo == start)
977 ++start;
978 for (; start < hi; ++start) {
979 /* set l to where *start belongs */
980 l = lo;
981 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000982 pivot = *r;
Tim Peters0fe977c2002-07-19 06:12:32 +0000983 /* Invariants:
984 * pivot >= all in [lo, l).
985 * pivot < all in [r, start).
986 * The second is vacuously true at the start.
987 */
988 assert(l < r);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000989 do {
990 p = l + ((r - l) >> 1);
Tim Petersa8c974c2002-07-19 03:30:57 +0000991 IFLT(pivot, *p)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000992 r = p;
993 else
Tim Peters0fe977c2002-07-19 06:12:32 +0000994 l = p+1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000995 } while (l < r);
Tim Peters0fe977c2002-07-19 06:12:32 +0000996 assert(l == r);
997 /* The invariants still hold, so pivot >= all in [lo, l) and
998 pivot < all in [l, start), so pivot belongs at l. Note
999 that if there are elements equal to pivot, l points to the
1000 first slot after them -- that's why this sort is stable.
1001 Slide over to make room.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001002 Caution: using memmove is much slower under MSVC 5;
1003 we're not usually moving many slots. */
1004 for (p = start; p > l; --p)
1005 *p = *(p-1);
1006 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001007 }
Guido van Rossum3f236de1996-12-10 23:55:39 +00001008 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001009
1010 fail:
1011 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001012}
1013
Tim Petersa64dc242002-08-01 02:13:36 +00001014/*
1015Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1016is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001017
Tim Petersa64dc242002-08-01 02:13:36 +00001018 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001019
Tim Petersa64dc242002-08-01 02:13:36 +00001020or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001021
Tim Petersa64dc242002-08-01 02:13:36 +00001022 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001023
Tim Petersa64dc242002-08-01 02:13:36 +00001024Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1025For its intended use in a stable mergesort, the strictness of the defn of
1026"descending" is needed so that the caller can safely reverse a descending
1027sequence without violating stability (strict > ensures there are no equal
1028elements to get out of order).
1029
1030Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001031*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001032static Py_ssize_t
Tim Petersa64dc242002-08-01 02:13:36 +00001033count_run(PyObject **lo, PyObject **hi, PyObject *compare, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001034{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001035 Py_ssize_t k;
1036 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001037
Tim Petersa64dc242002-08-01 02:13:36 +00001038 assert(lo < hi);
1039 *descending = 0;
1040 ++lo;
1041 if (lo == hi)
1042 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001043
Tim Petersa64dc242002-08-01 02:13:36 +00001044 n = 2;
1045 IFLT(*lo, *(lo-1)) {
1046 *descending = 1;
1047 for (lo = lo+1; lo < hi; ++lo, ++n) {
1048 IFLT(*lo, *(lo-1))
1049 ;
1050 else
1051 break;
1052 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001053 }
Tim Petersa64dc242002-08-01 02:13:36 +00001054 else {
1055 for (lo = lo+1; lo < hi; ++lo, ++n) {
1056 IFLT(*lo, *(lo-1))
1057 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001058 }
1059 }
1060
Tim Petersa64dc242002-08-01 02:13:36 +00001061 return n;
1062fail:
1063 return -1;
1064}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001065
Tim Petersa64dc242002-08-01 02:13:36 +00001066/*
1067Locate the proper position of key in a sorted vector; if the vector contains
1068an element equal to key, return the position immediately to the left of
1069the leftmost equal element. [gallop_right() does the same except returns
1070the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001071
Tim Petersa64dc242002-08-01 02:13:36 +00001072"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001073
Tim Petersa64dc242002-08-01 02:13:36 +00001074"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1075hint is to the final result, the faster this runs.
1076
1077The return value is the int k in 0..n such that
1078
1079 a[k-1] < key <= a[k]
1080
1081pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1082key belongs at index k; or, IOW, the first k elements of a should precede
1083key, and the last n-k should follow key.
1084
1085Returns -1 on error. See listsort.txt for info on the method.
1086*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001087static Py_ssize_t
1088gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
Tim Petersa64dc242002-08-01 02:13:36 +00001089{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001090 Py_ssize_t ofs;
1091 Py_ssize_t lastofs;
1092 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001093
1094 assert(key && a && n > 0 && hint >= 0 && hint < n);
1095
1096 a += hint;
1097 lastofs = 0;
1098 ofs = 1;
1099 IFLT(*a, key) {
1100 /* a[hint] < key -- gallop right, until
1101 * a[hint + lastofs] < key <= a[hint + ofs]
1102 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001103 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001104 while (ofs < maxofs) {
1105 IFLT(a[ofs], key) {
1106 lastofs = ofs;
1107 ofs = (ofs << 1) + 1;
1108 if (ofs <= 0) /* int overflow */
1109 ofs = maxofs;
1110 }
1111 else /* key <= a[hint + ofs] */
1112 break;
1113 }
1114 if (ofs > maxofs)
1115 ofs = maxofs;
1116 /* Translate back to offsets relative to &a[0]. */
1117 lastofs += hint;
1118 ofs += hint;
1119 }
1120 else {
1121 /* key <= a[hint] -- gallop left, until
1122 * a[hint - ofs] < key <= a[hint - lastofs]
1123 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001124 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001125 while (ofs < maxofs) {
1126 IFLT(*(a-ofs), key)
1127 break;
1128 /* key <= a[hint - ofs] */
1129 lastofs = ofs;
1130 ofs = (ofs << 1) + 1;
1131 if (ofs <= 0) /* int overflow */
1132 ofs = maxofs;
1133 }
1134 if (ofs > maxofs)
1135 ofs = maxofs;
1136 /* Translate back to positive offsets relative to &a[0]. */
1137 k = lastofs;
1138 lastofs = hint - ofs;
1139 ofs = hint - k;
1140 }
1141 a -= hint;
1142
1143 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1144 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1145 * right of lastofs but no farther right than ofs. Do a binary
1146 * search, with invariant a[lastofs-1] < key <= a[ofs].
1147 */
1148 ++lastofs;
1149 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001150 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001151
1152 IFLT(a[m], key)
1153 lastofs = m+1; /* a[m] < key */
1154 else
1155 ofs = m; /* key <= a[m] */
1156 }
1157 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1158 return ofs;
1159
1160fail:
1161 return -1;
1162}
1163
1164/*
1165Exactly like gallop_left(), except that if key already exists in a[0:n],
1166finds the position immediately to the right of the rightmost equal value.
1167
1168The return value is the int k in 0..n such that
1169
1170 a[k-1] <= key < a[k]
1171
1172or -1 if error.
1173
1174The code duplication is massive, but this is enough different given that
1175we're sticking to "<" comparisons that it's much harder to follow if
1176written as one routine with yet another "left or right?" flag.
1177*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001178static Py_ssize_t
1179gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
Tim Petersa64dc242002-08-01 02:13:36 +00001180{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001181 Py_ssize_t ofs;
1182 Py_ssize_t lastofs;
1183 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001184
1185 assert(key && a && n > 0 && hint >= 0 && hint < n);
1186
1187 a += hint;
1188 lastofs = 0;
1189 ofs = 1;
1190 IFLT(key, *a) {
1191 /* key < a[hint] -- gallop left, until
1192 * a[hint - ofs] <= key < a[hint - lastofs]
1193 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001194 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001195 while (ofs < maxofs) {
1196 IFLT(key, *(a-ofs)) {
1197 lastofs = ofs;
1198 ofs = (ofs << 1) + 1;
1199 if (ofs <= 0) /* int overflow */
1200 ofs = maxofs;
1201 }
1202 else /* a[hint - ofs] <= key */
1203 break;
1204 }
1205 if (ofs > maxofs)
1206 ofs = maxofs;
1207 /* Translate back to positive offsets relative to &a[0]. */
1208 k = lastofs;
1209 lastofs = hint - ofs;
1210 ofs = hint - k;
1211 }
1212 else {
1213 /* a[hint] <= key -- gallop right, until
1214 * a[hint + lastofs] <= key < a[hint + ofs]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001215 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001216 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001217 while (ofs < maxofs) {
1218 IFLT(key, a[ofs])
1219 break;
1220 /* a[hint + ofs] <= key */
1221 lastofs = ofs;
1222 ofs = (ofs << 1) + 1;
1223 if (ofs <= 0) /* int overflow */
1224 ofs = maxofs;
1225 }
1226 if (ofs > maxofs)
1227 ofs = maxofs;
1228 /* Translate back to offsets relative to &a[0]. */
1229 lastofs += hint;
1230 ofs += hint;
1231 }
1232 a -= hint;
1233
1234 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1235 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1236 * right of lastofs but no farther right than ofs. Do a binary
1237 * search, with invariant a[lastofs-1] <= key < a[ofs].
1238 */
1239 ++lastofs;
1240 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001241 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001242
1243 IFLT(key, a[m])
1244 ofs = m; /* key < a[m] */
1245 else
1246 lastofs = m+1; /* a[m] <= key */
1247 }
1248 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1249 return ofs;
1250
1251fail:
1252 return -1;
1253}
1254
1255/* The maximum number of entries in a MergeState's pending-runs stack.
1256 * This is enough to sort arrays of size up to about
1257 * 32 * phi ** MAX_MERGE_PENDING
1258 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1259 * with 2**64 elements.
1260 */
1261#define MAX_MERGE_PENDING 85
1262
Tim Peterse05f65a2002-08-10 05:21:15 +00001263/* When we get into galloping mode, we stay there until both runs win less
1264 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001265 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001266#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001267
1268/* Avoid malloc for small temp arrays. */
1269#define MERGESTATE_TEMP_SIZE 256
1270
1271/* One MergeState exists on the stack per invocation of mergesort. It's just
1272 * a convenient way to pass state around among the helper functions.
1273 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001274struct s_slice {
1275 PyObject **base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001276 Py_ssize_t len;
Tim Peterse05f65a2002-08-10 05:21:15 +00001277};
1278
Tim Petersa64dc242002-08-01 02:13:36 +00001279typedef struct s_MergeState {
1280 /* The user-supplied comparison function. or NULL if none given. */
1281 PyObject *compare;
1282
Tim Peterse05f65a2002-08-10 05:21:15 +00001283 /* This controls when we get *into* galloping mode. It's initialized
1284 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1285 * random data, and lower for highly structured data.
1286 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001287 Py_ssize_t min_gallop;
Tim Peterse05f65a2002-08-10 05:21:15 +00001288
Tim Petersa64dc242002-08-01 02:13:36 +00001289 /* 'a' is temp storage to help with merges. It contains room for
1290 * alloced entries.
1291 */
1292 PyObject **a; /* may point to temparray below */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001293 Py_ssize_t alloced;
Tim Petersa64dc242002-08-01 02:13:36 +00001294
1295 /* A stack of n pending runs yet to be merged. Run #i starts at
1296 * address base[i] and extends for len[i] elements. It's always
1297 * true (so long as the indices are in bounds) that
1298 *
Tim Peterse05f65a2002-08-10 05:21:15 +00001299 * pending[i].base + pending[i].len == pending[i+1].base
Tim Petersa64dc242002-08-01 02:13:36 +00001300 *
1301 * so we could cut the storage for this, but it's a minor amount,
1302 * and keeping all the info explicit simplifies the code.
1303 */
1304 int n;
Tim Peterse05f65a2002-08-10 05:21:15 +00001305 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001306
1307 /* 'a' points to this when possible, rather than muck with malloc. */
1308 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1309} MergeState;
1310
1311/* Conceptually a MergeState's constructor. */
1312static void
1313merge_init(MergeState *ms, PyObject *compare)
1314{
1315 assert(ms != NULL);
1316 ms->compare = compare;
1317 ms->a = ms->temparray;
1318 ms->alloced = MERGESTATE_TEMP_SIZE;
1319 ms->n = 0;
Tim Peterse05f65a2002-08-10 05:21:15 +00001320 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001321}
1322
1323/* Free all the temp memory owned by the MergeState. This must be called
1324 * when you're done with a MergeState, and may be called before then if
1325 * you want to free the temp memory early.
1326 */
1327static void
1328merge_freemem(MergeState *ms)
1329{
1330 assert(ms != NULL);
1331 if (ms->a != ms->temparray)
1332 PyMem_Free(ms->a);
1333 ms->a = ms->temparray;
1334 ms->alloced = MERGESTATE_TEMP_SIZE;
1335}
1336
1337/* Ensure enough temp memory for 'need' array slots is available.
1338 * Returns 0 on success and -1 if the memory can't be gotten.
1339 */
1340static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001341merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001342{
1343 assert(ms != NULL);
1344 if (need <= ms->alloced)
1345 return 0;
1346 /* Don't realloc! That can cost cycles to copy the old data, but
1347 * we don't care what's in the block.
1348 */
1349 merge_freemem(ms);
1350 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1351 if (ms->a) {
1352 ms->alloced = need;
1353 return 0;
1354 }
1355 PyErr_NoMemory();
1356 merge_freemem(ms); /* reset to sane state */
1357 return -1;
1358}
1359#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1360 merge_getmem(MS, NEED))
1361
1362/* Merge the na elements starting at pa with the nb elements starting at pb
1363 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1364 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1365 * merge, and should have na <= nb. See listsort.txt for more info.
1366 * Return 0 if successful, -1 if error.
1367 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001368static Py_ssize_t
1369merge_lo(MergeState *ms, PyObject **pa, Py_ssize_t na,
1370 PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001371{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001372 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001373 PyObject *compare;
1374 PyObject **dest;
1375 int result = -1; /* guilty until proved innocent */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001376 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001377
1378 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1379 if (MERGE_GETMEM(ms, na) < 0)
1380 return -1;
1381 memcpy(ms->a, pa, na * sizeof(PyObject*));
1382 dest = pa;
1383 pa = ms->a;
1384
1385 *dest++ = *pb++;
1386 --nb;
1387 if (nb == 0)
1388 goto Succeed;
1389 if (na == 1)
1390 goto CopyB;
1391
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001392 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001393 compare = ms->compare;
1394 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001395 Py_ssize_t acount = 0; /* # of times A won in a row */
1396 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001397
1398 /* Do the straightforward thing until (if ever) one run
1399 * appears to win consistently.
1400 */
1401 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001402 assert(na > 1 && nb > 0);
Tim Peters66860f62002-08-04 17:47:26 +00001403 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001404 if (k) {
1405 if (k < 0)
1406 goto Fail;
1407 *dest++ = *pb++;
1408 ++bcount;
1409 acount = 0;
1410 --nb;
1411 if (nb == 0)
1412 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001413 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001414 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001415 }
1416 else {
Tim Petersa64dc242002-08-01 02:13:36 +00001417 *dest++ = *pa++;
1418 ++acount;
1419 bcount = 0;
1420 --na;
1421 if (na == 1)
1422 goto CopyB;
Tim Peterse05f65a2002-08-10 05:21:15 +00001423 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001424 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001425 }
Tim Petersa64dc242002-08-01 02:13:36 +00001426 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001427
Tim Petersa64dc242002-08-01 02:13:36 +00001428 /* One run is winning so consistently that galloping may
1429 * be a huge win. So try that, and continue galloping until
1430 * (if ever) neither run appears to be winning consistently
1431 * anymore.
1432 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001433 ++min_gallop;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001434 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001435 assert(na > 1 && nb > 0);
1436 min_gallop -= min_gallop > 1;
1437 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001438 k = gallop_right(*pb, pa, na, 0, compare);
1439 acount = k;
1440 if (k) {
1441 if (k < 0)
1442 goto Fail;
1443 memcpy(dest, pa, k * sizeof(PyObject *));
1444 dest += k;
1445 pa += k;
1446 na -= k;
1447 if (na == 1)
1448 goto CopyB;
1449 /* na==0 is impossible now if the comparison
1450 * function is consistent, but we can't assume
1451 * that it is.
1452 */
1453 if (na == 0)
1454 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001455 }
Tim Petersa64dc242002-08-01 02:13:36 +00001456 *dest++ = *pb++;
1457 --nb;
1458 if (nb == 0)
1459 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001460
Tim Petersa64dc242002-08-01 02:13:36 +00001461 k = gallop_left(*pa, pb, nb, 0, compare);
1462 bcount = k;
1463 if (k) {
1464 if (k < 0)
1465 goto Fail;
1466 memmove(dest, pb, k * sizeof(PyObject *));
1467 dest += k;
1468 pb += k;
1469 nb -= k;
1470 if (nb == 0)
1471 goto Succeed;
1472 }
1473 *dest++ = *pa++;
1474 --na;
1475 if (na == 1)
1476 goto CopyB;
1477 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001478 ++min_gallop; /* penalize it for leaving galloping mode */
1479 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001480 }
1481Succeed:
1482 result = 0;
1483Fail:
1484 if (na)
1485 memcpy(dest, pa, na * sizeof(PyObject*));
1486 return result;
1487CopyB:
1488 assert(na == 1 && nb > 0);
1489 /* The last element of pa belongs at the end of the merge. */
1490 memmove(dest, pb, nb * sizeof(PyObject *));
1491 dest[nb] = *pa;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001492 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001493}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001494
Tim Petersa64dc242002-08-01 02:13:36 +00001495/* Merge the na elements starting at pa with the nb elements starting at pb
1496 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1497 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1498 * merge, and should have na >= nb. See listsort.txt for more info.
1499 * Return 0 if successful, -1 if error.
1500 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001501static Py_ssize_t
1502merge_hi(MergeState *ms, PyObject **pa, Py_ssize_t na, PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001503{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001504 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001505 PyObject *compare;
1506 PyObject **dest;
1507 int result = -1; /* guilty until proved innocent */
1508 PyObject **basea;
1509 PyObject **baseb;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001510 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001511
1512 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1513 if (MERGE_GETMEM(ms, nb) < 0)
1514 return -1;
1515 dest = pb + nb - 1;
1516 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1517 basea = pa;
1518 baseb = ms->a;
1519 pb = ms->a + nb - 1;
1520 pa += na - 1;
1521
1522 *dest-- = *pa--;
1523 --na;
1524 if (na == 0)
1525 goto Succeed;
1526 if (nb == 1)
1527 goto CopyA;
1528
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001529 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001530 compare = ms->compare;
1531 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001532 Py_ssize_t acount = 0; /* # of times A won in a row */
1533 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001534
1535 /* Do the straightforward thing until (if ever) one run
1536 * appears to win consistently.
1537 */
1538 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001539 assert(na > 0 && nb > 1);
Tim Peters66860f62002-08-04 17:47:26 +00001540 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001541 if (k) {
1542 if (k < 0)
1543 goto Fail;
1544 *dest-- = *pa--;
1545 ++acount;
1546 bcount = 0;
1547 --na;
1548 if (na == 0)
1549 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001550 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001551 break;
1552 }
1553 else {
1554 *dest-- = *pb--;
1555 ++bcount;
1556 acount = 0;
1557 --nb;
1558 if (nb == 1)
1559 goto CopyA;
Tim Peterse05f65a2002-08-10 05:21:15 +00001560 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001561 break;
1562 }
1563 }
1564
1565 /* One run is winning so consistently that galloping may
1566 * be a huge win. So try that, and continue galloping until
1567 * (if ever) neither run appears to be winning consistently
1568 * anymore.
1569 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001570 ++min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001571 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001572 assert(na > 0 && nb > 1);
1573 min_gallop -= min_gallop > 1;
1574 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001575 k = gallop_right(*pb, basea, na, na-1, compare);
1576 if (k < 0)
1577 goto Fail;
1578 k = na - k;
1579 acount = k;
1580 if (k) {
1581 dest -= k;
1582 pa -= k;
1583 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1584 na -= k;
1585 if (na == 0)
1586 goto Succeed;
1587 }
1588 *dest-- = *pb--;
1589 --nb;
1590 if (nb == 1)
1591 goto CopyA;
1592
1593 k = gallop_left(*pa, baseb, nb, nb-1, compare);
1594 if (k < 0)
1595 goto Fail;
1596 k = nb - k;
1597 bcount = k;
1598 if (k) {
1599 dest -= k;
1600 pb -= k;
1601 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1602 nb -= k;
1603 if (nb == 1)
1604 goto CopyA;
1605 /* nb==0 is impossible now if the comparison
1606 * function is consistent, but we can't assume
1607 * that it is.
1608 */
1609 if (nb == 0)
1610 goto Succeed;
1611 }
1612 *dest-- = *pa--;
1613 --na;
1614 if (na == 0)
1615 goto Succeed;
1616 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001617 ++min_gallop; /* penalize it for leaving galloping mode */
1618 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001619 }
1620Succeed:
1621 result = 0;
1622Fail:
1623 if (nb)
1624 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1625 return result;
1626CopyA:
1627 assert(nb == 1 && na > 0);
1628 /* The first element of pb belongs at the front of the merge. */
1629 dest -= na;
1630 pa -= na;
1631 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1632 *dest = *pb;
1633 return 0;
1634}
1635
1636/* Merge the two runs at stack indices i and i+1.
1637 * Returns 0 on success, -1 on error.
1638 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001639static Py_ssize_t
1640merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001641{
1642 PyObject **pa, **pb;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001643 Py_ssize_t na, nb;
1644 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001645 PyObject *compare;
1646
1647 assert(ms != NULL);
1648 assert(ms->n >= 2);
1649 assert(i >= 0);
1650 assert(i == ms->n - 2 || i == ms->n - 3);
1651
Tim Peterse05f65a2002-08-10 05:21:15 +00001652 pa = ms->pending[i].base;
1653 na = ms->pending[i].len;
1654 pb = ms->pending[i+1].base;
1655 nb = ms->pending[i+1].len;
Tim Petersa64dc242002-08-01 02:13:36 +00001656 assert(na > 0 && nb > 0);
1657 assert(pa + na == pb);
1658
1659 /* Record the length of the combined runs; if i is the 3rd-last
1660 * run now, also slide over the last run (which isn't involved
1661 * in this merge). The current run i+1 goes away in any case.
1662 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001663 ms->pending[i].len = na + nb;
1664 if (i == ms->n - 3)
1665 ms->pending[i+1] = ms->pending[i+2];
Tim Petersa64dc242002-08-01 02:13:36 +00001666 --ms->n;
1667
1668 /* Where does b start in a? Elements in a before that can be
1669 * ignored (already in place).
1670 */
1671 compare = ms->compare;
1672 k = gallop_right(*pb, pa, na, 0, compare);
1673 if (k < 0)
1674 return -1;
1675 pa += k;
1676 na -= k;
1677 if (na == 0)
1678 return 0;
1679
1680 /* Where does a end in b? Elements in b after that can be
1681 * ignored (already in place).
1682 */
1683 nb = gallop_left(pa[na-1], pb, nb, nb-1, compare);
1684 if (nb <= 0)
1685 return nb;
1686
1687 /* Merge what remains of the runs, using a temp array with
1688 * min(na, nb) elements.
1689 */
1690 if (na <= nb)
1691 return merge_lo(ms, pa, na, pb, nb);
1692 else
1693 return merge_hi(ms, pa, na, pb, nb);
1694}
1695
1696/* Examine the stack of runs waiting to be merged, merging adjacent runs
1697 * until the stack invariants are re-established:
1698 *
1699 * 1. len[-3] > len[-2] + len[-1]
1700 * 2. len[-2] > len[-1]
1701 *
1702 * See listsort.txt for more info.
1703 *
1704 * Returns 0 on success, -1 on error.
1705 */
1706static int
1707merge_collapse(MergeState *ms)
1708{
Tim Peterse05f65a2002-08-10 05:21:15 +00001709 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001710
1711 assert(ms);
1712 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001713 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001714 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1715 if (p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001716 --n;
1717 if (merge_at(ms, n) < 0)
1718 return -1;
1719 }
Tim Peterse05f65a2002-08-10 05:21:15 +00001720 else if (p[n].len <= p[n+1].len) {
Tim Petersa64dc242002-08-01 02:13:36 +00001721 if (merge_at(ms, n) < 0)
1722 return -1;
1723 }
1724 else
1725 break;
1726 }
1727 return 0;
1728}
1729
1730/* Regardless of invariants, merge all runs on the stack until only one
1731 * remains. This is used at the end of the mergesort.
1732 *
1733 * Returns 0 on success, -1 on error.
1734 */
1735static int
1736merge_force_collapse(MergeState *ms)
1737{
Tim Peterse05f65a2002-08-10 05:21:15 +00001738 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001739
1740 assert(ms);
1741 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001742 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001743 if (n > 0 && p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001744 --n;
1745 if (merge_at(ms, n) < 0)
1746 return -1;
1747 }
1748 return 0;
1749}
1750
1751/* Compute a good value for the minimum run length; natural runs shorter
1752 * than this are boosted artificially via binary insertion.
1753 *
1754 * If n < 64, return n (it's too small to bother with fancy stuff).
1755 * Else if n is an exact power of 2, return 32.
1756 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1757 * strictly less than, an exact power of 2.
1758 *
1759 * See listsort.txt for more info.
1760 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001761static Py_ssize_t
1762merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001763{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001764 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001765
1766 assert(n >= 0);
1767 while (n >= 64) {
1768 r |= n & 1;
1769 n >>= 1;
1770 }
1771 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001772}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001773
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001774/* Special wrapper to support stable sorting using the decorate-sort-undecorate
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001775 pattern. Holds a key which is used for comparisons and the original record
Tim Petersb38e2b62004-07-29 02:29:26 +00001776 which is returned during the undecorate phase. By exposing only the key
1777 during comparisons, the underlying sort stability characteristics are left
1778 unchanged. Also, if a custom comparison function is used, it will only see
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001779 the key instead of a full record. */
1780
1781typedef struct {
1782 PyObject_HEAD
1783 PyObject *key;
1784 PyObject *value;
1785} sortwrapperobject;
1786
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001787PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001788static PyObject *
1789sortwrapper_richcompare(sortwrapperobject *, sortwrapperobject *, int);
1790static void
1791sortwrapper_dealloc(sortwrapperobject *);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001792
1793static PyTypeObject sortwrapper_type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001794 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001795 "sortwrapper", /* tp_name */
1796 sizeof(sortwrapperobject), /* tp_basicsize */
1797 0, /* tp_itemsize */
1798 /* methods */
1799 (destructor)sortwrapper_dealloc, /* tp_dealloc */
1800 0, /* tp_print */
1801 0, /* tp_getattr */
1802 0, /* tp_setattr */
1803 0, /* tp_compare */
1804 0, /* tp_repr */
1805 0, /* tp_as_number */
1806 0, /* tp_as_sequence */
1807 0, /* tp_as_mapping */
1808 0, /* tp_hash */
1809 0, /* tp_call */
1810 0, /* tp_str */
1811 PyObject_GenericGetAttr, /* tp_getattro */
1812 0, /* tp_setattro */
1813 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001814 Py_TPFLAGS_DEFAULT, /* tp_flags */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001815 sortwrapper_doc, /* tp_doc */
1816 0, /* tp_traverse */
1817 0, /* tp_clear */
1818 (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
1819};
1820
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001821
1822static PyObject *
1823sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
1824{
1825 if (!PyObject_TypeCheck(b, &sortwrapper_type)) {
1826 PyErr_SetString(PyExc_TypeError,
1827 "expected a sortwrapperobject");
1828 return NULL;
1829 }
1830 return PyObject_RichCompare(a->key, b->key, op);
1831}
1832
1833static void
1834sortwrapper_dealloc(sortwrapperobject *so)
1835{
1836 Py_XDECREF(so->key);
1837 Py_XDECREF(so->value);
1838 PyObject_Del(so);
1839}
1840
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001841/* Returns a new reference to a sortwrapper.
1842 Consumes the references to the two underlying objects. */
1843
1844static PyObject *
1845build_sortwrapper(PyObject *key, PyObject *value)
1846{
1847 sortwrapperobject *so;
Tim Petersb38e2b62004-07-29 02:29:26 +00001848
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001849 so = PyObject_New(sortwrapperobject, &sortwrapper_type);
1850 if (so == NULL)
1851 return NULL;
1852 so->key = key;
1853 so->value = value;
1854 return (PyObject *)so;
1855}
1856
1857/* Returns a new reference to the value underlying the wrapper. */
1858static PyObject *
1859sortwrapper_getvalue(PyObject *so)
1860{
1861 PyObject *value;
1862
1863 if (!PyObject_TypeCheck(so, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001864 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001865 "expected a sortwrapperobject");
1866 return NULL;
1867 }
1868 value = ((sortwrapperobject *)so)->value;
1869 Py_INCREF(value);
1870 return value;
1871}
1872
1873/* Wrapper for user specified cmp functions in combination with a
1874 specified key function. Makes sure the cmp function is presented
1875 with the actual key instead of the sortwrapper */
1876
1877typedef struct {
1878 PyObject_HEAD
1879 PyObject *func;
1880} cmpwrapperobject;
1881
1882static void
1883cmpwrapper_dealloc(cmpwrapperobject *co)
1884{
1885 Py_XDECREF(co->func);
1886 PyObject_Del(co);
1887}
1888
1889static PyObject *
1890cmpwrapper_call(cmpwrapperobject *co, PyObject *args, PyObject *kwds)
1891{
1892 PyObject *x, *y, *xx, *yy;
1893
1894 if (!PyArg_UnpackTuple(args, "", 2, 2, &x, &y))
1895 return NULL;
1896 if (!PyObject_TypeCheck(x, &sortwrapper_type) ||
Raymond Hettingerae4a2992003-10-16 17:16:30 +00001897 !PyObject_TypeCheck(y, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001898 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001899 "expected a sortwrapperobject");
1900 return NULL;
1901 }
1902 xx = ((sortwrapperobject *)x)->key;
1903 yy = ((sortwrapperobject *)y)->key;
1904 return PyObject_CallFunctionObjArgs(co->func, xx, yy, NULL);
1905}
1906
1907PyDoc_STRVAR(cmpwrapper_doc, "cmp() wrapper for sort with custom keys.");
1908
1909static PyTypeObject cmpwrapper_type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001910 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001911 "cmpwrapper", /* tp_name */
1912 sizeof(cmpwrapperobject), /* tp_basicsize */
1913 0, /* tp_itemsize */
1914 /* methods */
1915 (destructor)cmpwrapper_dealloc, /* tp_dealloc */
1916 0, /* tp_print */
1917 0, /* tp_getattr */
1918 0, /* tp_setattr */
1919 0, /* tp_compare */
1920 0, /* tp_repr */
1921 0, /* tp_as_number */
1922 0, /* tp_as_sequence */
1923 0, /* tp_as_mapping */
1924 0, /* tp_hash */
1925 (ternaryfunc)cmpwrapper_call, /* tp_call */
1926 0, /* tp_str */
1927 PyObject_GenericGetAttr, /* tp_getattro */
1928 0, /* tp_setattro */
1929 0, /* tp_as_buffer */
1930 Py_TPFLAGS_DEFAULT, /* tp_flags */
1931 cmpwrapper_doc, /* tp_doc */
1932};
1933
1934static PyObject *
1935build_cmpwrapper(PyObject *cmpfunc)
1936{
1937 cmpwrapperobject *co;
Tim Petersb38e2b62004-07-29 02:29:26 +00001938
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001939 co = PyObject_New(cmpwrapperobject, &cmpwrapper_type);
1940 if (co == NULL)
1941 return NULL;
1942 Py_INCREF(cmpfunc);
1943 co->func = cmpfunc;
1944 return (PyObject *)co;
1945}
1946
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001947static int
1948is_default_cmp(PyObject *cmpfunc)
1949{
1950 PyCFunctionObject *f;
Neal Norwitzed2b7392007-08-26 04:51:10 +00001951 const char *module;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001952 if (cmpfunc == NULL || cmpfunc == Py_None)
1953 return 1;
1954 if (!PyCFunction_Check(cmpfunc))
1955 return 0;
Guido van Rossumf1624cd2006-08-24 23:43:52 +00001956 f = (PyCFunctionObject *)cmpfunc;
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001957 if (f->m_self != NULL)
1958 return 0;
Neal Norwitzed2b7392007-08-26 04:51:10 +00001959 if (!PyUnicode_Check(f->m_module))
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001960 return 0;
Neal Norwitzed2b7392007-08-26 04:51:10 +00001961 module = PyUnicode_AsString(f->m_module);
1962 if (module == NULL)
1963 return 0;
1964 if (strcmp(module, "__builtin__") != 0)
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001965 return 0;
1966 if (strcmp(f->m_ml->ml_name, "cmp") != 0)
1967 return 0;
1968 return 1;
1969}
1970
Tim Petersa64dc242002-08-01 02:13:36 +00001971/* An adaptive, stable, natural mergesort. See listsort.txt.
1972 * Returns Py_None on success, NULL on error. Even in case of error, the
1973 * list will be some permutation of its input state (nothing is lost or
1974 * duplicated).
1975 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001976static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001977listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001978{
Tim Petersa64dc242002-08-01 02:13:36 +00001979 MergeState ms;
1980 PyObject **lo, **hi;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001981 Py_ssize_t nremaining;
1982 Py_ssize_t minrun;
1983 Py_ssize_t saved_ob_size, saved_allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00001984 PyObject **saved_ob_item;
Armin Rigo93677f02004-07-29 12:40:23 +00001985 PyObject **final_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001986 PyObject *compare = NULL;
1987 PyObject *result = NULL; /* guilty until proved innocent */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001988 int reverse = 0;
1989 PyObject *keyfunc = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001990 Py_ssize_t i;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001991 PyObject *key, *value, *kvpair;
Martin v. Löwis15e62742006-02-27 16:46:16 +00001992 static char *kwlist[] = {"cmp", "key", "reverse", 0};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001993
Tim Petersa64dc242002-08-01 02:13:36 +00001994 assert(self != NULL);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001995 assert (PyList_Check(self));
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001996 if (args != NULL) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001997 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:sort",
1998 kwlist, &compare, &keyfunc, &reverse))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001999 return NULL;
2000 }
Guido van Rossum47b9ff62006-08-24 00:41:19 +00002001 if (is_default_cmp(compare))
Skip Montanaro4abd5f02003-01-02 20:51:08 +00002002 compare = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002003 if (keyfunc == Py_None)
2004 keyfunc = NULL;
2005 if (compare != NULL && keyfunc != NULL) {
2006 compare = build_cmpwrapper(compare);
2007 if (compare == NULL)
Hye-Shik Chang19cb1932003-12-10 07:31:08 +00002008 return NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002009 } else
2010 Py_XINCREF(compare);
2011
Tim Petersb9099c32002-11-12 22:08:10 +00002012 /* The list is temporarily made empty, so that mutations performed
2013 * by comparison functions can't affect the slice of memory we're
2014 * sorting (allowing mutations during sorting is a core-dump
2015 * factory, since ob_item may change).
2016 */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002017 saved_ob_size = Py_Size(self);
Tim Petersb9099c32002-11-12 22:08:10 +00002018 saved_ob_item = self->ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002019 saved_allocated = self->allocated;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002020 Py_Size(self) = 0;
Tim Peters51b4ade2004-07-29 04:07:15 +00002021 self->ob_item = NULL;
Armin Rigo93677f02004-07-29 12:40:23 +00002022 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00002023
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002024 if (keyfunc != NULL) {
2025 for (i=0 ; i < saved_ob_size ; i++) {
2026 value = saved_ob_item[i];
Tim Petersb38e2b62004-07-29 02:29:26 +00002027 key = PyObject_CallFunctionObjArgs(keyfunc, value,
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002028 NULL);
2029 if (key == NULL) {
2030 for (i=i-1 ; i>=0 ; i--) {
2031 kvpair = saved_ob_item[i];
2032 value = sortwrapper_getvalue(kvpair);
2033 saved_ob_item[i] = value;
2034 Py_DECREF(kvpair);
2035 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002036 goto dsu_fail;
2037 }
2038 kvpair = build_sortwrapper(key, value);
2039 if (kvpair == NULL)
2040 goto dsu_fail;
2041 saved_ob_item[i] = kvpair;
2042 }
2043 }
2044
2045 /* Reverse sort stability achieved by initially reversing the list,
2046 applying a stable forward sort, then reversing the final result. */
2047 if (reverse && saved_ob_size > 1)
2048 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2049
2050 merge_init(&ms, compare);
2051
Tim Petersb9099c32002-11-12 22:08:10 +00002052 nremaining = saved_ob_size;
Tim Petersa64dc242002-08-01 02:13:36 +00002053 if (nremaining < 2)
2054 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00002055
Tim Petersa64dc242002-08-01 02:13:36 +00002056 /* March over the array once, left to right, finding natural runs,
2057 * and extending short natural runs to minrun elements.
2058 */
Tim Petersb9099c32002-11-12 22:08:10 +00002059 lo = saved_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00002060 hi = lo + nremaining;
2061 minrun = merge_compute_minrun(nremaining);
2062 do {
2063 int descending;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002064 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00002065
Tim Petersa64dc242002-08-01 02:13:36 +00002066 /* Identify next run. */
2067 n = count_run(lo, hi, compare, &descending);
2068 if (n < 0)
2069 goto fail;
2070 if (descending)
2071 reverse_slice(lo, lo + n);
2072 /* If short, extend to min(minrun, nremaining). */
2073 if (n < minrun) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002074 const Py_ssize_t force = nremaining <= minrun ?
Tim Petersa64dc242002-08-01 02:13:36 +00002075 nremaining : minrun;
2076 if (binarysort(lo, lo + force, lo + n, compare) < 0)
2077 goto fail;
2078 n = force;
2079 }
2080 /* Push run onto pending-runs stack, and maybe merge. */
2081 assert(ms.n < MAX_MERGE_PENDING);
Tim Peterse05f65a2002-08-10 05:21:15 +00002082 ms.pending[ms.n].base = lo;
2083 ms.pending[ms.n].len = n;
Tim Petersa64dc242002-08-01 02:13:36 +00002084 ++ms.n;
2085 if (merge_collapse(&ms) < 0)
2086 goto fail;
2087 /* Advance to find next run. */
2088 lo += n;
2089 nremaining -= n;
2090 } while (nremaining);
2091 assert(lo == hi);
Tim Peters330f9e92002-07-19 07:05:44 +00002092
Tim Petersa64dc242002-08-01 02:13:36 +00002093 if (merge_force_collapse(&ms) < 0)
2094 goto fail;
2095 assert(ms.n == 1);
Tim Petersb9099c32002-11-12 22:08:10 +00002096 assert(ms.pending[0].base == saved_ob_item);
2097 assert(ms.pending[0].len == saved_ob_size);
Tim Petersa64dc242002-08-01 02:13:36 +00002098
2099succeed:
2100 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002101fail:
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002102 if (keyfunc != NULL) {
2103 for (i=0 ; i < saved_ob_size ; i++) {
2104 kvpair = saved_ob_item[i];
2105 value = sortwrapper_getvalue(kvpair);
2106 saved_ob_item[i] = value;
2107 Py_DECREF(kvpair);
2108 }
2109 }
2110
Armin Rigo93677f02004-07-29 12:40:23 +00002111 if (self->allocated != -1 && result != NULL) {
Tim Peters51b4ade2004-07-29 04:07:15 +00002112 /* The user mucked with the list during the sort,
2113 * and we don't already have another error to report.
2114 */
2115 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2116 result = NULL;
Tim Petersb9099c32002-11-12 22:08:10 +00002117 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002118
2119 if (reverse && saved_ob_size > 1)
2120 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2121
2122 merge_freemem(&ms);
2123
2124dsu_fail:
Armin Rigo93677f02004-07-29 12:40:23 +00002125 final_ob_item = self->ob_item;
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002126 i = Py_Size(self);
2127 Py_Size(self) = saved_ob_size;
Tim Petersb9099c32002-11-12 22:08:10 +00002128 self->ob_item = saved_ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002129 self->allocated = saved_allocated;
Armin Rigo93677f02004-07-29 12:40:23 +00002130 if (final_ob_item != NULL) {
2131 /* we cannot use list_clear() for this because it does not
2132 guarantee that the list is really empty when it returns */
2133 while (--i >= 0) {
2134 Py_XDECREF(final_ob_item[i]);
2135 }
2136 PyMem_FREE(final_ob_item);
2137 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002138 Py_XDECREF(compare);
Tim Petersa64dc242002-08-01 02:13:36 +00002139 Py_XINCREF(result);
2140 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002141}
Tim Peters330f9e92002-07-19 07:05:44 +00002142#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002143#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002144
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002145int
Fred Drakea2f55112000-07-09 15:16:51 +00002146PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002147{
2148 if (v == NULL || !PyList_Check(v)) {
2149 PyErr_BadInternalCall();
2150 return -1;
2151 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002152 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002153 if (v == NULL)
2154 return -1;
2155 Py_DECREF(v);
2156 return 0;
2157}
2158
Guido van Rossumb86c5492001-02-12 22:06:02 +00002159static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002160listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002161{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002162 if (Py_Size(self) > 1)
2163 reverse_slice(self->ob_item, self->ob_item + Py_Size(self));
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002164 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002165}
2166
Guido van Rossum84c76f51990-10-30 13:32:20 +00002167int
Fred Drakea2f55112000-07-09 15:16:51 +00002168PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002169{
Tim Peters6063e262002-08-08 01:06:39 +00002170 PyListObject *self = (PyListObject *)v;
2171
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002172 if (v == NULL || !PyList_Check(v)) {
2173 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002174 return -1;
2175 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002176 if (Py_Size(self) > 1)
2177 reverse_slice(self->ob_item, self->ob_item + Py_Size(self));
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002178 return 0;
2179}
2180
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002181PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002182PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002183{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002184 PyObject *w;
2185 PyObject **p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002186 Py_ssize_t n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002187 if (v == NULL || !PyList_Check(v)) {
2188 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002189 return NULL;
2190 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002191 n = Py_Size(v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002192 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002193 if (w == NULL)
2194 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002195 p = ((PyTupleObject *)w)->ob_item;
Thomas Wouters334fb892000-07-25 12:56:38 +00002196 memcpy((void *)p,
2197 (void *)((PyListObject *)v)->ob_item,
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002198 n*sizeof(PyObject *));
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002199 while (--n >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002200 Py_INCREF(*p);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002201 p++;
2202 }
2203 return w;
2204}
2205
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002206static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002207listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002208{
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002209 Py_ssize_t i, start=0, stop=Py_Size(self);
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002210 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002211
Walter Dörwalde8049bef2003-06-17 19:27:39 +00002212 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2213 _PyEval_SliceIndex, &start,
2214 _PyEval_SliceIndex, &stop))
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002215 return NULL;
Guido van Rossum2743d872003-06-17 14:25:14 +00002216 if (start < 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002217 start += Py_Size(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002218 if (start < 0)
2219 start = 0;
2220 }
2221 if (stop < 0) {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002222 stop += Py_Size(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002223 if (stop < 0)
2224 stop = 0;
2225 }
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002226 for (i = start; i < stop && i < Py_Size(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002227 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2228 if (cmp > 0)
Martin v. Löwis18e16552006-02-15 17:27:45 +00002229 return PyInt_FromSsize_t(i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002230 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002231 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002232 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002233 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002234 return NULL;
2235}
2236
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002237static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002238listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002239{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002240 Py_ssize_t count = 0;
2241 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002242
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002243 for (i = 0; i < Py_Size(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002244 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2245 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002246 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002247 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002248 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00002249 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002250 return PyInt_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002251}
2252
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002253static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002254listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002255{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002256 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002257
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002258 for (i = 0; i < Py_Size(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002259 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2260 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002261 if (list_ass_slice(self, i, i+1,
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002262 (PyObject *)NULL) == 0)
2263 Py_RETURN_NONE;
2264 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002265 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002266 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002267 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002268 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002269 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002270 return NULL;
2271}
2272
Jeremy Hylton8caad492000-06-23 14:18:11 +00002273static int
2274list_traverse(PyListObject *o, visitproc visit, void *arg)
2275{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002276 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002277
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002278 for (i = Py_Size(o); --i >= 0; )
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002279 Py_VISIT(o->ob_item[i]);
Jeremy Hylton8caad492000-06-23 14:18:11 +00002280 return 0;
2281}
2282
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002283static PyObject *
2284list_richcompare(PyObject *v, PyObject *w, int op)
2285{
2286 PyListObject *vl, *wl;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002287 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002288
2289 if (!PyList_Check(v) || !PyList_Check(w)) {
2290 Py_INCREF(Py_NotImplemented);
2291 return Py_NotImplemented;
2292 }
2293
2294 vl = (PyListObject *)v;
2295 wl = (PyListObject *)w;
2296
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002297 if (Py_Size(vl) != Py_Size(wl) && (op == Py_EQ || op == Py_NE)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002298 /* Shortcut: if the lengths differ, the lists differ */
2299 PyObject *res;
2300 if (op == Py_EQ)
2301 res = Py_False;
2302 else
2303 res = Py_True;
2304 Py_INCREF(res);
2305 return res;
2306 }
2307
2308 /* Search for the first index where items are different */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002309 for (i = 0; i < Py_Size(vl) && i < Py_Size(wl); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002310 int k = PyObject_RichCompareBool(vl->ob_item[i],
2311 wl->ob_item[i], Py_EQ);
2312 if (k < 0)
2313 return NULL;
2314 if (!k)
2315 break;
2316 }
2317
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002318 if (i >= Py_Size(vl) || i >= Py_Size(wl)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002319 /* No more items to compare -- compare sizes */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002320 Py_ssize_t vs = Py_Size(vl);
2321 Py_ssize_t ws = Py_Size(wl);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002322 int cmp;
2323 PyObject *res;
2324 switch (op) {
2325 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00002326 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002327 case Py_EQ: cmp = vs == ws; break;
2328 case Py_NE: cmp = vs != ws; break;
2329 case Py_GT: cmp = vs > ws; break;
2330 case Py_GE: cmp = vs >= ws; break;
2331 default: return NULL; /* cannot happen */
2332 }
2333 if (cmp)
2334 res = Py_True;
2335 else
2336 res = Py_False;
2337 Py_INCREF(res);
2338 return res;
2339 }
2340
2341 /* We have an item that differs -- shortcuts for EQ/NE */
2342 if (op == Py_EQ) {
2343 Py_INCREF(Py_False);
2344 return Py_False;
2345 }
2346 if (op == Py_NE) {
2347 Py_INCREF(Py_True);
2348 return Py_True;
2349 }
2350
2351 /* Compare the final item again using the proper operator */
2352 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
2353}
2354
Tim Peters6d6c1a32001-08-02 04:15:00 +00002355static int
2356list_init(PyListObject *self, PyObject *args, PyObject *kw)
2357{
2358 PyObject *arg = NULL;
Martin v. Löwis15e62742006-02-27 16:46:16 +00002359 static char *kwlist[] = {"sequence", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002360
2361 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2362 return -1;
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002363
2364 /* Verify list invariants established by PyType_GenericAlloc() */
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002365 assert(0 <= Py_Size(self));
2366 assert(Py_Size(self) <= self->allocated || self->allocated == -1);
Armin Rigoa37bbf22004-07-30 11:20:18 +00002367 assert(self->ob_item != NULL ||
2368 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002369
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002370 /* Empty previous contents */
Armin Rigo93677f02004-07-29 12:40:23 +00002371 if (self->ob_item != NULL) {
2372 (void)list_clear(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002373 }
2374 if (arg != NULL) {
2375 PyObject *rv = listextend(self, arg);
2376 if (rv == NULL)
2377 return -1;
2378 Py_DECREF(rv);
2379 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002380 return 0;
2381}
2382
Raymond Hettinger1021c442003-11-07 15:38:09 +00002383static PyObject *list_iter(PyObject *seq);
2384static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2385
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002386PyDoc_STRVAR(getitem_doc,
2387"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002388PyDoc_STRVAR(reversed_doc,
2389"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002390PyDoc_STRVAR(append_doc,
2391"L.append(object) -- append object to end");
2392PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002393"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002394PyDoc_STRVAR(insert_doc,
2395"L.insert(index, object) -- insert object before index");
2396PyDoc_STRVAR(pop_doc,
2397"L.pop([index]) -> item -- remove and return item at index (default last)");
2398PyDoc_STRVAR(remove_doc,
2399"L.remove(value) -- remove first occurrence of value");
2400PyDoc_STRVAR(index_doc,
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002401"L.index(value, [start, [stop]]) -> integer -- return first index of value");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002402PyDoc_STRVAR(count_doc,
2403"L.count(value) -> integer -- return number of occurrences of value");
2404PyDoc_STRVAR(reverse_doc,
2405"L.reverse() -- reverse *IN PLACE*");
2406PyDoc_STRVAR(sort_doc,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002407"L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n\
2408cmp(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002409
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002410static PyObject *list_subscript(PyListObject*, PyObject*);
2411
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002412static PyMethodDef list_methods[] = {
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002413 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
Raymond Hettinger1021c442003-11-07 15:38:09 +00002414 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002415 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002416 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002417 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002418 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002419 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002420 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002421 {"count", (PyCFunction)listcount, METH_O, count_doc},
2422 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002423 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
Tim Petersa64dc242002-08-01 02:13:36 +00002424 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002425};
2426
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002427static PySequenceMethods list_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002428 (lenfunc)list_length, /* sq_length */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002429 (binaryfunc)list_concat, /* sq_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002430 (ssizeargfunc)list_repeat, /* sq_repeat */
2431 (ssizeargfunc)list_item, /* sq_item */
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002432 0, /* sq_slice */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002433 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002434 0, /* sq_ass_slice */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002435 (objobjproc)list_contains, /* sq_contains */
2436 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002437 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002438};
2439
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002440PyDoc_STRVAR(list_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002441"list() -> new list\n"
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002442"list(sequence) -> new list initialized from sequence's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002443
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002444static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002445list_subscript(PyListObject* self, PyObject* item)
2446{
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002447 if (PyIndex_Check(item)) {
2448 Py_ssize_t i;
2449 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002450 if (i == -1 && PyErr_Occurred())
2451 return NULL;
2452 if (i < 0)
2453 i += PyList_GET_SIZE(self);
2454 return list_item(self, i);
2455 }
2456 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002457 Py_ssize_t start, stop, step, slicelength, cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002458 PyObject* result;
2459 PyObject* it;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002460 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002461
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002462 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_Size(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002463 &start, &stop, &step, &slicelength) < 0) {
2464 return NULL;
2465 }
2466
2467 if (slicelength <= 0) {
2468 return PyList_New(0);
2469 }
Thomas Woutersed03b412007-08-28 21:37:11 +00002470 else if (step == 1) {
2471 return list_slice(self, start, stop);
2472 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002473 else {
2474 result = PyList_New(slicelength);
2475 if (!result) return NULL;
2476
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002477 src = self->ob_item;
2478 dest = ((PyListObject *)result)->ob_item;
Tim Peters3b01a122002-07-19 02:35:45 +00002479 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002480 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002481 it = src[cur];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002482 Py_INCREF(it);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002483 dest[i] = it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002484 }
Tim Peters3b01a122002-07-19 02:35:45 +00002485
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002486 return result;
2487 }
2488 }
2489 else {
Thomas Wouters89f507f2006-12-13 04:49:30 +00002490 PyErr_Format(PyExc_TypeError,
2491 "list indices must be integers, not %.200s",
2492 item->ob_type->tp_name);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002493 return NULL;
2494 }
2495}
2496
Tim Peters3b01a122002-07-19 02:35:45 +00002497static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002498list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2499{
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002500 if (PyIndex_Check(item)) {
2501 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002502 if (i == -1 && PyErr_Occurred())
2503 return -1;
2504 if (i < 0)
2505 i += PyList_GET_SIZE(self);
2506 return list_ass_item(self, i, value);
2507 }
2508 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002509 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002510
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002511 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_Size(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002512 &start, &stop, &step, &slicelength) < 0) {
2513 return -1;
2514 }
2515
Thomas Woutersed03b412007-08-28 21:37:11 +00002516 if (step == 1)
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002517 return list_ass_slice(self, start, stop, value);
2518
Thomas Woutersed03b412007-08-28 21:37:11 +00002519 /* Make sure s[5:2] = [..] inserts at the right place:
2520 before 5, not before 2. */
2521 if ((step < 0 && start < stop) ||
2522 (step > 0 && start > stop))
2523 stop = start;
2524
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002525 if (value == NULL) {
2526 /* delete slice */
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002527 PyObject **garbage;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002528 Py_ssize_t cur, i;
Tim Peters3b01a122002-07-19 02:35:45 +00002529
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002530 if (slicelength <= 0)
2531 return 0;
2532
2533 if (step < 0) {
2534 stop = start + 1;
2535 start = stop + step*(slicelength - 1) - 1;
2536 step = -step;
2537 }
2538
2539 garbage = (PyObject**)
2540 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002541 if (!garbage) {
2542 PyErr_NoMemory();
2543 return -1;
2544 }
Tim Peters3b01a122002-07-19 02:35:45 +00002545
Thomas Woutersed03b412007-08-28 21:37:11 +00002546 /* drawing pictures might help understand these for
2547 loops. Basically, we memmove the parts of the
2548 list that are *not* part of the slice: step-1
2549 items for each item that is part of the slice,
2550 and then tail end of the list that was not
2551 covered by the slice */
Guido van Rossum75a20b12002-06-11 12:22:28 +00002552 for (cur = start, i = 0;
2553 cur < stop;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002554 cur += step, i++) {
Thomas Woutersed03b412007-08-28 21:37:11 +00002555 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002556
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002557 garbage[i] = PyList_GET_ITEM(self, cur);
2558
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002559 if (cur + step >= Py_Size(self)) {
2560 lim = Py_Size(self) - cur - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002561 }
2562
Tim Petersb38e2b62004-07-29 02:29:26 +00002563 memmove(self->ob_item + cur - i,
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002564 self->ob_item + cur + 1,
2565 lim * sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002566 }
Thomas Woutersed03b412007-08-28 21:37:11 +00002567 cur = start + slicelength*step;
2568 if (cur < Py_Size(self)) {
2569 memmove(self->ob_item + cur - slicelength,
2570 self->ob_item + cur,
2571 (Py_Size(self) - cur) *
2572 sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002573 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002574
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002575 Py_Size(self) -= slicelength;
2576 list_resize(self, Py_Size(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002577
2578 for (i = 0; i < slicelength; i++) {
2579 Py_DECREF(garbage[i]);
2580 }
2581 PyMem_FREE(garbage);
2582
2583 return 0;
2584 }
2585 else {
2586 /* assign slice */
Thomas Woutersed03b412007-08-28 21:37:11 +00002587 PyObject *ins, *seq;
2588 PyObject **garbage, **seqitems, **selfitems;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002589 Py_ssize_t cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002590
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002591 /* protect against a[::-1] = a */
Tim Peters3b01a122002-07-19 02:35:45 +00002592 if (self == (PyListObject*)value) {
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002593 seq = list_slice((PyListObject*)value, 0,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002594 PyList_GET_SIZE(value));
Tim Peters3b01a122002-07-19 02:35:45 +00002595 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002596 else {
Tim Petersb38e2b62004-07-29 02:29:26 +00002597 seq = PySequence_Fast(value,
Thomas Woutersed03b412007-08-28 21:37:11 +00002598 "must assign iterable "
2599 "to extended slice");
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002600 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002601 if (!seq)
2602 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002603
2604 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2605 PyErr_Format(PyExc_ValueError,
Thomas Woutersed03b412007-08-28 21:37:11 +00002606 "attempt to assign sequence of "
2607 "size %zd to extended slice of "
2608 "size %zd",
Martin v. Löwise0e89f72006-02-16 06:59:22 +00002609 PySequence_Fast_GET_SIZE(seq),
2610 slicelength);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002611 Py_DECREF(seq);
2612 return -1;
2613 }
2614
2615 if (!slicelength) {
2616 Py_DECREF(seq);
2617 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002618 }
2619
2620 garbage = (PyObject**)
2621 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Thomas Wouters89f507f2006-12-13 04:49:30 +00002622 if (!garbage) {
2623 Py_DECREF(seq);
2624 PyErr_NoMemory();
2625 return -1;
2626 }
Tim Peters3b01a122002-07-19 02:35:45 +00002627
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002628 selfitems = self->ob_item;
Raymond Hettinger42bec932004-03-12 16:38:17 +00002629 seqitems = PySequence_Fast_ITEMS(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002630 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002631 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002632 garbage[i] = selfitems[cur];
2633 ins = seqitems[i];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002634 Py_INCREF(ins);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002635 selfitems[cur] = ins;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002636 }
2637
2638 for (i = 0; i < slicelength; i++) {
2639 Py_DECREF(garbage[i]);
2640 }
Tim Peters3b01a122002-07-19 02:35:45 +00002641
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002642 PyMem_FREE(garbage);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002643 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002644
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002645 return 0;
2646 }
Tim Peters3b01a122002-07-19 02:35:45 +00002647 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002648 else {
Thomas Wouters89f507f2006-12-13 04:49:30 +00002649 PyErr_Format(PyExc_TypeError,
2650 "list indices must be integers, not %.200s",
2651 item->ob_type->tp_name);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002652 return -1;
2653 }
2654}
2655
2656static PyMappingMethods list_as_mapping = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002657 (lenfunc)list_length,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002658 (binaryfunc)list_subscript,
2659 (objobjargproc)list_ass_subscript
2660};
2661
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002662PyTypeObject PyList_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002663 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002664 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002665 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002666 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002667 (destructor)list_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00002668 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002669 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002670 0, /* tp_setattr */
2671 0, /* tp_compare */
2672 (reprfunc)list_repr, /* tp_repr */
2673 0, /* tp_as_number */
2674 &list_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002675 &list_as_mapping, /* tp_as_mapping */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00002676 0, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002677 0, /* tp_call */
2678 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002679 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002680 0, /* tp_setattro */
2681 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002682 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Thomas Wouters27d517b2007-02-25 20:39:11 +00002683 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002684 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002685 (traverseproc)list_traverse, /* tp_traverse */
2686 (inquiry)list_clear, /* tp_clear */
2687 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002688 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002689 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002690 0, /* tp_iternext */
2691 list_methods, /* tp_methods */
2692 0, /* tp_members */
2693 0, /* tp_getset */
2694 0, /* tp_base */
2695 0, /* tp_dict */
2696 0, /* tp_descr_get */
2697 0, /* tp_descr_set */
2698 0, /* tp_dictoffset */
2699 (initproc)list_init, /* tp_init */
2700 PyType_GenericAlloc, /* tp_alloc */
2701 PyType_GenericNew, /* tp_new */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002702 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002703};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002704
2705
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002706/*********************** List Iterator **************************/
2707
2708typedef struct {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002709 PyObject_HEAD
2710 long it_index;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002711 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002712} listiterobject;
2713
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002714static PyObject *list_iter(PyObject *);
2715static void listiter_dealloc(listiterobject *);
2716static int listiter_traverse(listiterobject *, visitproc, void *);
2717static PyObject *listiter_next(listiterobject *);
2718static PyObject *listiter_len(listiterobject *);
Raymond Hettinger435bf582004-03-18 22:43:10 +00002719
Armin Rigof5b3e362006-02-11 21:32:43 +00002720PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002721
2722static PyMethodDef listiter_methods[] = {
Armin Rigof5b3e362006-02-11 21:32:43 +00002723 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002724 {NULL, NULL} /* sentinel */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002725};
2726
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002727PyTypeObject PyListIter_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002728 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002729 "listiterator", /* tp_name */
2730 sizeof(listiterobject), /* tp_basicsize */
2731 0, /* tp_itemsize */
2732 /* methods */
2733 (destructor)listiter_dealloc, /* tp_dealloc */
2734 0, /* tp_print */
2735 0, /* tp_getattr */
2736 0, /* tp_setattr */
2737 0, /* tp_compare */
2738 0, /* tp_repr */
2739 0, /* tp_as_number */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002740 0, /* tp_as_sequence */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002741 0, /* tp_as_mapping */
2742 0, /* tp_hash */
2743 0, /* tp_call */
2744 0, /* tp_str */
2745 PyObject_GenericGetAttr, /* tp_getattro */
2746 0, /* tp_setattro */
2747 0, /* tp_as_buffer */
2748 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2749 0, /* tp_doc */
2750 (traverseproc)listiter_traverse, /* tp_traverse */
2751 0, /* tp_clear */
2752 0, /* tp_richcompare */
2753 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00002754 PyObject_SelfIter, /* tp_iter */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002755 (iternextfunc)listiter_next, /* tp_iternext */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002756 listiter_methods, /* tp_methods */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002757 0, /* tp_members */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002758};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002759
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002760
2761static PyObject *
2762list_iter(PyObject *seq)
2763{
2764 listiterobject *it;
2765
2766 if (!PyList_Check(seq)) {
2767 PyErr_BadInternalCall();
2768 return NULL;
2769 }
2770 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2771 if (it == NULL)
2772 return NULL;
2773 it->it_index = 0;
2774 Py_INCREF(seq);
2775 it->it_seq = (PyListObject *)seq;
2776 _PyObject_GC_TRACK(it);
2777 return (PyObject *)it;
2778}
2779
2780static void
2781listiter_dealloc(listiterobject *it)
2782{
2783 _PyObject_GC_UNTRACK(it);
2784 Py_XDECREF(it->it_seq);
2785 PyObject_GC_Del(it);
2786}
2787
2788static int
2789listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2790{
2791 Py_VISIT(it->it_seq);
2792 return 0;
2793}
2794
2795static PyObject *
2796listiter_next(listiterobject *it)
2797{
2798 PyListObject *seq;
2799 PyObject *item;
2800
2801 assert(it != NULL);
2802 seq = it->it_seq;
2803 if (seq == NULL)
2804 return NULL;
2805 assert(PyList_Check(seq));
2806
2807 if (it->it_index < PyList_GET_SIZE(seq)) {
2808 item = PyList_GET_ITEM(seq, it->it_index);
2809 ++it->it_index;
2810 Py_INCREF(item);
2811 return item;
2812 }
2813
2814 Py_DECREF(seq);
2815 it->it_seq = NULL;
2816 return NULL;
2817}
2818
2819static PyObject *
2820listiter_len(listiterobject *it)
2821{
2822 Py_ssize_t len;
2823 if (it->it_seq) {
2824 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2825 if (len >= 0)
2826 return PyInt_FromSsize_t(len);
2827 }
2828 return PyInt_FromLong(0);
2829}
Raymond Hettinger1021c442003-11-07 15:38:09 +00002830/*********************** List Reverse Iterator **************************/
2831
2832typedef struct {
2833 PyObject_HEAD
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002834 Py_ssize_t it_index;
Raymond Hettinger001f2282003-11-08 11:58:44 +00002835 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002836} listreviterobject;
2837
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002838static PyObject *list_reversed(PyListObject *, PyObject *);
2839static void listreviter_dealloc(listreviterobject *);
2840static int listreviter_traverse(listreviterobject *, visitproc, void *);
2841static PyObject *listreviter_next(listreviterobject *);
2842static Py_ssize_t listreviter_len(listreviterobject *);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002843
2844static PySequenceMethods listreviter_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002845 (lenfunc)listreviter_len, /* sq_length */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002846 0, /* sq_concat */
2847};
2848
Raymond Hettinger1021c442003-11-07 15:38:09 +00002849PyTypeObject PyListRevIter_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002850 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Raymond Hettinger1021c442003-11-07 15:38:09 +00002851 "listreverseiterator", /* tp_name */
2852 sizeof(listreviterobject), /* tp_basicsize */
2853 0, /* tp_itemsize */
2854 /* methods */
2855 (destructor)listreviter_dealloc, /* tp_dealloc */
2856 0, /* tp_print */
2857 0, /* tp_getattr */
2858 0, /* tp_setattr */
2859 0, /* tp_compare */
2860 0, /* tp_repr */
2861 0, /* tp_as_number */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002862 &listreviter_as_sequence, /* tp_as_sequence */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002863 0, /* tp_as_mapping */
2864 0, /* tp_hash */
2865 0, /* tp_call */
2866 0, /* tp_str */
2867 PyObject_GenericGetAttr, /* tp_getattro */
2868 0, /* tp_setattro */
2869 0, /* tp_as_buffer */
2870 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2871 0, /* tp_doc */
2872 (traverseproc)listreviter_traverse, /* tp_traverse */
2873 0, /* tp_clear */
2874 0, /* tp_richcompare */
2875 0, /* tp_weaklistoffset */
2876 PyObject_SelfIter, /* tp_iter */
2877 (iternextfunc)listreviter_next, /* tp_iternext */
2878 0,
2879};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002880
2881static PyObject *
2882list_reversed(PyListObject *seq, PyObject *unused)
2883{
2884 listreviterobject *it;
2885
2886 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2887 if (it == NULL)
2888 return NULL;
2889 assert(PyList_Check(seq));
2890 it->it_index = PyList_GET_SIZE(seq) - 1;
2891 Py_INCREF(seq);
2892 it->it_seq = seq;
2893 PyObject_GC_Track(it);
2894 return (PyObject *)it;
2895}
2896
2897static void
2898listreviter_dealloc(listreviterobject *it)
2899{
2900 PyObject_GC_UnTrack(it);
2901 Py_XDECREF(it->it_seq);
2902 PyObject_GC_Del(it);
2903}
2904
2905static int
2906listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2907{
2908 Py_VISIT(it->it_seq);
2909 return 0;
2910}
2911
2912static PyObject *
2913listreviter_next(listreviterobject *it)
2914{
2915 PyObject *item;
2916 Py_ssize_t index = it->it_index;
2917 PyListObject *seq = it->it_seq;
2918
2919 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2920 item = PyList_GET_ITEM(seq, index);
2921 it->it_index--;
2922 Py_INCREF(item);
2923 return item;
2924 }
2925 it->it_index = -1;
2926 if (seq != NULL) {
2927 it->it_seq = NULL;
2928 Py_DECREF(seq);
2929 }
2930 return NULL;
2931}
2932
2933static Py_ssize_t
2934listreviter_len(listreviterobject *it)
2935{
2936 Py_ssize_t len = it->it_index + 1;
2937 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
2938 return 0;
2939 return len;
2940}
2941