blob: d5f3a19dd4743d4904b390540906b470768f6113 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* List object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
4
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00005#ifdef STDC_HEADERS
6#include <stddef.h>
7#else
8#include <sys/types.h> /* For size_t */
9#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000010
Tim Peters8d9eb102004-07-31 02:24:20 +000011/* Ensure ob_item has room for at least newsize elements, and set
12 * ob_size to newsize. If newsize > ob_size on entry, the content
13 * of the new slots at exit is undefined heap trash; it's the caller's
14 * responsiblity to overwrite them with sane values.
15 * The number of allocated elements may grow, shrink, or stay the same.
16 * Failure is impossible if newsize <= self.allocated on entry, although
17 * that partly relies on an assumption that the system realloc() never
18 * fails when passed a number of bytes <= the number of bytes last
19 * allocated (the C standard doesn't guarantee this, but it's hard to
20 * imagine a realloc implementation where it wouldn't be true).
21 * Note that self->ob_item may change, and even if newsize is less
22 * than ob_size on entry.
23 */
Guido van Rossuma46d51d1995-01-26 22:59:43 +000024static int
Martin v. Löwis18e16552006-02-15 17:27:45 +000025list_resize(PyListObject *self, Py_ssize_t newsize)
Guido van Rossuma46d51d1995-01-26 22:59:43 +000026{
Raymond Hettinger4bb95402004-02-13 11:36:39 +000027 PyObject **items;
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000028 size_t new_allocated;
Martin v. Löwis18e16552006-02-15 17:27:45 +000029 Py_ssize_t allocated = self->allocated;
Tim Peters65b8b842001-05-26 05:28:40 +000030
Raymond Hettinger4bb95402004-02-13 11:36:39 +000031 /* Bypass realloc() when a previous overallocation is large enough
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000032 to accommodate the newsize. If the newsize falls lower than half
33 the allocated size, then proceed with the realloc() to shrink the list.
Raymond Hettinger4bb95402004-02-13 11:36:39 +000034 */
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000035 if (allocated >= newsize && newsize >= (allocated >> 1)) {
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +000036 assert(self->ob_item != NULL || newsize == 0);
Christian Heimes90aa7642007-12-19 02:45:37 +000037 Py_SIZE(self) = newsize;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000038 return 0;
39 }
40
41 /* This over-allocates proportional to the list size, making room
Tim Peters65b8b842001-05-26 05:28:40 +000042 * for additional growth. The over-allocation is mild, but is
43 * enough to give linear-time amortized behavior over a long
44 * sequence of appends() in the presence of a poorly-performing
Raymond Hettingerab517d22004-02-14 18:34:46 +000045 * system realloc().
46 * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
Tim Peters65b8b842001-05-26 05:28:40 +000047 */
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000048 new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6) + newsize;
49 if (newsize == 0)
50 new_allocated = 0;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000051 items = self->ob_item;
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000052 if (new_allocated <= ((~(size_t)0) / sizeof(PyObject *)))
53 PyMem_RESIZE(items, PyObject *, new_allocated);
Raymond Hettinger4bb95402004-02-13 11:36:39 +000054 else
55 items = NULL;
56 if (items == NULL) {
57 PyErr_NoMemory();
58 return -1;
59 }
60 self->ob_item = items;
Christian Heimes90aa7642007-12-19 02:45:37 +000061 Py_SIZE(self) = newsize;
Raymond Hettingera84f3ab2004-09-12 19:53:07 +000062 self->allocated = new_allocated;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000063 return 0;
64}
Guido van Rossuma46d51d1995-01-26 22:59:43 +000065
Christian Heimes77c02eb2008-02-09 02:18:51 +000066/* Debug statistic to compare allocations with reuse through the free list */
67#undef SHOW_ALLOC_COUNT
68#ifdef SHOW_ALLOC_COUNT
69static size_t count_alloc = 0;
70static size_t count_reuse = 0;
71
72static void
73show_alloc(void)
74{
Christian Heimes23daade02008-02-25 12:39:23 +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 Heimes77c02eb2008-02-09 02:18:51 +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 Heimes2202f872008-02-06 14:31:34 +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 Heimes2202f872008-02-06 14:31:34 +000096 while (numfree) {
Christian Heimes77c02eb2008-02-09 02:18:51 +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 Heimes77c02eb2008-02-09 02:18:51 +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 Heimes2202f872008-02-06 14:31:34 +0000124 if (numfree) {
125 numfree--;
126 op = free_list[numfree];
Raymond Hettinger0468e412004-05-05 05:37:53 +0000127 _Py_NewReference((PyObject *)op);
Christian Heimes77c02eb2008-02-09 02:18:51 +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 Heimes77c02eb2008-02-09 02:18:51 +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);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000143 if (op->ob_item == NULL) {
144 Py_DECREF(op);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000145 return PyErr_NoMemory();
Thomas Wouters0e3f5912006-08-11 14:57:12 +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 Heimes90aa7642007-12-19 02:45:37 +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 Heimes90aa7642007-12-19 02:45:37 +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 Heimes90aa7642007-12-19 02:45:37 +0000175 if (i < 0 || i >= Py_SIZE(op)) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000176 if (indexerr == NULL)
Neal Norwitz53cbdaa2007-08-23 21:42:55 +0000177 indexerr = PyUnicode_FromString(
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000178 "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 Heimes90aa7642007-12-19 02:45:37 +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 Heimes90aa7642007-12-19 02:45:37 +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 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +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);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +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 Heimes90aa7642007-12-19 02:45:37 +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 Heimes2202f872008-02-06 14:31:34 +0000300 if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op))
301 free_list[numfree++] = op;
Tim Petersb38e2b62004-07-29 02:29:26 +0000302 else
Christian Heimes90aa7642007-12-19 02:45:37 +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 Rossumc0b618a1997-05-02 03:12:38 +0000307static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000308list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000309{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000310 Py_ssize_t i;
Tim Petersa7259592001-06-16 05:11:17 +0000311 PyObject *s, *temp;
312 PyObject *pieces = NULL, *result = NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000313
314 i = Py_ReprEnter((PyObject*)v);
315 if (i != 0) {
Walter Dörwald1ab83302007-05-18 17:15:44 +0000316 return i > 0 ? PyUnicode_FromString("[...]") : NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000317 }
Tim Petersa7259592001-06-16 05:11:17 +0000318
Christian Heimes90aa7642007-12-19 02:45:37 +0000319 if (Py_SIZE(v) == 0) {
Walter Dörwald1ab83302007-05-18 17:15:44 +0000320 result = PyUnicode_FromString("[]");
Tim Petersa7259592001-06-16 05:11:17 +0000321 goto Done;
322 }
323
324 pieces = PyList_New(0);
325 if (pieces == NULL)
326 goto Done;
327
328 /* Do repr() on each element. Note that this may mutate the list,
329 so must refetch the list size on each iteration. */
Christian Heimes90aa7642007-12-19 02:45:37 +0000330 for (i = 0; i < Py_SIZE(v); ++i) {
Tim Petersa7259592001-06-16 05:11:17 +0000331 int status;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000332 if (Py_EnterRecursiveCall(" while getting the repr of a list"))
333 goto Done;
Tim Petersa7259592001-06-16 05:11:17 +0000334 s = PyObject_Repr(v->ob_item[i]);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000335 Py_LeaveRecursiveCall();
Tim Petersa7259592001-06-16 05:11:17 +0000336 if (s == NULL)
337 goto Done;
338 status = PyList_Append(pieces, s);
339 Py_DECREF(s); /* append created a new ref */
340 if (status < 0)
341 goto Done;
342 }
343
344 /* Add "[]" decorations to the first and last items. */
345 assert(PyList_GET_SIZE(pieces) > 0);
Walter Dörwald1ab83302007-05-18 17:15:44 +0000346 s = PyUnicode_FromString("[");
Tim Petersa7259592001-06-16 05:11:17 +0000347 if (s == NULL)
348 goto Done;
349 temp = PyList_GET_ITEM(pieces, 0);
Walter Dörwald1ab83302007-05-18 17:15:44 +0000350 PyUnicode_AppendAndDel(&s, temp);
Tim Petersa7259592001-06-16 05:11:17 +0000351 PyList_SET_ITEM(pieces, 0, s);
352 if (s == NULL)
353 goto Done;
354
Walter Dörwald1ab83302007-05-18 17:15:44 +0000355 s = PyUnicode_FromString("]");
Tim Petersa7259592001-06-16 05:11:17 +0000356 if (s == NULL)
357 goto Done;
358 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
Walter Dörwald1ab83302007-05-18 17:15:44 +0000359 PyUnicode_AppendAndDel(&temp, s);
Tim Petersa7259592001-06-16 05:11:17 +0000360 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
361 if (temp == NULL)
362 goto Done;
363
364 /* Paste them all together with ", " between. */
Walter Dörwald1ab83302007-05-18 17:15:44 +0000365 s = PyUnicode_FromString(", ");
Tim Petersa7259592001-06-16 05:11:17 +0000366 if (s == NULL)
367 goto Done;
Walter Dörwald1ab83302007-05-18 17:15:44 +0000368 result = PyUnicode_Join(s, pieces);
Tim Peters3b01a122002-07-19 02:35:45 +0000369 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +0000370
371Done:
372 Py_XDECREF(pieces);
Guido van Rossumfb376de1998-04-10 22:47:27 +0000373 Py_ReprLeave((PyObject *)v);
Tim Petersa7259592001-06-16 05:11:17 +0000374 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000375}
376
Martin v. Löwis18e16552006-02-15 17:27:45 +0000377static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000378list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000379{
Christian Heimes90aa7642007-12-19 02:45:37 +0000380 return Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000381}
382
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000383static int
Fred Drakea2f55112000-07-09 15:16:51 +0000384list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000385{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000386 Py_ssize_t i;
387 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000388
Christian Heimes90aa7642007-12-19 02:45:37 +0000389 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
Raymond Hettingeraae59992002-09-05 14:23:49 +0000390 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
Guido van Rossum65e1cea2001-01-17 22:11:59 +0000391 Py_EQ);
Neal Norwitzbb9c5f52002-09-05 21:32:55 +0000392 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000393}
394
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000395static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000396list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000397{
Christian Heimes90aa7642007-12-19 02:45:37 +0000398 if (i < 0 || i >= Py_SIZE(a)) {
Guido van Rossum929f1b81996-08-09 20:51:27 +0000399 if (indexerr == NULL)
Neal Norwitz53cbdaa2007-08-23 21:42:55 +0000400 indexerr = PyUnicode_FromString(
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000401 "list index out of range");
402 PyErr_SetObject(PyExc_IndexError, indexerr);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000403 return NULL;
404 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000405 Py_INCREF(a->ob_item[i]);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000406 return a->ob_item[i];
407}
408
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000409static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000410list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000411{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000412 PyListObject *np;
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000413 PyObject **src, **dest;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000414 Py_ssize_t i, len;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000415 if (ilow < 0)
416 ilow = 0;
Christian Heimes90aa7642007-12-19 02:45:37 +0000417 else if (ilow > Py_SIZE(a))
418 ilow = Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000419 if (ihigh < ilow)
420 ihigh = ilow;
Christian Heimes90aa7642007-12-19 02:45:37 +0000421 else if (ihigh > Py_SIZE(a))
422 ihigh = Py_SIZE(a);
Raymond Hettinger99842b62004-03-08 05:56:15 +0000423 len = ihigh - ilow;
424 np = (PyListObject *) PyList_New(len);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000425 if (np == NULL)
426 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000427
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000428 src = a->ob_item + ilow;
429 dest = np->ob_item;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000430 for (i = 0; i < len; i++) {
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000431 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000432 Py_INCREF(v);
Raymond Hettingerb7d05db2004-03-08 07:25:05 +0000433 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000434 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000435 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000436}
437
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000438PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000439PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000440{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000441 if (!PyList_Check(a)) {
442 PyErr_BadInternalCall();
Guido van Rossum234f9421993-06-17 12:35:49 +0000443 return NULL;
444 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000445 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000446}
447
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000448static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000449list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000450{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000451 Py_ssize_t size;
452 Py_ssize_t i;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000453 PyObject **src, **dest;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000454 PyListObject *np;
455 if (!PyList_Check(bb)) {
Fred Drakeb6a9ada2000-06-01 03:12:13 +0000456 PyErr_Format(PyExc_TypeError,
Fred Drake914a2ed2000-06-01 14:31:03 +0000457 "can only concatenate list (not \"%.200s\") to list",
458 bb->ob_type->tp_name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000459 return NULL;
460 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000461#define b ((PyListObject *)bb)
Christian Heimes90aa7642007-12-19 02:45:37 +0000462 size = Py_SIZE(a) + Py_SIZE(b);
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000463 if (size < 0)
464 return PyErr_NoMemory();
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000465 np = (PyListObject *) PyList_New(size);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000466 if (np == NULL) {
Guido van Rossum90933611991-06-07 16:10:43 +0000467 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000468 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000469 src = a->ob_item;
470 dest = np->ob_item;
Christian Heimes90aa7642007-12-19 02:45:37 +0000471 for (i = 0; i < Py_SIZE(a); i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000472 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000473 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000474 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000475 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000476 src = b->ob_item;
Christian Heimes90aa7642007-12-19 02:45:37 +0000477 dest = np->ob_item + Py_SIZE(a);
478 for (i = 0; i < Py_SIZE(b); i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000479 PyObject *v = src[i];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000480 Py_INCREF(v);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000481 dest[i] = v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000482 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000483 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000484#undef b
485}
486
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000487static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000488list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000489{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000490 Py_ssize_t i, j;
491 Py_ssize_t size;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000492 PyListObject *np;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000493 PyObject **p, **items;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000494 PyObject *elem;
Guido van Rossumed98d481991-03-06 13:07:53 +0000495 if (n < 0)
496 n = 0;
Christian Heimes90aa7642007-12-19 02:45:37 +0000497 size = Py_SIZE(a) * n;
498 if (n && size/n != Py_SIZE(a))
Guido van Rossuma5c0e6d2002-10-11 21:05:56 +0000499 return PyErr_NoMemory();
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000500 if (size == 0)
Christian Heimesaf98da12008-01-27 15:18:18 +0000501 return PyList_New(0);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000502 np = (PyListObject *) PyList_New(size);
Guido van Rossumed98d481991-03-06 13:07:53 +0000503 if (np == NULL)
504 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000505
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000506 items = np->ob_item;
Christian Heimes90aa7642007-12-19 02:45:37 +0000507 if (Py_SIZE(a) == 1) {
Raymond Hettinger6624e682003-05-21 05:58:46 +0000508 elem = a->ob_item[0];
509 for (i = 0; i < n; i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000510 items[i] = elem;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000511 Py_INCREF(elem);
512 }
513 return (PyObject *) np;
514 }
Guido van Rossumed98d481991-03-06 13:07:53 +0000515 p = np->ob_item;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000516 items = a->ob_item;
Guido van Rossumed98d481991-03-06 13:07:53 +0000517 for (i = 0; i < n; i++) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000518 for (j = 0; j < Py_SIZE(a); j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000519 *p = items[j];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000520 Py_INCREF(*p);
Guido van Rossumed98d481991-03-06 13:07:53 +0000521 p++;
522 }
523 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000524 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000525}
526
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000527static int
Armin Rigo93677f02004-07-29 12:40:23 +0000528list_clear(PyListObject *a)
529{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000530 Py_ssize_t i;
Armin Rigo93677f02004-07-29 12:40:23 +0000531 PyObject **item = a->ob_item;
532 if (item != NULL) {
533 /* Because XDECREF can recursively invoke operations on
534 this list, we make it empty first. */
Christian Heimes90aa7642007-12-19 02:45:37 +0000535 i = Py_SIZE(a);
536 Py_SIZE(a) = 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000537 a->ob_item = NULL;
538 a->allocated = 0;
539 while (--i >= 0) {
540 Py_XDECREF(item[i]);
541 }
542 PyMem_FREE(item);
543 }
544 /* Never fails; the return value can be ignored.
545 Note that there is no guarantee that the list is actually empty
546 at this point, because XDECREF may have populated it again! */
547 return 0;
548}
549
Tim Peters8fc4a912004-07-31 21:53:19 +0000550/* a[ilow:ihigh] = v if v != NULL.
551 * del a[ilow:ihigh] if v == NULL.
552 *
553 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
554 * guaranteed the call cannot fail.
555 */
Armin Rigo93677f02004-07-29 12:40:23 +0000556static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000557list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000558{
Guido van Rossumae7bf1a1995-01-17 10:21:11 +0000559 /* Because [X]DECREF can recursively invoke list operations on
560 this list, we must postpone all [X]DECREF activity until
561 after the list is back in its canonical shape. Therefore
562 we must allocate an additional array, 'recycle', into which
563 we temporarily copy the items that are deleted from the
564 list. :-( */
Tim Peters73572222004-07-31 02:54:42 +0000565 PyObject *recycle_on_stack[8];
566 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000567 PyObject **item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000568 PyObject **vitem = NULL;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000569 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000570 Py_ssize_t n; /* # of elements in replacement list */
571 Py_ssize_t norig; /* # of elements in list getting replaced */
572 Py_ssize_t d; /* Change in size */
573 Py_ssize_t k;
Tim Peters8d9eb102004-07-31 02:24:20 +0000574 size_t s;
575 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000576#define b ((PyListObject *)v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000577 if (v == NULL)
578 n = 0;
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000579 else {
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000580 if (a == b) {
581 /* Special case "a[i:j] = a" -- copy b first */
Christian Heimes90aa7642007-12-19 02:45:37 +0000582 v = list_slice(b, 0, Py_SIZE(b));
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000583 if (v == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000584 return result;
585 result = list_ass_slice(a, ilow, ihigh, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000586 Py_DECREF(v);
Tim Peters8d9eb102004-07-31 02:24:20 +0000587 return result;
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000588 }
Raymond Hettingerf889e102004-03-09 08:04:33 +0000589 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000590 if(v_as_SF == NULL)
Tim Peters8d9eb102004-07-31 02:24:20 +0000591 goto Error;
Michael W. Hudsonb4f49382003-08-14 17:04:28 +0000592 n = PySequence_Fast_GET_SIZE(v_as_SF);
Raymond Hettinger42bec932004-03-12 16:38:17 +0000593 vitem = PySequence_Fast_ITEMS(v_as_SF);
Guido van Rossum32dffaa1991-12-24 13:27:34 +0000594 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000595 if (ilow < 0)
596 ilow = 0;
Christian Heimes90aa7642007-12-19 02:45:37 +0000597 else if (ilow > Py_SIZE(a))
598 ilow = Py_SIZE(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000599
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000600 if (ihigh < ilow)
601 ihigh = ilow;
Christian Heimes90aa7642007-12-19 02:45:37 +0000602 else if (ihigh > Py_SIZE(a))
603 ihigh = Py_SIZE(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000604
Tim Peters8d9eb102004-07-31 02:24:20 +0000605 norig = ihigh - ilow;
606 assert(norig >= 0);
607 d = n - norig;
Christian Heimes90aa7642007-12-19 02:45:37 +0000608 if (Py_SIZE(a) + d == 0) {
Armin Rigo93677f02004-07-29 12:40:23 +0000609 Py_XDECREF(v_as_SF);
610 return list_clear(a);
611 }
612 item = a->ob_item;
Tim Peters8d9eb102004-07-31 02:24:20 +0000613 /* recycle the items that we are about to remove */
614 s = norig * sizeof(PyObject *);
Tim Peters73572222004-07-31 02:54:42 +0000615 if (s > sizeof(recycle_on_stack)) {
Armin Rigo1dd04a02004-07-30 11:38:22 +0000616 recycle = (PyObject **)PyMem_MALLOC(s);
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000617 if (recycle == NULL) {
618 PyErr_NoMemory();
Tim Peters8d9eb102004-07-31 02:24:20 +0000619 goto Error;
Martin v. Löwiscd12bfc2003-05-03 10:53:08 +0000620 }
621 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000622 memcpy(recycle, &item[ilow], s);
Tim Peters8d9eb102004-07-31 02:24:20 +0000623
Armin Rigo1dd04a02004-07-30 11:38:22 +0000624 if (d < 0) { /* Delete -d items */
625 memmove(&item[ihigh+d], &item[ihigh],
Christian Heimes90aa7642007-12-19 02:45:37 +0000626 (Py_SIZE(a) - ihigh)*sizeof(PyObject *));
627 list_resize(a, Py_SIZE(a) + d);
Armin Rigo1dd04a02004-07-30 11:38:22 +0000628 item = a->ob_item;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000629 }
Armin Rigo1dd04a02004-07-30 11:38:22 +0000630 else if (d > 0) { /* Insert d items */
Christian Heimes90aa7642007-12-19 02:45:37 +0000631 k = Py_SIZE(a);
Tim Peters73572222004-07-31 02:54:42 +0000632 if (list_resize(a, k+d) < 0)
Tim Peters8d9eb102004-07-31 02:24:20 +0000633 goto Error;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000634 item = a->ob_item;
Raymond Hettingerf889e102004-03-09 08:04:33 +0000635 memmove(&item[ihigh+d], &item[ihigh],
Tim Peters73572222004-07-31 02:54:42 +0000636 (k - ihigh)*sizeof(PyObject *));
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000637 }
638 for (k = 0; k < n; k++, ilow++) {
Raymond Hettingerf889e102004-03-09 08:04:33 +0000639 PyObject *w = vitem[k];
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000640 Py_XINCREF(w);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000641 item[ilow] = w;
642 }
Tim Peters73572222004-07-31 02:54:42 +0000643 for (k = norig - 1; k >= 0; --k)
644 Py_XDECREF(recycle[k]);
Tim Peters8d9eb102004-07-31 02:24:20 +0000645 result = 0;
646 Error:
Tim Peters73572222004-07-31 02:54:42 +0000647 if (recycle != recycle_on_stack)
Armin Rigo1dd04a02004-07-30 11:38:22 +0000648 PyMem_FREE(recycle);
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000649 Py_XDECREF(v_as_SF);
Tim Peters8d9eb102004-07-31 02:24:20 +0000650 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000651#undef b
652}
653
Guido van Rossum234f9421993-06-17 12:35:49 +0000654int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000655PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000656{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000657 if (!PyList_Check(a)) {
658 PyErr_BadInternalCall();
Guido van Rossum1fc238a1993-07-29 08:25:09 +0000659 return -1;
Guido van Rossum234f9421993-06-17 12:35:49 +0000660 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000661 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000662}
663
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000664static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000665list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000666{
667 PyObject **items;
Christian Heimesaf98da12008-01-27 15:18:18 +0000668 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000669
670
671 size = PyList_GET_SIZE(self);
Christian Heimesaf98da12008-01-27 15:18:18 +0000672 if (size == 0 || n == 1) {
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000673 Py_INCREF(self);
674 return (PyObject *)self;
675 }
676
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000677 if (n < 1) {
Armin Rigo93677f02004-07-29 12:40:23 +0000678 (void)list_clear(self);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000679 Py_INCREF(self);
680 return (PyObject *)self;
681 }
682
Christian Heimesaf98da12008-01-27 15:18:18 +0000683 if (size > PY_SSIZE_T_MAX / n) {
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000684 return PyErr_NoMemory();
Christian Heimesaf98da12008-01-27 15:18:18 +0000685 }
686
687 if (list_resize(self, size*n) == -1)
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000688 return NULL;
689
690 p = size;
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000691 items = self->ob_item;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000692 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
693 for (j = 0; j < size; j++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000694 PyObject *o = items[j];
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000695 Py_INCREF(o);
Raymond Hettingera6366fe2004-03-09 13:05:22 +0000696 items[p++] = o;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000697 }
698 }
699 Py_INCREF(self);
700 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000701}
702
Guido van Rossum4a450d01991-04-03 19:05:18 +0000703static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000704list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000705{
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000706 PyObject *old_value;
Christian Heimes90aa7642007-12-19 02:45:37 +0000707 if (i < 0 || i >= Py_SIZE(a)) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000708 PyErr_SetString(PyExc_IndexError,
709 "list assignment index out of range");
Guido van Rossum4a450d01991-04-03 19:05:18 +0000710 return -1;
711 }
712 if (v == NULL)
713 return list_ass_slice(a, i, i+1, v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000714 Py_INCREF(v);
Guido van Rossumd7047b31995-01-02 19:07:15 +0000715 old_value = a->ob_item[i];
Guido van Rossum4a450d01991-04-03 19:05:18 +0000716 a->ob_item[i] = v;
Tim Peters3b01a122002-07-19 02:35:45 +0000717 Py_DECREF(old_value);
Guido van Rossum4a450d01991-04-03 19:05:18 +0000718 return 0;
719}
720
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000721static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000722listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000723{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000724 Py_ssize_t i;
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000725 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000726 if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000727 return NULL;
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000728 if (ins1(self, i, v) == 0)
729 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000730 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000731}
732
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000733static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000734listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000735{
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +0000736 if (app1(self, v) == 0)
737 Py_RETURN_NONE;
Raymond Hettinger501f02c2004-04-12 14:01:16 +0000738 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000739}
740
Barry Warsawdedf6d61998-10-09 16:37:25 +0000741static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000742listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000743{
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000744 PyObject *it; /* iter(v) */
Martin v. Löwis18e16552006-02-15 17:27:45 +0000745 Py_ssize_t m; /* size of self */
746 Py_ssize_t n; /* guess for size of b */
747 Py_ssize_t mn; /* m + n */
748 Py_ssize_t i;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000749 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000750
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000751 /* Special cases:
Tim Petersb38e2b62004-07-29 02:29:26 +0000752 1) lists and tuples which can use PySequence_Fast ops
753 2) extending self to self requires making a copy first
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000754 */
755 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
Armin Rigo70d172d2004-03-20 22:19:23 +0000756 PyObject **src, **dest;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000757 b = PySequence_Fast(b, "argument must be iterable");
758 if (!b)
759 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000760 n = PySequence_Fast_GET_SIZE(b);
761 if (n == 0) {
762 /* short circuit when b is empty */
763 Py_DECREF(b);
764 Py_RETURN_NONE;
765 }
Christian Heimes90aa7642007-12-19 02:45:37 +0000766 m = Py_SIZE(self);
Armin Rigo70d172d2004-03-20 22:19:23 +0000767 if (list_resize(self, m + n) == -1) {
768 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000769 return NULL;
Armin Rigo70d172d2004-03-20 22:19:23 +0000770 }
771 /* note that we may still have self == b here for the
772 * situation a.extend(a), but the following code works
773 * in that case too. Just make sure to resize self
774 * before calling PySequence_Fast_ITEMS.
775 */
776 /* populate the end of self with b's items */
777 src = PySequence_Fast_ITEMS(b);
778 dest = self->ob_item + m;
779 for (i = 0; i < n; i++) {
780 PyObject *o = src[i];
781 Py_INCREF(o);
782 dest[i] = o;
783 }
784 Py_DECREF(b);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000785 Py_RETURN_NONE;
786 }
787
788 it = PyObject_GetIter(b);
789 if (it == NULL)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000790 return NULL;
Raymond Hettinger57c45422004-03-11 09:48:18 +0000791 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000792
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000793 /* Guess a result list size. */
Christian Heimes255f53b2007-12-08 15:33:56 +0000794 n = _PyObject_LengthHint(b, 8);
Christian Heimes90aa7642007-12-19 02:45:37 +0000795 m = Py_SIZE(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000796 mn = m + n;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000797 if (mn >= m) {
798 /* Make room. */
799 if (list_resize(self, mn) == -1)
800 goto error;
801 /* Make the list sane again. */
Christian Heimes90aa7642007-12-19 02:45:37 +0000802 Py_SIZE(self) = m;
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000803 }
804 /* Else m + n overflowed; on the chance that n lied, and there really
805 * is enough room, ignore it. If n was telling the truth, we'll
806 * eventually run out of memory during the loop.
807 */
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000808
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000809 /* Run iterator to exhaustion. */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000810 for (;;) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000811 PyObject *item = iternext(it);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000812 if (item == NULL) {
Raymond Hettinger57c45422004-03-11 09:48:18 +0000813 if (PyErr_Occurred()) {
814 if (PyErr_ExceptionMatches(PyExc_StopIteration))
815 PyErr_Clear();
816 else
817 goto error;
818 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000819 break;
820 }
Christian Heimes90aa7642007-12-19 02:45:37 +0000821 if (Py_SIZE(self) < self->allocated) {
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000822 /* steals ref */
Christian Heimes90aa7642007-12-19 02:45:37 +0000823 PyList_SET_ITEM(self, Py_SIZE(self), item);
824 ++Py_SIZE(self);
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000825 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000826 else {
Raymond Hettinger40a03822004-04-12 13:05:09 +0000827 int status = app1(self, item);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000828 Py_DECREF(item); /* append creates a new ref */
829 if (status < 0)
830 goto error;
831 }
832 }
833
834 /* Cut back result list if initial guess was too large. */
Christian Heimes90aa7642007-12-19 02:45:37 +0000835 if (Py_SIZE(self) < self->allocated)
836 list_resize(self, Py_SIZE(self)); /* shrinking can't fail */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000837
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000838 Py_DECREF(it);
839 Py_RETURN_NONE;
840
841 error:
842 Py_DECREF(it);
843 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000844}
845
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000846PyObject *
847_PyList_Extend(PyListObject *self, PyObject *b)
848{
849 return listextend(self, b);
850}
851
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000852static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000853list_inplace_concat(PyListObject *self, PyObject *other)
854{
855 PyObject *result;
856
857 result = listextend(self, other);
858 if (result == NULL)
859 return result;
860 Py_DECREF(result);
861 Py_INCREF(self);
862 return (PyObject *)self;
863}
864
865static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000866listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000867{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000868 Py_ssize_t i = -1;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000869 PyObject *v;
Tim Peters8fc4a912004-07-31 21:53:19 +0000870 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000871
Thomas Wouters89f507f2006-12-13 04:49:30 +0000872 if (!PyArg_ParseTuple(args, "|n:pop", &i))
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000873 return NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000874
Christian Heimes90aa7642007-12-19 02:45:37 +0000875 if (Py_SIZE(self) == 0) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000876 /* Special-case most common failure cause */
877 PyErr_SetString(PyExc_IndexError, "pop from empty list");
878 return NULL;
879 }
880 if (i < 0)
Christian Heimes90aa7642007-12-19 02:45:37 +0000881 i += Py_SIZE(self);
882 if (i < 0 || i >= Py_SIZE(self)) {
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000883 PyErr_SetString(PyExc_IndexError, "pop index out of range");
884 return NULL;
885 }
886 v = self->ob_item[i];
Christian Heimes90aa7642007-12-19 02:45:37 +0000887 if (i == Py_SIZE(self) - 1) {
888 status = list_resize(self, Py_SIZE(self) - 1);
Tim Peters8fc4a912004-07-31 21:53:19 +0000889 assert(status >= 0);
890 return v; /* and v now owns the reference the list had */
Raymond Hettingercb3e5802004-02-13 18:36:31 +0000891 }
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000892 Py_INCREF(v);
Tim Peters8fc4a912004-07-31 21:53:19 +0000893 status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
894 assert(status >= 0);
895 /* Use status, so that in a release build compilers don't
896 * complain about the unused name.
897 */
Brett Cannon651dd522004-08-08 21:21:18 +0000898 (void) status;
899
900 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000901}
902
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000903/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
904static void
905reverse_slice(PyObject **lo, PyObject **hi)
906{
907 assert(lo && hi);
908
909 --hi;
910 while (lo < hi) {
911 PyObject *t = *lo;
912 *lo = *hi;
913 *hi = t;
914 ++lo;
915 --hi;
916 }
917}
918
Tim Petersa64dc242002-08-01 02:13:36 +0000919/* Lots of code for an adaptive, stable, natural mergesort. There are many
920 * pieces to this algorithm; read listsort.txt for overviews and details.
921 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000922
Raymond Hettinger70b64fc2008-01-30 20:15:17 +0000923/* Comparison function: PyObject_RichCompareBool with Py_LT.
Tim Petersa64dc242002-08-01 02:13:36 +0000924 * Returns -1 on error, 1 if x < y, 0 if x >= y.
925 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000926
Raymond Hettinger70b64fc2008-01-30 20:15:17 +0000927#define ISLT(X, Y) (PyObject_RichCompareBool(X, Y, Py_LT))
Tim Peters66860f62002-08-04 17:47:26 +0000928
929/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +0000930 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
931 started. It makes more sense in context <wink>. X and Y are PyObject*s.
932*/
Raymond Hettinger70b64fc2008-01-30 20:15:17 +0000933#define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail; \
Tim Petersa8c974c2002-07-19 03:30:57 +0000934 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000935
936/* binarysort is the best method for sorting small arrays: it does
937 few compares, but can do data movement quadratic in the number of
938 elements.
Guido van Rossum42812581998-06-17 14:15:44 +0000939 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +0000940 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000941 On entry, must have lo <= start <= hi, and that [lo, start) is already
942 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +0000943 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000944 Even in case of error, the output slice will be some permutation of
945 the input (nothing is lost or duplicated).
946*/
Guido van Rossum3f236de1996-12-10 23:55:39 +0000947static int
Raymond Hettinger70b64fc2008-01-30 20:15:17 +0000948binarysort(PyObject **lo, PyObject **hi, PyObject **start)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000949{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000950 register Py_ssize_t k;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000951 register PyObject **l, **p, **r;
952 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000953
Tim Petersa8c974c2002-07-19 03:30:57 +0000954 assert(lo <= start && start <= hi);
955 /* assert [lo, start) is sorted */
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000956 if (lo == start)
957 ++start;
958 for (; start < hi; ++start) {
959 /* set l to where *start belongs */
960 l = lo;
961 r = start;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000962 pivot = *r;
Tim Peters0fe977c2002-07-19 06:12:32 +0000963 /* Invariants:
964 * pivot >= all in [lo, l).
965 * pivot < all in [r, start).
966 * The second is vacuously true at the start.
967 */
968 assert(l < r);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000969 do {
970 p = l + ((r - l) >> 1);
Tim Petersa8c974c2002-07-19 03:30:57 +0000971 IFLT(pivot, *p)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000972 r = p;
973 else
Tim Peters0fe977c2002-07-19 06:12:32 +0000974 l = p+1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000975 } while (l < r);
Tim Peters0fe977c2002-07-19 06:12:32 +0000976 assert(l == r);
977 /* The invariants still hold, so pivot >= all in [lo, l) and
978 pivot < all in [l, start), so pivot belongs at l. Note
979 that if there are elements equal to pivot, l points to the
980 first slot after them -- that's why this sort is stable.
981 Slide over to make room.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000982 Caution: using memmove is much slower under MSVC 5;
983 we're not usually moving many slots. */
984 for (p = start; p > l; --p)
985 *p = *(p-1);
986 *l = pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000987 }
Guido van Rossum3f236de1996-12-10 23:55:39 +0000988 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +0000989
990 fail:
991 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000992}
993
Tim Petersa64dc242002-08-01 02:13:36 +0000994/*
995Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
996is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000997
Tim Petersa64dc242002-08-01 02:13:36 +0000998 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +0000999
Tim Petersa64dc242002-08-01 02:13:36 +00001000or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001001
Tim Petersa64dc242002-08-01 02:13:36 +00001002 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001003
Tim Petersa64dc242002-08-01 02:13:36 +00001004Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1005For its intended use in a stable mergesort, the strictness of the defn of
1006"descending" is needed so that the caller can safely reverse a descending
1007sequence without violating stability (strict > ensures there are no equal
1008elements to get out of order).
1009
1010Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001011*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001012static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001013count_run(PyObject **lo, PyObject **hi, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001014{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001015 Py_ssize_t k;
1016 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001017
Tim Petersa64dc242002-08-01 02:13:36 +00001018 assert(lo < hi);
1019 *descending = 0;
1020 ++lo;
1021 if (lo == hi)
1022 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001023
Tim Petersa64dc242002-08-01 02:13:36 +00001024 n = 2;
1025 IFLT(*lo, *(lo-1)) {
1026 *descending = 1;
1027 for (lo = lo+1; lo < hi; ++lo, ++n) {
1028 IFLT(*lo, *(lo-1))
1029 ;
1030 else
1031 break;
1032 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001033 }
Tim Petersa64dc242002-08-01 02:13:36 +00001034 else {
1035 for (lo = lo+1; lo < hi; ++lo, ++n) {
1036 IFLT(*lo, *(lo-1))
1037 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001038 }
1039 }
1040
Tim Petersa64dc242002-08-01 02:13:36 +00001041 return n;
1042fail:
1043 return -1;
1044}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001045
Tim Petersa64dc242002-08-01 02:13:36 +00001046/*
1047Locate the proper position of key in a sorted vector; if the vector contains
1048an element equal to key, return the position immediately to the left of
1049the leftmost equal element. [gallop_right() does the same except returns
1050the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001051
Tim Petersa64dc242002-08-01 02:13:36 +00001052"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001053
Tim Petersa64dc242002-08-01 02:13:36 +00001054"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1055hint is to the final result, the faster this runs.
1056
1057The return value is the int k in 0..n such that
1058
1059 a[k-1] < key <= a[k]
1060
1061pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1062key belongs at index k; or, IOW, the first k elements of a should precede
1063key, and the last n-k should follow key.
1064
1065Returns -1 on error. See listsort.txt for info on the method.
1066*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001067static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001068gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001069{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001070 Py_ssize_t ofs;
1071 Py_ssize_t lastofs;
1072 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001073
1074 assert(key && a && n > 0 && hint >= 0 && hint < n);
1075
1076 a += hint;
1077 lastofs = 0;
1078 ofs = 1;
1079 IFLT(*a, key) {
1080 /* a[hint] < key -- gallop right, until
1081 * a[hint + lastofs] < key <= a[hint + ofs]
1082 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001083 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001084 while (ofs < maxofs) {
1085 IFLT(a[ofs], key) {
1086 lastofs = ofs;
1087 ofs = (ofs << 1) + 1;
1088 if (ofs <= 0) /* int overflow */
1089 ofs = maxofs;
1090 }
1091 else /* key <= a[hint + ofs] */
1092 break;
1093 }
1094 if (ofs > maxofs)
1095 ofs = maxofs;
1096 /* Translate back to offsets relative to &a[0]. */
1097 lastofs += hint;
1098 ofs += hint;
1099 }
1100 else {
1101 /* key <= a[hint] -- gallop left, until
1102 * a[hint - ofs] < key <= a[hint - lastofs]
1103 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001104 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001105 while (ofs < maxofs) {
1106 IFLT(*(a-ofs), key)
1107 break;
1108 /* key <= a[hint - ofs] */
1109 lastofs = ofs;
1110 ofs = (ofs << 1) + 1;
1111 if (ofs <= 0) /* int overflow */
1112 ofs = maxofs;
1113 }
1114 if (ofs > maxofs)
1115 ofs = maxofs;
1116 /* Translate back to positive offsets relative to &a[0]. */
1117 k = lastofs;
1118 lastofs = hint - ofs;
1119 ofs = hint - k;
1120 }
1121 a -= hint;
1122
1123 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1124 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1125 * right of lastofs but no farther right than ofs. Do a binary
1126 * search, with invariant a[lastofs-1] < key <= a[ofs].
1127 */
1128 ++lastofs;
1129 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001130 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001131
1132 IFLT(a[m], key)
1133 lastofs = m+1; /* a[m] < key */
1134 else
1135 ofs = m; /* key <= a[m] */
1136 }
1137 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1138 return ofs;
1139
1140fail:
1141 return -1;
1142}
1143
1144/*
1145Exactly like gallop_left(), except that if key already exists in a[0:n],
1146finds the position immediately to the right of the rightmost equal value.
1147
1148The return value is the int k in 0..n such that
1149
1150 a[k-1] <= key < a[k]
1151
1152or -1 if error.
1153
1154The code duplication is massive, but this is enough different given that
1155we're sticking to "<" comparisons that it's much harder to follow if
1156written as one routine with yet another "left or right?" flag.
1157*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001158static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001159gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001160{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001161 Py_ssize_t ofs;
1162 Py_ssize_t lastofs;
1163 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001164
1165 assert(key && a && n > 0 && hint >= 0 && hint < n);
1166
1167 a += hint;
1168 lastofs = 0;
1169 ofs = 1;
1170 IFLT(key, *a) {
1171 /* key < a[hint] -- gallop left, until
1172 * a[hint - ofs] <= key < a[hint - lastofs]
1173 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001174 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
Tim Petersa64dc242002-08-01 02:13:36 +00001175 while (ofs < maxofs) {
1176 IFLT(key, *(a-ofs)) {
1177 lastofs = ofs;
1178 ofs = (ofs << 1) + 1;
1179 if (ofs <= 0) /* int overflow */
1180 ofs = maxofs;
1181 }
1182 else /* a[hint - ofs] <= key */
1183 break;
1184 }
1185 if (ofs > maxofs)
1186 ofs = maxofs;
1187 /* Translate back to positive offsets relative to &a[0]. */
1188 k = lastofs;
1189 lastofs = hint - ofs;
1190 ofs = hint - k;
1191 }
1192 else {
1193 /* a[hint] <= key -- gallop right, until
1194 * a[hint + lastofs] <= key < a[hint + ofs]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001195 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001196 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
Tim Petersa64dc242002-08-01 02:13:36 +00001197 while (ofs < maxofs) {
1198 IFLT(key, a[ofs])
1199 break;
1200 /* a[hint + ofs] <= key */
1201 lastofs = ofs;
1202 ofs = (ofs << 1) + 1;
1203 if (ofs <= 0) /* int overflow */
1204 ofs = maxofs;
1205 }
1206 if (ofs > maxofs)
1207 ofs = maxofs;
1208 /* Translate back to offsets relative to &a[0]. */
1209 lastofs += hint;
1210 ofs += hint;
1211 }
1212 a -= hint;
1213
1214 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1215 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1216 * right of lastofs but no farther right than ofs. Do a binary
1217 * search, with invariant a[lastofs-1] <= key < a[ofs].
1218 */
1219 ++lastofs;
1220 while (lastofs < ofs) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001221 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001222
1223 IFLT(key, a[m])
1224 ofs = m; /* key < a[m] */
1225 else
1226 lastofs = m+1; /* a[m] <= key */
1227 }
1228 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1229 return ofs;
1230
1231fail:
1232 return -1;
1233}
1234
1235/* The maximum number of entries in a MergeState's pending-runs stack.
1236 * This is enough to sort arrays of size up to about
1237 * 32 * phi ** MAX_MERGE_PENDING
1238 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1239 * with 2**64 elements.
1240 */
1241#define MAX_MERGE_PENDING 85
1242
Tim Peterse05f65a2002-08-10 05:21:15 +00001243/* When we get into galloping mode, we stay there until both runs win less
1244 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001245 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001246#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001247
1248/* Avoid malloc for small temp arrays. */
1249#define MERGESTATE_TEMP_SIZE 256
1250
1251/* One MergeState exists on the stack per invocation of mergesort. It's just
1252 * a convenient way to pass state around among the helper functions.
1253 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001254struct s_slice {
1255 PyObject **base;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001256 Py_ssize_t len;
Tim Peterse05f65a2002-08-10 05:21:15 +00001257};
1258
Tim Petersa64dc242002-08-01 02:13:36 +00001259typedef struct s_MergeState {
Tim Peterse05f65a2002-08-10 05:21:15 +00001260 /* This controls when we get *into* galloping mode. It's initialized
1261 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1262 * random data, and lower for highly structured data.
1263 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001264 Py_ssize_t min_gallop;
Tim Peterse05f65a2002-08-10 05:21:15 +00001265
Tim Petersa64dc242002-08-01 02:13:36 +00001266 /* 'a' is temp storage to help with merges. It contains room for
1267 * alloced entries.
1268 */
1269 PyObject **a; /* may point to temparray below */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001270 Py_ssize_t alloced;
Tim Petersa64dc242002-08-01 02:13:36 +00001271
1272 /* A stack of n pending runs yet to be merged. Run #i starts at
1273 * address base[i] and extends for len[i] elements. It's always
1274 * true (so long as the indices are in bounds) that
1275 *
Tim Peterse05f65a2002-08-10 05:21:15 +00001276 * pending[i].base + pending[i].len == pending[i+1].base
Tim Petersa64dc242002-08-01 02:13:36 +00001277 *
1278 * so we could cut the storage for this, but it's a minor amount,
1279 * and keeping all the info explicit simplifies the code.
1280 */
1281 int n;
Tim Peterse05f65a2002-08-10 05:21:15 +00001282 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001283
1284 /* 'a' points to this when possible, rather than muck with malloc. */
1285 PyObject *temparray[MERGESTATE_TEMP_SIZE];
1286} MergeState;
1287
1288/* Conceptually a MergeState's constructor. */
1289static void
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001290merge_init(MergeState *ms)
Tim Petersa64dc242002-08-01 02:13:36 +00001291{
1292 assert(ms != NULL);
Tim Petersa64dc242002-08-01 02:13:36 +00001293 ms->a = ms->temparray;
1294 ms->alloced = MERGESTATE_TEMP_SIZE;
1295 ms->n = 0;
Tim Peterse05f65a2002-08-10 05:21:15 +00001296 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001297}
1298
1299/* Free all the temp memory owned by the MergeState. This must be called
1300 * when you're done with a MergeState, and may be called before then if
1301 * you want to free the temp memory early.
1302 */
1303static void
1304merge_freemem(MergeState *ms)
1305{
1306 assert(ms != NULL);
1307 if (ms->a != ms->temparray)
1308 PyMem_Free(ms->a);
1309 ms->a = ms->temparray;
1310 ms->alloced = MERGESTATE_TEMP_SIZE;
1311}
1312
1313/* Ensure enough temp memory for 'need' array slots is available.
1314 * Returns 0 on success and -1 if the memory can't be gotten.
1315 */
1316static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001317merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001318{
1319 assert(ms != NULL);
1320 if (need <= ms->alloced)
1321 return 0;
1322 /* Don't realloc! That can cost cycles to copy the old data, but
1323 * we don't care what's in the block.
1324 */
1325 merge_freemem(ms);
1326 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1327 if (ms->a) {
1328 ms->alloced = need;
1329 return 0;
1330 }
1331 PyErr_NoMemory();
1332 merge_freemem(ms); /* reset to sane state */
1333 return -1;
1334}
1335#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1336 merge_getmem(MS, NEED))
1337
1338/* Merge the na elements starting at pa with the nb elements starting at pb
1339 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1340 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1341 * merge, and should have na <= nb. See listsort.txt for more info.
1342 * Return 0 if successful, -1 if error.
1343 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001344static Py_ssize_t
1345merge_lo(MergeState *ms, PyObject **pa, Py_ssize_t na,
1346 PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001347{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001348 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001349 PyObject **dest;
1350 int result = -1; /* guilty until proved innocent */
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001351 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001352
1353 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1354 if (MERGE_GETMEM(ms, na) < 0)
1355 return -1;
1356 memcpy(ms->a, pa, na * sizeof(PyObject*));
1357 dest = pa;
1358 pa = ms->a;
1359
1360 *dest++ = *pb++;
1361 --nb;
1362 if (nb == 0)
1363 goto Succeed;
1364 if (na == 1)
1365 goto CopyB;
1366
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001367 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001368 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001369 Py_ssize_t acount = 0; /* # of times A won in a row */
1370 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001371
1372 /* Do the straightforward thing until (if ever) one run
1373 * appears to win consistently.
1374 */
1375 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001376 assert(na > 1 && nb > 0);
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001377 k = ISLT(*pb, *pa);
Tim Petersa64dc242002-08-01 02:13:36 +00001378 if (k) {
1379 if (k < 0)
1380 goto Fail;
1381 *dest++ = *pb++;
1382 ++bcount;
1383 acount = 0;
1384 --nb;
1385 if (nb == 0)
1386 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001387 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001388 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001389 }
1390 else {
Tim Petersa64dc242002-08-01 02:13:36 +00001391 *dest++ = *pa++;
1392 ++acount;
1393 bcount = 0;
1394 --na;
1395 if (na == 1)
1396 goto CopyB;
Tim Peterse05f65a2002-08-10 05:21:15 +00001397 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001398 break;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001399 }
Tim Petersa64dc242002-08-01 02:13:36 +00001400 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001401
Tim Petersa64dc242002-08-01 02:13:36 +00001402 /* One run is winning so consistently that galloping may
1403 * be a huge win. So try that, and continue galloping until
1404 * (if ever) neither run appears to be winning consistently
1405 * anymore.
1406 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001407 ++min_gallop;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001408 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001409 assert(na > 1 && nb > 0);
1410 min_gallop -= min_gallop > 1;
1411 ms->min_gallop = min_gallop;
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001412 k = gallop_right(*pb, pa, na, 0);
Tim Petersa64dc242002-08-01 02:13:36 +00001413 acount = k;
1414 if (k) {
1415 if (k < 0)
1416 goto Fail;
1417 memcpy(dest, pa, k * sizeof(PyObject *));
1418 dest += k;
1419 pa += k;
1420 na -= k;
1421 if (na == 1)
1422 goto CopyB;
1423 /* na==0 is impossible now if the comparison
1424 * function is consistent, but we can't assume
1425 * that it is.
1426 */
1427 if (na == 0)
1428 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001429 }
Tim Petersa64dc242002-08-01 02:13:36 +00001430 *dest++ = *pb++;
1431 --nb;
1432 if (nb == 0)
1433 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001434
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001435 k = gallop_left(*pa, pb, nb, 0);
Tim Petersa64dc242002-08-01 02:13:36 +00001436 bcount = k;
1437 if (k) {
1438 if (k < 0)
1439 goto Fail;
1440 memmove(dest, pb, k * sizeof(PyObject *));
1441 dest += k;
1442 pb += k;
1443 nb -= k;
1444 if (nb == 0)
1445 goto Succeed;
1446 }
1447 *dest++ = *pa++;
1448 --na;
1449 if (na == 1)
1450 goto CopyB;
1451 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001452 ++min_gallop; /* penalize it for leaving galloping mode */
1453 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001454 }
1455Succeed:
1456 result = 0;
1457Fail:
1458 if (na)
1459 memcpy(dest, pa, na * sizeof(PyObject*));
1460 return result;
1461CopyB:
1462 assert(na == 1 && nb > 0);
1463 /* The last element of pa belongs at the end of the merge. */
1464 memmove(dest, pb, nb * sizeof(PyObject *));
1465 dest[nb] = *pa;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001466 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001467}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001468
Tim Petersa64dc242002-08-01 02:13:36 +00001469/* Merge the na elements starting at pa with the nb elements starting at pb
1470 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1471 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1472 * merge, and should have na >= nb. See listsort.txt for more info.
1473 * Return 0 if successful, -1 if error.
1474 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001475static Py_ssize_t
1476merge_hi(MergeState *ms, PyObject **pa, Py_ssize_t na, PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001477{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001478 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001479 PyObject **dest;
1480 int result = -1; /* guilty until proved innocent */
1481 PyObject **basea;
1482 PyObject **baseb;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001483 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001484
1485 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1486 if (MERGE_GETMEM(ms, nb) < 0)
1487 return -1;
1488 dest = pb + nb - 1;
1489 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1490 basea = pa;
1491 baseb = ms->a;
1492 pb = ms->a + nb - 1;
1493 pa += na - 1;
1494
1495 *dest-- = *pa--;
1496 --na;
1497 if (na == 0)
1498 goto Succeed;
1499 if (nb == 1)
1500 goto CopyA;
1501
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001502 min_gallop = ms->min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001503 for (;;) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001504 Py_ssize_t acount = 0; /* # of times A won in a row */
1505 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001506
1507 /* Do the straightforward thing until (if ever) one run
1508 * appears to win consistently.
1509 */
1510 for (;;) {
Tim Peterse05f65a2002-08-10 05:21:15 +00001511 assert(na > 0 && nb > 1);
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001512 k = ISLT(*pb, *pa);
Tim Petersa64dc242002-08-01 02:13:36 +00001513 if (k) {
1514 if (k < 0)
1515 goto Fail;
1516 *dest-- = *pa--;
1517 ++acount;
1518 bcount = 0;
1519 --na;
1520 if (na == 0)
1521 goto Succeed;
Tim Peterse05f65a2002-08-10 05:21:15 +00001522 if (acount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001523 break;
1524 }
1525 else {
1526 *dest-- = *pb--;
1527 ++bcount;
1528 acount = 0;
1529 --nb;
1530 if (nb == 1)
1531 goto CopyA;
Tim Peterse05f65a2002-08-10 05:21:15 +00001532 if (bcount >= min_gallop)
Tim Petersa64dc242002-08-01 02:13:36 +00001533 break;
1534 }
1535 }
1536
1537 /* One run is winning so consistently that galloping may
1538 * be a huge win. So try that, and continue galloping until
1539 * (if ever) neither run appears to be winning consistently
1540 * anymore.
1541 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001542 ++min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001543 do {
Tim Peterse05f65a2002-08-10 05:21:15 +00001544 assert(na > 0 && nb > 1);
1545 min_gallop -= min_gallop > 1;
1546 ms->min_gallop = min_gallop;
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001547 k = gallop_right(*pb, basea, na, na-1);
Tim Petersa64dc242002-08-01 02:13:36 +00001548 if (k < 0)
1549 goto Fail;
1550 k = na - k;
1551 acount = k;
1552 if (k) {
1553 dest -= k;
1554 pa -= k;
1555 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1556 na -= k;
1557 if (na == 0)
1558 goto Succeed;
1559 }
1560 *dest-- = *pb--;
1561 --nb;
1562 if (nb == 1)
1563 goto CopyA;
1564
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001565 k = gallop_left(*pa, baseb, nb, nb-1);
Tim Petersa64dc242002-08-01 02:13:36 +00001566 if (k < 0)
1567 goto Fail;
1568 k = nb - k;
1569 bcount = k;
1570 if (k) {
1571 dest -= k;
1572 pb -= k;
1573 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1574 nb -= k;
1575 if (nb == 1)
1576 goto CopyA;
1577 /* nb==0 is impossible now if the comparison
1578 * function is consistent, but we can't assume
1579 * that it is.
1580 */
1581 if (nb == 0)
1582 goto Succeed;
1583 }
1584 *dest-- = *pa--;
1585 --na;
1586 if (na == 0)
1587 goto Succeed;
1588 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
Tim Peterse05f65a2002-08-10 05:21:15 +00001589 ++min_gallop; /* penalize it for leaving galloping mode */
1590 ms->min_gallop = min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001591 }
1592Succeed:
1593 result = 0;
1594Fail:
1595 if (nb)
1596 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1597 return result;
1598CopyA:
1599 assert(nb == 1 && na > 0);
1600 /* The first element of pb belongs at the front of the merge. */
1601 dest -= na;
1602 pa -= na;
1603 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1604 *dest = *pb;
1605 return 0;
1606}
1607
1608/* Merge the two runs at stack indices i and i+1.
1609 * Returns 0 on success, -1 on error.
1610 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001611static Py_ssize_t
1612merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001613{
1614 PyObject **pa, **pb;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001615 Py_ssize_t na, nb;
1616 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001617
1618 assert(ms != NULL);
1619 assert(ms->n >= 2);
1620 assert(i >= 0);
1621 assert(i == ms->n - 2 || i == ms->n - 3);
1622
Tim Peterse05f65a2002-08-10 05:21:15 +00001623 pa = ms->pending[i].base;
1624 na = ms->pending[i].len;
1625 pb = ms->pending[i+1].base;
1626 nb = ms->pending[i+1].len;
Tim Petersa64dc242002-08-01 02:13:36 +00001627 assert(na > 0 && nb > 0);
1628 assert(pa + na == pb);
1629
1630 /* Record the length of the combined runs; if i is the 3rd-last
1631 * run now, also slide over the last run (which isn't involved
1632 * in this merge). The current run i+1 goes away in any case.
1633 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001634 ms->pending[i].len = na + nb;
1635 if (i == ms->n - 3)
1636 ms->pending[i+1] = ms->pending[i+2];
Tim Petersa64dc242002-08-01 02:13:36 +00001637 --ms->n;
1638
1639 /* Where does b start in a? Elements in a before that can be
1640 * ignored (already in place).
1641 */
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001642 k = gallop_right(*pb, pa, na, 0);
Tim Petersa64dc242002-08-01 02:13:36 +00001643 if (k < 0)
1644 return -1;
1645 pa += k;
1646 na -= k;
1647 if (na == 0)
1648 return 0;
1649
1650 /* Where does a end in b? Elements in b after that can be
1651 * ignored (already in place).
1652 */
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001653 nb = gallop_left(pa[na-1], pb, nb, nb-1);
Tim Petersa64dc242002-08-01 02:13:36 +00001654 if (nb <= 0)
1655 return nb;
1656
1657 /* Merge what remains of the runs, using a temp array with
1658 * min(na, nb) elements.
1659 */
1660 if (na <= nb)
1661 return merge_lo(ms, pa, na, pb, nb);
1662 else
1663 return merge_hi(ms, pa, na, pb, nb);
1664}
1665
1666/* Examine the stack of runs waiting to be merged, merging adjacent runs
1667 * until the stack invariants are re-established:
1668 *
1669 * 1. len[-3] > len[-2] + len[-1]
1670 * 2. len[-2] > len[-1]
1671 *
1672 * See listsort.txt for more info.
1673 *
1674 * Returns 0 on success, -1 on error.
1675 */
1676static int
1677merge_collapse(MergeState *ms)
1678{
Tim Peterse05f65a2002-08-10 05:21:15 +00001679 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001680
1681 assert(ms);
1682 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001683 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001684 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1685 if (p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001686 --n;
1687 if (merge_at(ms, n) < 0)
1688 return -1;
1689 }
Tim Peterse05f65a2002-08-10 05:21:15 +00001690 else if (p[n].len <= p[n+1].len) {
Tim Petersa64dc242002-08-01 02:13:36 +00001691 if (merge_at(ms, n) < 0)
1692 return -1;
1693 }
1694 else
1695 break;
1696 }
1697 return 0;
1698}
1699
1700/* Regardless of invariants, merge all runs on the stack until only one
1701 * remains. This is used at the end of the mergesort.
1702 *
1703 * Returns 0 on success, -1 on error.
1704 */
1705static int
1706merge_force_collapse(MergeState *ms)
1707{
Tim Peterse05f65a2002-08-10 05:21:15 +00001708 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001709
1710 assert(ms);
1711 while (ms->n > 1) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001712 Py_ssize_t n = ms->n - 2;
Tim Peterse05f65a2002-08-10 05:21:15 +00001713 if (n > 0 && p[n-1].len < p[n+1].len)
Tim Petersa64dc242002-08-01 02:13:36 +00001714 --n;
1715 if (merge_at(ms, n) < 0)
1716 return -1;
1717 }
1718 return 0;
1719}
1720
1721/* Compute a good value for the minimum run length; natural runs shorter
1722 * than this are boosted artificially via binary insertion.
1723 *
1724 * If n < 64, return n (it's too small to bother with fancy stuff).
1725 * Else if n is an exact power of 2, return 32.
1726 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1727 * strictly less than, an exact power of 2.
1728 *
1729 * See listsort.txt for more info.
1730 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001731static Py_ssize_t
1732merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001733{
Martin v. Löwis18e16552006-02-15 17:27:45 +00001734 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001735
1736 assert(n >= 0);
1737 while (n >= 64) {
1738 r |= n & 1;
1739 n >>= 1;
1740 }
1741 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001742}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001743
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001744/* Special wrapper to support stable sorting using the decorate-sort-undecorate
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001745 pattern. Holds a key which is used for comparisons and the original record
Tim Petersb38e2b62004-07-29 02:29:26 +00001746 which is returned during the undecorate phase. By exposing only the key
1747 during comparisons, the underlying sort stability characteristics are left
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001748 unchanged. Also, the comparison function will only see the key instead of
1749 a full record. */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001750
1751typedef struct {
1752 PyObject_HEAD
1753 PyObject *key;
1754 PyObject *value;
1755} sortwrapperobject;
1756
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001757PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001758static PyObject *
1759sortwrapper_richcompare(sortwrapperobject *, sortwrapperobject *, int);
1760static void
1761sortwrapper_dealloc(sortwrapperobject *);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001762
Christian Heimesa22e8bd2007-11-29 22:35:39 +00001763PyTypeObject PySortWrapper_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001764 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001765 "sortwrapper", /* tp_name */
1766 sizeof(sortwrapperobject), /* tp_basicsize */
1767 0, /* tp_itemsize */
1768 /* methods */
1769 (destructor)sortwrapper_dealloc, /* tp_dealloc */
1770 0, /* tp_print */
1771 0, /* tp_getattr */
1772 0, /* tp_setattr */
1773 0, /* tp_compare */
1774 0, /* tp_repr */
1775 0, /* tp_as_number */
1776 0, /* tp_as_sequence */
1777 0, /* tp_as_mapping */
1778 0, /* tp_hash */
1779 0, /* tp_call */
1780 0, /* tp_str */
1781 PyObject_GenericGetAttr, /* tp_getattro */
1782 0, /* tp_setattro */
1783 0, /* tp_as_buffer */
Guido van Rossum3cf5b1e2006-07-27 21:53:35 +00001784 Py_TPFLAGS_DEFAULT, /* tp_flags */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001785 sortwrapper_doc, /* tp_doc */
1786 0, /* tp_traverse */
1787 0, /* tp_clear */
1788 (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
1789};
1790
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001791
1792static PyObject *
1793sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
1794{
Christian Heimesa22e8bd2007-11-29 22:35:39 +00001795 if (!PyObject_TypeCheck(b, &PySortWrapper_Type)) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001796 PyErr_SetString(PyExc_TypeError,
1797 "expected a sortwrapperobject");
1798 return NULL;
1799 }
1800 return PyObject_RichCompare(a->key, b->key, op);
1801}
1802
1803static void
1804sortwrapper_dealloc(sortwrapperobject *so)
1805{
1806 Py_XDECREF(so->key);
1807 Py_XDECREF(so->value);
1808 PyObject_Del(so);
1809}
1810
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001811/* Returns a new reference to a sortwrapper.
1812 Consumes the references to the two underlying objects. */
1813
1814static PyObject *
1815build_sortwrapper(PyObject *key, PyObject *value)
1816{
1817 sortwrapperobject *so;
Tim Petersb38e2b62004-07-29 02:29:26 +00001818
Christian Heimesa22e8bd2007-11-29 22:35:39 +00001819 so = PyObject_New(sortwrapperobject, &PySortWrapper_Type);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001820 if (so == NULL)
1821 return NULL;
1822 so->key = key;
1823 so->value = value;
1824 return (PyObject *)so;
1825}
1826
1827/* Returns a new reference to the value underlying the wrapper. */
1828static PyObject *
1829sortwrapper_getvalue(PyObject *so)
1830{
1831 PyObject *value;
1832
Christian Heimesa22e8bd2007-11-29 22:35:39 +00001833 if (!PyObject_TypeCheck(so, &PySortWrapper_Type)) {
Tim Petersb38e2b62004-07-29 02:29:26 +00001834 PyErr_SetString(PyExc_TypeError,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001835 "expected a sortwrapperobject");
1836 return NULL;
1837 }
1838 value = ((sortwrapperobject *)so)->value;
1839 Py_INCREF(value);
1840 return value;
1841}
1842
Tim Petersa64dc242002-08-01 02:13:36 +00001843/* An adaptive, stable, natural mergesort. See listsort.txt.
1844 * Returns Py_None on success, NULL on error. Even in case of error, the
1845 * list will be some permutation of its input state (nothing is lost or
1846 * duplicated).
1847 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001848static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001849listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001850{
Tim Petersa64dc242002-08-01 02:13:36 +00001851 MergeState ms;
1852 PyObject **lo, **hi;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001853 Py_ssize_t nremaining;
1854 Py_ssize_t minrun;
1855 Py_ssize_t saved_ob_size, saved_allocated;
Tim Petersb9099c32002-11-12 22:08:10 +00001856 PyObject **saved_ob_item;
Armin Rigo93677f02004-07-29 12:40:23 +00001857 PyObject **final_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001858 PyObject *result = NULL; /* guilty until proved innocent */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001859 int reverse = 0;
1860 PyObject *keyfunc = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001861 Py_ssize_t i;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001862 PyObject *key, *value, *kvpair;
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001863 static char *kwlist[] = {"key", "reverse", 0};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001864
Tim Petersa64dc242002-08-01 02:13:36 +00001865 assert(self != NULL);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001866 assert (PyList_Check(self));
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001867 if (args != NULL) {
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001868 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:sort",
1869 kwlist, &keyfunc, &reverse))
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001870 return NULL;
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001871 if (Py_SIZE(args) > 0) {
1872 PyErr_SetString(PyExc_TypeError,
1873 "must use keyword argument for key function");
1874 return NULL;
1875 }
Guido van Rossum4aa24f92000-02-24 15:23:03 +00001876 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001877 if (keyfunc == Py_None)
1878 keyfunc = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001879
Tim Petersb9099c32002-11-12 22:08:10 +00001880 /* The list is temporarily made empty, so that mutations performed
1881 * by comparison functions can't affect the slice of memory we're
1882 * sorting (allowing mutations during sorting is a core-dump
1883 * factory, since ob_item may change).
1884 */
Christian Heimes90aa7642007-12-19 02:45:37 +00001885 saved_ob_size = Py_SIZE(self);
Tim Petersb9099c32002-11-12 22:08:10 +00001886 saved_ob_item = self->ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001887 saved_allocated = self->allocated;
Christian Heimes90aa7642007-12-19 02:45:37 +00001888 Py_SIZE(self) = 0;
Tim Peters51b4ade2004-07-29 04:07:15 +00001889 self->ob_item = NULL;
Armin Rigo93677f02004-07-29 12:40:23 +00001890 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00001891
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001892 if (keyfunc != NULL) {
1893 for (i=0 ; i < saved_ob_size ; i++) {
1894 value = saved_ob_item[i];
Tim Petersb38e2b62004-07-29 02:29:26 +00001895 key = PyObject_CallFunctionObjArgs(keyfunc, value,
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001896 NULL);
1897 if (key == NULL) {
1898 for (i=i-1 ; i>=0 ; i--) {
1899 kvpair = saved_ob_item[i];
1900 value = sortwrapper_getvalue(kvpair);
1901 saved_ob_item[i] = value;
1902 Py_DECREF(kvpair);
1903 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001904 goto dsu_fail;
1905 }
1906 kvpair = build_sortwrapper(key, value);
1907 if (kvpair == NULL)
1908 goto dsu_fail;
1909 saved_ob_item[i] = kvpair;
1910 }
1911 }
1912
1913 /* Reverse sort stability achieved by initially reversing the list,
1914 applying a stable forward sort, then reversing the final result. */
1915 if (reverse && saved_ob_size > 1)
1916 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
1917
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001918 merge_init(&ms);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001919
Tim Petersb9099c32002-11-12 22:08:10 +00001920 nremaining = saved_ob_size;
Tim Petersa64dc242002-08-01 02:13:36 +00001921 if (nremaining < 2)
1922 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00001923
Tim Petersa64dc242002-08-01 02:13:36 +00001924 /* March over the array once, left to right, finding natural runs,
1925 * and extending short natural runs to minrun elements.
1926 */
Tim Petersb9099c32002-11-12 22:08:10 +00001927 lo = saved_ob_item;
Tim Petersa64dc242002-08-01 02:13:36 +00001928 hi = lo + nremaining;
1929 minrun = merge_compute_minrun(nremaining);
1930 do {
1931 int descending;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001932 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00001933
Tim Petersa64dc242002-08-01 02:13:36 +00001934 /* Identify next run. */
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001935 n = count_run(lo, hi, &descending);
Tim Petersa64dc242002-08-01 02:13:36 +00001936 if (n < 0)
1937 goto fail;
1938 if (descending)
1939 reverse_slice(lo, lo + n);
1940 /* If short, extend to min(minrun, nremaining). */
1941 if (n < minrun) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00001942 const Py_ssize_t force = nremaining <= minrun ?
Tim Petersa64dc242002-08-01 02:13:36 +00001943 nremaining : minrun;
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001944 if (binarysort(lo, lo + force, lo + n) < 0)
Tim Petersa64dc242002-08-01 02:13:36 +00001945 goto fail;
1946 n = force;
1947 }
1948 /* Push run onto pending-runs stack, and maybe merge. */
1949 assert(ms.n < MAX_MERGE_PENDING);
Tim Peterse05f65a2002-08-10 05:21:15 +00001950 ms.pending[ms.n].base = lo;
1951 ms.pending[ms.n].len = n;
Tim Petersa64dc242002-08-01 02:13:36 +00001952 ++ms.n;
1953 if (merge_collapse(&ms) < 0)
1954 goto fail;
1955 /* Advance to find next run. */
1956 lo += n;
1957 nremaining -= n;
1958 } while (nremaining);
1959 assert(lo == hi);
Tim Peters330f9e92002-07-19 07:05:44 +00001960
Tim Petersa64dc242002-08-01 02:13:36 +00001961 if (merge_force_collapse(&ms) < 0)
1962 goto fail;
1963 assert(ms.n == 1);
Tim Petersb9099c32002-11-12 22:08:10 +00001964 assert(ms.pending[0].base == saved_ob_item);
1965 assert(ms.pending[0].len == saved_ob_size);
Tim Petersa64dc242002-08-01 02:13:36 +00001966
1967succeed:
1968 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00001969fail:
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001970 if (keyfunc != NULL) {
1971 for (i=0 ; i < saved_ob_size ; i++) {
1972 kvpair = saved_ob_item[i];
1973 value = sortwrapper_getvalue(kvpair);
1974 saved_ob_item[i] = value;
1975 Py_DECREF(kvpair);
1976 }
1977 }
1978
Armin Rigo93677f02004-07-29 12:40:23 +00001979 if (self->allocated != -1 && result != NULL) {
Tim Peters51b4ade2004-07-29 04:07:15 +00001980 /* The user mucked with the list during the sort,
1981 * and we don't already have another error to report.
1982 */
1983 PyErr_SetString(PyExc_ValueError, "list modified during sort");
1984 result = NULL;
Tim Petersb9099c32002-11-12 22:08:10 +00001985 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001986
1987 if (reverse && saved_ob_size > 1)
1988 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
1989
1990 merge_freemem(&ms);
1991
1992dsu_fail:
Armin Rigo93677f02004-07-29 12:40:23 +00001993 final_ob_item = self->ob_item;
Christian Heimes90aa7642007-12-19 02:45:37 +00001994 i = Py_SIZE(self);
1995 Py_SIZE(self) = saved_ob_size;
Tim Petersb9099c32002-11-12 22:08:10 +00001996 self->ob_item = saved_ob_item;
Raymond Hettinger4bb95402004-02-13 11:36:39 +00001997 self->allocated = saved_allocated;
Armin Rigo93677f02004-07-29 12:40:23 +00001998 if (final_ob_item != NULL) {
1999 /* we cannot use list_clear() for this because it does not
2000 guarantee that the list is really empty when it returns */
2001 while (--i >= 0) {
2002 Py_XDECREF(final_ob_item[i]);
2003 }
2004 PyMem_FREE(final_ob_item);
2005 }
Tim Petersa64dc242002-08-01 02:13:36 +00002006 Py_XINCREF(result);
2007 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002008}
Tim Peters330f9e92002-07-19 07:05:44 +00002009#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002010#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002011
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002012int
Fred Drakea2f55112000-07-09 15:16:51 +00002013PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002014{
2015 if (v == NULL || !PyList_Check(v)) {
2016 PyErr_BadInternalCall();
2017 return -1;
2018 }
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002019 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002020 if (v == NULL)
2021 return -1;
2022 Py_DECREF(v);
2023 return 0;
2024}
2025
Guido van Rossumb86c5492001-02-12 22:06:02 +00002026static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002027listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002028{
Christian Heimes90aa7642007-12-19 02:45:37 +00002029 if (Py_SIZE(self) > 1)
2030 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002031 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002032}
2033
Guido van Rossum84c76f51990-10-30 13:32:20 +00002034int
Fred Drakea2f55112000-07-09 15:16:51 +00002035PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002036{
Tim Peters6063e262002-08-08 01:06:39 +00002037 PyListObject *self = (PyListObject *)v;
2038
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002039 if (v == NULL || !PyList_Check(v)) {
2040 PyErr_BadInternalCall();
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002041 return -1;
2042 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002043 if (Py_SIZE(self) > 1)
2044 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002045 return 0;
2046}
2047
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002048PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002049PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002050{
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002051 PyObject *w;
Christian Heimes2c181612007-12-17 20:04:13 +00002052 PyObject **p, **q;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002053 Py_ssize_t n;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002054 if (v == NULL || !PyList_Check(v)) {
2055 PyErr_BadInternalCall();
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002056 return NULL;
2057 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002058 n = Py_SIZE(v);
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002059 w = PyTuple_New(n);
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002060 if (w == NULL)
2061 return NULL;
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002062 p = ((PyTupleObject *)w)->ob_item;
Christian Heimes2c181612007-12-17 20:04:13 +00002063 q = ((PyListObject *)v)->ob_item;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002064 while (--n >= 0) {
Christian Heimes2c181612007-12-17 20:04:13 +00002065 Py_INCREF(*q);
2066 *p = *q;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002067 p++;
Christian Heimes2c181612007-12-17 20:04:13 +00002068 q++;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002069 }
2070 return w;
2071}
2072
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002073static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002074listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002075{
Christian Heimes90aa7642007-12-19 02:45:37 +00002076 Py_ssize_t i, start=0, stop=Py_SIZE(self);
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002077 PyObject *v;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002078
Walter Dörwalde8049bef2003-06-17 19:27:39 +00002079 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2080 _PyEval_SliceIndex, &start,
2081 _PyEval_SliceIndex, &stop))
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002082 return NULL;
Guido van Rossum2743d872003-06-17 14:25:14 +00002083 if (start < 0) {
Christian Heimes90aa7642007-12-19 02:45:37 +00002084 start += Py_SIZE(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002085 if (start < 0)
2086 start = 0;
2087 }
2088 if (stop < 0) {
Christian Heimes90aa7642007-12-19 02:45:37 +00002089 stop += Py_SIZE(self);
Guido van Rossum2743d872003-06-17 14:25:14 +00002090 if (stop < 0)
2091 stop = 0;
2092 }
Christian Heimes90aa7642007-12-19 02:45:37 +00002093 for (i = start; i < stop && i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002094 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2095 if (cmp > 0)
Christian Heimes217cfd12007-12-02 14:31:20 +00002096 return PyLong_FromSsize_t(i);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002097 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002098 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002099 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002100 PyErr_SetString(PyExc_ValueError, "list.index(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002101 return NULL;
2102}
2103
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002104static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002105listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002106{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002107 Py_ssize_t count = 0;
2108 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002109
Christian Heimes90aa7642007-12-19 02:45:37 +00002110 for (i = 0; i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002111 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2112 if (cmp > 0)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002113 count++;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002114 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002115 return NULL;
Guido van Rossume6f7d181991-10-20 20:20:40 +00002116 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002117 return PyLong_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002118}
2119
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002120static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002121listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002122{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002123 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002124
Christian Heimes90aa7642007-12-19 02:45:37 +00002125 for (i = 0; i < Py_SIZE(self); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002126 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2127 if (cmp > 0) {
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002128 if (list_ass_slice(self, i, i+1,
Raymond Hettinger45d0b5c2004-04-12 17:21:03 +00002129 (PyObject *)NULL) == 0)
2130 Py_RETURN_NONE;
2131 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002132 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002133 else if (cmp < 0)
Guido van Rossumc8b6df91997-05-23 00:06:51 +00002134 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002135 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002136 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
Guido van Rossumed98d481991-03-06 13:07:53 +00002137 return NULL;
2138}
2139
Jeremy Hylton8caad492000-06-23 14:18:11 +00002140static int
2141list_traverse(PyListObject *o, visitproc visit, void *arg)
2142{
Martin v. Löwis18e16552006-02-15 17:27:45 +00002143 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002144
Christian Heimes90aa7642007-12-19 02:45:37 +00002145 for (i = Py_SIZE(o); --i >= 0; )
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002146 Py_VISIT(o->ob_item[i]);
Jeremy Hylton8caad492000-06-23 14:18:11 +00002147 return 0;
2148}
2149
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002150static PyObject *
2151list_richcompare(PyObject *v, PyObject *w, int op)
2152{
2153 PyListObject *vl, *wl;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002154 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002155
2156 if (!PyList_Check(v) || !PyList_Check(w)) {
2157 Py_INCREF(Py_NotImplemented);
2158 return Py_NotImplemented;
2159 }
2160
2161 vl = (PyListObject *)v;
2162 wl = (PyListObject *)w;
2163
Christian Heimes90aa7642007-12-19 02:45:37 +00002164 if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002165 /* Shortcut: if the lengths differ, the lists differ */
2166 PyObject *res;
2167 if (op == Py_EQ)
2168 res = Py_False;
2169 else
2170 res = Py_True;
2171 Py_INCREF(res);
2172 return res;
2173 }
2174
2175 /* Search for the first index where items are different */
Christian Heimes90aa7642007-12-19 02:45:37 +00002176 for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002177 int k = PyObject_RichCompareBool(vl->ob_item[i],
2178 wl->ob_item[i], Py_EQ);
2179 if (k < 0)
2180 return NULL;
2181 if (!k)
2182 break;
2183 }
2184
Christian Heimes90aa7642007-12-19 02:45:37 +00002185 if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002186 /* No more items to compare -- compare sizes */
Christian Heimes90aa7642007-12-19 02:45:37 +00002187 Py_ssize_t vs = Py_SIZE(vl);
2188 Py_ssize_t ws = Py_SIZE(wl);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002189 int cmp;
2190 PyObject *res;
2191 switch (op) {
2192 case Py_LT: cmp = vs < ws; break;
Tim Peters6ee42342001-07-06 17:45:43 +00002193 case Py_LE: cmp = vs <= ws; break;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002194 case Py_EQ: cmp = vs == ws; break;
2195 case Py_NE: cmp = vs != ws; break;
2196 case Py_GT: cmp = vs > ws; break;
2197 case Py_GE: cmp = vs >= ws; break;
2198 default: return NULL; /* cannot happen */
2199 }
2200 if (cmp)
2201 res = Py_True;
2202 else
2203 res = Py_False;
2204 Py_INCREF(res);
2205 return res;
2206 }
2207
2208 /* We have an item that differs -- shortcuts for EQ/NE */
2209 if (op == Py_EQ) {
2210 Py_INCREF(Py_False);
2211 return Py_False;
2212 }
2213 if (op == Py_NE) {
2214 Py_INCREF(Py_True);
2215 return Py_True;
2216 }
2217
2218 /* Compare the final item again using the proper operator */
2219 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
2220}
2221
Tim Peters6d6c1a32001-08-02 04:15:00 +00002222static int
2223list_init(PyListObject *self, PyObject *args, PyObject *kw)
2224{
2225 PyObject *arg = NULL;
Martin v. Löwis15e62742006-02-27 16:46:16 +00002226 static char *kwlist[] = {"sequence", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002227
2228 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2229 return -1;
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002230
2231 /* Verify list invariants established by PyType_GenericAlloc() */
Christian Heimes90aa7642007-12-19 02:45:37 +00002232 assert(0 <= Py_SIZE(self));
2233 assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
Armin Rigoa37bbf22004-07-30 11:20:18 +00002234 assert(self->ob_item != NULL ||
2235 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002236
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002237 /* Empty previous contents */
Armin Rigo93677f02004-07-29 12:40:23 +00002238 if (self->ob_item != NULL) {
2239 (void)list_clear(self);
Raymond Hettinger90a39bf2004-02-15 03:57:00 +00002240 }
2241 if (arg != NULL) {
2242 PyObject *rv = listextend(self, arg);
2243 if (rv == NULL)
2244 return -1;
2245 Py_DECREF(rv);
2246 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00002247 return 0;
2248}
2249
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002250static PyObject *
2251list_sizeof(PyListObject *self)
2252{
2253 Py_ssize_t res;
2254
2255 res = sizeof(PyListObject) + self->allocated * sizeof(void*);
2256 return PyLong_FromSsize_t(res);
2257}
2258
Raymond Hettinger1021c442003-11-07 15:38:09 +00002259static PyObject *list_iter(PyObject *seq);
2260static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2261
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002262PyDoc_STRVAR(getitem_doc,
2263"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002264PyDoc_STRVAR(reversed_doc,
2265"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002266PyDoc_STRVAR(sizeof_doc,
2267"L.__sizeof__() -- size of L in memory, in bytes");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002268PyDoc_STRVAR(append_doc,
2269"L.append(object) -- append object to end");
2270PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002271"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002272PyDoc_STRVAR(insert_doc,
2273"L.insert(index, object) -- insert object before index");
2274PyDoc_STRVAR(pop_doc,
2275"L.pop([index]) -> item -- remove and return item at index (default last)");
2276PyDoc_STRVAR(remove_doc,
2277"L.remove(value) -- remove first occurrence of value");
2278PyDoc_STRVAR(index_doc,
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002279"L.index(value, [start, [stop]]) -> integer -- return first index of value");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002280PyDoc_STRVAR(count_doc,
2281"L.count(value) -> integer -- return number of occurrences of value");
2282PyDoc_STRVAR(reverse_doc,
2283"L.reverse() -- reverse *IN PLACE*");
2284PyDoc_STRVAR(sort_doc,
Georg Brandl4a983c52008-03-14 13:28:59 +00002285"L.sort(key=None, reverse=False) -- stable sort *IN PLACE*;\n\
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002286cmp(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002287
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002288static PyObject *list_subscript(PyListObject*, PyObject*);
2289
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002290static PyMethodDef list_methods[] = {
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002291 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
Raymond Hettinger1021c442003-11-07 15:38:09 +00002292 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002293 {"__sizeof__", (PyCFunction)list_sizeof, METH_NOARGS, sizeof_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002294 {"append", (PyCFunction)listappend, METH_O, append_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002295 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002296 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002297 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002298 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002299 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002300 {"count", (PyCFunction)listcount, METH_O, count_doc},
2301 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002302 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
Tim Petersa64dc242002-08-01 02:13:36 +00002303 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002304};
2305
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002306static PySequenceMethods list_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002307 (lenfunc)list_length, /* sq_length */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002308 (binaryfunc)list_concat, /* sq_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002309 (ssizeargfunc)list_repeat, /* sq_repeat */
2310 (ssizeargfunc)list_item, /* sq_item */
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002311 0, /* sq_slice */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002312 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002313 0, /* sq_ass_slice */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002314 (objobjproc)list_contains, /* sq_contains */
2315 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
Martin v. Löwis18e16552006-02-15 17:27:45 +00002316 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002317};
2318
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002319PyDoc_STRVAR(list_doc,
Tim Peters6d6c1a32001-08-02 04:15:00 +00002320"list() -> new list\n"
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002321"list(sequence) -> new list initialized from sequence's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002322
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002323static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002324list_subscript(PyListObject* self, PyObject* item)
2325{
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002326 if (PyIndex_Check(item)) {
2327 Py_ssize_t i;
2328 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002329 if (i == -1 && PyErr_Occurred())
2330 return NULL;
2331 if (i < 0)
2332 i += PyList_GET_SIZE(self);
2333 return list_item(self, i);
2334 }
2335 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002336 Py_ssize_t start, stop, step, slicelength, cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002337 PyObject* result;
2338 PyObject* it;
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002339 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002340
Christian Heimes90aa7642007-12-19 02:45:37 +00002341 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002342 &start, &stop, &step, &slicelength) < 0) {
2343 return NULL;
2344 }
2345
2346 if (slicelength <= 0) {
2347 return PyList_New(0);
2348 }
Thomas Woutersed03b412007-08-28 21:37:11 +00002349 else if (step == 1) {
2350 return list_slice(self, start, stop);
2351 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002352 else {
2353 result = PyList_New(slicelength);
2354 if (!result) return NULL;
2355
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002356 src = self->ob_item;
2357 dest = ((PyListObject *)result)->ob_item;
Tim Peters3b01a122002-07-19 02:35:45 +00002358 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002359 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002360 it = src[cur];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002361 Py_INCREF(it);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002362 dest[i] = it;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002363 }
Tim Peters3b01a122002-07-19 02:35:45 +00002364
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002365 return result;
2366 }
2367 }
2368 else {
Thomas Wouters89f507f2006-12-13 04:49:30 +00002369 PyErr_Format(PyExc_TypeError,
2370 "list indices must be integers, not %.200s",
2371 item->ob_type->tp_name);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002372 return NULL;
2373 }
2374}
2375
Tim Peters3b01a122002-07-19 02:35:45 +00002376static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002377list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2378{
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002379 if (PyIndex_Check(item)) {
2380 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002381 if (i == -1 && PyErr_Occurred())
2382 return -1;
2383 if (i < 0)
2384 i += PyList_GET_SIZE(self);
2385 return list_ass_item(self, i, value);
2386 }
2387 else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002388 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002389
Christian Heimes90aa7642007-12-19 02:45:37 +00002390 if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002391 &start, &stop, &step, &slicelength) < 0) {
2392 return -1;
2393 }
2394
Thomas Woutersed03b412007-08-28 21:37:11 +00002395 if (step == 1)
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002396 return list_ass_slice(self, start, stop, value);
2397
Thomas Woutersed03b412007-08-28 21:37:11 +00002398 /* Make sure s[5:2] = [..] inserts at the right place:
2399 before 5, not before 2. */
2400 if ((step < 0 && start < stop) ||
2401 (step > 0 && start > stop))
2402 stop = start;
2403
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002404 if (value == NULL) {
2405 /* delete slice */
Raymond Hettinger4bb95402004-02-13 11:36:39 +00002406 PyObject **garbage;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002407 Py_ssize_t cur, i;
Tim Peters3b01a122002-07-19 02:35:45 +00002408
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002409 if (slicelength <= 0)
2410 return 0;
2411
2412 if (step < 0) {
2413 stop = start + 1;
2414 start = stop + step*(slicelength - 1) - 1;
2415 step = -step;
2416 }
2417
2418 garbage = (PyObject**)
2419 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002420 if (!garbage) {
2421 PyErr_NoMemory();
2422 return -1;
2423 }
Tim Peters3b01a122002-07-19 02:35:45 +00002424
Thomas Woutersed03b412007-08-28 21:37:11 +00002425 /* drawing pictures might help understand these for
2426 loops. Basically, we memmove the parts of the
2427 list that are *not* part of the slice: step-1
2428 items for each item that is part of the slice,
2429 and then tail end of the list that was not
2430 covered by the slice */
Guido van Rossum75a20b12002-06-11 12:22:28 +00002431 for (cur = start, i = 0;
2432 cur < stop;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002433 cur += step, i++) {
Thomas Woutersed03b412007-08-28 21:37:11 +00002434 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002435
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002436 garbage[i] = PyList_GET_ITEM(self, cur);
2437
Christian Heimes90aa7642007-12-19 02:45:37 +00002438 if (cur + step >= Py_SIZE(self)) {
2439 lim = Py_SIZE(self) - cur - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002440 }
2441
Tim Petersb38e2b62004-07-29 02:29:26 +00002442 memmove(self->ob_item + cur - i,
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002443 self->ob_item + cur + 1,
2444 lim * sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002445 }
Thomas Woutersed03b412007-08-28 21:37:11 +00002446 cur = start + slicelength*step;
Christian Heimes90aa7642007-12-19 02:45:37 +00002447 if (cur < Py_SIZE(self)) {
Thomas Woutersed03b412007-08-28 21:37:11 +00002448 memmove(self->ob_item + cur - slicelength,
2449 self->ob_item + cur,
Christian Heimes90aa7642007-12-19 02:45:37 +00002450 (Py_SIZE(self) - cur) *
Thomas Woutersed03b412007-08-28 21:37:11 +00002451 sizeof(PyObject *));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002452 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002453
Christian Heimes90aa7642007-12-19 02:45:37 +00002454 Py_SIZE(self) -= slicelength;
2455 list_resize(self, Py_SIZE(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002456
2457 for (i = 0; i < slicelength; i++) {
2458 Py_DECREF(garbage[i]);
2459 }
2460 PyMem_FREE(garbage);
2461
2462 return 0;
2463 }
2464 else {
2465 /* assign slice */
Thomas Woutersed03b412007-08-28 21:37:11 +00002466 PyObject *ins, *seq;
2467 PyObject **garbage, **seqitems, **selfitems;
Martin v. Löwis18e16552006-02-15 17:27:45 +00002468 Py_ssize_t cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002469
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002470 /* protect against a[::-1] = a */
Tim Peters3b01a122002-07-19 02:35:45 +00002471 if (self == (PyListObject*)value) {
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002472 seq = list_slice((PyListObject*)value, 0,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002473 PyList_GET_SIZE(value));
Tim Peters3b01a122002-07-19 02:35:45 +00002474 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002475 else {
Tim Petersb38e2b62004-07-29 02:29:26 +00002476 seq = PySequence_Fast(value,
Thomas Woutersed03b412007-08-28 21:37:11 +00002477 "must assign iterable "
2478 "to extended slice");
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002479 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002480 if (!seq)
2481 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002482
2483 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2484 PyErr_Format(PyExc_ValueError,
Thomas Woutersed03b412007-08-28 21:37:11 +00002485 "attempt to assign sequence of "
2486 "size %zd to extended slice of "
2487 "size %zd",
Martin v. Löwise0e89f72006-02-16 06:59:22 +00002488 PySequence_Fast_GET_SIZE(seq),
2489 slicelength);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002490 Py_DECREF(seq);
2491 return -1;
2492 }
2493
2494 if (!slicelength) {
2495 Py_DECREF(seq);
2496 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002497 }
2498
2499 garbage = (PyObject**)
2500 PyMem_MALLOC(slicelength*sizeof(PyObject*));
Thomas Wouters89f507f2006-12-13 04:49:30 +00002501 if (!garbage) {
2502 Py_DECREF(seq);
2503 PyErr_NoMemory();
2504 return -1;
2505 }
Tim Peters3b01a122002-07-19 02:35:45 +00002506
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002507 selfitems = self->ob_item;
Raymond Hettinger42bec932004-03-12 16:38:17 +00002508 seqitems = PySequence_Fast_ITEMS(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002509 for (cur = start, i = 0; i < slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002510 cur += step, i++) {
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002511 garbage[i] = selfitems[cur];
2512 ins = seqitems[i];
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002513 Py_INCREF(ins);
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002514 selfitems[cur] = ins;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002515 }
2516
2517 for (i = 0; i < slicelength; i++) {
2518 Py_DECREF(garbage[i]);
2519 }
Tim Peters3b01a122002-07-19 02:35:45 +00002520
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002521 PyMem_FREE(garbage);
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002522 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002523
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002524 return 0;
2525 }
Tim Peters3b01a122002-07-19 02:35:45 +00002526 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002527 else {
Thomas Wouters89f507f2006-12-13 04:49: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 -1;
2532 }
2533}
2534
2535static PyMappingMethods list_as_mapping = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002536 (lenfunc)list_length,
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002537 (binaryfunc)list_subscript,
2538 (objobjargproc)list_ass_subscript
2539};
2540
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002541PyTypeObject PyList_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002542 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002543 "list",
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002544 sizeof(PyListObject),
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002545 0,
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002546 (destructor)list_dealloc, /* tp_dealloc */
Guido van Rossum04dbf3b2007-08-07 19:51:00 +00002547 0, /* tp_print */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002548 0, /* tp_getattr */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002549 0, /* tp_setattr */
2550 0, /* tp_compare */
2551 (reprfunc)list_repr, /* tp_repr */
2552 0, /* tp_as_number */
2553 &list_as_sequence, /* tp_as_sequence */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002554 &list_as_mapping, /* tp_as_mapping */
Guido van Rossum50e9fb92006-08-17 05:42:55 +00002555 0, /* tp_hash */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002556 0, /* tp_call */
2557 0, /* tp_str */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002558 PyObject_GenericGetAttr, /* tp_getattro */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002559 0, /* tp_setattro */
2560 0, /* tp_as_buffer */
Neil Schemenauere83c00e2001-08-29 23:54:21 +00002561 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Thomas Wouters27d517b2007-02-25 20:39:11 +00002562 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002563 list_doc, /* tp_doc */
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002564 (traverseproc)list_traverse, /* tp_traverse */
2565 (inquiry)list_clear, /* tp_clear */
2566 list_richcompare, /* tp_richcompare */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002567 0, /* tp_weaklistoffset */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002568 list_iter, /* tp_iter */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002569 0, /* tp_iternext */
2570 list_methods, /* tp_methods */
2571 0, /* tp_members */
2572 0, /* tp_getset */
2573 0, /* tp_base */
2574 0, /* tp_dict */
2575 0, /* tp_descr_get */
2576 0, /* tp_descr_set */
2577 0, /* tp_dictoffset */
2578 (initproc)list_init, /* tp_init */
2579 PyType_GenericAlloc, /* tp_alloc */
2580 PyType_GenericNew, /* tp_new */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002581 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002582};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002583
2584
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002585/*********************** List Iterator **************************/
2586
2587typedef struct {
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002588 PyObject_HEAD
2589 long it_index;
Guido van Rossum86103ae2002-07-16 20:07:32 +00002590 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002591} listiterobject;
2592
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002593static PyObject *list_iter(PyObject *);
2594static void listiter_dealloc(listiterobject *);
2595static int listiter_traverse(listiterobject *, visitproc, void *);
2596static PyObject *listiter_next(listiterobject *);
2597static PyObject *listiter_len(listiterobject *);
Raymond Hettinger435bf582004-03-18 22:43:10 +00002598
Armin Rigof5b3e362006-02-11 21:32:43 +00002599PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002600
2601static PyMethodDef listiter_methods[] = {
Armin Rigof5b3e362006-02-11 21:32:43 +00002602 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002603 {NULL, NULL} /* sentinel */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002604};
2605
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002606PyTypeObject PyListIter_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002607 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Christian Heimesf83be4e2007-11-28 09:44:38 +00002608 "list_iterator", /* tp_name */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002609 sizeof(listiterobject), /* tp_basicsize */
2610 0, /* tp_itemsize */
2611 /* methods */
2612 (destructor)listiter_dealloc, /* tp_dealloc */
2613 0, /* tp_print */
2614 0, /* tp_getattr */
2615 0, /* tp_setattr */
2616 0, /* tp_compare */
2617 0, /* tp_repr */
2618 0, /* tp_as_number */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002619 0, /* tp_as_sequence */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002620 0, /* tp_as_mapping */
2621 0, /* tp_hash */
2622 0, /* tp_call */
2623 0, /* tp_str */
2624 PyObject_GenericGetAttr, /* tp_getattro */
2625 0, /* tp_setattro */
2626 0, /* tp_as_buffer */
2627 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2628 0, /* tp_doc */
2629 (traverseproc)listiter_traverse, /* tp_traverse */
2630 0, /* tp_clear */
2631 0, /* tp_richcompare */
2632 0, /* tp_weaklistoffset */
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +00002633 PyObject_SelfIter, /* tp_iter */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002634 (iternextfunc)listiter_next, /* tp_iternext */
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002635 listiter_methods, /* tp_methods */
Guido van Rossum6b6272c2002-07-16 20:10:23 +00002636 0, /* tp_members */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002637};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002638
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002639
2640static PyObject *
2641list_iter(PyObject *seq)
2642{
2643 listiterobject *it;
2644
2645 if (!PyList_Check(seq)) {
2646 PyErr_BadInternalCall();
2647 return NULL;
2648 }
2649 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2650 if (it == NULL)
2651 return NULL;
2652 it->it_index = 0;
2653 Py_INCREF(seq);
2654 it->it_seq = (PyListObject *)seq;
2655 _PyObject_GC_TRACK(it);
2656 return (PyObject *)it;
2657}
2658
2659static void
2660listiter_dealloc(listiterobject *it)
2661{
2662 _PyObject_GC_UNTRACK(it);
2663 Py_XDECREF(it->it_seq);
2664 PyObject_GC_Del(it);
2665}
2666
2667static int
2668listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2669{
2670 Py_VISIT(it->it_seq);
2671 return 0;
2672}
2673
2674static PyObject *
2675listiter_next(listiterobject *it)
2676{
2677 PyListObject *seq;
2678 PyObject *item;
2679
2680 assert(it != NULL);
2681 seq = it->it_seq;
2682 if (seq == NULL)
2683 return NULL;
2684 assert(PyList_Check(seq));
2685
2686 if (it->it_index < PyList_GET_SIZE(seq)) {
2687 item = PyList_GET_ITEM(seq, it->it_index);
2688 ++it->it_index;
2689 Py_INCREF(item);
2690 return item;
2691 }
2692
2693 Py_DECREF(seq);
2694 it->it_seq = NULL;
2695 return NULL;
2696}
2697
2698static PyObject *
2699listiter_len(listiterobject *it)
2700{
2701 Py_ssize_t len;
2702 if (it->it_seq) {
2703 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2704 if (len >= 0)
Christian Heimes217cfd12007-12-02 14:31:20 +00002705 return PyLong_FromSsize_t(len);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002706 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002707 return PyLong_FromLong(0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002708}
Raymond Hettinger1021c442003-11-07 15:38:09 +00002709/*********************** List Reverse Iterator **************************/
2710
2711typedef struct {
2712 PyObject_HEAD
Martin v. Löwiseb079f12006-02-16 14:32:27 +00002713 Py_ssize_t it_index;
Raymond Hettinger001f2282003-11-08 11:58:44 +00002714 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002715} listreviterobject;
2716
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002717static PyObject *list_reversed(PyListObject *, PyObject *);
2718static void listreviter_dealloc(listreviterobject *);
2719static int listreviter_traverse(listreviterobject *, visitproc, void *);
2720static PyObject *listreviter_next(listreviterobject *);
2721static Py_ssize_t listreviter_len(listreviterobject *);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002722
2723static PySequenceMethods listreviter_as_sequence = {
Martin v. Löwis18e16552006-02-15 17:27:45 +00002724 (lenfunc)listreviter_len, /* sq_length */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002725 0, /* sq_concat */
2726};
2727
Raymond Hettinger1021c442003-11-07 15:38:09 +00002728PyTypeObject PyListRevIter_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002729 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Christian Heimesf83be4e2007-11-28 09:44:38 +00002730 "list_reverseiterator", /* tp_name */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002731 sizeof(listreviterobject), /* tp_basicsize */
2732 0, /* tp_itemsize */
2733 /* methods */
2734 (destructor)listreviter_dealloc, /* tp_dealloc */
2735 0, /* tp_print */
2736 0, /* tp_getattr */
2737 0, /* tp_setattr */
2738 0, /* tp_compare */
2739 0, /* tp_repr */
2740 0, /* tp_as_number */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002741 &listreviter_as_sequence, /* tp_as_sequence */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002742 0, /* tp_as_mapping */
2743 0, /* tp_hash */
2744 0, /* tp_call */
2745 0, /* tp_str */
2746 PyObject_GenericGetAttr, /* tp_getattro */
2747 0, /* tp_setattro */
2748 0, /* tp_as_buffer */
2749 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2750 0, /* tp_doc */
2751 (traverseproc)listreviter_traverse, /* tp_traverse */
2752 0, /* tp_clear */
2753 0, /* tp_richcompare */
2754 0, /* tp_weaklistoffset */
2755 PyObject_SelfIter, /* tp_iter */
2756 (iternextfunc)listreviter_next, /* tp_iternext */
2757 0,
2758};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002759
2760static PyObject *
2761list_reversed(PyListObject *seq, PyObject *unused)
2762{
2763 listreviterobject *it;
2764
2765 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2766 if (it == NULL)
2767 return NULL;
2768 assert(PyList_Check(seq));
2769 it->it_index = PyList_GET_SIZE(seq) - 1;
2770 Py_INCREF(seq);
2771 it->it_seq = seq;
2772 PyObject_GC_Track(it);
2773 return (PyObject *)it;
2774}
2775
2776static void
2777listreviter_dealloc(listreviterobject *it)
2778{
2779 PyObject_GC_UnTrack(it);
2780 Py_XDECREF(it->it_seq);
2781 PyObject_GC_Del(it);
2782}
2783
2784static int
2785listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2786{
2787 Py_VISIT(it->it_seq);
2788 return 0;
2789}
2790
2791static PyObject *
2792listreviter_next(listreviterobject *it)
2793{
2794 PyObject *item;
2795 Py_ssize_t index = it->it_index;
2796 PyListObject *seq = it->it_seq;
2797
2798 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2799 item = PyList_GET_ITEM(seq, index);
2800 it->it_index--;
2801 Py_INCREF(item);
2802 return item;
2803 }
2804 it->it_index = -1;
2805 if (seq != NULL) {
2806 it->it_seq = NULL;
2807 Py_DECREF(seq);
2808 }
2809 return NULL;
2810}
2811
2812static Py_ssize_t
2813listreviter_len(listreviterobject *it)
2814{
2815 Py_ssize_t len = it->it_index + 1;
2816 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
2817 return 0;
2818 return len;
2819}
2820