blob: 9a8b64e76f5f668ea675d14a745388b866259f72 [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 Heimese93237d2007-12-19 02:37:44 +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 Heimese93237d2007-12-19 02:37:44 +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 Heimesb4ee4a12008-02-07 17:15:30 +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{
Christian Heimes09bde042008-02-24 12:26:16 +000075 fprintf(stderr, "List allocations: %" PY_FORMAT_SIZE_T "d\n",
76 count_alloc);
77 fprintf(stderr, "List reuse through freelist: %" PY_FORMAT_SIZE_T
78 "d\n", count_reuse);
Christian Heimesb4ee4a12008-02-07 17:15:30 +000079 fprintf(stderr, "%.2f%% reuse rate\n\n",
80 (100.0*count_reuse/(count_alloc+count_reuse)));
81}
82#endif
83
Raymond Hettinger0468e412004-05-05 05:37:53 +000084/* Empty list reuse scheme to save calls to malloc and free */
Christian Heimes5b970ad2008-02-06 13:33:44 +000085#ifndef PyList_MAXFREELIST
86#define PyList_MAXFREELIST 80
87#endif
88static PyListObject *free_list[PyList_MAXFREELIST];
89static int numfree = 0;
Raymond Hettinger0468e412004-05-05 05:37:53 +000090
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +000091void
92PyList_Fini(void)
93{
94 PyListObject *op;
95
Christian Heimes5b970ad2008-02-06 13:33:44 +000096 while (numfree) {
Christian Heimes48397d62008-02-08 00:14:34 +000097 op = free_list[--numfree];
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +000098 assert(PyList_CheckExact(op));
99 PyObject_GC_Del(op);
100 }
101}
102
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000103PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000104PyList_New(Py_ssize_t size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000105{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000106 PyListObject *op;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +0000107 size_t nbytes;
Christian Heimesb4ee4a12008-02-07 17:15:30 +0000108#ifdef SHOW_ALLOC_COUNT
109 static int initialized = 0;
110 if (!initialized) {
111 Py_AtExit(show_alloc);
112 initialized = 1;
113 }
114#endif
Tim Peters3986d4e2004-07-29 02:28:42 +0000115
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000116 if (size < 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000117 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000118 return NULL;
119 }
Tim Peters7049d812004-01-18 20:31:02 +0000120 nbytes = size * sizeof(PyObject *);
Guido van Rossum1e28e5e1992-08-19 16:46:30 +0000121 /* Check for overflow */
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000122 if (nbytes / sizeof(PyObject *) != (size_t)size)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000123 return PyErr_NoMemory();
Christian Heimes5b970ad2008-02-06 13:33:44 +0000124 if (numfree) {
125 numfree--;
126 op = free_list[numfree];
Raymond Hettinger0468e412004-05-05 05:37:53 +0000127 _Py_NewReference((PyObject *)op);
Christian Heimesb4ee4a12008-02-07 17:15:30 +0000128#ifdef SHOW_ALLOC_COUNT
129 count_reuse++;
130#endif
Raymond Hettinger0468e412004-05-05 05:37:53 +0000131 } else {
132 op = PyObject_GC_New(PyListObject, &PyList_Type);
133 if (op == NULL)
134 return NULL;
Christian Heimesb4ee4a12008-02-07 17:15:30 +0000135#ifdef SHOW_ALLOC_COUNT
136 count_alloc++;
137#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000138 }
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000139 if (size <= 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000140 op->ob_item = NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000141 else {
Guido van Rossumb18618d2000-05-03 23:44:39 +0000142 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
Neal Norwitza00c0b92006-06-12 02:08:41 +0000143 if (op->ob_item == NULL) {
144 Py_DECREF(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000145 return PyErr_NoMemory();
Neal Norwitza00c0b92006-06-12 02:08:41 +0000146 }
Tim Peters3986d4e2004-07-29 02:28:42 +0000147 memset(op->ob_item, 0, nbytes);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000148 }
Christian Heimese93237d2007-12-19 02:37:44 +0000149 Py_SIZE(op) = size;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000150 op->allocated = size;
Neil Schemenauere83c00e2001-08-29 23:54:21 +0000151 _PyObject_GC_TRACK(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000152 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000153}
154
Martin v. Löwis18e16552006-02-15 17:27:45 +0000155Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000156PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000157{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000158 if (!PyList_Check(op)) {
159 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000160 return -1;
161 }
162 else
Christian Heimese93237d2007-12-19 02:37:44 +0000163 return Py_SIZE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000164}
165
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000166static PyObject *indexerr = NULL;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000167
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000168PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000169PyList_GetItem(PyObject *op, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000170{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000171 if (!PyList_Check(op)) {
172 PyErr_BadInternalCall();
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000173 return NULL;
174 }
Christian Heimese93237d2007-12-19 02:37:44 +0000175 if (i < 0 || i >= Py_SIZE(op)) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000176 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000177 indexerr = PyString_FromString(
178 "list index out of range");
179 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000180 return NULL;
181 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000182 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000183}
184
185int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000186PyList_SetItem(register PyObject *op, register Py_ssize_t i,
Fred Drakea2f55112000-07-09 15:16:51 +0000187 register PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000188{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000189 register PyObject *olditem;
190 register PyObject **p;
191 if (!PyList_Check(op)) {
192 Py_XDECREF(newitem);
193 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000194 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000195 }
Christian Heimese93237d2007-12-19 02:37:44 +0000196 if (i < 0 || i >= Py_SIZE(op)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000197 Py_XDECREF(newitem);
198 PyErr_SetString(PyExc_IndexError,
199 "list assignment index out of range");
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000200 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000201 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000202 p = ((PyListObject *)op) -> ob_item + i;
Guido van Rossum5fe60581995-03-09 12:12:50 +0000203 olditem = *p;
204 *p = newitem;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000205 Py_XDECREF(olditem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000206 return 0;
207}
208
209static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000210ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000211{
Christian Heimese93237d2007-12-19 02:37:44 +0000212 Py_ssize_t i, n = Py_SIZE(self);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000213 PyObject **items;
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000214 if (v == NULL) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000215 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000216 return -1;
217 }
Martin v. Löwisb1ed7fa2006-04-13 07:52:27 +0000218 if (n == PY_SSIZE_T_MAX) {
Trent Micka5846642000-08-13 22:47:45 +0000219 PyErr_SetString(PyExc_OverflowError,
220 "cannot add more objects to list");
221 return -1;
222 }
Tim Petersb38e2b62004-07-29 02:29:26 +0000223
Raymond Hettingerd4ff7412004-03-15 09:01:31 +0000224 if (list_resize(self, n+1) == -1)
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000225 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000226
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000227 if (where < 0) {
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000228 where += n;
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000229 if (where < 0)
230 where = 0;
231 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000232 if (where > n)
233 where = n;
234 items = self->ob_item;
235 for (i = n; --i >= where; )
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000236 items[i+1] = items[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000237 Py_INCREF(v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000238 items[where] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000239 return 0;
240}
241
242int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000243PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000244{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000245 if (!PyList_Check(op)) {
246 PyErr_BadInternalCall();
Guido van Rossum2a9096b1990-10-21 22:15:08 +0000247 return -1;
248 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000249 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000250}
251
Raymond Hettinger40a03822004-04-12 13:05:09 +0000252static int
253app1(PyListObject *self, PyObject *v)
254{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000255 Py_ssize_t n = PyList_GET_SIZE(self);
Raymond Hettinger40a03822004-04-12 13:05:09 +0000256
257 assert (v != NULL);
Martin v. Löwisb1ed7fa2006-04-13 07:52:27 +0000258 if (n == PY_SSIZE_T_MAX) {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000259 PyErr_SetString(PyExc_OverflowError,
260 "cannot add more objects to list");
261 return -1;
262 }
263
264 if (list_resize(self, n+1) == -1)
265 return -1;
266
267 Py_INCREF(v);
268 PyList_SET_ITEM(self, n, v);
269 return 0;
270}
271
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000272int
Fred Drakea2f55112000-07-09 15:16:51 +0000273PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000274{
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000275 if (PyList_Check(op) && (newitem != NULL))
276 return app1((PyListObject *)op, newitem);
277 PyErr_BadInternalCall();
278 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000279}
280
281/* Methods */
282
283static void
Fred Drakea2f55112000-07-09 15:16:51 +0000284list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000285{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000286 Py_ssize_t i;
Guido van Rossumff413af2002-03-28 20:34:59 +0000287 PyObject_GC_UnTrack(op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000288 Py_TRASHCAN_SAFE_BEGIN(op)
Jack Jansen7874d1f1995-01-19 12:09:27 +0000289 if (op->ob_item != NULL) {
Guido van Rossumfa717011999-06-09 15:19:34 +0000290 /* Do it backwards, for Christian Tismer.
291 There's a simple test case where somehow this reduces
292 thrashing when a *very* large list is created and
293 immediately deleted. */
Christian Heimese93237d2007-12-19 02:37:44 +0000294 i = Py_SIZE(op);
Guido van Rossumfa717011999-06-09 15:19:34 +0000295 while (--i >= 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000296 Py_XDECREF(op->ob_item[i]);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000297 }
Guido van Rossumb18618d2000-05-03 23:44:39 +0000298 PyMem_FREE(op->ob_item);
Jack Jansen7874d1f1995-01-19 12:09:27 +0000299 }
Christian Heimes5b970ad2008-02-06 13:33:44 +0000300 if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op))
301 free_list[numfree++] = op;
Tim Petersb38e2b62004-07-29 02:29:26 +0000302 else
Christian Heimese93237d2007-12-19 02:37:44 +0000303 Py_TYPE(op)->tp_free((PyObject *)op);
Guido van Rossumd724b232000-03-13 16:01:29 +0000304 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000305}
306
Guido van Rossum90933611991-06-07 16:10:43 +0000307static int
Fred Drakea2f55112000-07-09 15:16:51 +0000308list_print(PyListObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000309{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000310 int rc;
311 Py_ssize_t i;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000312
Martin v. Löwis18e16552006-02-15 17:27:45 +0000313 rc = Py_ReprEnter((PyObject*)op);
314 if (rc != 0) {
315 if (rc < 0)
316 return rc;
Brett Cannon01531592007-09-17 03:28:34 +0000317 Py_BEGIN_ALLOW_THREADS
Guido van Rossumfb376de1998-04-10 22:47:27 +0000318 fprintf(fp, "[...]");
Brett Cannon01531592007-09-17 03:28:34 +0000319 Py_END_ALLOW_THREADS
Guido van Rossumfb376de1998-04-10 22:47:27 +0000320 return 0;
321 }
Brett Cannon01531592007-09-17 03:28:34 +0000322 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000323 fprintf(fp, "[");
Brett Cannon01531592007-09-17 03:28:34 +0000324 Py_END_ALLOW_THREADS
Christian Heimese93237d2007-12-19 02:37:44 +0000325 for (i = 0; i < Py_SIZE(op); i++) {
Brett Cannon01531592007-09-17 03:28:34 +0000326 if (i > 0) {
327 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000328 fprintf(fp, ", ");
Brett Cannon01531592007-09-17 03:28:34 +0000329 Py_END_ALLOW_THREADS
330 }
Guido van Rossumfb376de1998-04-10 22:47:27 +0000331 if (PyObject_Print(op->ob_item[i], fp, 0) != 0) {
332 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000333 return -1;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000334 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000335 }
Brett Cannon01531592007-09-17 03:28:34 +0000336 Py_BEGIN_ALLOW_THREADS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000337 fprintf(fp, "]");
Brett Cannon01531592007-09-17 03:28:34 +0000338 Py_END_ALLOW_THREADS
Guido van Rossumfb376de1998-04-10 22:47:27 +0000339 Py_ReprLeave((PyObject *)op);
Guido van Rossum90933611991-06-07 16:10:43 +0000340 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000341}
342
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000343static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000344list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000345{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000346 Py_ssize_t i;
Tim Petersa7259592001-06-16 05:11:17 +0000347 PyObject *s, *temp;
348 PyObject *pieces = NULL, *result = NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000349
350 i = Py_ReprEnter((PyObject*)v);
351 if (i != 0) {
Tim Petersa7259592001-06-16 05:11:17 +0000352 return i > 0 ? PyString_FromString("[...]") : NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000353 }
Tim Petersa7259592001-06-16 05:11:17 +0000354
Christian Heimese93237d2007-12-19 02:37:44 +0000355 if (Py_SIZE(v) == 0) {
Tim Petersa7259592001-06-16 05:11:17 +0000356 result = PyString_FromString("[]");
357 goto Done;
358 }
359
360 pieces = PyList_New(0);
361 if (pieces == NULL)
362 goto Done;
363
364 /* Do repr() on each element. Note that this may mutate the list,
365 so must refetch the list size on each iteration. */
Christian Heimese93237d2007-12-19 02:37:44 +0000366 for (i = 0; i < Py_SIZE(v); ++i) {
Tim Petersa7259592001-06-16 05:11:17 +0000367 int status;
Brett Cannona0c05512007-09-10 21:38:27 +0000368 if (Py_EnterRecursiveCall(" while getting the repr of a list"))
369 goto Done;
Tim Petersa7259592001-06-16 05:11:17 +0000370 s = PyObject_Repr(v->ob_item[i]);
Brett Cannona0c05512007-09-10 21:38:27 +0000371 Py_LeaveRecursiveCall();
Tim Petersa7259592001-06-16 05:11:17 +0000372 if (s == NULL)
373 goto Done;
374 status = PyList_Append(pieces, s);
375 Py_DECREF(s); /* append created a new ref */
376 if (status < 0)
377 goto Done;
378 }
379
380 /* Add "[]" decorations to the first and last items. */
381 assert(PyList_GET_SIZE(pieces) > 0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000382 s = PyString_FromString("[");
Tim Petersa7259592001-06-16 05:11:17 +0000383 if (s == NULL)
384 goto Done;
385 temp = PyList_GET_ITEM(pieces, 0);
386 PyString_ConcatAndDel(&s, temp);
387 PyList_SET_ITEM(pieces, 0, s);
388 if (s == NULL)
389 goto Done;
390
391 s = PyString_FromString("]");
392 if (s == NULL)
393 goto Done;
394 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
395 PyString_ConcatAndDel(&temp, s);
396 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
397 if (temp == NULL)
398 goto Done;
399
400 /* Paste them all together with ", " between. */
401 s = PyString_FromString(", ");
402 if (s == NULL)
403 goto Done;
404 result = _PyString_Join(s, pieces);
Tim Peters3b01a122002-07-19 02:35:45 +0000405 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +0000406
407Done:
408 Py_XDECREF(pieces);
Guido van Rossumfb376de1998-04-10 22:47:27 +0000409 Py_ReprLeave((PyObject *)v);
Tim Petersa7259592001-06-16 05:11:17 +0000410 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000411}
412
Martin v. Löwis18e16552006-02-15 17:27:45 +0000413static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000414list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000415{
Christian Heimese93237d2007-12-19 02:37:44 +0000416 return Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000417}
418
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000419static int
Fred Drakea2f55112000-07-09 15:16:51 +0000420list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000421{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000422 Py_ssize_t i;
423 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000424
Christian Heimese93237d2007-12-19 02:37:44 +0000425 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
Raymond Hettingeraae59992002-09-05 14:23:49 +0000426 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000427 Py_EQ);
Neal Norwitzbb9c5f52002-09-05 21:32:55 +0000428 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000429}
430
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000431static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000432list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000433{
Christian Heimese93237d2007-12-19 02:37:44 +0000434 if (i < 0 || i >= Py_SIZE(a)) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000435 if (indexerr == NULL)
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000436 indexerr = PyString_FromString(
437 "list index out of range");
438 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000439 return NULL;
440 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000441 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000442 return a->ob_item[i];
443}
444
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000445static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000446list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000447{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000448 PyListObject *np;
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000449 PyObject **src, **dest;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000450 Py_ssize_t i, len;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000451 if (ilow < 0)
452 ilow = 0;
Christian Heimese93237d2007-12-19 02:37:44 +0000453 else if (ilow > Py_SIZE(a))
454 ilow = Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000455 if (ihigh < ilow)
456 ihigh = ilow;
Christian Heimese93237d2007-12-19 02:37:44 +0000457 else if (ihigh > Py_SIZE(a))
458 ihigh = Py_SIZE(a);
Raymond Hettinger99842b62004-03-08 05:56:15 +0000459 len = ihigh - ilow;
460 np = (PyListObject *) PyList_New(len);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000461 if (np == NULL)
462 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000463
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000464 src = a->ob_item + ilow;
465 dest = np->ob_item;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000466 for (i = 0; i < len; i++) {
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000467 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000468 Py_INCREF(v);
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000469 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000470 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000471 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000472}
473
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000474PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000475PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000476{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000477 if (!PyList_Check(a)) {
478 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000479 return NULL;
480 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000481 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000482}
483
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000484static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000485list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000486{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000487 Py_ssize_t size;
488 Py_ssize_t i;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000489 PyObject **src, **dest;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000490 PyListObject *np;
491 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000492 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000493 "can only concatenate list (not \"%.200s\") to list",
494 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000495 return NULL;
496 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000497#define b ((PyListObject *)bb)
Christian Heimese93237d2007-12-19 02:37:44 +0000498 size = Py_SIZE(a) + Py_SIZE(b);
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000499 if (size < 0)
500 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000501 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000502 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000503 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000504 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000505 src = a->ob_item;
506 dest = np->ob_item;
Christian Heimese93237d2007-12-19 02:37:44 +0000507 for (i = 0; i < Py_SIZE(a); i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000508 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000509 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000510 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000511 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000512 src = b->ob_item;
Christian Heimese93237d2007-12-19 02:37:44 +0000513 dest = np->ob_item + Py_SIZE(a);
514 for (i = 0; i < Py_SIZE(b); i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000515 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000516 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000517 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000518 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000519 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000520#undef b
521}
522
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000523static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000524list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000525{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000526 Py_ssize_t i, j;
527 Py_ssize_t size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000528 PyListObject *np;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000529 PyObject **p, **items;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000530 PyObject *elem;
Guido van Rossumed98d481991-03-06 13:07:53 +0000531 if (n < 0)
532 n = 0;
Christian Heimese93237d2007-12-19 02:37:44 +0000533 size = Py_SIZE(a) * n;
534 if (n && size/n != Py_SIZE(a))
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000535 return PyErr_NoMemory();
Armin Rigoa1e42e12007-10-17 18:46:37 +0000536 if (size == 0)
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000537 return PyList_New(0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000538 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000539 if (np == NULL)
540 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000541
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000542 items = np->ob_item;
Christian Heimese93237d2007-12-19 02:37:44 +0000543 if (Py_SIZE(a) == 1) {
Raymond Hettinger6624e682003-05-21 05:58:46 +0000544 elem = a->ob_item[0];
545 for (i = 0; i < n; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000546 items[i] = elem;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000547 Py_INCREF(elem);
548 }
549 return (PyObject *) np;
550 }
Guido van Rossumed98d481991-03-06 13:07:53 +0000551 p = np->ob_item;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000552 items = a->ob_item;
Guido van Rossumed98d481991-03-06 13:07:53 +0000553 for (i = 0; i < n; i++) {
Christian Heimese93237d2007-12-19 02:37:44 +0000554 for (j = 0; j < Py_SIZE(a); j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000555 *p = items[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000556 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000557 p++;
558 }
559 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000560 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000561}
562
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000563static int
Armin Rigo93677f02004-07-29 12:40:23 +0000564list_clear(PyListObject *a)
565{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000566 Py_ssize_t i;
Armin Rigo93677f02004-07-29 12:40:23 +0000567 PyObject **item = a->ob_item;
568 if (item != NULL) {
569 /* Because XDECREF can recursively invoke operations on
570 this list, we make it empty first. */
Christian Heimese93237d2007-12-19 02:37:44 +0000571 i = Py_SIZE(a);
572 Py_SIZE(a) = 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000573 a->ob_item = NULL;
574 a->allocated = 0;
575 while (--i >= 0) {
576 Py_XDECREF(item[i]);
577 }
578 PyMem_FREE(item);
579 }
580 /* Never fails; the return value can be ignored.
581 Note that there is no guarantee that the list is actually empty
582 at this point, because XDECREF may have populated it again! */
583 return 0;
584}
585
Tim Peters8fc4a912004-07-31 21:53:19 +0000586/* a[ilow:ihigh] = v if v != NULL.
587 * del a[ilow:ihigh] if v == NULL.
588 *
589 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
590 * guaranteed the call cannot fail.
591 */
Armin Rigo93677f02004-07-29 12:40:23 +0000592static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000593list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000594{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000595 /* Because [X]DECREF can recursively invoke list operations on
596 this list, we must postpone all [X]DECREF activity until
597 after the list is back in its canonical shape. Therefore
598 we must allocate an additional array, 'recycle', into which
599 we temporarily copy the items that are deleted from the
600 list. :-( */
Tim Peters73572222004-07-31 02:54:42 +0000601 PyObject *recycle_on_stack[8];
602 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000603 PyObject **item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000604 PyObject **vitem = NULL;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000605 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000606 Py_ssize_t n; /* # of elements in replacement list */
607 Py_ssize_t norig; /* # of elements in list getting replaced */
608 Py_ssize_t d; /* Change in size */
609 Py_ssize_t k;
Tim Peters8d9eb102004-07-31 02:24:20 +0000610 size_t s;
611 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000612#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000613 if (v == NULL)
614 n = 0;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000615 else {
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000616 if (a == b) {
617 /* Special case "a[i:j] = a" -- copy b first */
Christian Heimese93237d2007-12-19 02:37:44 +0000618 v = list_slice(b, 0, Py_SIZE(b));
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000619 if (v == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000620 return result;
621 result = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000622 Py_DECREF(v);
Tim Peters8d9eb102004-07-31 02:24:20 +0000623 return result;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000624 }
Raymond Hettingerf889e102004-03-09 08:04:33 +0000625 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000626 if(v_as_SF == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000627 goto Error;
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000628 n = PySequence_Fast_GET_SIZE(v_as_SF);
Raymond Hettinger42bec932004-03-12 16:38:17 +0000629 vitem = PySequence_Fast_ITEMS(v_as_SF);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000630 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000631 if (ilow < 0)
632 ilow = 0;
Christian Heimese93237d2007-12-19 02:37:44 +0000633 else if (ilow > Py_SIZE(a))
634 ilow = Py_SIZE(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000635
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000636 if (ihigh < ilow)
637 ihigh = ilow;
Christian Heimese93237d2007-12-19 02:37:44 +0000638 else if (ihigh > Py_SIZE(a))
639 ihigh = Py_SIZE(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000640
Tim Peters8d9eb102004-07-31 02:24:20 +0000641 norig = ihigh - ilow;
642 assert(norig >= 0);
643 d = n - norig;
Christian Heimese93237d2007-12-19 02:37:44 +0000644 if (Py_SIZE(a) + d == 0) {
Armin Rigo93677f02004-07-29 12:40:23 +0000645 Py_XDECREF(v_as_SF);
646 return list_clear(a);
647 }
648 item = a->ob_item;
Tim Peters8d9eb102004-07-31 02:24:20 +0000649 /* recycle the items that we are about to remove */
650 s = norig * sizeof(PyObject *);
Tim Peters73572222004-07-31 02:54:42 +0000651 if (s > sizeof(recycle_on_stack)) {
Armin Rigo1dd04a02004-07-30 11:38:22 +0000652 recycle = (PyObject **)PyMem_MALLOC(s);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000653 if (recycle == NULL) {
654 PyErr_NoMemory();
Tim Peters8d9eb102004-07-31 02:24:20 +0000655 goto Error;
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000656 }
657 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000658 memcpy(recycle, &item[ilow], s);
Tim Peters8d9eb102004-07-31 02:24:20 +0000659
Armin Rigo1dd04a02004-07-30 11:38:22 +0000660 if (d < 0) { /* Delete -d items */
661 memmove(&item[ihigh+d], &item[ihigh],
Christian Heimese93237d2007-12-19 02:37:44 +0000662 (Py_SIZE(a) - ihigh)*sizeof(PyObject *));
663 list_resize(a, Py_SIZE(a) + d);
Armin Rigo1dd04a02004-07-30 11:38:22 +0000664 item = a->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000665 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000666 else if (d > 0) { /* Insert d items */
Christian Heimese93237d2007-12-19 02:37:44 +0000667 k = Py_SIZE(a);
Tim Peters73572222004-07-31 02:54:42 +0000668 if (list_resize(a, k+d) < 0)
Tim Peters8d9eb102004-07-31 02:24:20 +0000669 goto Error;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000670 item = a->ob_item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000671 memmove(&item[ihigh+d], &item[ihigh],
Tim Peters73572222004-07-31 02:54:42 +0000672 (k - ihigh)*sizeof(PyObject *));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000673 }
674 for (k = 0; k < n; k++, ilow++) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000675 PyObject *w = vitem[k];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000676 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000677 item[ilow] = w;
678 }
Tim Peters73572222004-07-31 02:54:42 +0000679 for (k = norig - 1; k >= 0; --k)
680 Py_XDECREF(recycle[k]);
Tim Peters8d9eb102004-07-31 02:24:20 +0000681 result = 0;
682 Error:
Tim Peters73572222004-07-31 02:54:42 +0000683 if (recycle != recycle_on_stack)
Armin Rigo1dd04a02004-07-30 11:38:22 +0000684 PyMem_FREE(recycle);
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000685 Py_XDECREF(v_as_SF);
Tim Peters8d9eb102004-07-31 02:24:20 +0000686 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000687#undef b
688}
689
Guido van Rossum234f9421993-06-17 12:35:49 +0000690int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000691PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000692{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000693 if (!PyList_Check(a)) {
694 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000695 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000696 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000697 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000698}
699
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000700static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000701list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000702{
703 PyObject **items;
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000704 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000705
706
707 size = PyList_GET_SIZE(self);
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000708 if (size == 0 || n == 1) {
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000709 Py_INCREF(self);
710 return (PyObject *)self;
711 }
712
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000713 if (n < 1) {
Armin Rigo93677f02004-07-29 12:40:23 +0000714 (void)list_clear(self);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000715 Py_INCREF(self);
716 return (PyObject *)self;
717 }
718
Thomas Woutersa97744c2008-01-25 21:09:34 +0000719 if (size > PY_SSIZE_T_MAX / n) {
Armin Rigoa1e42e12007-10-17 18:46:37 +0000720 return PyErr_NoMemory();
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000721 }
722
723 if (list_resize(self, size*n) == -1)
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000724 return NULL;
725
726 p = size;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000727 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000728 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
729 for (j = 0; j < size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000730 PyObject *o = items[j];
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000731 Py_INCREF(o);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000732 items[p++] = o;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000733 }
734 }
735 Py_INCREF(self);
736 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000737}
738
Guido van Rossum4a450d01991-04-03 19:05:18 +0000739static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000740list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000741{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000742 PyObject *old_value;
Christian Heimese93237d2007-12-19 02:37:44 +0000743 if (i < 0 || i >= Py_SIZE(a)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000744 PyErr_SetString(PyExc_IndexError,
745 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000746 return -1;
747 }
748 if (v == NULL)
749 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000750 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000751 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000752 a->ob_item[i] = v;
Tim Peters3b01a122002-07-19 02:35:45 +0000753 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000754 return 0;
755}
756
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000757static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000758listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000759{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000760 Py_ssize_t i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000761 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000762 if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000763 return NULL;
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000764 if (ins1(self, i, v) == 0)
765 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000766 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000767}
768
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000769static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000770listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000771{
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000772 if (app1(self, v) == 0)
773 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000774 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000775}
776
Barry Warsawdedf6d61998-10-09 16:37:25 +0000777static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000778listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000779{
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000780 PyObject *it; /* iter(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000781 Py_ssize_t m; /* size of self */
782 Py_ssize_t n; /* guess for size of b */
783 Py_ssize_t mn; /* m + n */
784 Py_ssize_t i;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000785 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000786
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000787 /* Special cases:
Tim Petersb38e2b62004-07-29 02:29:26 +0000788 1) lists and tuples which can use PySequence_Fast ops
789 2) extending self to self requires making a copy first
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000790 */
791 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
Armin Rigo70d172d2004-03-20 22:19:23 +0000792 PyObject **src, **dest;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000793 b = PySequence_Fast(b, "argument must be iterable");
794 if (!b)
795 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000796 n = PySequence_Fast_GET_SIZE(b);
797 if (n == 0) {
798 /* short circuit when b is empty */
799 Py_DECREF(b);
800 Py_RETURN_NONE;
801 }
Christian Heimese93237d2007-12-19 02:37:44 +0000802 m = Py_SIZE(self);
Armin Rigo70d172d2004-03-20 22:19:23 +0000803 if (list_resize(self, m + n) == -1) {
804 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000805 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000806 }
807 /* note that we may still have self == b here for the
808 * situation a.extend(a), but the following code works
809 * in that case too. Just make sure to resize self
810 * before calling PySequence_Fast_ITEMS.
811 */
812 /* populate the end of self with b's items */
813 src = PySequence_Fast_ITEMS(b);
814 dest = self->ob_item + m;
815 for (i = 0; i < n; i++) {
816 PyObject *o = src[i];
817 Py_INCREF(o);
818 dest[i] = o;
819 }
820 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000821 Py_RETURN_NONE;
822 }
823
824 it = PyObject_GetIter(b);
825 if (it == NULL)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000826 return NULL;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000827 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000828
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000829 /* Guess a result list size. */
Raymond Hettinger4e2f7142007-12-06 00:56:53 +0000830 n = _PyObject_LengthHint(b, 8);
Christian Heimese93237d2007-12-19 02:37:44 +0000831 m = Py_SIZE(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000832 mn = m + n;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000833 if (mn >= m) {
834 /* Make room. */
835 if (list_resize(self, mn) == -1)
836 goto error;
837 /* Make the list sane again. */
Christian Heimese93237d2007-12-19 02:37:44 +0000838 Py_SIZE(self) = m;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000839 }
840 /* Else m + n overflowed; on the chance that n lied, and there really
841 * is enough room, ignore it. If n was telling the truth, we'll
842 * eventually run out of memory during the loop.
843 */
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000844
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000845 /* Run iterator to exhaustion. */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000846 for (;;) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000847 PyObject *item = iternext(it);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000848 if (item == NULL) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000849 if (PyErr_Occurred()) {
850 if (PyErr_ExceptionMatches(PyExc_StopIteration))
851 PyErr_Clear();
852 else
853 goto error;
854 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000855 break;
856 }
Christian Heimese93237d2007-12-19 02:37:44 +0000857 if (Py_SIZE(self) < self->allocated) {
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000858 /* steals ref */
Christian Heimese93237d2007-12-19 02:37:44 +0000859 PyList_SET_ITEM(self, Py_SIZE(self), item);
860 ++Py_SIZE(self);
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000861 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000862 else {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000863 int status = app1(self, item);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000864 Py_DECREF(item); /* append creates a new ref */
865 if (status < 0)
866 goto error;
867 }
868 }
869
870 /* Cut back result list if initial guess was too large. */
Christian Heimese93237d2007-12-19 02:37:44 +0000871 if (Py_SIZE(self) < self->allocated)
872 list_resize(self, Py_SIZE(self)); /* shrinking can't fail */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000873
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000874 Py_DECREF(it);
875 Py_RETURN_NONE;
876
877 error:
878 Py_DECREF(it);
879 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000880}
881
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000882PyObject *
883_PyList_Extend(PyListObject *self, PyObject *b)
884{
885 return listextend(self, b);
886}
887
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000888static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000889list_inplace_concat(PyListObject *self, PyObject *other)
890{
891 PyObject *result;
892
893 result = listextend(self, other);
894 if (result == NULL)
895 return result;
896 Py_DECREF(result);
897 Py_INCREF(self);
898 return (PyObject *)self;
899}
900
901static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000902listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000903{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000904 Py_ssize_t i = -1;
Armin Rigo7ccbca92006-10-04 12:17:45 +0000905 PyObject *v;
Tim Peters8fc4a912004-07-31 21:53:19 +0000906 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000907
Armin Rigo7ccbca92006-10-04 12:17:45 +0000908 if (!PyArg_ParseTuple(args, "|n:pop", &i))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000909 return NULL;
Armin Rigo7ccbca92006-10-04 12:17:45 +0000910
Christian Heimese93237d2007-12-19 02:37:44 +0000911 if (Py_SIZE(self) == 0) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000912 /* Special-case most common failure cause */
913 PyErr_SetString(PyExc_IndexError, "pop from empty list");
914 return NULL;
915 }
916 if (i < 0)
Christian Heimese93237d2007-12-19 02:37:44 +0000917 i += Py_SIZE(self);
918 if (i < 0 || i >= Py_SIZE(self)) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000919 PyErr_SetString(PyExc_IndexError, "pop index out of range");
920 return NULL;
921 }
922 v = self->ob_item[i];
Christian Heimese93237d2007-12-19 02:37:44 +0000923 if (i == Py_SIZE(self) - 1) {
924 status = list_resize(self, Py_SIZE(self) - 1);
Tim Peters8fc4a912004-07-31 21:53:19 +0000925 assert(status >= 0);
926 return v; /* and v now owns the reference the list had */
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000927 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000928 Py_INCREF(v);
Tim Peters8fc4a912004-07-31 21:53:19 +0000929 status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
930 assert(status >= 0);
931 /* Use status, so that in a release build compilers don't
932 * complain about the unused name.
933 */
Brett Cannon651dd522004-08-08 21:21:18 +0000934 (void) status;
935
936 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000937}
938
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000939/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
940static void
941reverse_slice(PyObject **lo, PyObject **hi)
942{
943 assert(lo && hi);
944
945 --hi;
946 while (lo < hi) {
947 PyObject *t = *lo;
948 *lo = *hi;
949 *hi = t;
950 ++lo;
951 --hi;
952 }
953}
954
Tim Petersa64dc242002-08-01 02:13:36 +0000955/* Lots of code for an adaptive, stable, natural mergesort. There are many
956 * pieces to this algorithm; read listsort.txt for overviews and details.
957 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000958
Guido van Rossum3f236de1996-12-10 23:55:39 +0000959/* Comparison function. Takes care of calling a user-supplied
Tim Peters66860f62002-08-04 17:47:26 +0000960 * comparison function (any callable Python object), which must not be
961 * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool
962 * with Py_LT if you know it's NULL).
Tim Petersa64dc242002-08-01 02:13:36 +0000963 * Returns -1 on error, 1 if x < y, 0 if x >= y.
964 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000965static int
Tim Petersa8c974c2002-07-19 03:30:57 +0000966islt(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000967{
Tim Petersf2a04732002-07-11 21:46:16 +0000968 PyObject *res;
969 PyObject *args;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000970 Py_ssize_t i;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000971
Tim Peters66860f62002-08-04 17:47:26 +0000972 assert(compare != NULL);
Tim Petersa8c974c2002-07-19 03:30:57 +0000973 /* Call the user's comparison function and translate the 3-way
974 * result into true or false (or error).
975 */
Tim Petersf2a04732002-07-11 21:46:16 +0000976 args = PyTuple_New(2);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000977 if (args == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000978 return -1;
Tim Petersf2a04732002-07-11 21:46:16 +0000979 Py_INCREF(x);
980 Py_INCREF(y);
981 PyTuple_SET_ITEM(args, 0, x);
982 PyTuple_SET_ITEM(args, 1, y);
Tim Peters58cf3612002-07-15 05:16:13 +0000983 res = PyObject_Call(compare, args, NULL);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000984 Py_DECREF(args);
Guido van Rossum3f236de1996-12-10 23:55:39 +0000985 if (res == NULL)
Tim Petersa8c974c2002-07-19 03:30:57 +0000986 return -1;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000987 if (!PyInt_Check(res)) {
Georg Brandl283a1352006-11-19 08:48:30 +0000988 PyErr_Format(PyExc_TypeError,
989 "comparison function must return int, not %.200s",
990 res->ob_type->tp_name);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000991 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +0000992 return -1;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000993 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000994 i = PyInt_AsLong(res);
995 Py_DECREF(res);
Tim Petersa8c974c2002-07-19 03:30:57 +0000996 return i < 0;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000997}
998
Tim Peters66860f62002-08-04 17:47:26 +0000999/* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
1000 * islt. This avoids a layer of function call in the usual case, and
1001 * sorting does many comparisons.
1002 * Returns -1 on error, 1 if x < y, 0 if x >= y.
1003 */
1004#define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
1005 PyObject_RichCompareBool(X, Y, Py_LT) : \
1006 islt(X, Y, COMPARE))
1007
1008/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +00001009 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
1010 started. It makes more sense in context <wink>. X and Y are PyObject*s.
1011*/
Tim Peters66860f62002-08-04 17:47:26 +00001012#define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
Tim Petersa8c974c2002-07-19 03:30:57 +00001013 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001014
1015/* binarysort is the best method for sorting small arrays: it does
1016 few compares, but can do data movement quadratic in the number of
1017 elements.
Guido van Rossum42812581998-06-17 14:15:44 +00001018 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +00001019 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001020 On entry, must have lo <= start <= hi, and that [lo, start) is already
1021 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +00001022 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001023 Even in case of error, the output slice will be some permutation of
1024 the input (nothing is lost or duplicated).
1025*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00001026static int
Fred Drakea2f55112000-07-09 15:16:51 +00001027binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
1028 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001029{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001030 register Py_ssize_t k;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001031 register PyObject **l, **p, **r;
1032 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001033
Tim Petersa8c974c2002-07-19 03:30:57 +00001034 assert(lo <= start && start <= hi);
1035 /* assert [lo, start) is sorted */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001036 if (lo == start)
1037 ++start;
1038 for (; start < hi; ++start) {
1039 /* set l to where *start belongs */
1040 l = lo;
1041 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001042 pivot = *r;
Tim Peters0fe977c2002-07-19 06:12:32 +00001043 /* Invariants:
1044 * pivot >= all in [lo, l).
1045 * pivot < all in [r, start).
1046 * The second is vacuously true at the start.
1047 */
1048 assert(l < r);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001049 do {
1050 p = l + ((r - l) >> 1);
Tim Petersa8c974c2002-07-19 03:30:57 +00001051 IFLT(pivot, *p)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001052 r = p;
1053 else
Tim Peters0fe977c2002-07-19 06:12:32 +00001054 l = p+1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001055 } while (l < r);
Tim Peters0fe977c2002-07-19 06:12:32 +00001056 assert(l == r);
1057 /* The invariants still hold, so pivot >= all in [lo, l) and
1058 pivot < all in [l, start), so pivot belongs at l. Note
1059 that if there are elements equal to pivot, l points to the
1060 first slot after them -- that's why this sort is stable.
1061 Slide over to make room.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001062 Caution: using memmove is much slower under MSVC 5;
1063 we're not usually moving many slots. */
1064 for (p = start; p > l; --p)
1065 *p = *(p-1);
1066 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001067 }
Guido van Rossum3f236de1996-12-10 23:55:39 +00001068 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001069
1070 fail:
1071 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001072}
1073
Tim Petersa64dc242002-08-01 02:13:36 +00001074/*
1075Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1076is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001077
Tim Petersa64dc242002-08-01 02:13:36 +00001078 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001079
Tim Petersa64dc242002-08-01 02:13:36 +00001080or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001081
Tim Petersa64dc242002-08-01 02:13:36 +00001082 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001083
Tim Petersa64dc242002-08-01 02:13:36 +00001084Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1085For its intended use in a stable mergesort, the strictness of the defn of
1086"descending" is needed so that the caller can safely reverse a descending
1087sequence without violating stability (strict > ensures there are no equal
1088elements to get out of order).
1089
1090Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001091*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001092static Py_ssize_t
Tim Petersa64dc242002-08-01 02:13:36 +00001093count_run(PyObject **lo, PyObject **hi, PyObject *compare, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001094{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001095 Py_ssize_t k;
1096 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001097
Tim Petersa64dc242002-08-01 02:13:36 +00001098 assert(lo < hi);
1099 *descending = 0;
1100 ++lo;
1101 if (lo == hi)
1102 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001103
Tim Petersa64dc242002-08-01 02:13:36 +00001104 n = 2;
1105 IFLT(*lo, *(lo-1)) {
1106 *descending = 1;
1107 for (lo = lo+1; lo < hi; ++lo, ++n) {
1108 IFLT(*lo, *(lo-1))
1109 ;
1110 else
1111 break;
1112 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001113 }
Tim Petersa64dc242002-08-01 02:13:36 +00001114 else {
1115 for (lo = lo+1; lo < hi; ++lo, ++n) {
1116 IFLT(*lo, *(lo-1))
1117 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001118 }
1119 }
1120
Tim Petersa64dc242002-08-01 02:13:36 +00001121 return n;
1122fail:
1123 return -1;
1124}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001125
Tim Petersa64dc242002-08-01 02:13:36 +00001126/*
1127Locate the proper position of key in a sorted vector; if the vector contains
1128an element equal to key, return the position immediately to the left of
1129the leftmost equal element. [gallop_right() does the same except returns
1130the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001131
Tim Petersa64dc242002-08-01 02:13:36 +00001132"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001133
Tim Petersa64dc242002-08-01 02:13:36 +00001134"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1135hint is to the final result, the faster this runs.
1136
1137The return value is the int k in 0..n such that
1138
1139 a[k-1] < key <= a[k]
1140
1141pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1142key belongs at index k; or, IOW, the first k elements of a should precede
1143key, and the last n-k should follow key.
1144
1145Returns -1 on error. See listsort.txt for info on the method.
1146*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001147static Py_ssize_t
1148gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
Tim Petersa64dc242002-08-01 02:13:36 +00001149{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001150 Py_ssize_t ofs;
1151 Py_ssize_t lastofs;
1152 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001153
1154 assert(key && a && n > 0 && hint >= 0 && hint < n);
1155
1156 a += hint;
1157 lastofs = 0;
1158 ofs = 1;
1159 IFLT(*a, key) {
1160 /* a[hint] < key -- gallop right, until
1161 * a[hint + lastofs] < key <= a[hint + ofs]
1162 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001163 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001164 while (ofs < maxofs) {
1165 IFLT(a[ofs], key) {
1166 lastofs = ofs;
1167 ofs = (ofs << 1) + 1;
1168 if (ofs <= 0) /* int overflow */
1169 ofs = maxofs;
1170 }
1171 else /* key <= a[hint + ofs] */
1172 break;
1173 }
1174 if (ofs > maxofs)
1175 ofs = maxofs;
1176 /* Translate back to offsets relative to &a[0]. */
1177 lastofs += hint;
1178 ofs += hint;
1179 }
1180 else {
1181 /* key <= a[hint] -- gallop left, until
1182 * a[hint - ofs] < key <= a[hint - lastofs]
1183 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001184 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001185 while (ofs < maxofs) {
1186 IFLT(*(a-ofs), key)
1187 break;
1188 /* key <= a[hint - ofs] */
1189 lastofs = ofs;
1190 ofs = (ofs << 1) + 1;
1191 if (ofs <= 0) /* int overflow */
1192 ofs = maxofs;
1193 }
1194 if (ofs > maxofs)
1195 ofs = maxofs;
1196 /* Translate back to positive offsets relative to &a[0]. */
1197 k = lastofs;
1198 lastofs = hint - ofs;
1199 ofs = hint - k;
1200 }
1201 a -= hint;
1202
1203 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1204 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1205 * right of lastofs but no farther right than ofs. Do a binary
1206 * search, with invariant a[lastofs-1] < key <= a[ofs].
1207 */
1208 ++lastofs;
1209 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001210 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001211
1212 IFLT(a[m], key)
1213 lastofs = m+1; /* a[m] < key */
1214 else
1215 ofs = m; /* key <= a[m] */
1216 }
1217 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1218 return ofs;
1219
1220fail:
1221 return -1;
1222}
1223
1224/*
1225Exactly like gallop_left(), except that if key already exists in a[0:n],
1226finds the position immediately to the right of the rightmost equal value.
1227
1228The return value is the int k in 0..n such that
1229
1230 a[k-1] <= key < a[k]
1231
1232or -1 if error.
1233
1234The code duplication is massive, but this is enough different given that
1235we're sticking to "<" comparisons that it's much harder to follow if
1236written as one routine with yet another "left or right?" flag.
1237*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001238static Py_ssize_t
1239gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
Tim Petersa64dc242002-08-01 02:13:36 +00001240{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001241 Py_ssize_t ofs;
1242 Py_ssize_t lastofs;
1243 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001244
1245 assert(key && a && n > 0 && hint >= 0 && hint < n);
1246
1247 a += hint;
1248 lastofs = 0;
1249 ofs = 1;
1250 IFLT(key, *a) {
1251 /* key < a[hint] -- gallop left, until
1252 * a[hint - ofs] <= key < a[hint - lastofs]
1253 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001254 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001255 while (ofs < maxofs) {
1256 IFLT(key, *(a-ofs)) {
1257 lastofs = ofs;
1258 ofs = (ofs << 1) + 1;
1259 if (ofs <= 0) /* int overflow */
1260 ofs = maxofs;
1261 }
1262 else /* a[hint - ofs] <= key */
1263 break;
1264 }
1265 if (ofs > maxofs)
1266 ofs = maxofs;
1267 /* Translate back to positive offsets relative to &a[0]. */
1268 k = lastofs;
1269 lastofs = hint - ofs;
1270 ofs = hint - k;
1271 }
1272 else {
1273 /* a[hint] <= key -- gallop right, until
1274 * a[hint + lastofs] <= key < a[hint + ofs]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001275 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001276 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001277 while (ofs < maxofs) {
1278 IFLT(key, a[ofs])
1279 break;
1280 /* a[hint + ofs] <= key */
1281 lastofs = ofs;
1282 ofs = (ofs << 1) + 1;
1283 if (ofs <= 0) /* int overflow */
1284 ofs = maxofs;
1285 }
1286 if (ofs > maxofs)
1287 ofs = maxofs;
1288 /* Translate back to offsets relative to &a[0]. */
1289 lastofs += hint;
1290 ofs += hint;
1291 }
1292 a -= hint;
1293
1294 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1295 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1296 * right of lastofs but no farther right than ofs. Do a binary
1297 * search, with invariant a[lastofs-1] <= key < a[ofs].
1298 */
1299 ++lastofs;
1300 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001301 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001302
1303 IFLT(key, a[m])
1304 ofs = m; /* key < a[m] */
1305 else
1306 lastofs = m+1; /* a[m] <= key */
1307 }
1308 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1309 return ofs;
1310
1311fail:
1312 return -1;
1313}
1314
1315/* The maximum number of entries in a MergeState's pending-runs stack.
1316 * This is enough to sort arrays of size up to about
1317 * 32 * phi ** MAX_MERGE_PENDING
1318 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1319 * with 2**64 elements.
1320 */
1321#define MAX_MERGE_PENDING 85
1322
Tim Peterse05f65a2002-08-10 05:21:15 +00001323/* When we get into galloping mode, we stay there until both runs win less
1324 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001325 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001326#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001327
1328/* Avoid malloc for small temp arrays. */
1329#define MERGESTATE_TEMP_SIZE 256
1330
1331/* One MergeState exists on the stack per invocation of mergesort. It's just
1332 * a convenient way to pass state around among the helper functions.
1333 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001334struct s_slice {
1335 PyObject **base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001336 Py_ssize_t len;
Tim Peterse05f65a2002-08-10 05:21:15 +00001337};
1338
Tim Petersa64dc242002-08-01 02:13:36 +00001339typedef struct s_MergeState {
1340 /* The user-supplied comparison function. or NULL if none given. */
1341 PyObject *compare;
1342
Tim Peterse05f65a2002-08-10 05:21:15 +00001343 /* This controls when we get *into* galloping mode. It's initialized
1344 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1345 * random data, and lower for highly structured data.
1346 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001347 Py_ssize_t min_gallop;
Tim Peterse05f65a2002-08-10 05:21:15 +00001348
Tim Petersa64dc242002-08-01 02:13:36 +00001349 /* 'a' is temp storage to help with merges. It contains room for
1350 * alloced entries.
1351 */
1352 PyObject **a; /* may point to temparray below */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001353 Py_ssize_t alloced;
Tim Petersa64dc242002-08-01 02:13:36 +00001354
1355 /* A stack of n pending runs yet to be merged. Run #i starts at
1356 * address base[i] and extends for len[i] elements. It's always
1357 * true (so long as the indices are in bounds) that
1358 *
Tim Peterse05f65a2002-08-10 05:21:15 +00001359 * pending[i].base + pending[i].len == pending[i+1].base
Tim Petersa64dc242002-08-01 02:13:36 +00001360 *
1361 * so we could cut the storage for this, but it's a minor amount,
1362 * and keeping all the info explicit simplifies the code.
1363 */
1364 int n;
Tim Peterse05f65a2002-08-10 05:21:15 +00001365 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001366
1367 /* 'a' points to this when possible, rather than muck with malloc. */
1368 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1369} MergeState;
1370
1371/* Conceptually a MergeState's constructor. */
1372static void
1373merge_init(MergeState *ms, PyObject *compare)
1374{
1375 assert(ms != NULL);
1376 ms->compare = compare;
1377 ms->a = ms->temparray;
1378 ms->alloced = MERGESTATE_TEMP_SIZE;
1379 ms->n = 0;
Tim Peterse05f65a2002-08-10 05:21:15 +00001380 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001381}
1382
1383/* Free all the temp memory owned by the MergeState. This must be called
1384 * when you're done with a MergeState, and may be called before then if
1385 * you want to free the temp memory early.
1386 */
1387static void
1388merge_freemem(MergeState *ms)
1389{
1390 assert(ms != NULL);
1391 if (ms->a != ms->temparray)
1392 PyMem_Free(ms->a);
1393 ms->a = ms->temparray;
1394 ms->alloced = MERGESTATE_TEMP_SIZE;
1395}
1396
1397/* Ensure enough temp memory for 'need' array slots is available.
1398 * Returns 0 on success and -1 if the memory can't be gotten.
1399 */
1400static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001401merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001402{
1403 assert(ms != NULL);
1404 if (need <= ms->alloced)
1405 return 0;
1406 /* Don't realloc! That can cost cycles to copy the old data, but
1407 * we don't care what's in the block.
1408 */
1409 merge_freemem(ms);
1410 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1411 if (ms->a) {
1412 ms->alloced = need;
1413 return 0;
1414 }
1415 PyErr_NoMemory();
1416 merge_freemem(ms); /* reset to sane state */
1417 return -1;
1418}
1419#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1420 merge_getmem(MS, NEED))
1421
1422/* Merge the na elements starting at pa with the nb elements starting at pb
1423 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1424 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1425 * merge, and should have na <= nb. See listsort.txt for more info.
1426 * Return 0 if successful, -1 if error.
1427 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001428static Py_ssize_t
1429merge_lo(MergeState *ms, PyObject **pa, Py_ssize_t na,
1430 PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001431{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001432 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001433 PyObject *compare;
1434 PyObject **dest;
1435 int result = -1; /* guilty until proved innocent */
Neal Norwitz7fd96072006-08-19 04:28:55 +00001436 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001437
1438 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1439 if (MERGE_GETMEM(ms, na) < 0)
1440 return -1;
1441 memcpy(ms->a, pa, na * sizeof(PyObject*));
1442 dest = pa;
1443 pa = ms->a;
1444
1445 *dest++ = *pb++;
1446 --nb;
1447 if (nb == 0)
1448 goto Succeed;
1449 if (na == 1)
1450 goto CopyB;
1451
Neal Norwitz7fd96072006-08-19 04:28:55 +00001452 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001453 compare = ms->compare;
1454 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001455 Py_ssize_t acount = 0; /* # of times A won in a row */
1456 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001457
1458 /* Do the straightforward thing until (if ever) one run
1459 * appears to win consistently.
1460 */
1461 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001462 assert(na > 1 && nb > 0);
Tim Peters66860f62002-08-04 17:47:26 +00001463 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001464 if (k) {
1465 if (k < 0)
1466 goto Fail;
1467 *dest++ = *pb++;
1468 ++bcount;
1469 acount = 0;
1470 --nb;
1471 if (nb == 0)
1472 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001473 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001474 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001475 }
1476 else {
Tim Petersa64dc242002-08-01 02:13:36 +00001477 *dest++ = *pa++;
1478 ++acount;
1479 bcount = 0;
1480 --na;
1481 if (na == 1)
1482 goto CopyB;
Tim Peterse05f65a2002-08-10 05:21:15 +00001483 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001484 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001485 }
Tim Petersa64dc242002-08-01 02:13:36 +00001486 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001487
Tim Petersa64dc242002-08-01 02:13:36 +00001488 /* One run is winning so consistently that galloping may
1489 * be a huge win. So try that, and continue galloping until
1490 * (if ever) neither run appears to be winning consistently
1491 * anymore.
1492 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001493 ++min_gallop;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001494 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001495 assert(na > 1 && nb > 0);
1496 min_gallop -= min_gallop > 1;
1497 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001498 k = gallop_right(*pb, pa, na, 0, compare);
1499 acount = k;
1500 if (k) {
1501 if (k < 0)
1502 goto Fail;
1503 memcpy(dest, pa, k * sizeof(PyObject *));
1504 dest += k;
1505 pa += k;
1506 na -= k;
1507 if (na == 1)
1508 goto CopyB;
1509 /* na==0 is impossible now if the comparison
1510 * function is consistent, but we can't assume
1511 * that it is.
1512 */
1513 if (na == 0)
1514 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001515 }
Tim Petersa64dc242002-08-01 02:13:36 +00001516 *dest++ = *pb++;
1517 --nb;
1518 if (nb == 0)
1519 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001520
Tim Petersa64dc242002-08-01 02:13:36 +00001521 k = gallop_left(*pa, pb, nb, 0, compare);
1522 bcount = k;
1523 if (k) {
1524 if (k < 0)
1525 goto Fail;
1526 memmove(dest, pb, k * sizeof(PyObject *));
1527 dest += k;
1528 pb += k;
1529 nb -= k;
1530 if (nb == 0)
1531 goto Succeed;
1532 }
1533 *dest++ = *pa++;
1534 --na;
1535 if (na == 1)
1536 goto CopyB;
1537 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001538 ++min_gallop; /* penalize it for leaving galloping mode */
1539 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001540 }
1541Succeed:
1542 result = 0;
1543Fail:
1544 if (na)
1545 memcpy(dest, pa, na * sizeof(PyObject*));
1546 return result;
1547CopyB:
1548 assert(na == 1 && nb > 0);
1549 /* The last element of pa belongs at the end of the merge. */
1550 memmove(dest, pb, nb * sizeof(PyObject *));
1551 dest[nb] = *pa;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001552 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001553}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001554
Tim Petersa64dc242002-08-01 02:13:36 +00001555/* Merge the na elements starting at pa with the nb elements starting at pb
1556 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1557 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1558 * merge, and should have na >= nb. See listsort.txt for more info.
1559 * Return 0 if successful, -1 if error.
1560 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001561static Py_ssize_t
1562merge_hi(MergeState *ms, PyObject **pa, Py_ssize_t na, PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001563{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001564 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001565 PyObject *compare;
1566 PyObject **dest;
1567 int result = -1; /* guilty until proved innocent */
1568 PyObject **basea;
1569 PyObject **baseb;
Neal Norwitz7fd96072006-08-19 04:28:55 +00001570 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001571
1572 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1573 if (MERGE_GETMEM(ms, nb) < 0)
1574 return -1;
1575 dest = pb + nb - 1;
1576 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1577 basea = pa;
1578 baseb = ms->a;
1579 pb = ms->a + nb - 1;
1580 pa += na - 1;
1581
1582 *dest-- = *pa--;
1583 --na;
1584 if (na == 0)
1585 goto Succeed;
1586 if (nb == 1)
1587 goto CopyA;
1588
Neal Norwitz7fd96072006-08-19 04:28:55 +00001589 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001590 compare = ms->compare;
1591 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001592 Py_ssize_t acount = 0; /* # of times A won in a row */
1593 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001594
1595 /* Do the straightforward thing until (if ever) one run
1596 * appears to win consistently.
1597 */
1598 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001599 assert(na > 0 && nb > 1);
Tim Peters66860f62002-08-04 17:47:26 +00001600 k = ISLT(*pb, *pa, compare);
Tim Petersa64dc242002-08-01 02:13:36 +00001601 if (k) {
1602 if (k < 0)
1603 goto Fail;
1604 *dest-- = *pa--;
1605 ++acount;
1606 bcount = 0;
1607 --na;
1608 if (na == 0)
1609 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001610 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001611 break;
1612 }
1613 else {
1614 *dest-- = *pb--;
1615 ++bcount;
1616 acount = 0;
1617 --nb;
1618 if (nb == 1)
1619 goto CopyA;
Tim Peterse05f65a2002-08-10 05:21:15 +00001620 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001621 break;
1622 }
1623 }
1624
1625 /* One run is winning so consistently that galloping may
1626 * be a huge win. So try that, and continue galloping until
1627 * (if ever) neither run appears to be winning consistently
1628 * anymore.
1629 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001630 ++min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001631 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001632 assert(na > 0 && nb > 1);
1633 min_gallop -= min_gallop > 1;
1634 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001635 k = gallop_right(*pb, basea, na, na-1, compare);
1636 if (k < 0)
1637 goto Fail;
1638 k = na - k;
1639 acount = k;
1640 if (k) {
1641 dest -= k;
1642 pa -= k;
1643 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1644 na -= k;
1645 if (na == 0)
1646 goto Succeed;
1647 }
1648 *dest-- = *pb--;
1649 --nb;
1650 if (nb == 1)
1651 goto CopyA;
1652
1653 k = gallop_left(*pa, baseb, nb, nb-1, compare);
1654 if (k < 0)
1655 goto Fail;
1656 k = nb - k;
1657 bcount = k;
1658 if (k) {
1659 dest -= k;
1660 pb -= k;
1661 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1662 nb -= k;
1663 if (nb == 1)
1664 goto CopyA;
1665 /* nb==0 is impossible now if the comparison
1666 * function is consistent, but we can't assume
1667 * that it is.
1668 */
1669 if (nb == 0)
1670 goto Succeed;
1671 }
1672 *dest-- = *pa--;
1673 --na;
1674 if (na == 0)
1675 goto Succeed;
1676 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001677 ++min_gallop; /* penalize it for leaving galloping mode */
1678 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001679 }
1680Succeed:
1681 result = 0;
1682Fail:
1683 if (nb)
1684 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1685 return result;
1686CopyA:
1687 assert(nb == 1 && na > 0);
1688 /* The first element of pb belongs at the front of the merge. */
1689 dest -= na;
1690 pa -= na;
1691 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1692 *dest = *pb;
1693 return 0;
1694}
1695
1696/* Merge the two runs at stack indices i and i+1.
1697 * Returns 0 on success, -1 on error.
1698 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001699static Py_ssize_t
1700merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001701{
1702 PyObject **pa, **pb;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001703 Py_ssize_t na, nb;
1704 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001705 PyObject *compare;
1706
1707 assert(ms != NULL);
1708 assert(ms->n >= 2);
1709 assert(i >= 0);
1710 assert(i == ms->n - 2 || i == ms->n - 3);
1711
Tim Peterse05f65a2002-08-10 05:21:15 +00001712 pa = ms->pending[i].base;
1713 na = ms->pending[i].len;
1714 pb = ms->pending[i+1].base;
1715 nb = ms->pending[i+1].len;
Tim Petersa64dc242002-08-01 02:13:36 +00001716 assert(na > 0 && nb > 0);
1717 assert(pa + na == pb);
1718
1719 /* Record the length of the combined runs; if i is the 3rd-last
1720 * run now, also slide over the last run (which isn't involved
1721 * in this merge). The current run i+1 goes away in any case.
1722 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001723 ms->pending[i].len = na + nb;
1724 if (i == ms->n - 3)
1725 ms->pending[i+1] = ms->pending[i+2];
Tim Petersa64dc242002-08-01 02:13:36 +00001726 --ms->n;
1727
1728 /* Where does b start in a? Elements in a before that can be
1729 * ignored (already in place).
1730 */
1731 compare = ms->compare;
1732 k = gallop_right(*pb, pa, na, 0, compare);
1733 if (k < 0)
1734 return -1;
1735 pa += k;
1736 na -= k;
1737 if (na == 0)
1738 return 0;
1739
1740 /* Where does a end in b? Elements in b after that can be
1741 * ignored (already in place).
1742 */
1743 nb = gallop_left(pa[na-1], pb, nb, nb-1, compare);
1744 if (nb <= 0)
1745 return nb;
1746
1747 /* Merge what remains of the runs, using a temp array with
1748 * min(na, nb) elements.
1749 */
1750 if (na <= nb)
1751 return merge_lo(ms, pa, na, pb, nb);
1752 else
1753 return merge_hi(ms, pa, na, pb, nb);
1754}
1755
1756/* Examine the stack of runs waiting to be merged, merging adjacent runs
1757 * until the stack invariants are re-established:
1758 *
1759 * 1. len[-3] > len[-2] + len[-1]
1760 * 2. len[-2] > len[-1]
1761 *
1762 * See listsort.txt for more info.
1763 *
1764 * Returns 0 on success, -1 on error.
1765 */
1766static int
1767merge_collapse(MergeState *ms)
1768{
Tim Peterse05f65a2002-08-10 05:21:15 +00001769 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001770
1771 assert(ms);
1772 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001773 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001774 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1775 if (p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001776 --n;
1777 if (merge_at(ms, n) < 0)
1778 return -1;
1779 }
Tim Peterse05f65a2002-08-10 05:21:15 +00001780 else if (p[n].len <= p[n+1].len) {
Tim Petersa64dc242002-08-01 02:13:36 +00001781 if (merge_at(ms, n) < 0)
1782 return -1;
1783 }
1784 else
1785 break;
1786 }
1787 return 0;
1788}
1789
1790/* Regardless of invariants, merge all runs on the stack until only one
1791 * remains. This is used at the end of the mergesort.
1792 *
1793 * Returns 0 on success, -1 on error.
1794 */
1795static int
1796merge_force_collapse(MergeState *ms)
1797{
Tim Peterse05f65a2002-08-10 05:21:15 +00001798 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001799
1800 assert(ms);
1801 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001802 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001803 if (n > 0 && p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001804 --n;
1805 if (merge_at(ms, n) < 0)
1806 return -1;
1807 }
1808 return 0;
1809}
1810
1811/* Compute a good value for the minimum run length; natural runs shorter
1812 * than this are boosted artificially via binary insertion.
1813 *
1814 * If n < 64, return n (it's too small to bother with fancy stuff).
1815 * Else if n is an exact power of 2, return 32.
1816 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1817 * strictly less than, an exact power of 2.
1818 *
1819 * See listsort.txt for more info.
1820 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001821static Py_ssize_t
1822merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001823{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001824 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001825
1826 assert(n >= 0);
1827 while (n >= 64) {
1828 r |= n & 1;
1829 n >>= 1;
1830 }
1831 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001832}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001833
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001834/* Special wrapper to support stable sorting using the decorate-sort-undecorate
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001835 pattern. Holds a key which is used for comparisons and the original record
Tim Petersb38e2b62004-07-29 02:29:26 +00001836 which is returned during the undecorate phase. By exposing only the key
1837 during comparisons, the underlying sort stability characteristics are left
1838 unchanged. Also, if a custom comparison function is used, it will only see
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001839 the key instead of a full record. */
1840
1841typedef struct {
1842 PyObject_HEAD
1843 PyObject *key;
1844 PyObject *value;
1845} sortwrapperobject;
1846
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001847PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
Anthony Baxter377be112006-04-11 06:54:30 +00001848static PyObject *
1849sortwrapper_richcompare(sortwrapperobject *, sortwrapperobject *, int);
1850static void
1851sortwrapper_dealloc(sortwrapperobject *);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001852
1853static PyTypeObject sortwrapper_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001854 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001855 "sortwrapper", /* tp_name */
1856 sizeof(sortwrapperobject), /* tp_basicsize */
1857 0, /* tp_itemsize */
1858 /* methods */
1859 (destructor)sortwrapper_dealloc, /* tp_dealloc */
1860 0, /* tp_print */
1861 0, /* tp_getattr */
1862 0, /* tp_setattr */
1863 0, /* tp_compare */
1864 0, /* tp_repr */
1865 0, /* tp_as_number */
1866 0, /* tp_as_sequence */
1867 0, /* tp_as_mapping */
1868 0, /* tp_hash */
1869 0, /* tp_call */
1870 0, /* tp_str */
1871 PyObject_GenericGetAttr, /* tp_getattro */
1872 0, /* tp_setattro */
1873 0, /* tp_as_buffer */
Tim Petersb38e2b62004-07-29 02:29:26 +00001874 Py_TPFLAGS_DEFAULT |
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001875 Py_TPFLAGS_HAVE_RICHCOMPARE, /* tp_flags */
1876 sortwrapper_doc, /* tp_doc */
1877 0, /* tp_traverse */
1878 0, /* tp_clear */
1879 (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
1880};
1881
Anthony Baxter377be112006-04-11 06:54:30 +00001882
1883static PyObject *
1884sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
1885{
1886 if (!PyObject_TypeCheck(b, &sortwrapper_type)) {
1887 PyErr_SetString(PyExc_TypeError,
1888 "expected a sortwrapperobject");
1889 return NULL;
1890 }
1891 return PyObject_RichCompare(a->key, b->key, op);
1892}
1893
1894static void
1895sortwrapper_dealloc(sortwrapperobject *so)
1896{
1897 Py_XDECREF(so->key);
1898 Py_XDECREF(so->value);
1899 PyObject_Del(so);
1900}
1901
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001902/* Returns a new reference to a sortwrapper.
1903 Consumes the references to the two underlying objects. */
1904
1905static PyObject *
1906build_sortwrapper(PyObject *key, PyObject *value)
1907{
1908 sortwrapperobject *so;
Tim Petersb38e2b62004-07-29 02:29:26 +00001909
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001910 so = PyObject_New(sortwrapperobject, &sortwrapper_type);
1911 if (so == NULL)
1912 return NULL;
1913 so->key = key;
1914 so->value = value;
1915 return (PyObject *)so;
1916}
1917
1918/* Returns a new reference to the value underlying the wrapper. */
1919static PyObject *
1920sortwrapper_getvalue(PyObject *so)
1921{
1922 PyObject *value;
1923
1924 if (!PyObject_TypeCheck(so, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001925 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001926 "expected a sortwrapperobject");
1927 return NULL;
1928 }
1929 value = ((sortwrapperobject *)so)->value;
1930 Py_INCREF(value);
1931 return value;
1932}
1933
1934/* Wrapper for user specified cmp functions in combination with a
1935 specified key function. Makes sure the cmp function is presented
1936 with the actual key instead of the sortwrapper */
1937
1938typedef struct {
1939 PyObject_HEAD
1940 PyObject *func;
1941} cmpwrapperobject;
1942
1943static void
1944cmpwrapper_dealloc(cmpwrapperobject *co)
1945{
1946 Py_XDECREF(co->func);
1947 PyObject_Del(co);
1948}
1949
1950static PyObject *
1951cmpwrapper_call(cmpwrapperobject *co, PyObject *args, PyObject *kwds)
1952{
1953 PyObject *x, *y, *xx, *yy;
1954
1955 if (!PyArg_UnpackTuple(args, "", 2, 2, &x, &y))
1956 return NULL;
1957 if (!PyObject_TypeCheck(x, &sortwrapper_type) ||
Raymond Hettingerae4a2992003-10-16 17:16:30 +00001958 !PyObject_TypeCheck(y, &sortwrapper_type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001959 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001960 "expected a sortwrapperobject");
1961 return NULL;
1962 }
1963 xx = ((sortwrapperobject *)x)->key;
1964 yy = ((sortwrapperobject *)y)->key;
1965 return PyObject_CallFunctionObjArgs(co->func, xx, yy, NULL);
1966}
1967
1968PyDoc_STRVAR(cmpwrapper_doc, "cmp() wrapper for sort with custom keys.");
1969
1970static PyTypeObject cmpwrapper_type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00001971 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001972 "cmpwrapper", /* tp_name */
1973 sizeof(cmpwrapperobject), /* tp_basicsize */
1974 0, /* tp_itemsize */
1975 /* methods */
1976 (destructor)cmpwrapper_dealloc, /* tp_dealloc */
1977 0, /* tp_print */
1978 0, /* tp_getattr */
1979 0, /* tp_setattr */
1980 0, /* tp_compare */
1981 0, /* tp_repr */
1982 0, /* tp_as_number */
1983 0, /* tp_as_sequence */
1984 0, /* tp_as_mapping */
1985 0, /* tp_hash */
1986 (ternaryfunc)cmpwrapper_call, /* tp_call */
1987 0, /* tp_str */
1988 PyObject_GenericGetAttr, /* tp_getattro */
1989 0, /* tp_setattro */
1990 0, /* tp_as_buffer */
1991 Py_TPFLAGS_DEFAULT, /* tp_flags */
1992 cmpwrapper_doc, /* tp_doc */
1993};
1994
1995static PyObject *
1996build_cmpwrapper(PyObject *cmpfunc)
1997{
1998 cmpwrapperobject *co;
Tim Petersb38e2b62004-07-29 02:29:26 +00001999
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002000 co = PyObject_New(cmpwrapperobject, &cmpwrapper_type);
2001 if (co == NULL)
2002 return NULL;
2003 Py_INCREF(cmpfunc);
2004 co->func = cmpfunc;
2005 return (PyObject *)co;
2006}
2007
Tim Petersa64dc242002-08-01 02:13:36 +00002008/* An adaptive, stable, natural mergesort. See listsort.txt.
2009 * Returns Py_None on success, NULL on error. Even in case of error, the
2010 * list will be some permutation of its input state (nothing is lost or
2011 * duplicated).
2012 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002013static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002014listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00002015{
Tim Petersa64dc242002-08-01 02:13:36 +00002016 MergeState ms;
2017 PyObject **lo, **hi;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002018 Py_ssize_t nremaining;
2019 Py_ssize_t minrun;
2020 Py_ssize_t saved_ob_size, saved_allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00002021 PyObject **saved_ob_item;
Armin Rigo93677f02004-07-29 12:40:23 +00002022 PyObject **final_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00002023 PyObject *compare = NULL;
2024 PyObject *result = NULL; /* guilty until proved innocent */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002025 int reverse = 0;
2026 PyObject *keyfunc = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002027 Py_ssize_t i;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002028 PyObject *key, *value, *kvpair;
Martin v. Löwis15e62742006-02-27 16:46:16 +00002029 static char *kwlist[] = {"cmp", "key", "reverse", 0};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002030
Tim Petersa64dc242002-08-01 02:13:36 +00002031 assert(self != NULL);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002032 assert (PyList_Check(self));
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002033 if (args != NULL) {
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002034 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:sort",
2035 kwlist, &compare, &keyfunc, &reverse))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002036 return NULL;
2037 }
Skip Montanaro4abd5f02003-01-02 20:51:08 +00002038 if (compare == Py_None)
2039 compare = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002040 if (keyfunc == Py_None)
2041 keyfunc = NULL;
2042 if (compare != NULL && keyfunc != NULL) {
2043 compare = build_cmpwrapper(compare);
2044 if (compare == NULL)
Hye-Shik Chang19cb1932003-12-10 07:31:08 +00002045 return NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002046 } else
2047 Py_XINCREF(compare);
2048
Tim Petersb9099c32002-11-12 22:08:10 +00002049 /* The list is temporarily made empty, so that mutations performed
2050 * by comparison functions can't affect the slice of memory we're
2051 * sorting (allowing mutations during sorting is a core-dump
2052 * factory, since ob_item may change).
2053 */
Christian Heimese93237d2007-12-19 02:37:44 +00002054 saved_ob_size = Py_SIZE(self);
Tim Petersb9099c32002-11-12 22:08:10 +00002055 saved_ob_item = self->ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002056 saved_allocated = self->allocated;
Christian Heimese93237d2007-12-19 02:37:44 +00002057 Py_SIZE(self) = 0;
Tim Peters51b4ade2004-07-29 04:07:15 +00002058 self->ob_item = NULL;
Armin Rigo93677f02004-07-29 12:40:23 +00002059 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00002060
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002061 if (keyfunc != NULL) {
2062 for (i=0 ; i < saved_ob_size ; i++) {
2063 value = saved_ob_item[i];
Tim Petersb38e2b62004-07-29 02:29:26 +00002064 key = PyObject_CallFunctionObjArgs(keyfunc, value,
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002065 NULL);
2066 if (key == NULL) {
2067 for (i=i-1 ; i>=0 ; i--) {
2068 kvpair = saved_ob_item[i];
2069 value = sortwrapper_getvalue(kvpair);
2070 saved_ob_item[i] = value;
2071 Py_DECREF(kvpair);
2072 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002073 goto dsu_fail;
2074 }
2075 kvpair = build_sortwrapper(key, value);
2076 if (kvpair == NULL)
2077 goto dsu_fail;
2078 saved_ob_item[i] = kvpair;
2079 }
2080 }
2081
2082 /* Reverse sort stability achieved by initially reversing the list,
2083 applying a stable forward sort, then reversing the final result. */
2084 if (reverse && saved_ob_size > 1)
2085 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2086
2087 merge_init(&ms, compare);
2088
Tim Petersb9099c32002-11-12 22:08:10 +00002089 nremaining = saved_ob_size;
Tim Petersa64dc242002-08-01 02:13:36 +00002090 if (nremaining < 2)
2091 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00002092
Tim Petersa64dc242002-08-01 02:13:36 +00002093 /* March over the array once, left to right, finding natural runs,
2094 * and extending short natural runs to minrun elements.
2095 */
Tim Petersb9099c32002-11-12 22:08:10 +00002096 lo = saved_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00002097 hi = lo + nremaining;
2098 minrun = merge_compute_minrun(nremaining);
2099 do {
2100 int descending;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002101 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00002102
Tim Petersa64dc242002-08-01 02:13:36 +00002103 /* Identify next run. */
2104 n = count_run(lo, hi, compare, &descending);
2105 if (n < 0)
2106 goto fail;
2107 if (descending)
2108 reverse_slice(lo, lo + n);
2109 /* If short, extend to min(minrun, nremaining). */
2110 if (n < minrun) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002111 const Py_ssize_t force = nremaining <= minrun ?
Tim Petersa64dc242002-08-01 02:13:36 +00002112 nremaining : minrun;
2113 if (binarysort(lo, lo + force, lo + n, compare) < 0)
2114 goto fail;
2115 n = force;
2116 }
2117 /* Push run onto pending-runs stack, and maybe merge. */
2118 assert(ms.n < MAX_MERGE_PENDING);
Tim Peterse05f65a2002-08-10 05:21:15 +00002119 ms.pending[ms.n].base = lo;
2120 ms.pending[ms.n].len = n;
Tim Petersa64dc242002-08-01 02:13:36 +00002121 ++ms.n;
2122 if (merge_collapse(&ms) < 0)
2123 goto fail;
2124 /* Advance to find next run. */
2125 lo += n;
2126 nremaining -= n;
2127 } while (nremaining);
2128 assert(lo == hi);
Tim Peters330f9e92002-07-19 07:05:44 +00002129
Tim Petersa64dc242002-08-01 02:13:36 +00002130 if (merge_force_collapse(&ms) < 0)
2131 goto fail;
2132 assert(ms.n == 1);
Tim Petersb9099c32002-11-12 22:08:10 +00002133 assert(ms.pending[0].base == saved_ob_item);
2134 assert(ms.pending[0].len == saved_ob_size);
Tim Petersa64dc242002-08-01 02:13:36 +00002135
2136succeed:
2137 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002138fail:
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002139 if (keyfunc != NULL) {
2140 for (i=0 ; i < saved_ob_size ; i++) {
2141 kvpair = saved_ob_item[i];
2142 value = sortwrapper_getvalue(kvpair);
2143 saved_ob_item[i] = value;
2144 Py_DECREF(kvpair);
2145 }
2146 }
2147
Armin Rigo93677f02004-07-29 12:40:23 +00002148 if (self->allocated != -1 && result != NULL) {
Tim Peters51b4ade2004-07-29 04:07:15 +00002149 /* The user mucked with the list during the sort,
2150 * and we don't already have another error to report.
2151 */
2152 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2153 result = NULL;
Tim Petersb9099c32002-11-12 22:08:10 +00002154 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002155
2156 if (reverse && saved_ob_size > 1)
2157 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
2158
2159 merge_freemem(&ms);
2160
2161dsu_fail:
Armin Rigo93677f02004-07-29 12:40:23 +00002162 final_ob_item = self->ob_item;
Christian Heimese93237d2007-12-19 02:37:44 +00002163 i = Py_SIZE(self);
2164 Py_SIZE(self) = saved_ob_size;
Tim Petersb9099c32002-11-12 22:08:10 +00002165 self->ob_item = saved_ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002166 self->allocated = saved_allocated;
Armin Rigo93677f02004-07-29 12:40:23 +00002167 if (final_ob_item != NULL) {
2168 /* we cannot use list_clear() for this because it does not
2169 guarantee that the list is really empty when it returns */
2170 while (--i >= 0) {
2171 Py_XDECREF(final_ob_item[i]);
2172 }
2173 PyMem_FREE(final_ob_item);
2174 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002175 Py_XDECREF(compare);
Tim Petersa64dc242002-08-01 02:13:36 +00002176 Py_XINCREF(result);
2177 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002178}
Tim Peters330f9e92002-07-19 07:05:44 +00002179#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002180#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002181
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002182int
Fred Drakea2f55112000-07-09 15:16:51 +00002183PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002184{
2185 if (v == NULL || !PyList_Check(v)) {
2186 PyErr_BadInternalCall();
2187 return -1;
2188 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002189 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002190 if (v == NULL)
2191 return -1;
2192 Py_DECREF(v);
2193 return 0;
2194}
2195
Guido van Rossumb86c5492001-02-12 22:06:02 +00002196static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002197listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002198{
Christian Heimese93237d2007-12-19 02:37:44 +00002199 if (Py_SIZE(self) > 1)
2200 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002201 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002202}
2203
Guido van Rossum84c76f51990-10-30 13:32:20 +00002204int
Fred Drakea2f55112000-07-09 15:16:51 +00002205PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002206{
Tim Peters6063e262002-08-08 01:06:39 +00002207 PyListObject *self = (PyListObject *)v;
2208
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002209 if (v == NULL || !PyList_Check(v)) {
2210 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002211 return -1;
2212 }
Christian Heimese93237d2007-12-19 02:37:44 +00002213 if (Py_SIZE(self) > 1)
2214 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002215 return 0;
2216}
2217
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002218PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002219PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002220{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002221 PyObject *w;
Raymond Hettinger6c87af52007-12-15 00:07:25 +00002222 PyObject **p, **q;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002223 Py_ssize_t n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002224 if (v == NULL || !PyList_Check(v)) {
2225 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002226 return NULL;
2227 }
Christian Heimese93237d2007-12-19 02:37:44 +00002228 n = Py_SIZE(v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002229 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002230 if (w == NULL)
2231 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002232 p = ((PyTupleObject *)w)->ob_item;
Raymond Hettinger6c87af52007-12-15 00:07:25 +00002233 q = ((PyListObject *)v)->ob_item;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002234 while (--n >= 0) {
Raymond Hettinger6c87af52007-12-15 00:07:25 +00002235 Py_INCREF(*q);
2236 *p = *q;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002237 p++;
Raymond Hettinger6c87af52007-12-15 00:07:25 +00002238 q++;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002239 }
2240 return w;
2241}
2242
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002243static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002244listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002245{
Christian Heimese93237d2007-12-19 02:37:44 +00002246 Py_ssize_t i, start=0, stop=Py_SIZE(self);
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002247 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002248
Walter Dörwalde8049bef2003-06-17 19:27:39 +00002249 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2250 _PyEval_SliceIndex, &start,
2251 _PyEval_SliceIndex, &stop))
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002252 return NULL;
Guido van Rossum2743d872003-06-17 14:25:14 +00002253 if (start < 0) {
Christian Heimese93237d2007-12-19 02:37:44 +00002254 start += Py_SIZE(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002255 if (start < 0)
2256 start = 0;
2257 }
2258 if (stop < 0) {
Christian Heimese93237d2007-12-19 02:37:44 +00002259 stop += Py_SIZE(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002260 if (stop < 0)
2261 stop = 0;
2262 }
Christian Heimese93237d2007-12-19 02:37:44 +00002263 for (i = start; i < stop && i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002264 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2265 if (cmp > 0)
Martin v. Löwis18e16552006-02-15 17:27:45 +00002266 return PyInt_FromSsize_t(i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002267 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002268 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002269 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002270 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002271 return NULL;
2272}
2273
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002274static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002275listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002276{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002277 Py_ssize_t count = 0;
2278 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002279
Christian Heimese93237d2007-12-19 02:37:44 +00002280 for (i = 0; i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002281 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2282 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002283 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002284 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002285 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00002286 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00002287 return PyInt_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002288}
2289
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002290static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002291listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002292{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002293 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002294
Christian Heimese93237d2007-12-19 02:37:44 +00002295 for (i = 0; i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002296 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2297 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002298 if (list_ass_slice(self, i, i+1,
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002299 (PyObject *)NULL) == 0)
2300 Py_RETURN_NONE;
2301 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002302 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002303 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002304 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002305 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002306 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002307 return NULL;
2308}
2309
Jeremy Hylton8caad492000-06-23 14:18:11 +00002310static int
2311list_traverse(PyListObject *o, visitproc visit, void *arg)
2312{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002313 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002314
Christian Heimese93237d2007-12-19 02:37:44 +00002315 for (i = Py_SIZE(o); --i >= 0; )
Thomas Woutersc6e55062006-04-15 21:47:09 +00002316 Py_VISIT(o->ob_item[i]);
Jeremy Hylton8caad492000-06-23 14:18:11 +00002317 return 0;
2318}
2319
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002320static PyObject *
2321list_richcompare(PyObject *v, PyObject *w, int op)
2322{
2323 PyListObject *vl, *wl;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002324 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002325
2326 if (!PyList_Check(v) || !PyList_Check(w)) {
2327 Py_INCREF(Py_NotImplemented);
2328 return Py_NotImplemented;
2329 }
2330
2331 vl = (PyListObject *)v;
2332 wl = (PyListObject *)w;
2333
Christian Heimese93237d2007-12-19 02:37:44 +00002334 if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002335 /* Shortcut: if the lengths differ, the lists differ */
2336 PyObject *res;
2337 if (op == Py_EQ)
2338 res = Py_False;
2339 else
2340 res = Py_True;
2341 Py_INCREF(res);
2342 return res;
2343 }
2344
2345 /* Search for the first index where items are different */
Christian Heimese93237d2007-12-19 02:37:44 +00002346 for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002347 int k = PyObject_RichCompareBool(vl->ob_item[i],
2348 wl->ob_item[i], Py_EQ);
2349 if (k < 0)
2350 return NULL;
2351 if (!k)
2352 break;
2353 }
2354
Christian Heimese93237d2007-12-19 02:37:44 +00002355 if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002356 /* No more items to compare -- compare sizes */
Christian Heimese93237d2007-12-19 02:37:44 +00002357 Py_ssize_t vs = Py_SIZE(vl);
2358 Py_ssize_t ws = Py_SIZE(wl);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002359 int cmp;
2360 PyObject *res;
2361 switch (op) {
2362 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00002363 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002364 case Py_EQ: cmp = vs == ws; break;
2365 case Py_NE: cmp = vs != ws; break;
2366 case Py_GT: cmp = vs > ws; break;
2367 case Py_GE: cmp = vs >= ws; break;
2368 default: return NULL; /* cannot happen */
2369 }
2370 if (cmp)
2371 res = Py_True;
2372 else
2373 res = Py_False;
2374 Py_INCREF(res);
2375 return res;
2376 }
2377
2378 /* We have an item that differs -- shortcuts for EQ/NE */
2379 if (op == Py_EQ) {
2380 Py_INCREF(Py_False);
2381 return Py_False;
2382 }
2383 if (op == Py_NE) {
2384 Py_INCREF(Py_True);
2385 return Py_True;
2386 }
2387
2388 /* Compare the final item again using the proper operator */
2389 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
2390}
2391
Tim Peters6d6c1a32001-08-02 04:15:00 +00002392static int
2393list_init(PyListObject *self, PyObject *args, PyObject *kw)
2394{
2395 PyObject *arg = NULL;
Martin v. Löwis15e62742006-02-27 16:46:16 +00002396 static char *kwlist[] = {"sequence", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002397
2398 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2399 return -1;
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002400
2401 /* Verify list invariants established by PyType_GenericAlloc() */
Christian Heimese93237d2007-12-19 02:37:44 +00002402 assert(0 <= Py_SIZE(self));
2403 assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
Armin Rigoa37bbf22004-07-30 11:20:18 +00002404 assert(self->ob_item != NULL ||
2405 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002406
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002407 /* Empty previous contents */
Armin Rigo93677f02004-07-29 12:40:23 +00002408 if (self->ob_item != NULL) {
2409 (void)list_clear(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002410 }
2411 if (arg != NULL) {
2412 PyObject *rv = listextend(self, arg);
2413 if (rv == NULL)
2414 return -1;
2415 Py_DECREF(rv);
2416 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002417 return 0;
2418}
2419
Raymond Hettinger1021c442003-11-07 15:38:09 +00002420static PyObject *list_iter(PyObject *seq);
2421static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2422
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002423PyDoc_STRVAR(getitem_doc,
2424"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002425PyDoc_STRVAR(reversed_doc,
2426"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002427PyDoc_STRVAR(append_doc,
2428"L.append(object) -- append object to end");
2429PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002430"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002431PyDoc_STRVAR(insert_doc,
2432"L.insert(index, object) -- insert object before index");
2433PyDoc_STRVAR(pop_doc,
2434"L.pop([index]) -> item -- remove and return item at index (default last)");
2435PyDoc_STRVAR(remove_doc,
2436"L.remove(value) -- remove first occurrence of value");
2437PyDoc_STRVAR(index_doc,
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002438"L.index(value, [start, [stop]]) -> integer -- return first index of value");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002439PyDoc_STRVAR(count_doc,
2440"L.count(value) -> integer -- return number of occurrences of value");
2441PyDoc_STRVAR(reverse_doc,
2442"L.reverse() -- reverse *IN PLACE*");
2443PyDoc_STRVAR(sort_doc,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002444"L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n\
2445cmp(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002446
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002447static PyObject *list_subscript(PyListObject*, PyObject*);
2448
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002449static PyMethodDef list_methods[] = {
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002450 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
Raymond Hettinger1021c442003-11-07 15:38:09 +00002451 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002452 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002453 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002454 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002455 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002456 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002457 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002458 {"count", (PyCFunction)listcount, METH_O, count_doc},
2459 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002460 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
Tim Petersa64dc242002-08-01 02:13:36 +00002461 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002462};
2463
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002464static PySequenceMethods list_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002465 (lenfunc)list_length, /* sq_length */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002466 (binaryfunc)list_concat, /* sq_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002467 (ssizeargfunc)list_repeat, /* sq_repeat */
2468 (ssizeargfunc)list_item, /* sq_item */
2469 (ssizessizeargfunc)list_slice, /* sq_slice */
2470 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
2471 (ssizessizeobjargproc)list_ass_slice, /* sq_ass_slice */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002472 (objobjproc)list_contains, /* sq_contains */
2473 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002474 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002475};
2476
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002477PyDoc_STRVAR(list_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002478"list() -> new list\n"
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002479"list(sequence) -> new list initialized from sequence's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002480
Guido van Rossum38fff8c2006-03-07 18:50:55 +00002481
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002482static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002483list_subscript(PyListObject* self, PyObject* item)
2484{
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00002485 if (PyIndex_Check(item)) {
2486 Py_ssize_t i;
2487 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002488 if (i == -1 && PyErr_Occurred())
2489 return NULL;
2490 if (i < 0)
2491 i += PyList_GET_SIZE(self);
2492 return list_item(self, i);
2493 }
2494 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002495 Py_ssize_t start, stop, step, slicelength, cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002496 PyObject* result;
2497 PyObject* it;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002498 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002499
Christian Heimese93237d2007-12-19 02:37:44 +00002500 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002501 &start, &stop, &step, &slicelength) < 0) {
2502 return NULL;
2503 }
2504
2505 if (slicelength <= 0) {
2506 return PyList_New(0);
2507 }
Thomas Wouters3ccec682007-08-28 15:28:19 +00002508 else if (step == 1) {
2509 return list_slice(self, start, stop);
2510 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002511 else {
2512 result = PyList_New(slicelength);
2513 if (!result) return NULL;
2514
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002515 src = self->ob_item;
2516 dest = ((PyListObject *)result)->ob_item;
Tim Peters3b01a122002-07-19 02:35:45 +00002517 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002518 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002519 it = src[cur];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002520 Py_INCREF(it);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002521 dest[i] = it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002522 }
Tim Peters3b01a122002-07-19 02:35:45 +00002523
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002524 return result;
2525 }
2526 }
2527 else {
Georg Brandl283a1352006-11-19 08:48:30 +00002528 PyErr_Format(PyExc_TypeError,
2529 "list indices must be integers, not %.200s",
2530 item->ob_type->tp_name);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002531 return NULL;
2532 }
2533}
2534
Tim Peters3b01a122002-07-19 02:35:45 +00002535static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002536list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2537{
Neal Norwitz8a87f5d2006-08-12 17:03:09 +00002538 if (PyIndex_Check(item)) {
2539 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002540 if (i == -1 && PyErr_Occurred())
2541 return -1;
2542 if (i < 0)
2543 i += PyList_GET_SIZE(self);
2544 return list_ass_item(self, i, value);
2545 }
2546 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002547 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002548
Christian Heimese93237d2007-12-19 02:37:44 +00002549 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002550 &start, &stop, &step, &slicelength) < 0) {
2551 return -1;
2552 }
2553
Thomas Wouters3ccec682007-08-28 15:28:19 +00002554 if (step == 1)
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002555 return list_ass_slice(self, start, stop, value);
2556
Thomas Wouters3ccec682007-08-28 15:28:19 +00002557 /* Make sure s[5:2] = [..] inserts at the right place:
2558 before 5, not before 2. */
2559 if ((step < 0 && start < stop) ||
2560 (step > 0 && start > stop))
2561 stop = start;
2562
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002563 if (value == NULL) {
2564 /* delete slice */
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002565 PyObject **garbage;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002566 Py_ssize_t cur, i;
Tim Peters3b01a122002-07-19 02:35:45 +00002567
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002568 if (slicelength <= 0)
2569 return 0;
2570
2571 if (step < 0) {
2572 stop = start + 1;
2573 start = stop + step*(slicelength - 1) - 1;
2574 step = -step;
2575 }
2576
2577 garbage = (PyObject**)
2578 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Neal Norwitzb88cfad2006-08-12 03:16:54 +00002579 if (!garbage) {
2580 PyErr_NoMemory();
2581 return -1;
2582 }
Tim Peters3b01a122002-07-19 02:35:45 +00002583
Thomas Wouters3ccec682007-08-28 15:28:19 +00002584 /* drawing pictures might help understand these for
2585 loops. Basically, we memmove the parts of the
2586 list that are *not* part of the slice: step-1
2587 items for each item that is part of the slice,
2588 and then tail end of the list that was not
2589 covered by the slice */
Guido van Rossum75a20b12002-06-11 12:22:28 +00002590 for (cur = start, i = 0;
2591 cur < stop;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002592 cur += step, i++) {
Thomas Wouters3ccec682007-08-28 15:28:19 +00002593 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002594
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002595 garbage[i] = PyList_GET_ITEM(self, cur);
2596
Christian Heimese93237d2007-12-19 02:37:44 +00002597 if (cur + step >= Py_SIZE(self)) {
2598 lim = Py_SIZE(self) - cur - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002599 }
2600
Tim Petersb38e2b62004-07-29 02:29:26 +00002601 memmove(self->ob_item + cur - i,
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002602 self->ob_item + cur + 1,
2603 lim * sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002604 }
Thomas Wouters3ccec682007-08-28 15:28:19 +00002605 cur = start + slicelength*step;
Christian Heimese93237d2007-12-19 02:37:44 +00002606 if (cur < Py_SIZE(self)) {
Thomas Wouters3ccec682007-08-28 15:28:19 +00002607 memmove(self->ob_item + cur - slicelength,
2608 self->ob_item + cur,
Christian Heimese93237d2007-12-19 02:37:44 +00002609 (Py_SIZE(self) - cur) *
Thomas Wouters3ccec682007-08-28 15:28:19 +00002610 sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002611 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002612
Christian Heimese93237d2007-12-19 02:37:44 +00002613 Py_SIZE(self) -= slicelength;
2614 list_resize(self, Py_SIZE(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002615
2616 for (i = 0; i < slicelength; i++) {
2617 Py_DECREF(garbage[i]);
2618 }
2619 PyMem_FREE(garbage);
2620
2621 return 0;
2622 }
2623 else {
2624 /* assign slice */
Thomas Wouters3ccec682007-08-28 15:28:19 +00002625 PyObject *ins, *seq;
2626 PyObject **garbage, **seqitems, **selfitems;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002627 Py_ssize_t cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002628
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002629 /* protect against a[::-1] = a */
Tim Peters3b01a122002-07-19 02:35:45 +00002630 if (self == (PyListObject*)value) {
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002631 seq = list_slice((PyListObject*)value, 0,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002632 PyList_GET_SIZE(value));
Tim Peters3b01a122002-07-19 02:35:45 +00002633 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002634 else {
Tim Petersb38e2b62004-07-29 02:29:26 +00002635 seq = PySequence_Fast(value,
Thomas Wouters3ccec682007-08-28 15:28:19 +00002636 "must assign iterable "
2637 "to extended slice");
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002638 }
Neal Norwitzb88cfad2006-08-12 03:16:54 +00002639 if (!seq)
2640 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002641
2642 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2643 PyErr_Format(PyExc_ValueError,
Thomas Wouters3ccec682007-08-28 15:28:19 +00002644 "attempt to assign sequence of "
2645 "size %zd to extended slice of "
2646 "size %zd",
Martin v. Löwise0e89f72006-02-16 06:59:22 +00002647 PySequence_Fast_GET_SIZE(seq),
2648 slicelength);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002649 Py_DECREF(seq);
2650 return -1;
2651 }
2652
2653 if (!slicelength) {
2654 Py_DECREF(seq);
2655 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002656 }
2657
2658 garbage = (PyObject**)
2659 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Neal Norwitze7e4e2d2006-10-28 21:20:12 +00002660 if (!garbage) {
2661 Py_DECREF(seq);
2662 PyErr_NoMemory();
2663 return -1;
2664 }
Tim Peters3b01a122002-07-19 02:35:45 +00002665
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002666 selfitems = self->ob_item;
Raymond Hettinger42bec932004-03-12 16:38:17 +00002667 seqitems = PySequence_Fast_ITEMS(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002668 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002669 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002670 garbage[i] = selfitems[cur];
2671 ins = seqitems[i];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002672 Py_INCREF(ins);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002673 selfitems[cur] = ins;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002674 }
2675
2676 for (i = 0; i < slicelength; i++) {
2677 Py_DECREF(garbage[i]);
2678 }
Tim Peters3b01a122002-07-19 02:35:45 +00002679
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002680 PyMem_FREE(garbage);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002681 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002682
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002683 return 0;
2684 }
Tim Peters3b01a122002-07-19 02:35:45 +00002685 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002686 else {
Georg Brandl283a1352006-11-19 08:48:30 +00002687 PyErr_Format(PyExc_TypeError,
2688 "list indices must be integers, not %.200s",
2689 item->ob_type->tp_name);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002690 return -1;
2691 }
2692}
2693
2694static PyMappingMethods list_as_mapping = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002695 (lenfunc)list_length,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002696 (binaryfunc)list_subscript,
2697 (objobjargproc)list_ass_subscript
2698};
2699
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002700PyTypeObject PyList_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002701 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002702 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002703 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002704 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002705 (destructor)list_dealloc, /* tp_dealloc */
2706 (printfunc)list_print, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002707 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002708 0, /* tp_setattr */
2709 0, /* tp_compare */
2710 (reprfunc)list_repr, /* tp_repr */
2711 0, /* tp_as_number */
2712 &list_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002713 &list_as_mapping, /* tp_as_mapping */
Guido van Rossum64c06e32007-11-22 00:55:51 +00002714 0, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002715 0, /* tp_call */
2716 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002717 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002718 0, /* tp_setattro */
2719 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002720 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Neal Norwitzee3a1b52007-02-25 19:44:48 +00002721 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002722 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002723 (traverseproc)list_traverse, /* tp_traverse */
2724 (inquiry)list_clear, /* tp_clear */
2725 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002726 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002727 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002728 0, /* tp_iternext */
2729 list_methods, /* tp_methods */
2730 0, /* tp_members */
2731 0, /* tp_getset */
2732 0, /* tp_base */
2733 0, /* tp_dict */
2734 0, /* tp_descr_get */
2735 0, /* tp_descr_set */
2736 0, /* tp_dictoffset */
2737 (initproc)list_init, /* tp_init */
2738 PyType_GenericAlloc, /* tp_alloc */
2739 PyType_GenericNew, /* tp_new */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002740 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002741};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002742
2743
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002744/*********************** List Iterator **************************/
2745
2746typedef struct {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002747 PyObject_HEAD
2748 long it_index;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002749 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002750} listiterobject;
2751
Anthony Baxter377be112006-04-11 06:54:30 +00002752static PyObject *list_iter(PyObject *);
2753static void listiter_dealloc(listiterobject *);
2754static int listiter_traverse(listiterobject *, visitproc, void *);
2755static PyObject *listiter_next(listiterobject *);
2756static PyObject *listiter_len(listiterobject *);
2757
2758PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
2759
2760static PyMethodDef listiter_methods[] = {
2761 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
2762 {NULL, NULL} /* sentinel */
2763};
2764
2765PyTypeObject PyListIter_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002766 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Anthony Baxter377be112006-04-11 06:54:30 +00002767 "listiterator", /* tp_name */
2768 sizeof(listiterobject), /* tp_basicsize */
2769 0, /* tp_itemsize */
2770 /* methods */
2771 (destructor)listiter_dealloc, /* tp_dealloc */
2772 0, /* tp_print */
2773 0, /* tp_getattr */
2774 0, /* tp_setattr */
2775 0, /* tp_compare */
2776 0, /* tp_repr */
2777 0, /* tp_as_number */
2778 0, /* tp_as_sequence */
2779 0, /* tp_as_mapping */
2780 0, /* tp_hash */
2781 0, /* tp_call */
2782 0, /* tp_str */
2783 PyObject_GenericGetAttr, /* tp_getattro */
2784 0, /* tp_setattro */
2785 0, /* tp_as_buffer */
2786 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2787 0, /* tp_doc */
2788 (traverseproc)listiter_traverse, /* tp_traverse */
2789 0, /* tp_clear */
2790 0, /* tp_richcompare */
2791 0, /* tp_weaklistoffset */
2792 PyObject_SelfIter, /* tp_iter */
2793 (iternextfunc)listiter_next, /* tp_iternext */
2794 listiter_methods, /* tp_methods */
2795 0, /* tp_members */
2796};
2797
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002798
Guido van Rossum5086e492002-07-16 15:56:52 +00002799static PyObject *
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002800list_iter(PyObject *seq)
2801{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002802 listiterobject *it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002803
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002804 if (!PyList_Check(seq)) {
2805 PyErr_BadInternalCall();
2806 return NULL;
2807 }
2808 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2809 if (it == NULL)
2810 return NULL;
2811 it->it_index = 0;
2812 Py_INCREF(seq);
2813 it->it_seq = (PyListObject *)seq;
2814 _PyObject_GC_TRACK(it);
2815 return (PyObject *)it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002816}
2817
2818static void
2819listiter_dealloc(listiterobject *it)
2820{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002821 _PyObject_GC_UNTRACK(it);
Guido van Rossum86103ae2002-07-16 20:07:32 +00002822 Py_XDECREF(it->it_seq);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002823 PyObject_GC_Del(it);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002824}
2825
2826static int
2827listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2828{
Thomas Woutersc6e55062006-04-15 21:47:09 +00002829 Py_VISIT(it->it_seq);
2830 return 0;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002831}
2832
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002833static PyObject *
Tim Peters93b2cc42002-06-01 05:22:55 +00002834listiter_next(listiterobject *it)
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002835{
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002836 PyListObject *seq;
2837 PyObject *item;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002838
Tim Peters93b2cc42002-06-01 05:22:55 +00002839 assert(it != NULL);
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002840 seq = it->it_seq;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002841 if (seq == NULL)
2842 return NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002843 assert(PyList_Check(seq));
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002844
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002845 if (it->it_index < PyList_GET_SIZE(seq)) {
Tim Peters93b2cc42002-06-01 05:22:55 +00002846 item = PyList_GET_ITEM(seq, it->it_index);
2847 ++it->it_index;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002848 Py_INCREF(item);
2849 return item;
2850 }
Guido van Rossum86103ae2002-07-16 20:07:32 +00002851
2852 Py_DECREF(seq);
2853 it->it_seq = NULL;
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002854 return NULL;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002855}
2856
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002857static PyObject *
Raymond Hettinger435bf582004-03-18 22:43:10 +00002858listiter_len(listiterobject *it)
2859{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002860 Py_ssize_t len;
Raymond Hettinger40a03822004-04-12 13:05:09 +00002861 if (it->it_seq) {
2862 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2863 if (len >= 0)
Martin v. Löwis18e16552006-02-15 17:27:45 +00002864 return PyInt_FromSsize_t(len);
Raymond Hettinger40a03822004-04-12 13:05:09 +00002865 }
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002866 return PyInt_FromLong(0);
Raymond Hettinger435bf582004-03-18 22:43:10 +00002867}
Anthony Baxter377be112006-04-11 06:54:30 +00002868/*********************** List Reverse Iterator **************************/
Raymond Hettinger435bf582004-03-18 22:43:10 +00002869
Anthony Baxter377be112006-04-11 06:54:30 +00002870typedef struct {
2871 PyObject_HEAD
2872 Py_ssize_t it_index;
2873 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
2874} listreviterobject;
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002875
Anthony Baxter377be112006-04-11 06:54:30 +00002876static PyObject *list_reversed(PyListObject *, PyObject *);
2877static void listreviter_dealloc(listreviterobject *);
2878static int listreviter_traverse(listreviterobject *, visitproc, void *);
2879static PyObject *listreviter_next(listreviterobject *);
2880static Py_ssize_t listreviter_len(listreviterobject *);
2881
2882static PySequenceMethods listreviter_as_sequence = {
2883 (lenfunc)listreviter_len, /* sq_length */
2884 0, /* sq_concat */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002885};
2886
Anthony Baxter377be112006-04-11 06:54:30 +00002887PyTypeObject PyListRevIter_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00002888 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Anthony Baxter377be112006-04-11 06:54:30 +00002889 "listreverseiterator", /* tp_name */
2890 sizeof(listreviterobject), /* tp_basicsize */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002891 0, /* tp_itemsize */
2892 /* methods */
Anthony Baxter377be112006-04-11 06:54:30 +00002893 (destructor)listreviter_dealloc, /* tp_dealloc */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002894 0, /* tp_print */
2895 0, /* tp_getattr */
2896 0, /* tp_setattr */
2897 0, /* tp_compare */
2898 0, /* tp_repr */
2899 0, /* tp_as_number */
Anthony Baxter377be112006-04-11 06:54:30 +00002900 &listreviter_as_sequence, /* tp_as_sequence */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002901 0, /* tp_as_mapping */
2902 0, /* tp_hash */
2903 0, /* tp_call */
2904 0, /* tp_str */
2905 PyObject_GenericGetAttr, /* tp_getattro */
2906 0, /* tp_setattro */
2907 0, /* tp_as_buffer */
2908 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2909 0, /* tp_doc */
Anthony Baxter377be112006-04-11 06:54:30 +00002910 (traverseproc)listreviter_traverse, /* tp_traverse */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002911 0, /* tp_clear */
2912 0, /* tp_richcompare */
2913 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00002914 PyObject_SelfIter, /* tp_iter */
Anthony Baxter377be112006-04-11 06:54:30 +00002915 (iternextfunc)listreviter_next, /* tp_iternext */
2916 0,
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002917};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002918
Raymond Hettinger1021c442003-11-07 15:38:09 +00002919static PyObject *
2920list_reversed(PyListObject *seq, PyObject *unused)
2921{
2922 listreviterobject *it;
2923
2924 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2925 if (it == NULL)
2926 return NULL;
2927 assert(PyList_Check(seq));
2928 it->it_index = PyList_GET_SIZE(seq) - 1;
2929 Py_INCREF(seq);
2930 it->it_seq = seq;
2931 PyObject_GC_Track(it);
2932 return (PyObject *)it;
2933}
2934
2935static void
2936listreviter_dealloc(listreviterobject *it)
2937{
2938 PyObject_GC_UnTrack(it);
2939 Py_XDECREF(it->it_seq);
2940 PyObject_GC_Del(it);
2941}
2942
2943static int
2944listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2945{
Thomas Woutersc6e55062006-04-15 21:47:09 +00002946 Py_VISIT(it->it_seq);
2947 return 0;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002948}
2949
2950static PyObject *
2951listreviter_next(listreviterobject *it)
2952{
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002953 PyObject *item;
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002954 Py_ssize_t index = it->it_index;
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002955 PyListObject *seq = it->it_seq;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002956
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002957 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2958 item = PyList_GET_ITEM(seq, index);
Raymond Hettinger1021c442003-11-07 15:38:09 +00002959 it->it_index--;
2960 Py_INCREF(item);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002961 return item;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002962 }
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002963 it->it_index = -1;
2964 if (seq != NULL) {
2965 it->it_seq = NULL;
2966 Py_DECREF(seq);
2967 }
2968 return NULL;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002969}
2970
Martin v. Löwis18e16552006-02-15 17:27:45 +00002971static Py_ssize_t
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002972listreviter_len(listreviterobject *it)
2973{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002974 Py_ssize_t len = it->it_index + 1;
Raymond Hettinger40a03822004-04-12 13:05:09 +00002975 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
2976 return 0;
2977 return len;
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002978}