blob: d2917d2caa96921308e88665f1fc5aa36a0182c7 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* List object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
4
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00005#ifdef STDC_HEADERS
6#include <stddef.h>
7#else
8#include <sys/types.h> /* For size_t */
9#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000010
Tim Peters8d9eb102004-07-31 02:24:20 +000011/* Ensure ob_item has room for at least newsize elements, and set
12 * ob_size to newsize. If newsize > ob_size on entry, the content
13 * of the new slots at exit is undefined heap trash; it's the caller's
14 * responsiblity to overwrite them with sane values.
15 * The number of allocated elements may grow, shrink, or stay the same.
16 * Failure is impossible if newsize <= self.allocated on entry, although
17 * that partly relies on an assumption that the system realloc() never
18 * fails when passed a number of bytes <= the number of bytes last
19 * allocated (the C standard doesn't guarantee this, but it's hard to
20 * imagine a realloc implementation where it wouldn't be true).
21 * Note that self->ob_item may change, and even if newsize is less
22 * than ob_size on entry.
23 */
Guido van Rossuma46d51d1995-01-26 22:59:43 +000024static int
Martin v. Löwis18e16552006-02-15 17:27:45 +000025list_resize(PyListObject *self, Py_ssize_t newsize)
Guido van Rossuma46d51d1995-01-26 22:59:43 +000026{
Raymond Hettinger4bb95402004-02-13 11:36:39 +000027 PyObject **items;
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000028 size_t new_allocated;
Martin v. Löwis18e16552006-02-15 17:27:45 +000029 Py_ssize_t allocated = self->allocated;
Tim Peters65b8b842001-05-26 05:28:40 +000030
Raymond Hettinger4bb95402004-02-13 11:36:39 +000031 /* Bypass realloc() when a previous overallocation is large enough
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000032 to accommodate the newsize. If the newsize falls lower than half
33 the allocated size, then proceed with the realloc() to shrink the list.
Raymond Hettinger4bb95402004-02-13 11:36:39 +000034 */
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000035 if (allocated >= newsize && newsize >= (allocated >> 1)) {
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +000036 assert(self->ob_item != NULL || newsize == 0);
Christian Heimes90aa7642007-12-19 02:45:37 +000037 Py_SIZE(self) = newsize;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000038 return 0;
39 }
40
41 /* This over-allocates proportional to the list size, making room
Tim Peters65b8b842001-05-26 05:28:40 +000042 * for additional growth. The over-allocation is mild, but is
43 * enough to give linear-time amortized behavior over a long
44 * sequence of appends() in the presence of a poorly-performing
Raymond Hettingerab517d22004-02-14 18:34:46 +000045 * system realloc().
46 * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
Tim Peters65b8b842001-05-26 05:28:40 +000047 */
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000048 new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6) + newsize;
49 if (newsize == 0)
50 new_allocated = 0;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000051 items = self->ob_item;
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000052 if (new_allocated <= ((~(size_t)0) / sizeof(PyObject *)))
53 PyMem_RESIZE(items, PyObject *, new_allocated);
Raymond Hettinger4bb95402004-02-13 11:36:39 +000054 else
55 items = NULL;
56 if (items == NULL) {
57 PyErr_NoMemory();
58 return -1;
59 }
60 self->ob_item = items;
Christian Heimes90aa7642007-12-19 02:45:37 +000061 Py_SIZE(self) = newsize;
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000062 self->allocated = new_allocated;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000063 return 0;
64}
Guido van Rossuma46d51d1995-01-26 22:59:43 +000065
Christian Heimes77c02eb2008-02-09 02:18:51 +000066/* Debug statistic to compare allocations with reuse through the free list */
67#undef SHOW_ALLOC_COUNT
68#ifdef SHOW_ALLOC_COUNT
69static size_t count_alloc = 0;
70static size_t count_reuse = 0;
71
72static void
73show_alloc(void)
74{
75 fprintf(stderr, "List allocations: %zd\n", count_alloc);
76 fprintf(stderr, "List reuse through freelist: %zd\n", count_reuse);
77 fprintf(stderr, "%.2f%% reuse rate\n\n",
78 (100.0*count_reuse/(count_alloc+count_reuse)));
79}
80#endif
81
Raymond Hettinger0468e412004-05-05 05:37:53 +000082/* Empty list reuse scheme to save calls to malloc and free */
Christian Heimes2202f872008-02-06 14:31:34 +000083#ifndef PyList_MAXFREELIST
84#define PyList_MAXFREELIST 80
85#endif
86static PyListObject *free_list[PyList_MAXFREELIST];
87static int numfree = 0;
Raymond Hettinger0468e412004-05-05 05:37:53 +000088
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +000089void
90PyList_Fini(void)
91{
92 PyListObject *op;
93
Christian Heimes2202f872008-02-06 14:31:34 +000094 while (numfree) {
Christian Heimes77c02eb2008-02-09 02:18:51 +000095 op = free_list[--numfree];
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +000096 assert(PyList_CheckExact(op));
97 PyObject_GC_Del(op);
98 }
99}
100
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000101PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000102PyList_New(Py_ssize_t size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000103{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000104 PyListObject *op;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +0000105 size_t nbytes;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000106#ifdef SHOW_ALLOC_COUNT
107 static int initialized = 0;
108 if (!initialized) {
109 Py_AtExit(show_alloc);
110 initialized = 1;
111 }
112#endif
Tim Peters3986d4e2004-07-29 02:28:42 +0000113
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000114 if (size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000115 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000116 return NULL;
117 }
Tim Peters7049d812004-01-18 20:31:02 +0000118 nbytes = size * sizeof(PyObject *);
Guido van Rossum1e28e5e1992-08-19 16:46:30 +0000119 /* Check for overflow */
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000120 if (nbytes / sizeof(PyObject *) != (size_t)size)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000121 return PyErr_NoMemory();
Christian Heimes2202f872008-02-06 14:31:34 +0000122 if (numfree) {
123 numfree--;
124 op = free_list[numfree];
Raymond Hettinger0468e412004-05-05 05:37:53 +0000125 _Py_NewReference((PyObject *)op);
Christian Heimes77c02eb2008-02-09 02:18:51 +0000126#ifdef SHOW_ALLOC_COUNT
127 count_reuse++;
128#endif
Raymond Hettinger0468e412004-05-05 05:37:53 +0000129 } else {
130 op = PyObject_GC_New(PyListObject, &PyList_Type);
131 if (op == NULL)
132 return NULL;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000133#ifdef SHOW_ALLOC_COUNT
134 count_alloc++;
135#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000136 }
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000137 if (size <= 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000138 op->ob_item = NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000139 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +0000140 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000141 if (op->ob_item == NULL) {
142 Py_DECREF(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000143 return PyErr_NoMemory();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000144 }
Tim Peters3986d4e2004-07-29 02:28:42 +0000145 memset(op->ob_item, 0, nbytes);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000146 }
Christian Heimes90aa7642007-12-19 02:45:37 +0000147 Py_SIZE(op) = size;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000148 op->allocated = size;
Neil Schemenauere83c00e2001-08-29 23:54:21 +0000149 _PyObject_GC_TRACK(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000150 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000151}
152
Martin v. Löwis18e16552006-02-15 17:27:45 +0000153Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000154PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000155{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000156 if (!PyList_Check(op)) {
157 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000158 return -1;
159 }
160 else
Christian Heimes90aa7642007-12-19 02:45:37 +0000161 return Py_SIZE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000162}
163
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000164static PyObject *indexerr = NULL;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000165
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000166PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000167PyList_GetItem(PyObject *op, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000168{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000169 if (!PyList_Check(op)) {
170 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000171 return NULL;
172 }
Christian Heimes90aa7642007-12-19 02:45:37 +0000173 if (i < 0 || i >= Py_SIZE(op)) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000174 if (indexerr == NULL)
Neal Norwitz53cbdaa2007-08-23 21:42:55 +0000175 indexerr = PyUnicode_FromString(
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000176 "list index out of range");
177 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000178 return NULL;
179 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000180 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000181}
182
183int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000184PyList_SetItem(register PyObject *op, register Py_ssize_t i,
Fred Drakea2f55112000-07-09 15:16:51 +0000185 register PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000186{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000187 register PyObject *olditem;
188 register PyObject **p;
189 if (!PyList_Check(op)) {
190 Py_XDECREF(newitem);
191 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000192 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000193 }
Christian Heimes90aa7642007-12-19 02:45:37 +0000194 if (i < 0 || i >= Py_SIZE(op)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000195 Py_XDECREF(newitem);
196 PyErr_SetString(PyExc_IndexError,
197 "list assignment index out of range");
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000198 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000199 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000200 p = ((PyListObject *)op) -> ob_item + i;
Guido van Rossum5fe60581995-03-09 12:12:50 +0000201 olditem = *p;
202 *p = newitem;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000203 Py_XDECREF(olditem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000204 return 0;
205}
206
207static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000208ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000209{
Christian Heimes90aa7642007-12-19 02:45:37 +0000210 Py_ssize_t i, n = Py_SIZE(self);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000211 PyObject **items;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000212 if (v == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000213 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000214 return -1;
215 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000216 if (n == PY_SSIZE_T_MAX) {
Trent Micka5846642000-08-13 22:47:45 +0000217 PyErr_SetString(PyExc_OverflowError,
218 "cannot add more objects to list");
219 return -1;
220 }
Tim Petersb38e2b62004-07-29 02:29:26 +0000221
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000222 if (list_resize(self, n+1) == -1)
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000223 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000224
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000225 if (where < 0) {
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000226 where += n;
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000227 if (where < 0)
228 where = 0;
229 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000230 if (where > n)
231 where = n;
232 items = self->ob_item;
233 for (i = n; --i >= where; )
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000234 items[i+1] = items[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000235 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000236 items[where] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000237 return 0;
238}
239
240int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000241PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000242{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000243 if (!PyList_Check(op)) {
244 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000245 return -1;
246 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000247 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000248}
249
Raymond Hettinger40a03822004-04-12 13:05:09 +0000250static int
251app1(PyListObject *self, PyObject *v)
252{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000253 Py_ssize_t n = PyList_GET_SIZE(self);
Raymond Hettinger40a03822004-04-12 13:05:09 +0000254
255 assert (v != NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000256 if (n == PY_SSIZE_T_MAX) {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000257 PyErr_SetString(PyExc_OverflowError,
258 "cannot add more objects to list");
259 return -1;
260 }
261
262 if (list_resize(self, n+1) == -1)
263 return -1;
264
265 Py_INCREF(v);
266 PyList_SET_ITEM(self, n, v);
267 return 0;
268}
269
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000270int
Fred Drakea2f55112000-07-09 15:16:51 +0000271PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000272{
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000273 if (PyList_Check(op) && (newitem != NULL))
274 return app1((PyListObject *)op, newitem);
275 PyErr_BadInternalCall();
276 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000277}
278
279/* Methods */
280
281static void
Fred Drakea2f55112000-07-09 15:16:51 +0000282list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000283{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000284 Py_ssize_t i;
Guido van Rossumff413af2002-03-28 20:34:59 +0000285 PyObject_GC_UnTrack(op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000286 Py_TRASHCAN_SAFE_BEGIN(op)
Jack Jansen7874d1f1995-01-19 12:09:27 +0000287 if (op->ob_item != NULL) {
Guido van Rossumfa717011999-06-09 15:19:34 +0000288 /* Do it backwards, for Christian Tismer.
289 There's a simple test case where somehow this reduces
290 thrashing when a *very* large list is created and
291 immediately deleted. */
Christian Heimes90aa7642007-12-19 02:45:37 +0000292 i = Py_SIZE(op);
Guido van Rossumfa717011999-06-09 15:19:34 +0000293 while (--i >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000294 Py_XDECREF(op->ob_item[i]);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000295 }
Guido van Rossumb18618d2000-05-03 23:44:39 +0000296 PyMem_FREE(op->ob_item);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000297 }
Christian Heimes2202f872008-02-06 14:31:34 +0000298 if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op))
299 free_list[numfree++] = op;
Tim Petersb38e2b62004-07-29 02:29:26 +0000300 else
Christian Heimes90aa7642007-12-19 02:45:37 +0000301 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000302 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000303}
304
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000305static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000306list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000307{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000308 Py_ssize_t i;
Tim Petersa7259592001-06-16 05:11:17 +0000309 PyObject *s, *temp;
310 PyObject *pieces = NULL, *result = NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000311
312 i = Py_ReprEnter((PyObject*)v);
313 if (i != 0) {
Walter Dörwald1ab83302007-05-18 17:15:44 +0000314 return i > 0 ? PyUnicode_FromString("[...]") : NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000315 }
Tim Petersa7259592001-06-16 05:11:17 +0000316
Christian Heimes90aa7642007-12-19 02:45:37 +0000317 if (Py_SIZE(v) == 0) {
Walter Dörwald1ab83302007-05-18 17:15:44 +0000318 result = PyUnicode_FromString("[]");
Tim Petersa7259592001-06-16 05:11:17 +0000319 goto Done;
320 }
321
322 pieces = PyList_New(0);
323 if (pieces == NULL)
324 goto Done;
325
326 /* Do repr() on each element. Note that this may mutate the list,
327 so must refetch the list size on each iteration. */
Christian Heimes90aa7642007-12-19 02:45:37 +0000328 for (i = 0; i < Py_SIZE(v); ++i) {
Tim Petersa7259592001-06-16 05:11:17 +0000329 int status;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000330 if (Py_EnterRecursiveCall(" while getting the repr of a list"))
331 goto Done;
Tim Petersa7259592001-06-16 05:11:17 +0000332 s = PyObject_Repr(v->ob_item[i]);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000333 Py_LeaveRecursiveCall();
Tim Petersa7259592001-06-16 05:11:17 +0000334 if (s == NULL)
335 goto Done;
336 status = PyList_Append(pieces, s);
337 Py_DECREF(s); /* append created a new ref */
338 if (status < 0)
339 goto Done;
340 }
341
342 /* Add "[]" decorations to the first and last items. */
343 assert(PyList_GET_SIZE(pieces) > 0);
Walter Dörwald1ab83302007-05-18 17:15:44 +0000344 s = PyUnicode_FromString("[");
Tim Petersa7259592001-06-16 05:11:17 +0000345 if (s == NULL)
346 goto Done;
347 temp = PyList_GET_ITEM(pieces, 0);
Walter Dörwald1ab83302007-05-18 17:15:44 +0000348 PyUnicode_AppendAndDel(&s, temp);
Tim Petersa7259592001-06-16 05:11:17 +0000349 PyList_SET_ITEM(pieces, 0, s);
350 if (s == NULL)
351 goto Done;
352
Walter Dörwald1ab83302007-05-18 17:15:44 +0000353 s = PyUnicode_FromString("]");
Tim Petersa7259592001-06-16 05:11:17 +0000354 if (s == NULL)
355 goto Done;
356 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
Walter Dörwald1ab83302007-05-18 17:15:44 +0000357 PyUnicode_AppendAndDel(&temp, s);
Tim Petersa7259592001-06-16 05:11:17 +0000358 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
359 if (temp == NULL)
360 goto Done;
361
362 /* Paste them all together with ", " between. */
Walter Dörwald1ab83302007-05-18 17:15:44 +0000363 s = PyUnicode_FromString(", ");
Tim Petersa7259592001-06-16 05:11:17 +0000364 if (s == NULL)
365 goto Done;
Walter Dörwald1ab83302007-05-18 17:15:44 +0000366 result = PyUnicode_Join(s, pieces);
Tim Peters3b01a122002-07-19 02:35:45 +0000367 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +0000368
369Done:
370 Py_XDECREF(pieces);
Guido van Rossumfb376de1998-04-10 22:47:27 +0000371 Py_ReprLeave((PyObject *)v);
Tim Petersa7259592001-06-16 05:11:17 +0000372 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000373}
374
Martin v. Löwis18e16552006-02-15 17:27:45 +0000375static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000376list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000377{
Christian Heimes90aa7642007-12-19 02:45:37 +0000378 return Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000379}
380
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000381static int
Fred Drakea2f55112000-07-09 15:16:51 +0000382list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000383{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000384 Py_ssize_t i;
385 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000386
Christian Heimes90aa7642007-12-19 02:45:37 +0000387 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
Raymond Hettingeraae59992002-09-05 14:23:49 +0000388 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000389 Py_EQ);
Neal Norwitzbb9c5f52002-09-05 21:32:55 +0000390 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000391}
392
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000393static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000394list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000395{
Christian Heimes90aa7642007-12-19 02:45:37 +0000396 if (i < 0 || i >= Py_SIZE(a)) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000397 if (indexerr == NULL)
Neal Norwitz53cbdaa2007-08-23 21:42:55 +0000398 indexerr = PyUnicode_FromString(
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000399 "list index out of range");
400 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000401 return NULL;
402 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000403 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000404 return a->ob_item[i];
405}
406
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000407static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000408list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000409{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000410 PyListObject *np;
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000411 PyObject **src, **dest;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000412 Py_ssize_t i, len;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000413 if (ilow < 0)
414 ilow = 0;
Christian Heimes90aa7642007-12-19 02:45:37 +0000415 else if (ilow > Py_SIZE(a))
416 ilow = Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000417 if (ihigh < ilow)
418 ihigh = ilow;
Christian Heimes90aa7642007-12-19 02:45:37 +0000419 else if (ihigh > Py_SIZE(a))
420 ihigh = Py_SIZE(a);
Raymond Hettinger99842b62004-03-08 05:56:15 +0000421 len = ihigh - ilow;
422 np = (PyListObject *) PyList_New(len);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000423 if (np == NULL)
424 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000425
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000426 src = a->ob_item + ilow;
427 dest = np->ob_item;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000428 for (i = 0; i < len; i++) {
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000429 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000430 Py_INCREF(v);
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000431 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000432 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000433 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000434}
435
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000436PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000437PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000438{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000439 if (!PyList_Check(a)) {
440 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000441 return NULL;
442 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000443 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000444}
445
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000446static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000447list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000448{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000449 Py_ssize_t size;
450 Py_ssize_t i;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000451 PyObject **src, **dest;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000452 PyListObject *np;
453 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000454 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000455 "can only concatenate list (not \"%.200s\") to list",
456 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000457 return NULL;
458 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000459#define b ((PyListObject *)bb)
Christian Heimes90aa7642007-12-19 02:45:37 +0000460 size = Py_SIZE(a) + Py_SIZE(b);
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000461 if (size < 0)
462 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000463 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000464 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000465 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000466 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000467 src = a->ob_item;
468 dest = np->ob_item;
Christian Heimes90aa7642007-12-19 02:45:37 +0000469 for (i = 0; i < Py_SIZE(a); i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000470 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000471 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000472 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000473 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000474 src = b->ob_item;
Christian Heimes90aa7642007-12-19 02:45:37 +0000475 dest = np->ob_item + Py_SIZE(a);
476 for (i = 0; i < Py_SIZE(b); i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000477 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000478 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000479 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000480 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000481 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000482#undef b
483}
484
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000485static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000486list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000487{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000488 Py_ssize_t i, j;
489 Py_ssize_t size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000490 PyListObject *np;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000491 PyObject **p, **items;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000492 PyObject *elem;
Guido van Rossumed98d481991-03-06 13:07:53 +0000493 if (n < 0)
494 n = 0;
Christian Heimes90aa7642007-12-19 02:45:37 +0000495 size = Py_SIZE(a) * n;
496 if (n && size/n != Py_SIZE(a))
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000497 return PyErr_NoMemory();
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000498 if (size == 0)
Christian Heimesaf98da12008-01-27 15:18:18 +0000499 return PyList_New(0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000500 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000501 if (np == NULL)
502 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000503
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000504 items = np->ob_item;
Christian Heimes90aa7642007-12-19 02:45:37 +0000505 if (Py_SIZE(a) == 1) {
Raymond Hettinger6624e682003-05-21 05:58:46 +0000506 elem = a->ob_item[0];
507 for (i = 0; i < n; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000508 items[i] = elem;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000509 Py_INCREF(elem);
510 }
511 return (PyObject *) np;
512 }
Guido van Rossumed98d481991-03-06 13:07:53 +0000513 p = np->ob_item;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000514 items = a->ob_item;
Guido van Rossumed98d481991-03-06 13:07:53 +0000515 for (i = 0; i < n; i++) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000516 for (j = 0; j < Py_SIZE(a); j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000517 *p = items[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000518 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000519 p++;
520 }
521 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000522 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000523}
524
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000525static int
Armin Rigo93677f02004-07-29 12:40:23 +0000526list_clear(PyListObject *a)
527{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000528 Py_ssize_t i;
Armin Rigo93677f02004-07-29 12:40:23 +0000529 PyObject **item = a->ob_item;
530 if (item != NULL) {
531 /* Because XDECREF can recursively invoke operations on
532 this list, we make it empty first. */
Christian Heimes90aa7642007-12-19 02:45:37 +0000533 i = Py_SIZE(a);
534 Py_SIZE(a) = 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000535 a->ob_item = NULL;
536 a->allocated = 0;
537 while (--i >= 0) {
538 Py_XDECREF(item[i]);
539 }
540 PyMem_FREE(item);
541 }
542 /* Never fails; the return value can be ignored.
543 Note that there is no guarantee that the list is actually empty
544 at this point, because XDECREF may have populated it again! */
545 return 0;
546}
547
Tim Peters8fc4a912004-07-31 21:53:19 +0000548/* a[ilow:ihigh] = v if v != NULL.
549 * del a[ilow:ihigh] if v == NULL.
550 *
551 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
552 * guaranteed the call cannot fail.
553 */
Armin Rigo93677f02004-07-29 12:40:23 +0000554static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000555list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000556{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000557 /* Because [X]DECREF can recursively invoke list operations on
558 this list, we must postpone all [X]DECREF activity until
559 after the list is back in its canonical shape. Therefore
560 we must allocate an additional array, 'recycle', into which
561 we temporarily copy the items that are deleted from the
562 list. :-( */
Tim Peters73572222004-07-31 02:54:42 +0000563 PyObject *recycle_on_stack[8];
564 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000565 PyObject **item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000566 PyObject **vitem = NULL;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000567 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000568 Py_ssize_t n; /* # of elements in replacement list */
569 Py_ssize_t norig; /* # of elements in list getting replaced */
570 Py_ssize_t d; /* Change in size */
571 Py_ssize_t k;
Tim Peters8d9eb102004-07-31 02:24:20 +0000572 size_t s;
573 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000574#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000575 if (v == NULL)
576 n = 0;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000577 else {
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000578 if (a == b) {
579 /* Special case "a[i:j] = a" -- copy b first */
Christian Heimes90aa7642007-12-19 02:45:37 +0000580 v = list_slice(b, 0, Py_SIZE(b));
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000581 if (v == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000582 return result;
583 result = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000584 Py_DECREF(v);
Tim Peters8d9eb102004-07-31 02:24:20 +0000585 return result;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000586 }
Raymond Hettingerf889e102004-03-09 08:04:33 +0000587 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000588 if(v_as_SF == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000589 goto Error;
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000590 n = PySequence_Fast_GET_SIZE(v_as_SF);
Raymond Hettinger42bec932004-03-12 16:38:17 +0000591 vitem = PySequence_Fast_ITEMS(v_as_SF);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000592 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000593 if (ilow < 0)
594 ilow = 0;
Christian Heimes90aa7642007-12-19 02:45:37 +0000595 else if (ilow > Py_SIZE(a))
596 ilow = Py_SIZE(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000597
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000598 if (ihigh < ilow)
599 ihigh = ilow;
Christian Heimes90aa7642007-12-19 02:45:37 +0000600 else if (ihigh > Py_SIZE(a))
601 ihigh = Py_SIZE(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000602
Tim Peters8d9eb102004-07-31 02:24:20 +0000603 norig = ihigh - ilow;
604 assert(norig >= 0);
605 d = n - norig;
Christian Heimes90aa7642007-12-19 02:45:37 +0000606 if (Py_SIZE(a) + d == 0) {
Armin Rigo93677f02004-07-29 12:40:23 +0000607 Py_XDECREF(v_as_SF);
608 return list_clear(a);
609 }
610 item = a->ob_item;
Tim Peters8d9eb102004-07-31 02:24:20 +0000611 /* recycle the items that we are about to remove */
612 s = norig * sizeof(PyObject *);
Tim Peters73572222004-07-31 02:54:42 +0000613 if (s > sizeof(recycle_on_stack)) {
Armin Rigo1dd04a02004-07-30 11:38:22 +0000614 recycle = (PyObject **)PyMem_MALLOC(s);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000615 if (recycle == NULL) {
616 PyErr_NoMemory();
Tim Peters8d9eb102004-07-31 02:24:20 +0000617 goto Error;
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000618 }
619 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000620 memcpy(recycle, &item[ilow], s);
Tim Peters8d9eb102004-07-31 02:24:20 +0000621
Armin Rigo1dd04a02004-07-30 11:38:22 +0000622 if (d < 0) { /* Delete -d items */
623 memmove(&item[ihigh+d], &item[ihigh],
Christian Heimes90aa7642007-12-19 02:45:37 +0000624 (Py_SIZE(a) - ihigh)*sizeof(PyObject *));
625 list_resize(a, Py_SIZE(a) + d);
Armin Rigo1dd04a02004-07-30 11:38:22 +0000626 item = a->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000627 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000628 else if (d > 0) { /* Insert d items */
Christian Heimes90aa7642007-12-19 02:45:37 +0000629 k = Py_SIZE(a);
Tim Peters73572222004-07-31 02:54:42 +0000630 if (list_resize(a, k+d) < 0)
Tim Peters8d9eb102004-07-31 02:24:20 +0000631 goto Error;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000632 item = a->ob_item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000633 memmove(&item[ihigh+d], &item[ihigh],
Tim Peters73572222004-07-31 02:54:42 +0000634 (k - ihigh)*sizeof(PyObject *));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000635 }
636 for (k = 0; k < n; k++, ilow++) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000637 PyObject *w = vitem[k];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000638 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000639 item[ilow] = w;
640 }
Tim Peters73572222004-07-31 02:54:42 +0000641 for (k = norig - 1; k >= 0; --k)
642 Py_XDECREF(recycle[k]);
Tim Peters8d9eb102004-07-31 02:24:20 +0000643 result = 0;
644 Error:
Tim Peters73572222004-07-31 02:54:42 +0000645 if (recycle != recycle_on_stack)
Armin Rigo1dd04a02004-07-30 11:38:22 +0000646 PyMem_FREE(recycle);
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000647 Py_XDECREF(v_as_SF);
Tim Peters8d9eb102004-07-31 02:24:20 +0000648 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000649#undef b
650}
651
Guido van Rossum234f9421993-06-17 12:35:49 +0000652int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000653PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000654{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000655 if (!PyList_Check(a)) {
656 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000657 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000658 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000659 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000660}
661
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000662static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000663list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000664{
665 PyObject **items;
Christian Heimesaf98da12008-01-27 15:18:18 +0000666 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000667
668
669 size = PyList_GET_SIZE(self);
Christian Heimesaf98da12008-01-27 15:18:18 +0000670 if (size == 0 || n == 1) {
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000671 Py_INCREF(self);
672 return (PyObject *)self;
673 }
674
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000675 if (n < 1) {
Armin Rigo93677f02004-07-29 12:40:23 +0000676 (void)list_clear(self);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000677 Py_INCREF(self);
678 return (PyObject *)self;
679 }
680
Christian Heimesaf98da12008-01-27 15:18:18 +0000681 if (size > PY_SSIZE_T_MAX / n) {
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000682 return PyErr_NoMemory();
Christian Heimesaf98da12008-01-27 15:18:18 +0000683 }
684
685 if (list_resize(self, size*n) == -1)
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000686 return NULL;
687
688 p = size;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000689 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000690 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
691 for (j = 0; j < size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000692 PyObject *o = items[j];
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000693 Py_INCREF(o);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000694 items[p++] = o;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000695 }
696 }
697 Py_INCREF(self);
698 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000699}
700
Guido van Rossum4a450d01991-04-03 19:05:18 +0000701static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000702list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000703{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000704 PyObject *old_value;
Christian Heimes90aa7642007-12-19 02:45:37 +0000705 if (i < 0 || i >= Py_SIZE(a)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000706 PyErr_SetString(PyExc_IndexError,
707 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000708 return -1;
709 }
710 if (v == NULL)
711 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000712 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000713 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000714 a->ob_item[i] = v;
Tim Peters3b01a122002-07-19 02:35:45 +0000715 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000716 return 0;
717}
718
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000719static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000720listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000721{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000722 Py_ssize_t i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000723 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000724 if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000725 return NULL;
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000726 if (ins1(self, i, v) == 0)
727 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000728 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000729}
730
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000731static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000732listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000733{
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000734 if (app1(self, v) == 0)
735 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000736 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000737}
738
Barry Warsawdedf6d61998-10-09 16:37:25 +0000739static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000740listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000741{
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000742 PyObject *it; /* iter(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000743 Py_ssize_t m; /* size of self */
744 Py_ssize_t n; /* guess for size of b */
745 Py_ssize_t mn; /* m + n */
746 Py_ssize_t i;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000747 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000748
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000749 /* Special cases:
Tim Petersb38e2b62004-07-29 02:29:26 +0000750 1) lists and tuples which can use PySequence_Fast ops
751 2) extending self to self requires making a copy first
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000752 */
753 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
Armin Rigo70d172d2004-03-20 22:19:23 +0000754 PyObject **src, **dest;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000755 b = PySequence_Fast(b, "argument must be iterable");
756 if (!b)
757 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000758 n = PySequence_Fast_GET_SIZE(b);
759 if (n == 0) {
760 /* short circuit when b is empty */
761 Py_DECREF(b);
762 Py_RETURN_NONE;
763 }
Christian Heimes90aa7642007-12-19 02:45:37 +0000764 m = Py_SIZE(self);
Armin Rigo70d172d2004-03-20 22:19:23 +0000765 if (list_resize(self, m + n) == -1) {
766 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000767 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000768 }
769 /* note that we may still have self == b here for the
770 * situation a.extend(a), but the following code works
771 * in that case too. Just make sure to resize self
772 * before calling PySequence_Fast_ITEMS.
773 */
774 /* populate the end of self with b's items */
775 src = PySequence_Fast_ITEMS(b);
776 dest = self->ob_item + m;
777 for (i = 0; i < n; i++) {
778 PyObject *o = src[i];
779 Py_INCREF(o);
780 dest[i] = o;
781 }
782 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000783 Py_RETURN_NONE;
784 }
785
786 it = PyObject_GetIter(b);
787 if (it == NULL)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000788 return NULL;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000789 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000790
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000791 /* Guess a result list size. */
Christian Heimes255f53b2007-12-08 15:33:56 +0000792 n = _PyObject_LengthHint(b, 8);
Christian Heimes90aa7642007-12-19 02:45:37 +0000793 m = Py_SIZE(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000794 mn = m + n;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000795 if (mn >= m) {
796 /* Make room. */
797 if (list_resize(self, mn) == -1)
798 goto error;
799 /* Make the list sane again. */
Christian Heimes90aa7642007-12-19 02:45:37 +0000800 Py_SIZE(self) = m;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000801 }
802 /* Else m + n overflowed; on the chance that n lied, and there really
803 * is enough room, ignore it. If n was telling the truth, we'll
804 * eventually run out of memory during the loop.
805 */
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000806
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000807 /* Run iterator to exhaustion. */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000808 for (;;) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000809 PyObject *item = iternext(it);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000810 if (item == NULL) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000811 if (PyErr_Occurred()) {
812 if (PyErr_ExceptionMatches(PyExc_StopIteration))
813 PyErr_Clear();
814 else
815 goto error;
816 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000817 break;
818 }
Christian Heimes90aa7642007-12-19 02:45:37 +0000819 if (Py_SIZE(self) < self->allocated) {
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000820 /* steals ref */
Christian Heimes90aa7642007-12-19 02:45:37 +0000821 PyList_SET_ITEM(self, Py_SIZE(self), item);
822 ++Py_SIZE(self);
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000823 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000824 else {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000825 int status = app1(self, item);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000826 Py_DECREF(item); /* append creates a new ref */
827 if (status < 0)
828 goto error;
829 }
830 }
831
832 /* Cut back result list if initial guess was too large. */
Christian Heimes90aa7642007-12-19 02:45:37 +0000833 if (Py_SIZE(self) < self->allocated)
834 list_resize(self, Py_SIZE(self)); /* shrinking can't fail */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000835
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000836 Py_DECREF(it);
837 Py_RETURN_NONE;
838
839 error:
840 Py_DECREF(it);
841 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000842}
843
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000844PyObject *
845_PyList_Extend(PyListObject *self, PyObject *b)
846{
847 return listextend(self, b);
848}
849
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000850static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000851list_inplace_concat(PyListObject *self, PyObject *other)
852{
853 PyObject *result;
854
855 result = listextend(self, other);
856 if (result == NULL)
857 return result;
858 Py_DECREF(result);
859 Py_INCREF(self);
860 return (PyObject *)self;
861}
862
863static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000864listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000865{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000866 Py_ssize_t i = -1;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000867 PyObject *v;
Tim Peters8fc4a912004-07-31 21:53:19 +0000868 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000869
Thomas Wouters89f507f2006-12-13 04:49:30 +0000870 if (!PyArg_ParseTuple(args, "|n:pop", &i))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000871 return NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000872
Christian Heimes90aa7642007-12-19 02:45:37 +0000873 if (Py_SIZE(self) == 0) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000874 /* Special-case most common failure cause */
875 PyErr_SetString(PyExc_IndexError, "pop from empty list");
876 return NULL;
877 }
878 if (i < 0)
Christian Heimes90aa7642007-12-19 02:45:37 +0000879 i += Py_SIZE(self);
880 if (i < 0 || i >= Py_SIZE(self)) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000881 PyErr_SetString(PyExc_IndexError, "pop index out of range");
882 return NULL;
883 }
884 v = self->ob_item[i];
Christian Heimes90aa7642007-12-19 02:45:37 +0000885 if (i == Py_SIZE(self) - 1) {
886 status = list_resize(self, Py_SIZE(self) - 1);
Tim Peters8fc4a912004-07-31 21:53:19 +0000887 assert(status >= 0);
888 return v; /* and v now owns the reference the list had */
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000889 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000890 Py_INCREF(v);
Tim Peters8fc4a912004-07-31 21:53:19 +0000891 status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
892 assert(status >= 0);
893 /* Use status, so that in a release build compilers don't
894 * complain about the unused name.
895 */
Brett Cannon651dd522004-08-08 21:21:18 +0000896 (void) status;
897
898 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000899}
900
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000901/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
902static void
903reverse_slice(PyObject **lo, PyObject **hi)
904{
905 assert(lo && hi);
906
907 --hi;
908 while (lo < hi) {
909 PyObject *t = *lo;
910 *lo = *hi;
911 *hi = t;
912 ++lo;
913 --hi;
914 }
915}
916
Tim Petersa64dc242002-08-01 02:13:36 +0000917/* Lots of code for an adaptive, stable, natural mergesort. There are many
918 * pieces to this algorithm; read listsort.txt for overviews and details.
919 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000920
Raymond Hettinger70b64fc2008-01-30 20:15:17 +0000921/* Comparison function: PyObject_RichCompareBool with Py_LT.
Tim Petersa64dc242002-08-01 02:13:36 +0000922 * Returns -1 on error, 1 if x < y, 0 if x >= y.
923 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000924
Raymond Hettinger70b64fc2008-01-30 20:15:17 +0000925#define ISLT(X, Y) (PyObject_RichCompareBool(X, Y, Py_LT))
Tim Peters66860f62002-08-04 17:47:26 +0000926
927/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +0000928 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
929 started. It makes more sense in context <wink>. X and Y are PyObject*s.
930*/
Raymond Hettinger70b64fc2008-01-30 20:15:17 +0000931#define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail; \
Tim Petersa8c974c2002-07-19 03:30:57 +0000932 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000933
934/* binarysort is the best method for sorting small arrays: it does
935 few compares, but can do data movement quadratic in the number of
936 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000937 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +0000938 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000939 On entry, must have lo <= start <= hi, and that [lo, start) is already
940 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +0000941 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000942 Even in case of error, the output slice will be some permutation of
943 the input (nothing is lost or duplicated).
944*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000945static int
Raymond Hettinger70b64fc2008-01-30 20:15:17 +0000946binarysort(PyObject **lo, PyObject **hi, PyObject **start)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000947{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000948 register Py_ssize_t k;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000949 register PyObject **l, **p, **r;
950 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000951
Tim Petersa8c974c2002-07-19 03:30:57 +0000952 assert(lo <= start && start <= hi);
953 /* assert [lo, start) is sorted */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000954 if (lo == start)
955 ++start;
956 for (; start < hi; ++start) {
957 /* set l to where *start belongs */
958 l = lo;
959 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000960 pivot = *r;
Tim Peters0fe977c2002-07-19 06:12:32 +0000961 /* Invariants:
962 * pivot >= all in [lo, l).
963 * pivot < all in [r, start).
964 * The second is vacuously true at the start.
965 */
966 assert(l < r);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000967 do {
968 p = l + ((r - l) >> 1);
Tim Petersa8c974c2002-07-19 03:30:57 +0000969 IFLT(pivot, *p)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000970 r = p;
971 else
Tim Peters0fe977c2002-07-19 06:12:32 +0000972 l = p+1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000973 } while (l < r);
Tim Peters0fe977c2002-07-19 06:12:32 +0000974 assert(l == r);
975 /* The invariants still hold, so pivot >= all in [lo, l) and
976 pivot < all in [l, start), so pivot belongs at l. Note
977 that if there are elements equal to pivot, l points to the
978 first slot after them -- that's why this sort is stable.
979 Slide over to make room.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000980 Caution: using memmove is much slower under MSVC 5;
981 we're not usually moving many slots. */
982 for (p = start; p > l; --p)
983 *p = *(p-1);
984 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000985 }
Guido van Rossum3f236de1996-12-10 23:55:39 +0000986 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000987
988 fail:
989 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000990}
991
Tim Petersa64dc242002-08-01 02:13:36 +0000992/*
993Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
994is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000995
Tim Petersa64dc242002-08-01 02:13:36 +0000996 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000997
Tim Petersa64dc242002-08-01 02:13:36 +0000998or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000999
Tim Petersa64dc242002-08-01 02:13:36 +00001000 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001001
Tim Petersa64dc242002-08-01 02:13:36 +00001002Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1003For its intended use in a stable mergesort, the strictness of the defn of
1004"descending" is needed so that the caller can safely reverse a descending
1005sequence without violating stability (strict > ensures there are no equal
1006elements to get out of order).
1007
1008Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001009*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001010static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001011count_run(PyObject **lo, PyObject **hi, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001012{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001013 Py_ssize_t k;
1014 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001015
Tim Petersa64dc242002-08-01 02:13:36 +00001016 assert(lo < hi);
1017 *descending = 0;
1018 ++lo;
1019 if (lo == hi)
1020 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001021
Tim Petersa64dc242002-08-01 02:13:36 +00001022 n = 2;
1023 IFLT(*lo, *(lo-1)) {
1024 *descending = 1;
1025 for (lo = lo+1; lo < hi; ++lo, ++n) {
1026 IFLT(*lo, *(lo-1))
1027 ;
1028 else
1029 break;
1030 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001031 }
Tim Petersa64dc242002-08-01 02:13:36 +00001032 else {
1033 for (lo = lo+1; lo < hi; ++lo, ++n) {
1034 IFLT(*lo, *(lo-1))
1035 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001036 }
1037 }
1038
Tim Petersa64dc242002-08-01 02:13:36 +00001039 return n;
1040fail:
1041 return -1;
1042}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001043
Tim Petersa64dc242002-08-01 02:13:36 +00001044/*
1045Locate the proper position of key in a sorted vector; if the vector contains
1046an element equal to key, return the position immediately to the left of
1047the leftmost equal element. [gallop_right() does the same except returns
1048the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001049
Tim Petersa64dc242002-08-01 02:13:36 +00001050"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001051
Tim Petersa64dc242002-08-01 02:13:36 +00001052"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1053hint is to the final result, the faster this runs.
1054
1055The return value is the int k in 0..n such that
1056
1057 a[k-1] < key <= a[k]
1058
1059pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1060key belongs at index k; or, IOW, the first k elements of a should precede
1061key, and the last n-k should follow key.
1062
1063Returns -1 on error. See listsort.txt for info on the method.
1064*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001065static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001066gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001067{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001068 Py_ssize_t ofs;
1069 Py_ssize_t lastofs;
1070 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001071
1072 assert(key && a && n > 0 && hint >= 0 && hint < n);
1073
1074 a += hint;
1075 lastofs = 0;
1076 ofs = 1;
1077 IFLT(*a, key) {
1078 /* a[hint] < key -- gallop right, until
1079 * a[hint + lastofs] < key <= a[hint + ofs]
1080 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001081 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001082 while (ofs < maxofs) {
1083 IFLT(a[ofs], key) {
1084 lastofs = ofs;
1085 ofs = (ofs << 1) + 1;
1086 if (ofs <= 0) /* int overflow */
1087 ofs = maxofs;
1088 }
1089 else /* key <= a[hint + ofs] */
1090 break;
1091 }
1092 if (ofs > maxofs)
1093 ofs = maxofs;
1094 /* Translate back to offsets relative to &a[0]. */
1095 lastofs += hint;
1096 ofs += hint;
1097 }
1098 else {
1099 /* key <= a[hint] -- gallop left, until
1100 * a[hint - ofs] < key <= a[hint - lastofs]
1101 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001102 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001103 while (ofs < maxofs) {
1104 IFLT(*(a-ofs), key)
1105 break;
1106 /* key <= a[hint - ofs] */
1107 lastofs = ofs;
1108 ofs = (ofs << 1) + 1;
1109 if (ofs <= 0) /* int overflow */
1110 ofs = maxofs;
1111 }
1112 if (ofs > maxofs)
1113 ofs = maxofs;
1114 /* Translate back to positive offsets relative to &a[0]. */
1115 k = lastofs;
1116 lastofs = hint - ofs;
1117 ofs = hint - k;
1118 }
1119 a -= hint;
1120
1121 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1122 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1123 * right of lastofs but no farther right than ofs. Do a binary
1124 * search, with invariant a[lastofs-1] < key <= a[ofs].
1125 */
1126 ++lastofs;
1127 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001128 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001129
1130 IFLT(a[m], key)
1131 lastofs = m+1; /* a[m] < key */
1132 else
1133 ofs = m; /* key <= a[m] */
1134 }
1135 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1136 return ofs;
1137
1138fail:
1139 return -1;
1140}
1141
1142/*
1143Exactly like gallop_left(), except that if key already exists in a[0:n],
1144finds the position immediately to the right of the rightmost equal value.
1145
1146The return value is the int k in 0..n such that
1147
1148 a[k-1] <= key < a[k]
1149
1150or -1 if error.
1151
1152The code duplication is massive, but this is enough different given that
1153we're sticking to "<" comparisons that it's much harder to follow if
1154written as one routine with yet another "left or right?" flag.
1155*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001156static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001157gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001158{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001159 Py_ssize_t ofs;
1160 Py_ssize_t lastofs;
1161 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001162
1163 assert(key && a && n > 0 && hint >= 0 && hint < n);
1164
1165 a += hint;
1166 lastofs = 0;
1167 ofs = 1;
1168 IFLT(key, *a) {
1169 /* key < a[hint] -- gallop left, until
1170 * a[hint - ofs] <= key < a[hint - lastofs]
1171 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001172 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001173 while (ofs < maxofs) {
1174 IFLT(key, *(a-ofs)) {
1175 lastofs = ofs;
1176 ofs = (ofs << 1) + 1;
1177 if (ofs <= 0) /* int overflow */
1178 ofs = maxofs;
1179 }
1180 else /* a[hint - ofs] <= key */
1181 break;
1182 }
1183 if (ofs > maxofs)
1184 ofs = maxofs;
1185 /* Translate back to positive offsets relative to &a[0]. */
1186 k = lastofs;
1187 lastofs = hint - ofs;
1188 ofs = hint - k;
1189 }
1190 else {
1191 /* a[hint] <= key -- gallop right, until
1192 * a[hint + lastofs] <= key < a[hint + ofs]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001193 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001194 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001195 while (ofs < maxofs) {
1196 IFLT(key, a[ofs])
1197 break;
1198 /* a[hint + ofs] <= key */
1199 lastofs = ofs;
1200 ofs = (ofs << 1) + 1;
1201 if (ofs <= 0) /* int overflow */
1202 ofs = maxofs;
1203 }
1204 if (ofs > maxofs)
1205 ofs = maxofs;
1206 /* Translate back to offsets relative to &a[0]. */
1207 lastofs += hint;
1208 ofs += hint;
1209 }
1210 a -= hint;
1211
1212 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1213 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1214 * right of lastofs but no farther right than ofs. Do a binary
1215 * search, with invariant a[lastofs-1] <= key < a[ofs].
1216 */
1217 ++lastofs;
1218 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001219 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001220
1221 IFLT(key, a[m])
1222 ofs = m; /* key < a[m] */
1223 else
1224 lastofs = m+1; /* a[m] <= key */
1225 }
1226 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1227 return ofs;
1228
1229fail:
1230 return -1;
1231}
1232
1233/* The maximum number of entries in a MergeState's pending-runs stack.
1234 * This is enough to sort arrays of size up to about
1235 * 32 * phi ** MAX_MERGE_PENDING
1236 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1237 * with 2**64 elements.
1238 */
1239#define MAX_MERGE_PENDING 85
1240
Tim Peterse05f65a2002-08-10 05:21:15 +00001241/* When we get into galloping mode, we stay there until both runs win less
1242 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001243 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001244#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001245
1246/* Avoid malloc for small temp arrays. */
1247#define MERGESTATE_TEMP_SIZE 256
1248
1249/* One MergeState exists on the stack per invocation of mergesort. It's just
1250 * a convenient way to pass state around among the helper functions.
1251 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001252struct s_slice {
1253 PyObject **base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001254 Py_ssize_t len;
Tim Peterse05f65a2002-08-10 05:21:15 +00001255};
1256
Tim Petersa64dc242002-08-01 02:13:36 +00001257typedef struct s_MergeState {
Tim Peterse05f65a2002-08-10 05:21:15 +00001258 /* This controls when we get *into* galloping mode. It's initialized
1259 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1260 * random data, and lower for highly structured data.
1261 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001262 Py_ssize_t min_gallop;
Tim Peterse05f65a2002-08-10 05:21:15 +00001263
Tim Petersa64dc242002-08-01 02:13:36 +00001264 /* 'a' is temp storage to help with merges. It contains room for
1265 * alloced entries.
1266 */
1267 PyObject **a; /* may point to temparray below */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001268 Py_ssize_t alloced;
Tim Petersa64dc242002-08-01 02:13:36 +00001269
1270 /* A stack of n pending runs yet to be merged. Run #i starts at
1271 * address base[i] and extends for len[i] elements. It's always
1272 * true (so long as the indices are in bounds) that
1273 *
Tim Peterse05f65a2002-08-10 05:21:15 +00001274 * pending[i].base + pending[i].len == pending[i+1].base
Tim Petersa64dc242002-08-01 02:13:36 +00001275 *
1276 * so we could cut the storage for this, but it's a minor amount,
1277 * and keeping all the info explicit simplifies the code.
1278 */
1279 int n;
Tim Peterse05f65a2002-08-10 05:21:15 +00001280 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001281
1282 /* 'a' points to this when possible, rather than muck with malloc. */
1283 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1284} MergeState;
1285
1286/* Conceptually a MergeState's constructor. */
1287static void
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001288merge_init(MergeState *ms)
Tim Petersa64dc242002-08-01 02:13:36 +00001289{
1290 assert(ms != NULL);
Tim Petersa64dc242002-08-01 02:13:36 +00001291 ms->a = ms->temparray;
1292 ms->alloced = MERGESTATE_TEMP_SIZE;
1293 ms->n = 0;
Tim Peterse05f65a2002-08-10 05:21:15 +00001294 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001295}
1296
1297/* Free all the temp memory owned by the MergeState. This must be called
1298 * when you're done with a MergeState, and may be called before then if
1299 * you want to free the temp memory early.
1300 */
1301static void
1302merge_freemem(MergeState *ms)
1303{
1304 assert(ms != NULL);
1305 if (ms->a != ms->temparray)
1306 PyMem_Free(ms->a);
1307 ms->a = ms->temparray;
1308 ms->alloced = MERGESTATE_TEMP_SIZE;
1309}
1310
1311/* Ensure enough temp memory for 'need' array slots is available.
1312 * Returns 0 on success and -1 if the memory can't be gotten.
1313 */
1314static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001315merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001316{
1317 assert(ms != NULL);
1318 if (need <= ms->alloced)
1319 return 0;
1320 /* Don't realloc! That can cost cycles to copy the old data, but
1321 * we don't care what's in the block.
1322 */
1323 merge_freemem(ms);
1324 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1325 if (ms->a) {
1326 ms->alloced = need;
1327 return 0;
1328 }
1329 PyErr_NoMemory();
1330 merge_freemem(ms); /* reset to sane state */
1331 return -1;
1332}
1333#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1334 merge_getmem(MS, NEED))
1335
1336/* Merge the na elements starting at pa with the nb elements starting at pb
1337 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1338 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1339 * merge, and should have na <= nb. See listsort.txt for more info.
1340 * Return 0 if successful, -1 if error.
1341 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001342static Py_ssize_t
1343merge_lo(MergeState *ms, PyObject **pa, Py_ssize_t na,
1344 PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001345{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001346 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001347 PyObject **dest;
1348 int result = -1; /* guilty until proved innocent */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001349 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001350
1351 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1352 if (MERGE_GETMEM(ms, na) < 0)
1353 return -1;
1354 memcpy(ms->a, pa, na * sizeof(PyObject*));
1355 dest = pa;
1356 pa = ms->a;
1357
1358 *dest++ = *pb++;
1359 --nb;
1360 if (nb == 0)
1361 goto Succeed;
1362 if (na == 1)
1363 goto CopyB;
1364
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001365 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001366 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001367 Py_ssize_t acount = 0; /* # of times A won in a row */
1368 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001369
1370 /* Do the straightforward thing until (if ever) one run
1371 * appears to win consistently.
1372 */
1373 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001374 assert(na > 1 && nb > 0);
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001375 k = ISLT(*pb, *pa);
Tim Petersa64dc242002-08-01 02:13:36 +00001376 if (k) {
1377 if (k < 0)
1378 goto Fail;
1379 *dest++ = *pb++;
1380 ++bcount;
1381 acount = 0;
1382 --nb;
1383 if (nb == 0)
1384 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001385 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001386 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001387 }
1388 else {
Tim Petersa64dc242002-08-01 02:13:36 +00001389 *dest++ = *pa++;
1390 ++acount;
1391 bcount = 0;
1392 --na;
1393 if (na == 1)
1394 goto CopyB;
Tim Peterse05f65a2002-08-10 05:21:15 +00001395 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001396 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001397 }
Tim Petersa64dc242002-08-01 02:13:36 +00001398 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001399
Tim Petersa64dc242002-08-01 02:13:36 +00001400 /* One run is winning so consistently that galloping may
1401 * be a huge win. So try that, and continue galloping until
1402 * (if ever) neither run appears to be winning consistently
1403 * anymore.
1404 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001405 ++min_gallop;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001406 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001407 assert(na > 1 && nb > 0);
1408 min_gallop -= min_gallop > 1;
1409 ms->min_gallop = min_gallop;
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001410 k = gallop_right(*pb, pa, na, 0);
Tim Petersa64dc242002-08-01 02:13:36 +00001411 acount = k;
1412 if (k) {
1413 if (k < 0)
1414 goto Fail;
1415 memcpy(dest, pa, k * sizeof(PyObject *));
1416 dest += k;
1417 pa += k;
1418 na -= k;
1419 if (na == 1)
1420 goto CopyB;
1421 /* na==0 is impossible now if the comparison
1422 * function is consistent, but we can't assume
1423 * that it is.
1424 */
1425 if (na == 0)
1426 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001427 }
Tim Petersa64dc242002-08-01 02:13:36 +00001428 *dest++ = *pb++;
1429 --nb;
1430 if (nb == 0)
1431 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001432
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001433 k = gallop_left(*pa, pb, nb, 0);
Tim Petersa64dc242002-08-01 02:13:36 +00001434 bcount = k;
1435 if (k) {
1436 if (k < 0)
1437 goto Fail;
1438 memmove(dest, pb, k * sizeof(PyObject *));
1439 dest += k;
1440 pb += k;
1441 nb -= k;
1442 if (nb == 0)
1443 goto Succeed;
1444 }
1445 *dest++ = *pa++;
1446 --na;
1447 if (na == 1)
1448 goto CopyB;
1449 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001450 ++min_gallop; /* penalize it for leaving galloping mode */
1451 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001452 }
1453Succeed:
1454 result = 0;
1455Fail:
1456 if (na)
1457 memcpy(dest, pa, na * sizeof(PyObject*));
1458 return result;
1459CopyB:
1460 assert(na == 1 && nb > 0);
1461 /* The last element of pa belongs at the end of the merge. */
1462 memmove(dest, pb, nb * sizeof(PyObject *));
1463 dest[nb] = *pa;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001464 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001465}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001466
Tim Petersa64dc242002-08-01 02:13:36 +00001467/* Merge the na elements starting at pa with the nb elements starting at pb
1468 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1469 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1470 * merge, and should have na >= nb. See listsort.txt for more info.
1471 * Return 0 if successful, -1 if error.
1472 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001473static Py_ssize_t
1474merge_hi(MergeState *ms, PyObject **pa, Py_ssize_t na, PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001475{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001476 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001477 PyObject **dest;
1478 int result = -1; /* guilty until proved innocent */
1479 PyObject **basea;
1480 PyObject **baseb;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001481 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001482
1483 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1484 if (MERGE_GETMEM(ms, nb) < 0)
1485 return -1;
1486 dest = pb + nb - 1;
1487 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1488 basea = pa;
1489 baseb = ms->a;
1490 pb = ms->a + nb - 1;
1491 pa += na - 1;
1492
1493 *dest-- = *pa--;
1494 --na;
1495 if (na == 0)
1496 goto Succeed;
1497 if (nb == 1)
1498 goto CopyA;
1499
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001500 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001501 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001502 Py_ssize_t acount = 0; /* # of times A won in a row */
1503 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001504
1505 /* Do the straightforward thing until (if ever) one run
1506 * appears to win consistently.
1507 */
1508 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001509 assert(na > 0 && nb > 1);
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001510 k = ISLT(*pb, *pa);
Tim Petersa64dc242002-08-01 02:13:36 +00001511 if (k) {
1512 if (k < 0)
1513 goto Fail;
1514 *dest-- = *pa--;
1515 ++acount;
1516 bcount = 0;
1517 --na;
1518 if (na == 0)
1519 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001520 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001521 break;
1522 }
1523 else {
1524 *dest-- = *pb--;
1525 ++bcount;
1526 acount = 0;
1527 --nb;
1528 if (nb == 1)
1529 goto CopyA;
Tim Peterse05f65a2002-08-10 05:21:15 +00001530 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001531 break;
1532 }
1533 }
1534
1535 /* One run is winning so consistently that galloping may
1536 * be a huge win. So try that, and continue galloping until
1537 * (if ever) neither run appears to be winning consistently
1538 * anymore.
1539 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001540 ++min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001541 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001542 assert(na > 0 && nb > 1);
1543 min_gallop -= min_gallop > 1;
1544 ms->min_gallop = min_gallop;
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001545 k = gallop_right(*pb, basea, na, na-1);
Tim Petersa64dc242002-08-01 02:13:36 +00001546 if (k < 0)
1547 goto Fail;
1548 k = na - k;
1549 acount = k;
1550 if (k) {
1551 dest -= k;
1552 pa -= k;
1553 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1554 na -= k;
1555 if (na == 0)
1556 goto Succeed;
1557 }
1558 *dest-- = *pb--;
1559 --nb;
1560 if (nb == 1)
1561 goto CopyA;
1562
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001563 k = gallop_left(*pa, baseb, nb, nb-1);
Tim Petersa64dc242002-08-01 02:13:36 +00001564 if (k < 0)
1565 goto Fail;
1566 k = nb - k;
1567 bcount = k;
1568 if (k) {
1569 dest -= k;
1570 pb -= k;
1571 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1572 nb -= k;
1573 if (nb == 1)
1574 goto CopyA;
1575 /* nb==0 is impossible now if the comparison
1576 * function is consistent, but we can't assume
1577 * that it is.
1578 */
1579 if (nb == 0)
1580 goto Succeed;
1581 }
1582 *dest-- = *pa--;
1583 --na;
1584 if (na == 0)
1585 goto Succeed;
1586 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001587 ++min_gallop; /* penalize it for leaving galloping mode */
1588 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001589 }
1590Succeed:
1591 result = 0;
1592Fail:
1593 if (nb)
1594 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1595 return result;
1596CopyA:
1597 assert(nb == 1 && na > 0);
1598 /* The first element of pb belongs at the front of the merge. */
1599 dest -= na;
1600 pa -= na;
1601 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1602 *dest = *pb;
1603 return 0;
1604}
1605
1606/* Merge the two runs at stack indices i and i+1.
1607 * Returns 0 on success, -1 on error.
1608 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001609static Py_ssize_t
1610merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001611{
1612 PyObject **pa, **pb;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001613 Py_ssize_t na, nb;
1614 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001615
1616 assert(ms != NULL);
1617 assert(ms->n >= 2);
1618 assert(i >= 0);
1619 assert(i == ms->n - 2 || i == ms->n - 3);
1620
Tim Peterse05f65a2002-08-10 05:21:15 +00001621 pa = ms->pending[i].base;
1622 na = ms->pending[i].len;
1623 pb = ms->pending[i+1].base;
1624 nb = ms->pending[i+1].len;
Tim Petersa64dc242002-08-01 02:13:36 +00001625 assert(na > 0 && nb > 0);
1626 assert(pa + na == pb);
1627
1628 /* Record the length of the combined runs; if i is the 3rd-last
1629 * run now, also slide over the last run (which isn't involved
1630 * in this merge). The current run i+1 goes away in any case.
1631 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001632 ms->pending[i].len = na + nb;
1633 if (i == ms->n - 3)
1634 ms->pending[i+1] = ms->pending[i+2];
Tim Petersa64dc242002-08-01 02:13:36 +00001635 --ms->n;
1636
1637 /* Where does b start in a? Elements in a before that can be
1638 * ignored (already in place).
1639 */
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001640 k = gallop_right(*pb, pa, na, 0);
Tim Petersa64dc242002-08-01 02:13:36 +00001641 if (k < 0)
1642 return -1;
1643 pa += k;
1644 na -= k;
1645 if (na == 0)
1646 return 0;
1647
1648 /* Where does a end in b? Elements in b after that can be
1649 * ignored (already in place).
1650 */
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001651 nb = gallop_left(pa[na-1], pb, nb, nb-1);
Tim Petersa64dc242002-08-01 02:13:36 +00001652 if (nb <= 0)
1653 return nb;
1654
1655 /* Merge what remains of the runs, using a temp array with
1656 * min(na, nb) elements.
1657 */
1658 if (na <= nb)
1659 return merge_lo(ms, pa, na, pb, nb);
1660 else
1661 return merge_hi(ms, pa, na, pb, nb);
1662}
1663
1664/* Examine the stack of runs waiting to be merged, merging adjacent runs
1665 * until the stack invariants are re-established:
1666 *
1667 * 1. len[-3] > len[-2] + len[-1]
1668 * 2. len[-2] > len[-1]
1669 *
1670 * See listsort.txt for more info.
1671 *
1672 * Returns 0 on success, -1 on error.
1673 */
1674static int
1675merge_collapse(MergeState *ms)
1676{
Tim Peterse05f65a2002-08-10 05:21:15 +00001677 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001678
1679 assert(ms);
1680 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001681 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001682 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1683 if (p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001684 --n;
1685 if (merge_at(ms, n) < 0)
1686 return -1;
1687 }
Tim Peterse05f65a2002-08-10 05:21:15 +00001688 else if (p[n].len <= p[n+1].len) {
Tim Petersa64dc242002-08-01 02:13:36 +00001689 if (merge_at(ms, n) < 0)
1690 return -1;
1691 }
1692 else
1693 break;
1694 }
1695 return 0;
1696}
1697
1698/* Regardless of invariants, merge all runs on the stack until only one
1699 * remains. This is used at the end of the mergesort.
1700 *
1701 * Returns 0 on success, -1 on error.
1702 */
1703static int
1704merge_force_collapse(MergeState *ms)
1705{
Tim Peterse05f65a2002-08-10 05:21:15 +00001706 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001707
1708 assert(ms);
1709 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001710 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001711 if (n > 0 && p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001712 --n;
1713 if (merge_at(ms, n) < 0)
1714 return -1;
1715 }
1716 return 0;
1717}
1718
1719/* Compute a good value for the minimum run length; natural runs shorter
1720 * than this are boosted artificially via binary insertion.
1721 *
1722 * If n < 64, return n (it's too small to bother with fancy stuff).
1723 * Else if n is an exact power of 2, return 32.
1724 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1725 * strictly less than, an exact power of 2.
1726 *
1727 * See listsort.txt for more info.
1728 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001729static Py_ssize_t
1730merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001731{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001732 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001733
1734 assert(n >= 0);
1735 while (n >= 64) {
1736 r |= n & 1;
1737 n >>= 1;
1738 }
1739 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001740}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001741
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001742/* Special wrapper to support stable sorting using the decorate-sort-undecorate
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001743 pattern. Holds a key which is used for comparisons and the original record
Tim Petersb38e2b62004-07-29 02:29:26 +00001744 which is returned during the undecorate phase. By exposing only the key
1745 during comparisons, the underlying sort stability characteristics are left
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001746 unchanged. Also, the comparison function will only see the key instead of
1747 a full record. */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001748
1749typedef struct {
1750 PyObject_HEAD
1751 PyObject *key;
1752 PyObject *value;
1753} sortwrapperobject;
1754
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001755PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001756static PyObject *
1757sortwrapper_richcompare(sortwrapperobject *, sortwrapperobject *, int);
1758static void
1759sortwrapper_dealloc(sortwrapperobject *);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001760
Christian Heimesa22e8bd2007-11-29 22:35:39 +00001761PyTypeObject PySortWrapper_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001762 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001763 "sortwrapper", /* tp_name */
1764 sizeof(sortwrapperobject), /* tp_basicsize */
1765 0, /* tp_itemsize */
1766 /* methods */
1767 (destructor)sortwrapper_dealloc, /* tp_dealloc */
1768 0, /* tp_print */
1769 0, /* tp_getattr */
1770 0, /* tp_setattr */
1771 0, /* tp_compare */
1772 0, /* tp_repr */
1773 0, /* tp_as_number */
1774 0, /* tp_as_sequence */
1775 0, /* tp_as_mapping */
1776 0, /* tp_hash */
1777 0, /* tp_call */
1778 0, /* tp_str */
1779 PyObject_GenericGetAttr, /* tp_getattro */
1780 0, /* tp_setattro */
1781 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001782 Py_TPFLAGS_DEFAULT, /* tp_flags */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001783 sortwrapper_doc, /* tp_doc */
1784 0, /* tp_traverse */
1785 0, /* tp_clear */
1786 (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
1787};
1788
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001789
1790static PyObject *
1791sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
1792{
Christian Heimesa22e8bd2007-11-29 22:35:39 +00001793 if (!PyObject_TypeCheck(b, &PySortWrapper_Type)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001794 PyErr_SetString(PyExc_TypeError,
1795 "expected a sortwrapperobject");
1796 return NULL;
1797 }
1798 return PyObject_RichCompare(a->key, b->key, op);
1799}
1800
1801static void
1802sortwrapper_dealloc(sortwrapperobject *so)
1803{
1804 Py_XDECREF(so->key);
1805 Py_XDECREF(so->value);
1806 PyObject_Del(so);
1807}
1808
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001809/* Returns a new reference to a sortwrapper.
1810 Consumes the references to the two underlying objects. */
1811
1812static PyObject *
1813build_sortwrapper(PyObject *key, PyObject *value)
1814{
1815 sortwrapperobject *so;
Tim Petersb38e2b62004-07-29 02:29:26 +00001816
Christian Heimesa22e8bd2007-11-29 22:35:39 +00001817 so = PyObject_New(sortwrapperobject, &PySortWrapper_Type);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001818 if (so == NULL)
1819 return NULL;
1820 so->key = key;
1821 so->value = value;
1822 return (PyObject *)so;
1823}
1824
1825/* Returns a new reference to the value underlying the wrapper. */
1826static PyObject *
1827sortwrapper_getvalue(PyObject *so)
1828{
1829 PyObject *value;
1830
Christian Heimesa22e8bd2007-11-29 22:35:39 +00001831 if (!PyObject_TypeCheck(so, &PySortWrapper_Type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001832 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001833 "expected a sortwrapperobject");
1834 return NULL;
1835 }
1836 value = ((sortwrapperobject *)so)->value;
1837 Py_INCREF(value);
1838 return value;
1839}
1840
Tim Petersa64dc242002-08-01 02:13:36 +00001841/* An adaptive, stable, natural mergesort. See listsort.txt.
1842 * Returns Py_None on success, NULL on error. Even in case of error, the
1843 * list will be some permutation of its input state (nothing is lost or
1844 * duplicated).
1845 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001846static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001847listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001848{
Tim Petersa64dc242002-08-01 02:13:36 +00001849 MergeState ms;
1850 PyObject **lo, **hi;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001851 Py_ssize_t nremaining;
1852 Py_ssize_t minrun;
1853 Py_ssize_t saved_ob_size, saved_allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00001854 PyObject **saved_ob_item;
Armin Rigo93677f02004-07-29 12:40:23 +00001855 PyObject **final_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001856 PyObject *result = NULL; /* guilty until proved innocent */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001857 int reverse = 0;
1858 PyObject *keyfunc = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001859 Py_ssize_t i;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001860 PyObject *key, *value, *kvpair;
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001861 static char *kwlist[] = {"key", "reverse", 0};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001862
Tim Petersa64dc242002-08-01 02:13:36 +00001863 assert(self != NULL);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001864 assert (PyList_Check(self));
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001865 if (args != NULL) {
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001866 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:sort",
1867 kwlist, &keyfunc, &reverse))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001868 return NULL;
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001869 if (Py_SIZE(args) > 0) {
1870 PyErr_SetString(PyExc_TypeError,
1871 "must use keyword argument for key function");
1872 return NULL;
1873 }
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001874 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001875 if (keyfunc == Py_None)
1876 keyfunc = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001877
Tim Petersb9099c32002-11-12 22:08:10 +00001878 /* The list is temporarily made empty, so that mutations performed
1879 * by comparison functions can't affect the slice of memory we're
1880 * sorting (allowing mutations during sorting is a core-dump
1881 * factory, since ob_item may change).
1882 */
Christian Heimes90aa7642007-12-19 02:45:37 +00001883 saved_ob_size = Py_SIZE(self);
Tim Petersb9099c32002-11-12 22:08:10 +00001884 saved_ob_item = self->ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001885 saved_allocated = self->allocated;
Christian Heimes90aa7642007-12-19 02:45:37 +00001886 Py_SIZE(self) = 0;
Tim Peters51b4ade2004-07-29 04:07:15 +00001887 self->ob_item = NULL;
Armin Rigo93677f02004-07-29 12:40:23 +00001888 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00001889
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001890 if (keyfunc != NULL) {
1891 for (i=0 ; i < saved_ob_size ; i++) {
1892 value = saved_ob_item[i];
Tim Petersb38e2b62004-07-29 02:29:26 +00001893 key = PyObject_CallFunctionObjArgs(keyfunc, value,
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001894 NULL);
1895 if (key == NULL) {
1896 for (i=i-1 ; i>=0 ; i--) {
1897 kvpair = saved_ob_item[i];
1898 value = sortwrapper_getvalue(kvpair);
1899 saved_ob_item[i] = value;
1900 Py_DECREF(kvpair);
1901 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001902 goto dsu_fail;
1903 }
1904 kvpair = build_sortwrapper(key, value);
1905 if (kvpair == NULL)
1906 goto dsu_fail;
1907 saved_ob_item[i] = kvpair;
1908 }
1909 }
1910
1911 /* Reverse sort stability achieved by initially reversing the list,
1912 applying a stable forward sort, then reversing the final result. */
1913 if (reverse && saved_ob_size > 1)
1914 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
1915
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001916 merge_init(&ms);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001917
Tim Petersb9099c32002-11-12 22:08:10 +00001918 nremaining = saved_ob_size;
Tim Petersa64dc242002-08-01 02:13:36 +00001919 if (nremaining < 2)
1920 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00001921
Tim Petersa64dc242002-08-01 02:13:36 +00001922 /* March over the array once, left to right, finding natural runs,
1923 * and extending short natural runs to minrun elements.
1924 */
Tim Petersb9099c32002-11-12 22:08:10 +00001925 lo = saved_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001926 hi = lo + nremaining;
1927 minrun = merge_compute_minrun(nremaining);
1928 do {
1929 int descending;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001930 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00001931
Tim Petersa64dc242002-08-01 02:13:36 +00001932 /* Identify next run. */
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001933 n = count_run(lo, hi, &descending);
Tim Petersa64dc242002-08-01 02:13:36 +00001934 if (n < 0)
1935 goto fail;
1936 if (descending)
1937 reverse_slice(lo, lo + n);
1938 /* If short, extend to min(minrun, nremaining). */
1939 if (n < minrun) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001940 const Py_ssize_t force = nremaining <= minrun ?
Tim Petersa64dc242002-08-01 02:13:36 +00001941 nremaining : minrun;
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001942 if (binarysort(lo, lo + force, lo + n) < 0)
Tim Petersa64dc242002-08-01 02:13:36 +00001943 goto fail;
1944 n = force;
1945 }
1946 /* Push run onto pending-runs stack, and maybe merge. */
1947 assert(ms.n < MAX_MERGE_PENDING);
Tim Peterse05f65a2002-08-10 05:21:15 +00001948 ms.pending[ms.n].base = lo;
1949 ms.pending[ms.n].len = n;
Tim Petersa64dc242002-08-01 02:13:36 +00001950 ++ms.n;
1951 if (merge_collapse(&ms) < 0)
1952 goto fail;
1953 /* Advance to find next run. */
1954 lo += n;
1955 nremaining -= n;
1956 } while (nremaining);
1957 assert(lo == hi);
Tim Peters330f9e92002-07-19 07:05:44 +00001958
Tim Petersa64dc242002-08-01 02:13:36 +00001959 if (merge_force_collapse(&ms) < 0)
1960 goto fail;
1961 assert(ms.n == 1);
Tim Petersb9099c32002-11-12 22:08:10 +00001962 assert(ms.pending[0].base == saved_ob_item);
1963 assert(ms.pending[0].len == saved_ob_size);
Tim Petersa64dc242002-08-01 02:13:36 +00001964
1965succeed:
1966 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00001967fail:
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001968 if (keyfunc != NULL) {
1969 for (i=0 ; i < saved_ob_size ; i++) {
1970 kvpair = saved_ob_item[i];
1971 value = sortwrapper_getvalue(kvpair);
1972 saved_ob_item[i] = value;
1973 Py_DECREF(kvpair);
1974 }
1975 }
1976
Armin Rigo93677f02004-07-29 12:40:23 +00001977 if (self->allocated != -1 && result != NULL) {
Tim Peters51b4ade2004-07-29 04:07:15 +00001978 /* The user mucked with the list during the sort,
1979 * and we don't already have another error to report.
1980 */
1981 PyErr_SetString(PyExc_ValueError, "list modified during sort");
1982 result = NULL;
Tim Petersb9099c32002-11-12 22:08:10 +00001983 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001984
1985 if (reverse && saved_ob_size > 1)
1986 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
1987
1988 merge_freemem(&ms);
1989
1990dsu_fail:
Armin Rigo93677f02004-07-29 12:40:23 +00001991 final_ob_item = self->ob_item;
Christian Heimes90aa7642007-12-19 02:45:37 +00001992 i = Py_SIZE(self);
1993 Py_SIZE(self) = saved_ob_size;
Tim Petersb9099c32002-11-12 22:08:10 +00001994 self->ob_item = saved_ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001995 self->allocated = saved_allocated;
Armin Rigo93677f02004-07-29 12:40:23 +00001996 if (final_ob_item != NULL) {
1997 /* we cannot use list_clear() for this because it does not
1998 guarantee that the list is really empty when it returns */
1999 while (--i >= 0) {
2000 Py_XDECREF(final_ob_item[i]);
2001 }
2002 PyMem_FREE(final_ob_item);
2003 }
Tim Petersa64dc242002-08-01 02:13:36 +00002004 Py_XINCREF(result);
2005 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002006}
Tim Peters330f9e92002-07-19 07:05:44 +00002007#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002008#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002009
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002010int
Fred Drakea2f55112000-07-09 15:16:51 +00002011PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002012{
2013 if (v == NULL || !PyList_Check(v)) {
2014 PyErr_BadInternalCall();
2015 return -1;
2016 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002017 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002018 if (v == NULL)
2019 return -1;
2020 Py_DECREF(v);
2021 return 0;
2022}
2023
Guido van Rossumb86c5492001-02-12 22:06:02 +00002024static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002025listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002026{
Christian Heimes90aa7642007-12-19 02:45:37 +00002027 if (Py_SIZE(self) > 1)
2028 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002029 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002030}
2031
Guido van Rossum84c76f51990-10-30 13:32:20 +00002032int
Fred Drakea2f55112000-07-09 15:16:51 +00002033PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002034{
Tim Peters6063e262002-08-08 01:06:39 +00002035 PyListObject *self = (PyListObject *)v;
2036
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002037 if (v == NULL || !PyList_Check(v)) {
2038 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002039 return -1;
2040 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002041 if (Py_SIZE(self) > 1)
2042 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002043 return 0;
2044}
2045
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002046PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002047PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002048{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002049 PyObject *w;
Christian Heimes2c181612007-12-17 20:04:13 +00002050 PyObject **p, **q;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002051 Py_ssize_t n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002052 if (v == NULL || !PyList_Check(v)) {
2053 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002054 return NULL;
2055 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002056 n = Py_SIZE(v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002057 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002058 if (w == NULL)
2059 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002060 p = ((PyTupleObject *)w)->ob_item;
Christian Heimes2c181612007-12-17 20:04:13 +00002061 q = ((PyListObject *)v)->ob_item;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002062 while (--n >= 0) {
Christian Heimes2c181612007-12-17 20:04:13 +00002063 Py_INCREF(*q);
2064 *p = *q;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002065 p++;
Christian Heimes2c181612007-12-17 20:04:13 +00002066 q++;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002067 }
2068 return w;
2069}
2070
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002071static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002072listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002073{
Christian Heimes90aa7642007-12-19 02:45:37 +00002074 Py_ssize_t i, start=0, stop=Py_SIZE(self);
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002075 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002076
Walter Dörwalde8049bef2003-06-17 19:27:39 +00002077 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2078 _PyEval_SliceIndex, &start,
2079 _PyEval_SliceIndex, &stop))
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002080 return NULL;
Guido van Rossum2743d872003-06-17 14:25:14 +00002081 if (start < 0) {
Christian Heimes90aa7642007-12-19 02:45:37 +00002082 start += Py_SIZE(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002083 if (start < 0)
2084 start = 0;
2085 }
2086 if (stop < 0) {
Christian Heimes90aa7642007-12-19 02:45:37 +00002087 stop += Py_SIZE(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002088 if (stop < 0)
2089 stop = 0;
2090 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002091 for (i = start; i < stop && i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002092 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2093 if (cmp > 0)
Christian Heimes217cfd12007-12-02 14:31:20 +00002094 return PyLong_FromSsize_t(i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002095 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002096 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002097 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002098 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002099 return NULL;
2100}
2101
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002102static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002103listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002104{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002105 Py_ssize_t count = 0;
2106 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002107
Christian Heimes90aa7642007-12-19 02:45:37 +00002108 for (i = 0; i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002109 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2110 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002111 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002112 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002113 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00002114 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002115 return PyLong_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002116}
2117
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002118static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002119listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002120{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002121 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002122
Christian Heimes90aa7642007-12-19 02:45:37 +00002123 for (i = 0; i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002124 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2125 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002126 if (list_ass_slice(self, i, i+1,
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002127 (PyObject *)NULL) == 0)
2128 Py_RETURN_NONE;
2129 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002130 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002131 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002132 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002133 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002134 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002135 return NULL;
2136}
2137
Jeremy Hylton8caad492000-06-23 14:18:11 +00002138static int
2139list_traverse(PyListObject *o, visitproc visit, void *arg)
2140{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002141 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002142
Christian Heimes90aa7642007-12-19 02:45:37 +00002143 for (i = Py_SIZE(o); --i >= 0; )
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002144 Py_VISIT(o->ob_item[i]);
Jeremy Hylton8caad492000-06-23 14:18:11 +00002145 return 0;
2146}
2147
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002148static PyObject *
2149list_richcompare(PyObject *v, PyObject *w, int op)
2150{
2151 PyListObject *vl, *wl;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002152 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002153
2154 if (!PyList_Check(v) || !PyList_Check(w)) {
2155 Py_INCREF(Py_NotImplemented);
2156 return Py_NotImplemented;
2157 }
2158
2159 vl = (PyListObject *)v;
2160 wl = (PyListObject *)w;
2161
Christian Heimes90aa7642007-12-19 02:45:37 +00002162 if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002163 /* Shortcut: if the lengths differ, the lists differ */
2164 PyObject *res;
2165 if (op == Py_EQ)
2166 res = Py_False;
2167 else
2168 res = Py_True;
2169 Py_INCREF(res);
2170 return res;
2171 }
2172
2173 /* Search for the first index where items are different */
Christian Heimes90aa7642007-12-19 02:45:37 +00002174 for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002175 int k = PyObject_RichCompareBool(vl->ob_item[i],
2176 wl->ob_item[i], Py_EQ);
2177 if (k < 0)
2178 return NULL;
2179 if (!k)
2180 break;
2181 }
2182
Christian Heimes90aa7642007-12-19 02:45:37 +00002183 if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002184 /* No more items to compare -- compare sizes */
Christian Heimes90aa7642007-12-19 02:45:37 +00002185 Py_ssize_t vs = Py_SIZE(vl);
2186 Py_ssize_t ws = Py_SIZE(wl);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002187 int cmp;
2188 PyObject *res;
2189 switch (op) {
2190 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00002191 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002192 case Py_EQ: cmp = vs == ws; break;
2193 case Py_NE: cmp = vs != ws; break;
2194 case Py_GT: cmp = vs > ws; break;
2195 case Py_GE: cmp = vs >= ws; break;
2196 default: return NULL; /* cannot happen */
2197 }
2198 if (cmp)
2199 res = Py_True;
2200 else
2201 res = Py_False;
2202 Py_INCREF(res);
2203 return res;
2204 }
2205
2206 /* We have an item that differs -- shortcuts for EQ/NE */
2207 if (op == Py_EQ) {
2208 Py_INCREF(Py_False);
2209 return Py_False;
2210 }
2211 if (op == Py_NE) {
2212 Py_INCREF(Py_True);
2213 return Py_True;
2214 }
2215
2216 /* Compare the final item again using the proper operator */
2217 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
2218}
2219
Tim Peters6d6c1a32001-08-02 04:15:00 +00002220static int
2221list_init(PyListObject *self, PyObject *args, PyObject *kw)
2222{
2223 PyObject *arg = NULL;
Martin v. Löwis15e62742006-02-27 16:46:16 +00002224 static char *kwlist[] = {"sequence", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002225
2226 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2227 return -1;
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002228
2229 /* Verify list invariants established by PyType_GenericAlloc() */
Christian Heimes90aa7642007-12-19 02:45:37 +00002230 assert(0 <= Py_SIZE(self));
2231 assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
Armin Rigoa37bbf22004-07-30 11:20:18 +00002232 assert(self->ob_item != NULL ||
2233 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002234
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002235 /* Empty previous contents */
Armin Rigo93677f02004-07-29 12:40:23 +00002236 if (self->ob_item != NULL) {
2237 (void)list_clear(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002238 }
2239 if (arg != NULL) {
2240 PyObject *rv = listextend(self, arg);
2241 if (rv == NULL)
2242 return -1;
2243 Py_DECREF(rv);
2244 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002245 return 0;
2246}
2247
Raymond Hettinger1021c442003-11-07 15:38:09 +00002248static PyObject *list_iter(PyObject *seq);
2249static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2250
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002251PyDoc_STRVAR(getitem_doc,
2252"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002253PyDoc_STRVAR(reversed_doc,
2254"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002255PyDoc_STRVAR(append_doc,
2256"L.append(object) -- append object to end");
2257PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002258"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002259PyDoc_STRVAR(insert_doc,
2260"L.insert(index, object) -- insert object before index");
2261PyDoc_STRVAR(pop_doc,
2262"L.pop([index]) -> item -- remove and return item at index (default last)");
2263PyDoc_STRVAR(remove_doc,
2264"L.remove(value) -- remove first occurrence of value");
2265PyDoc_STRVAR(index_doc,
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002266"L.index(value, [start, [stop]]) -> integer -- return first index of value");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002267PyDoc_STRVAR(count_doc,
2268"L.count(value) -> integer -- return number of occurrences of value");
2269PyDoc_STRVAR(reverse_doc,
2270"L.reverse() -- reverse *IN PLACE*");
2271PyDoc_STRVAR(sort_doc,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002272"L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n\
2273cmp(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002274
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002275static PyObject *list_subscript(PyListObject*, PyObject*);
2276
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002277static PyMethodDef list_methods[] = {
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002278 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
Raymond Hettinger1021c442003-11-07 15:38:09 +00002279 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002280 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002281 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002282 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002283 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002284 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002285 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002286 {"count", (PyCFunction)listcount, METH_O, count_doc},
2287 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002288 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
Tim Petersa64dc242002-08-01 02:13:36 +00002289 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002290};
2291
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002292static PySequenceMethods list_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002293 (lenfunc)list_length, /* sq_length */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002294 (binaryfunc)list_concat, /* sq_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002295 (ssizeargfunc)list_repeat, /* sq_repeat */
2296 (ssizeargfunc)list_item, /* sq_item */
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002297 0, /* sq_slice */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002298 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002299 0, /* sq_ass_slice */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002300 (objobjproc)list_contains, /* sq_contains */
2301 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002302 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002303};
2304
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002305PyDoc_STRVAR(list_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002306"list() -> new list\n"
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002307"list(sequence) -> new list initialized from sequence's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002308
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002309static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002310list_subscript(PyListObject* self, PyObject* item)
2311{
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002312 if (PyIndex_Check(item)) {
2313 Py_ssize_t i;
2314 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002315 if (i == -1 && PyErr_Occurred())
2316 return NULL;
2317 if (i < 0)
2318 i += PyList_GET_SIZE(self);
2319 return list_item(self, i);
2320 }
2321 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002322 Py_ssize_t start, stop, step, slicelength, cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002323 PyObject* result;
2324 PyObject* it;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002325 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002326
Christian Heimes90aa7642007-12-19 02:45:37 +00002327 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002328 &start, &stop, &step, &slicelength) < 0) {
2329 return NULL;
2330 }
2331
2332 if (slicelength <= 0) {
2333 return PyList_New(0);
2334 }
Thomas Woutersed03b412007-08-28 21:37:11 +00002335 else if (step == 1) {
2336 return list_slice(self, start, stop);
2337 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002338 else {
2339 result = PyList_New(slicelength);
2340 if (!result) return NULL;
2341
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002342 src = self->ob_item;
2343 dest = ((PyListObject *)result)->ob_item;
Tim Peters3b01a122002-07-19 02:35:45 +00002344 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002345 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002346 it = src[cur];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002347 Py_INCREF(it);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002348 dest[i] = it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002349 }
Tim Peters3b01a122002-07-19 02:35:45 +00002350
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002351 return result;
2352 }
2353 }
2354 else {
Thomas Wouters89f507f2006-12-13 04:49:30 +00002355 PyErr_Format(PyExc_TypeError,
2356 "list indices must be integers, not %.200s",
2357 item->ob_type->tp_name);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002358 return NULL;
2359 }
2360}
2361
Tim Peters3b01a122002-07-19 02:35:45 +00002362static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002363list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2364{
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002365 if (PyIndex_Check(item)) {
2366 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002367 if (i == -1 && PyErr_Occurred())
2368 return -1;
2369 if (i < 0)
2370 i += PyList_GET_SIZE(self);
2371 return list_ass_item(self, i, value);
2372 }
2373 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002374 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002375
Christian Heimes90aa7642007-12-19 02:45:37 +00002376 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002377 &start, &stop, &step, &slicelength) < 0) {
2378 return -1;
2379 }
2380
Thomas Woutersed03b412007-08-28 21:37:11 +00002381 if (step == 1)
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002382 return list_ass_slice(self, start, stop, value);
2383
Thomas Woutersed03b412007-08-28 21:37:11 +00002384 /* Make sure s[5:2] = [..] inserts at the right place:
2385 before 5, not before 2. */
2386 if ((step < 0 && start < stop) ||
2387 (step > 0 && start > stop))
2388 stop = start;
2389
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002390 if (value == NULL) {
2391 /* delete slice */
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002392 PyObject **garbage;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002393 Py_ssize_t cur, i;
Tim Peters3b01a122002-07-19 02:35:45 +00002394
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002395 if (slicelength <= 0)
2396 return 0;
2397
2398 if (step < 0) {
2399 stop = start + 1;
2400 start = stop + step*(slicelength - 1) - 1;
2401 step = -step;
2402 }
2403
2404 garbage = (PyObject**)
2405 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002406 if (!garbage) {
2407 PyErr_NoMemory();
2408 return -1;
2409 }
Tim Peters3b01a122002-07-19 02:35:45 +00002410
Thomas Woutersed03b412007-08-28 21:37:11 +00002411 /* drawing pictures might help understand these for
2412 loops. Basically, we memmove the parts of the
2413 list that are *not* part of the slice: step-1
2414 items for each item that is part of the slice,
2415 and then tail end of the list that was not
2416 covered by the slice */
Guido van Rossum75a20b12002-06-11 12:22:28 +00002417 for (cur = start, i = 0;
2418 cur < stop;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002419 cur += step, i++) {
Thomas Woutersed03b412007-08-28 21:37:11 +00002420 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002421
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002422 garbage[i] = PyList_GET_ITEM(self, cur);
2423
Christian Heimes90aa7642007-12-19 02:45:37 +00002424 if (cur + step >= Py_SIZE(self)) {
2425 lim = Py_SIZE(self) - cur - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002426 }
2427
Tim Petersb38e2b62004-07-29 02:29:26 +00002428 memmove(self->ob_item + cur - i,
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002429 self->ob_item + cur + 1,
2430 lim * sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002431 }
Thomas Woutersed03b412007-08-28 21:37:11 +00002432 cur = start + slicelength*step;
Christian Heimes90aa7642007-12-19 02:45:37 +00002433 if (cur < Py_SIZE(self)) {
Thomas Woutersed03b412007-08-28 21:37:11 +00002434 memmove(self->ob_item + cur - slicelength,
2435 self->ob_item + cur,
Christian Heimes90aa7642007-12-19 02:45:37 +00002436 (Py_SIZE(self) - cur) *
Thomas Woutersed03b412007-08-28 21:37:11 +00002437 sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002438 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002439
Christian Heimes90aa7642007-12-19 02:45:37 +00002440 Py_SIZE(self) -= slicelength;
2441 list_resize(self, Py_SIZE(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002442
2443 for (i = 0; i < slicelength; i++) {
2444 Py_DECREF(garbage[i]);
2445 }
2446 PyMem_FREE(garbage);
2447
2448 return 0;
2449 }
2450 else {
2451 /* assign slice */
Thomas Woutersed03b412007-08-28 21:37:11 +00002452 PyObject *ins, *seq;
2453 PyObject **garbage, **seqitems, **selfitems;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002454 Py_ssize_t cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002455
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002456 /* protect against a[::-1] = a */
Tim Peters3b01a122002-07-19 02:35:45 +00002457 if (self == (PyListObject*)value) {
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002458 seq = list_slice((PyListObject*)value, 0,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002459 PyList_GET_SIZE(value));
Tim Peters3b01a122002-07-19 02:35:45 +00002460 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002461 else {
Tim Petersb38e2b62004-07-29 02:29:26 +00002462 seq = PySequence_Fast(value,
Thomas Woutersed03b412007-08-28 21:37:11 +00002463 "must assign iterable "
2464 "to extended slice");
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002465 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002466 if (!seq)
2467 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002468
2469 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2470 PyErr_Format(PyExc_ValueError,
Thomas Woutersed03b412007-08-28 21:37:11 +00002471 "attempt to assign sequence of "
2472 "size %zd to extended slice of "
2473 "size %zd",
Martin v. Löwise0e89f72006-02-16 06:59:22 +00002474 PySequence_Fast_GET_SIZE(seq),
2475 slicelength);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002476 Py_DECREF(seq);
2477 return -1;
2478 }
2479
2480 if (!slicelength) {
2481 Py_DECREF(seq);
2482 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002483 }
2484
2485 garbage = (PyObject**)
2486 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Thomas Wouters89f507f2006-12-13 04:49:30 +00002487 if (!garbage) {
2488 Py_DECREF(seq);
2489 PyErr_NoMemory();
2490 return -1;
2491 }
Tim Peters3b01a122002-07-19 02:35:45 +00002492
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002493 selfitems = self->ob_item;
Raymond Hettinger42bec932004-03-12 16:38:17 +00002494 seqitems = PySequence_Fast_ITEMS(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002495 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002496 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002497 garbage[i] = selfitems[cur];
2498 ins = seqitems[i];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002499 Py_INCREF(ins);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002500 selfitems[cur] = ins;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002501 }
2502
2503 for (i = 0; i < slicelength; i++) {
2504 Py_DECREF(garbage[i]);
2505 }
Tim Peters3b01a122002-07-19 02:35:45 +00002506
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002507 PyMem_FREE(garbage);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002508 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002509
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002510 return 0;
2511 }
Tim Peters3b01a122002-07-19 02:35:45 +00002512 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002513 else {
Thomas Wouters89f507f2006-12-13 04:49:30 +00002514 PyErr_Format(PyExc_TypeError,
2515 "list indices must be integers, not %.200s",
2516 item->ob_type->tp_name);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002517 return -1;
2518 }
2519}
2520
2521static PyMappingMethods list_as_mapping = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002522 (lenfunc)list_length,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002523 (binaryfunc)list_subscript,
2524 (objobjargproc)list_ass_subscript
2525};
2526
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002527PyTypeObject PyList_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002528 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002529 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002530 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002531 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002532 (destructor)list_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00002533 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002534 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002535 0, /* tp_setattr */
2536 0, /* tp_compare */
2537 (reprfunc)list_repr, /* tp_repr */
2538 0, /* tp_as_number */
2539 &list_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002540 &list_as_mapping, /* tp_as_mapping */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00002541 0, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002542 0, /* tp_call */
2543 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002544 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002545 0, /* tp_setattro */
2546 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002547 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Thomas Wouters27d517b2007-02-25 20:39:11 +00002548 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002549 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002550 (traverseproc)list_traverse, /* tp_traverse */
2551 (inquiry)list_clear, /* tp_clear */
2552 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002553 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002554 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002555 0, /* tp_iternext */
2556 list_methods, /* tp_methods */
2557 0, /* tp_members */
2558 0, /* tp_getset */
2559 0, /* tp_base */
2560 0, /* tp_dict */
2561 0, /* tp_descr_get */
2562 0, /* tp_descr_set */
2563 0, /* tp_dictoffset */
2564 (initproc)list_init, /* tp_init */
2565 PyType_GenericAlloc, /* tp_alloc */
2566 PyType_GenericNew, /* tp_new */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002567 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002568};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002569
2570
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002571/*********************** List Iterator **************************/
2572
2573typedef struct {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002574 PyObject_HEAD
2575 long it_index;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002576 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002577} listiterobject;
2578
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002579static PyObject *list_iter(PyObject *);
2580static void listiter_dealloc(listiterobject *);
2581static int listiter_traverse(listiterobject *, visitproc, void *);
2582static PyObject *listiter_next(listiterobject *);
2583static PyObject *listiter_len(listiterobject *);
Raymond Hettinger435bf582004-03-18 22:43:10 +00002584
Armin Rigof5b3e362006-02-11 21:32:43 +00002585PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002586
2587static PyMethodDef listiter_methods[] = {
Armin Rigof5b3e362006-02-11 21:32:43 +00002588 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002589 {NULL, NULL} /* sentinel */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002590};
2591
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002592PyTypeObject PyListIter_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002593 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Christian Heimesf83be4e2007-11-28 09:44:38 +00002594 "list_iterator", /* tp_name */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002595 sizeof(listiterobject), /* tp_basicsize */
2596 0, /* tp_itemsize */
2597 /* methods */
2598 (destructor)listiter_dealloc, /* tp_dealloc */
2599 0, /* tp_print */
2600 0, /* tp_getattr */
2601 0, /* tp_setattr */
2602 0, /* tp_compare */
2603 0, /* tp_repr */
2604 0, /* tp_as_number */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002605 0, /* tp_as_sequence */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002606 0, /* tp_as_mapping */
2607 0, /* tp_hash */
2608 0, /* tp_call */
2609 0, /* tp_str */
2610 PyObject_GenericGetAttr, /* tp_getattro */
2611 0, /* tp_setattro */
2612 0, /* tp_as_buffer */
2613 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2614 0, /* tp_doc */
2615 (traverseproc)listiter_traverse, /* tp_traverse */
2616 0, /* tp_clear */
2617 0, /* tp_richcompare */
2618 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00002619 PyObject_SelfIter, /* tp_iter */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002620 (iternextfunc)listiter_next, /* tp_iternext */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002621 listiter_methods, /* tp_methods */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002622 0, /* tp_members */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002623};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002624
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002625
2626static PyObject *
2627list_iter(PyObject *seq)
2628{
2629 listiterobject *it;
2630
2631 if (!PyList_Check(seq)) {
2632 PyErr_BadInternalCall();
2633 return NULL;
2634 }
2635 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2636 if (it == NULL)
2637 return NULL;
2638 it->it_index = 0;
2639 Py_INCREF(seq);
2640 it->it_seq = (PyListObject *)seq;
2641 _PyObject_GC_TRACK(it);
2642 return (PyObject *)it;
2643}
2644
2645static void
2646listiter_dealloc(listiterobject *it)
2647{
2648 _PyObject_GC_UNTRACK(it);
2649 Py_XDECREF(it->it_seq);
2650 PyObject_GC_Del(it);
2651}
2652
2653static int
2654listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2655{
2656 Py_VISIT(it->it_seq);
2657 return 0;
2658}
2659
2660static PyObject *
2661listiter_next(listiterobject *it)
2662{
2663 PyListObject *seq;
2664 PyObject *item;
2665
2666 assert(it != NULL);
2667 seq = it->it_seq;
2668 if (seq == NULL)
2669 return NULL;
2670 assert(PyList_Check(seq));
2671
2672 if (it->it_index < PyList_GET_SIZE(seq)) {
2673 item = PyList_GET_ITEM(seq, it->it_index);
2674 ++it->it_index;
2675 Py_INCREF(item);
2676 return item;
2677 }
2678
2679 Py_DECREF(seq);
2680 it->it_seq = NULL;
2681 return NULL;
2682}
2683
2684static PyObject *
2685listiter_len(listiterobject *it)
2686{
2687 Py_ssize_t len;
2688 if (it->it_seq) {
2689 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2690 if (len >= 0)
Christian Heimes217cfd12007-12-02 14:31:20 +00002691 return PyLong_FromSsize_t(len);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002692 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002693 return PyLong_FromLong(0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002694}
Raymond Hettinger1021c442003-11-07 15:38:09 +00002695/*********************** List Reverse Iterator **************************/
2696
2697typedef struct {
2698 PyObject_HEAD
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002699 Py_ssize_t it_index;
Raymond Hettinger001f2282003-11-08 11:58:44 +00002700 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002701} listreviterobject;
2702
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002703static PyObject *list_reversed(PyListObject *, PyObject *);
2704static void listreviter_dealloc(listreviterobject *);
2705static int listreviter_traverse(listreviterobject *, visitproc, void *);
2706static PyObject *listreviter_next(listreviterobject *);
2707static Py_ssize_t listreviter_len(listreviterobject *);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002708
2709static PySequenceMethods listreviter_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002710 (lenfunc)listreviter_len, /* sq_length */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002711 0, /* sq_concat */
2712};
2713
Raymond Hettinger1021c442003-11-07 15:38:09 +00002714PyTypeObject PyListRevIter_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002715 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Christian Heimesf83be4e2007-11-28 09:44:38 +00002716 "list_reverseiterator", /* tp_name */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002717 sizeof(listreviterobject), /* tp_basicsize */
2718 0, /* tp_itemsize */
2719 /* methods */
2720 (destructor)listreviter_dealloc, /* tp_dealloc */
2721 0, /* tp_print */
2722 0, /* tp_getattr */
2723 0, /* tp_setattr */
2724 0, /* tp_compare */
2725 0, /* tp_repr */
2726 0, /* tp_as_number */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002727 &listreviter_as_sequence, /* tp_as_sequence */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002728 0, /* tp_as_mapping */
2729 0, /* tp_hash */
2730 0, /* tp_call */
2731 0, /* tp_str */
2732 PyObject_GenericGetAttr, /* tp_getattro */
2733 0, /* tp_setattro */
2734 0, /* tp_as_buffer */
2735 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2736 0, /* tp_doc */
2737 (traverseproc)listreviter_traverse, /* tp_traverse */
2738 0, /* tp_clear */
2739 0, /* tp_richcompare */
2740 0, /* tp_weaklistoffset */
2741 PyObject_SelfIter, /* tp_iter */
2742 (iternextfunc)listreviter_next, /* tp_iternext */
2743 0,
2744};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002745
2746static PyObject *
2747list_reversed(PyListObject *seq, PyObject *unused)
2748{
2749 listreviterobject *it;
2750
2751 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2752 if (it == NULL)
2753 return NULL;
2754 assert(PyList_Check(seq));
2755 it->it_index = PyList_GET_SIZE(seq) - 1;
2756 Py_INCREF(seq);
2757 it->it_seq = seq;
2758 PyObject_GC_Track(it);
2759 return (PyObject *)it;
2760}
2761
2762static void
2763listreviter_dealloc(listreviterobject *it)
2764{
2765 PyObject_GC_UnTrack(it);
2766 Py_XDECREF(it->it_seq);
2767 PyObject_GC_Del(it);
2768}
2769
2770static int
2771listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2772{
2773 Py_VISIT(it->it_seq);
2774 return 0;
2775}
2776
2777static PyObject *
2778listreviter_next(listreviterobject *it)
2779{
2780 PyObject *item;
2781 Py_ssize_t index = it->it_index;
2782 PyListObject *seq = it->it_seq;
2783
2784 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2785 item = PyList_GET_ITEM(seq, index);
2786 it->it_index--;
2787 Py_INCREF(item);
2788 return item;
2789 }
2790 it->it_index = -1;
2791 if (seq != NULL) {
2792 it->it_seq = NULL;
2793 Py_DECREF(seq);
2794 }
2795 return NULL;
2796}
2797
2798static Py_ssize_t
2799listreviter_len(listreviterobject *it)
2800{
2801 Py_ssize_t len = it->it_index + 1;
2802 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
2803 return 0;
2804 return len;
2805}
2806