blob: 00de597e5686221b25563cbf51d05be87a9bb22f [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
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00008#include <sys/types.h> /* For size_t */
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00009#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
Ezio Melotti13925002011-03-16 11:05:33 +020014 * responsibility to overwrite them with sane values.
Tim Peters8d9eb102004-07-31 02:24:20 +000015 * 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{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000027 PyObject **items;
28 size_t new_allocated;
29 Py_ssize_t allocated = self->allocated;
Tim Peters65b8b842001-05-26 05:28:40 +000030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000031 /* Bypass realloc() when a previous overallocation is large enough
32 to accommodate the newsize. If the newsize falls lower than half
33 the allocated size, then proceed with the realloc() to shrink the list.
34 */
35 if (allocated >= newsize && newsize >= (allocated >> 1)) {
36 assert(self->ob_item != NULL || newsize == 0);
37 Py_SIZE(self) = newsize;
38 return 0;
39 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +000040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000041 /* This over-allocates proportional to the list size, making room
42 * 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
45 * system realloc().
46 * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
47 */
48 new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +000049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000050 /* check for integer overflow */
51 if (new_allocated > PY_SIZE_MAX - newsize) {
52 PyErr_NoMemory();
53 return -1;
54 } else {
55 new_allocated += newsize;
56 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +000057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 if (newsize == 0)
59 new_allocated = 0;
60 items = self->ob_item;
Mark Dickinsonc0420fd2011-09-19 19:18:37 +010061 if (new_allocated <= (PY_SIZE_MAX / sizeof(PyObject *)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000062 PyMem_RESIZE(items, PyObject *, new_allocated);
63 else
64 items = NULL;
65 if (items == NULL) {
66 PyErr_NoMemory();
67 return -1;
68 }
69 self->ob_item = items;
70 Py_SIZE(self) = newsize;
71 self->allocated = new_allocated;
72 return 0;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000073}
Guido van Rossuma46d51d1995-01-26 22:59:43 +000074
Christian Heimes77c02eb2008-02-09 02:18:51 +000075/* Debug statistic to compare allocations with reuse through the free list */
76#undef SHOW_ALLOC_COUNT
77#ifdef SHOW_ALLOC_COUNT
78static size_t count_alloc = 0;
79static size_t count_reuse = 0;
80
81static void
82show_alloc(void)
83{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000084 fprintf(stderr, "List allocations: %" PY_FORMAT_SIZE_T "d\n",
85 count_alloc);
86 fprintf(stderr, "List reuse through freelist: %" PY_FORMAT_SIZE_T
87 "d\n", count_reuse);
88 fprintf(stderr, "%.2f%% reuse rate\n\n",
89 (100.0*count_reuse/(count_alloc+count_reuse)));
Christian Heimes77c02eb2008-02-09 02:18:51 +000090}
91#endif
92
Raymond Hettinger0468e412004-05-05 05:37:53 +000093/* Empty list reuse scheme to save calls to malloc and free */
Christian Heimes2202f872008-02-06 14:31:34 +000094#ifndef PyList_MAXFREELIST
95#define PyList_MAXFREELIST 80
96#endif
97static PyListObject *free_list[PyList_MAXFREELIST];
98static int numfree = 0;
Raymond Hettinger0468e412004-05-05 05:37:53 +000099
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000100void
101PyList_Fini(void)
102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 PyListObject *op;
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 while (numfree) {
106 op = free_list[--numfree];
107 assert(PyList_CheckExact(op));
108 PyObject_GC_Del(op);
109 }
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000110}
111
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000112PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000113PyList_New(Py_ssize_t size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000114{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 PyListObject *op;
116 size_t nbytes;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000117#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 static int initialized = 0;
119 if (!initialized) {
120 Py_AtExit(show_alloc);
121 initialized = 1;
122 }
Christian Heimes77c02eb2008-02-09 02:18:51 +0000123#endif
Tim Peters3986d4e2004-07-29 02:28:42 +0000124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 if (size < 0) {
126 PyErr_BadInternalCall();
127 return NULL;
128 }
129 /* Check for overflow without an actual overflow,
130 * which can cause compiler to optimise out */
131 if ((size_t)size > PY_SIZE_MAX / sizeof(PyObject *))
132 return PyErr_NoMemory();
133 nbytes = size * sizeof(PyObject *);
134 if (numfree) {
135 numfree--;
136 op = free_list[numfree];
137 _Py_NewReference((PyObject *)op);
Christian Heimes77c02eb2008-02-09 02:18:51 +0000138#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 count_reuse++;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000140#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 } else {
142 op = PyObject_GC_New(PyListObject, &PyList_Type);
143 if (op == NULL)
144 return NULL;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000145#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000146 count_alloc++;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000147#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 }
149 if (size <= 0)
150 op->ob_item = NULL;
151 else {
152 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
153 if (op->ob_item == NULL) {
154 Py_DECREF(op);
155 return PyErr_NoMemory();
156 }
157 memset(op->ob_item, 0, nbytes);
158 }
159 Py_SIZE(op) = size;
160 op->allocated = size;
161 _PyObject_GC_TRACK(op);
162 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000163}
164
Martin v. Löwis18e16552006-02-15 17:27:45 +0000165Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000166PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000167{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 if (!PyList_Check(op)) {
169 PyErr_BadInternalCall();
170 return -1;
171 }
172 else
173 return Py_SIZE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000174}
175
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000176static PyObject *indexerr = NULL;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000177
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000178PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000179PyList_GetItem(PyObject *op, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 if (!PyList_Check(op)) {
182 PyErr_BadInternalCall();
183 return NULL;
184 }
185 if (i < 0 || i >= Py_SIZE(op)) {
186 if (indexerr == NULL) {
187 indexerr = PyUnicode_FromString(
188 "list index out of range");
189 if (indexerr == NULL)
190 return NULL;
191 }
192 PyErr_SetObject(PyExc_IndexError, indexerr);
193 return NULL;
194 }
195 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000196}
197
198int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000199PyList_SetItem(register PyObject *op, register Py_ssize_t i,
Fred Drakea2f55112000-07-09 15:16:51 +0000200 register PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 register PyObject *olditem;
203 register PyObject **p;
204 if (!PyList_Check(op)) {
205 Py_XDECREF(newitem);
206 PyErr_BadInternalCall();
207 return -1;
208 }
209 if (i < 0 || i >= Py_SIZE(op)) {
210 Py_XDECREF(newitem);
211 PyErr_SetString(PyExc_IndexError,
212 "list assignment index out of range");
213 return -1;
214 }
215 p = ((PyListObject *)op) -> ob_item + i;
216 olditem = *p;
217 *p = newitem;
218 Py_XDECREF(olditem);
219 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000220}
221
222static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000223ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 Py_ssize_t i, n = Py_SIZE(self);
226 PyObject **items;
227 if (v == NULL) {
228 PyErr_BadInternalCall();
229 return -1;
230 }
231 if (n == PY_SSIZE_T_MAX) {
232 PyErr_SetString(PyExc_OverflowError,
233 "cannot add more objects to list");
234 return -1;
235 }
Tim Petersb38e2b62004-07-29 02:29:26 +0000236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 if (list_resize(self, n+1) == -1)
238 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 if (where < 0) {
241 where += n;
242 if (where < 0)
243 where = 0;
244 }
245 if (where > n)
246 where = n;
247 items = self->ob_item;
248 for (i = n; --i >= where; )
249 items[i+1] = items[i];
250 Py_INCREF(v);
251 items[where] = v;
252 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000253}
254
255int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000256PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 if (!PyList_Check(op)) {
259 PyErr_BadInternalCall();
260 return -1;
261 }
262 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000263}
264
Raymond Hettinger40a03822004-04-12 13:05:09 +0000265static int
266app1(PyListObject *self, PyObject *v)
267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 Py_ssize_t n = PyList_GET_SIZE(self);
Raymond Hettinger40a03822004-04-12 13:05:09 +0000269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 assert (v != NULL);
271 if (n == PY_SSIZE_T_MAX) {
272 PyErr_SetString(PyExc_OverflowError,
273 "cannot add more objects to list");
274 return -1;
275 }
Raymond Hettinger40a03822004-04-12 13:05:09 +0000276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 if (list_resize(self, n+1) == -1)
278 return -1;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 Py_INCREF(v);
281 PyList_SET_ITEM(self, n, v);
282 return 0;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000283}
284
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000285int
Fred Drakea2f55112000-07-09 15:16:51 +0000286PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 if (PyList_Check(op) && (newitem != NULL))
289 return app1((PyListObject *)op, newitem);
290 PyErr_BadInternalCall();
291 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000292}
293
294/* Methods */
295
296static void
Fred Drakea2f55112000-07-09 15:16:51 +0000297list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 Py_ssize_t i;
300 PyObject_GC_UnTrack(op);
301 Py_TRASHCAN_SAFE_BEGIN(op)
302 if (op->ob_item != NULL) {
303 /* Do it backwards, for Christian Tismer.
304 There's a simple test case where somehow this reduces
305 thrashing when a *very* large list is created and
306 immediately deleted. */
307 i = Py_SIZE(op);
308 while (--i >= 0) {
309 Py_XDECREF(op->ob_item[i]);
310 }
311 PyMem_FREE(op->ob_item);
312 }
313 if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op))
314 free_list[numfree++] = op;
315 else
316 Py_TYPE(op)->tp_free((PyObject *)op);
317 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000318}
319
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000320static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000321list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 Py_ssize_t i;
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200324 PyObject *s = NULL;
325 _PyAccu acc;
326 static PyObject *sep = NULL;
327
328 if (Py_SIZE(v) == 0) {
329 return PyUnicode_FromString("[]");
330 }
331
332 if (sep == NULL) {
333 sep = PyUnicode_FromString(", ");
334 if (sep == NULL)
335 return NULL;
336 }
Guido van Rossumfb376de1998-04-10 22:47:27 +0000337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 i = Py_ReprEnter((PyObject*)v);
339 if (i != 0) {
340 return i > 0 ? PyUnicode_FromString("[...]") : NULL;
341 }
Tim Petersa7259592001-06-16 05:11:17 +0000342
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200343 if (_PyAccu_Init(&acc))
344 goto error;
Tim Petersa7259592001-06-16 05:11:17 +0000345
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200346 s = PyUnicode_FromString("[");
347 if (s == NULL || _PyAccu_Accumulate(&acc, s))
348 goto error;
349 Py_CLEAR(s);
Tim Petersa7259592001-06-16 05:11:17 +0000350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 /* Do repr() on each element. Note that this may mutate the list,
352 so must refetch the list size on each iteration. */
353 for (i = 0; i < Py_SIZE(v); ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 if (Py_EnterRecursiveCall(" while getting the repr of a list"))
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200355 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 s = PyObject_Repr(v->ob_item[i]);
357 Py_LeaveRecursiveCall();
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200358 if (i > 0 && _PyAccu_Accumulate(&acc, sep))
359 goto error;
360 if (s == NULL || _PyAccu_Accumulate(&acc, s))
361 goto error;
362 Py_CLEAR(s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 s = PyUnicode_FromString("]");
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200365 if (s == NULL || _PyAccu_Accumulate(&acc, s))
366 goto error;
367 Py_CLEAR(s);
Tim Petersa7259592001-06-16 05:11:17 +0000368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 Py_ReprLeave((PyObject *)v);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200370 return _PyAccu_Finish(&acc);
371
372error:
373 _PyAccu_Destroy(&acc);
374 Py_XDECREF(s);
375 Py_ReprLeave((PyObject *)v);
376 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000377}
378
Martin v. Löwis18e16552006-02-15 17:27:45 +0000379static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000380list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 return Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000383}
384
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000385static int
Fred Drakea2f55112000-07-09 15:16:51 +0000386list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000387{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 Py_ssize_t i;
389 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
392 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
393 Py_EQ);
394 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000395}
396
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000397static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000398list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 if (i < 0 || i >= Py_SIZE(a)) {
401 if (indexerr == NULL) {
402 indexerr = PyUnicode_FromString(
403 "list index out of range");
404 if (indexerr == NULL)
405 return NULL;
406 }
407 PyErr_SetObject(PyExc_IndexError, indexerr);
408 return NULL;
409 }
410 Py_INCREF(a->ob_item[i]);
411 return a->ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000412}
413
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000414static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000415list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 PyListObject *np;
418 PyObject **src, **dest;
419 Py_ssize_t i, len;
420 if (ilow < 0)
421 ilow = 0;
422 else if (ilow > Py_SIZE(a))
423 ilow = Py_SIZE(a);
424 if (ihigh < ilow)
425 ihigh = ilow;
426 else if (ihigh > Py_SIZE(a))
427 ihigh = Py_SIZE(a);
428 len = ihigh - ilow;
429 np = (PyListObject *) PyList_New(len);
430 if (np == NULL)
431 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 src = a->ob_item + ilow;
434 dest = np->ob_item;
435 for (i = 0; i < len; i++) {
436 PyObject *v = src[i];
437 Py_INCREF(v);
438 dest[i] = v;
439 }
440 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000441}
442
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000443PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000444PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 if (!PyList_Check(a)) {
447 PyErr_BadInternalCall();
448 return NULL;
449 }
450 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000451}
452
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000453static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000454list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 Py_ssize_t size;
457 Py_ssize_t i;
458 PyObject **src, **dest;
459 PyListObject *np;
460 if (!PyList_Check(bb)) {
461 PyErr_Format(PyExc_TypeError,
462 "can only concatenate list (not \"%.200s\") to list",
463 bb->ob_type->tp_name);
464 return NULL;
465 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000466#define b ((PyListObject *)bb)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 size = Py_SIZE(a) + Py_SIZE(b);
468 if (size < 0)
469 return PyErr_NoMemory();
470 np = (PyListObject *) PyList_New(size);
471 if (np == NULL) {
472 return NULL;
473 }
474 src = a->ob_item;
475 dest = np->ob_item;
476 for (i = 0; i < Py_SIZE(a); i++) {
477 PyObject *v = src[i];
478 Py_INCREF(v);
479 dest[i] = v;
480 }
481 src = b->ob_item;
482 dest = np->ob_item + Py_SIZE(a);
483 for (i = 0; i < Py_SIZE(b); i++) {
484 PyObject *v = src[i];
485 Py_INCREF(v);
486 dest[i] = v;
487 }
488 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000489#undef b
490}
491
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000492static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000493list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000494{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 Py_ssize_t i, j;
496 Py_ssize_t size;
497 PyListObject *np;
498 PyObject **p, **items;
499 PyObject *elem;
500 if (n < 0)
501 n = 0;
Mark Dickinsonc0420fd2011-09-19 19:18:37 +0100502 if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 return PyErr_NoMemory();
Mark Dickinsonc0420fd2011-09-19 19:18:37 +0100504 size = Py_SIZE(a) * n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 if (size == 0)
506 return PyList_New(0);
507 np = (PyListObject *) PyList_New(size);
508 if (np == NULL)
509 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 items = np->ob_item;
512 if (Py_SIZE(a) == 1) {
513 elem = a->ob_item[0];
514 for (i = 0; i < n; i++) {
515 items[i] = elem;
516 Py_INCREF(elem);
517 }
518 return (PyObject *) np;
519 }
520 p = np->ob_item;
521 items = a->ob_item;
522 for (i = 0; i < n; i++) {
523 for (j = 0; j < Py_SIZE(a); j++) {
524 *p = items[j];
525 Py_INCREF(*p);
526 p++;
527 }
528 }
529 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000530}
531
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000532static int
Armin Rigo93677f02004-07-29 12:40:23 +0000533list_clear(PyListObject *a)
534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 Py_ssize_t i;
536 PyObject **item = a->ob_item;
537 if (item != NULL) {
538 /* Because XDECREF can recursively invoke operations on
539 this list, we make it empty first. */
540 i = Py_SIZE(a);
541 Py_SIZE(a) = 0;
542 a->ob_item = NULL;
543 a->allocated = 0;
544 while (--i >= 0) {
545 Py_XDECREF(item[i]);
546 }
547 PyMem_FREE(item);
548 }
549 /* Never fails; the return value can be ignored.
550 Note that there is no guarantee that the list is actually empty
551 at this point, because XDECREF may have populated it again! */
552 return 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000553}
554
Tim Peters8fc4a912004-07-31 21:53:19 +0000555/* a[ilow:ihigh] = v if v != NULL.
556 * del a[ilow:ihigh] if v == NULL.
557 *
558 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
559 * guaranteed the call cannot fail.
560 */
Armin Rigo93677f02004-07-29 12:40:23 +0000561static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000562list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000563{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 /* Because [X]DECREF can recursively invoke list operations on
565 this list, we must postpone all [X]DECREF activity until
566 after the list is back in its canonical shape. Therefore
567 we must allocate an additional array, 'recycle', into which
568 we temporarily copy the items that are deleted from the
569 list. :-( */
570 PyObject *recycle_on_stack[8];
571 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
572 PyObject **item;
573 PyObject **vitem = NULL;
574 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
575 Py_ssize_t n; /* # of elements in replacement list */
576 Py_ssize_t norig; /* # of elements in list getting replaced */
577 Py_ssize_t d; /* Change in size */
578 Py_ssize_t k;
579 size_t s;
580 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000581#define b ((PyListObject *)v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 if (v == NULL)
583 n = 0;
584 else {
585 if (a == b) {
586 /* Special case "a[i:j] = a" -- copy b first */
587 v = list_slice(b, 0, Py_SIZE(b));
588 if (v == NULL)
589 return result;
590 result = list_ass_slice(a, ilow, ihigh, v);
591 Py_DECREF(v);
592 return result;
593 }
594 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
595 if(v_as_SF == NULL)
596 goto Error;
597 n = PySequence_Fast_GET_SIZE(v_as_SF);
598 vitem = PySequence_Fast_ITEMS(v_as_SF);
599 }
600 if (ilow < 0)
601 ilow = 0;
602 else if (ilow > Py_SIZE(a))
603 ilow = Py_SIZE(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 if (ihigh < ilow)
606 ihigh = ilow;
607 else if (ihigh > Py_SIZE(a))
608 ihigh = Py_SIZE(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 norig = ihigh - ilow;
611 assert(norig >= 0);
612 d = n - norig;
613 if (Py_SIZE(a) + d == 0) {
614 Py_XDECREF(v_as_SF);
615 return list_clear(a);
616 }
617 item = a->ob_item;
618 /* recycle the items that we are about to remove */
619 s = norig * sizeof(PyObject *);
620 if (s > sizeof(recycle_on_stack)) {
621 recycle = (PyObject **)PyMem_MALLOC(s);
622 if (recycle == NULL) {
623 PyErr_NoMemory();
624 goto Error;
625 }
626 }
627 memcpy(recycle, &item[ilow], s);
Tim Peters8d9eb102004-07-31 02:24:20 +0000628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 if (d < 0) { /* Delete -d items */
630 memmove(&item[ihigh+d], &item[ihigh],
631 (Py_SIZE(a) - ihigh)*sizeof(PyObject *));
632 list_resize(a, Py_SIZE(a) + d);
633 item = a->ob_item;
634 }
635 else if (d > 0) { /* Insert d items */
636 k = Py_SIZE(a);
637 if (list_resize(a, k+d) < 0)
638 goto Error;
639 item = a->ob_item;
640 memmove(&item[ihigh+d], &item[ihigh],
641 (k - ihigh)*sizeof(PyObject *));
642 }
643 for (k = 0; k < n; k++, ilow++) {
644 PyObject *w = vitem[k];
645 Py_XINCREF(w);
646 item[ilow] = w;
647 }
648 for (k = norig - 1; k >= 0; --k)
649 Py_XDECREF(recycle[k]);
650 result = 0;
Tim Peters8d9eb102004-07-31 02:24:20 +0000651 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 if (recycle != recycle_on_stack)
653 PyMem_FREE(recycle);
654 Py_XDECREF(v_as_SF);
655 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000656#undef b
657}
658
Guido van Rossum234f9421993-06-17 12:35:49 +0000659int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000660PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000661{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 if (!PyList_Check(a)) {
663 PyErr_BadInternalCall();
664 return -1;
665 }
666 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000667}
668
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000669static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000670list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 PyObject **items;
673 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000674
675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 size = PyList_GET_SIZE(self);
677 if (size == 0 || n == 1) {
678 Py_INCREF(self);
679 return (PyObject *)self;
680 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 if (n < 1) {
683 (void)list_clear(self);
684 Py_INCREF(self);
685 return (PyObject *)self;
686 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 if (size > PY_SSIZE_T_MAX / n) {
689 return PyErr_NoMemory();
690 }
Christian Heimesaf98da12008-01-27 15:18:18 +0000691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 if (list_resize(self, size*n) == -1)
693 return NULL;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 p = size;
696 items = self->ob_item;
697 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
698 for (j = 0; j < size; j++) {
699 PyObject *o = items[j];
700 Py_INCREF(o);
701 items[p++] = o;
702 }
703 }
704 Py_INCREF(self);
705 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000706}
707
Guido van Rossum4a450d01991-04-03 19:05:18 +0000708static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000709list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 PyObject *old_value;
712 if (i < 0 || i >= Py_SIZE(a)) {
713 PyErr_SetString(PyExc_IndexError,
714 "list assignment index out of range");
715 return -1;
716 }
717 if (v == NULL)
718 return list_ass_slice(a, i, i+1, v);
719 Py_INCREF(v);
720 old_value = a->ob_item[i];
721 a->ob_item[i] = v;
722 Py_DECREF(old_value);
723 return 0;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000724}
725
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000726static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000727listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 Py_ssize_t i;
730 PyObject *v;
731 if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
732 return NULL;
733 if (ins1(self, i, v) == 0)
734 Py_RETURN_NONE;
735 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000736}
737
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000738static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000739listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 if (app1(self, v) == 0)
742 Py_RETURN_NONE;
743 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000744}
745
Barry Warsawdedf6d61998-10-09 16:37:25 +0000746static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000747listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000748{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 PyObject *it; /* iter(v) */
750 Py_ssize_t m; /* size of self */
751 Py_ssize_t n; /* guess for size of b */
752 Py_ssize_t mn; /* m + n */
753 Py_ssize_t i;
754 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 /* Special cases:
757 1) lists and tuples which can use PySequence_Fast ops
758 2) extending self to self requires making a copy first
759 */
760 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
761 PyObject **src, **dest;
762 b = PySequence_Fast(b, "argument must be iterable");
763 if (!b)
764 return NULL;
765 n = PySequence_Fast_GET_SIZE(b);
766 if (n == 0) {
767 /* short circuit when b is empty */
768 Py_DECREF(b);
769 Py_RETURN_NONE;
770 }
771 m = Py_SIZE(self);
772 if (list_resize(self, m + n) == -1) {
773 Py_DECREF(b);
774 return NULL;
775 }
776 /* note that we may still have self == b here for the
777 * situation a.extend(a), but the following code works
778 * in that case too. Just make sure to resize self
779 * before calling PySequence_Fast_ITEMS.
780 */
781 /* populate the end of self with b's items */
782 src = PySequence_Fast_ITEMS(b);
783 dest = self->ob_item + m;
784 for (i = 0; i < n; i++) {
785 PyObject *o = src[i];
786 Py_INCREF(o);
787 dest[i] = o;
788 }
789 Py_DECREF(b);
790 Py_RETURN_NONE;
791 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000792
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 it = PyObject_GetIter(b);
794 if (it == NULL)
795 return NULL;
796 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 /* Guess a result list size. */
799 n = _PyObject_LengthHint(b, 8);
800 if (n == -1) {
801 Py_DECREF(it);
802 return NULL;
803 }
804 m = Py_SIZE(self);
805 mn = m + n;
806 if (mn >= m) {
807 /* Make room. */
808 if (list_resize(self, mn) == -1)
809 goto error;
810 /* Make the list sane again. */
811 Py_SIZE(self) = m;
812 }
813 /* Else m + n overflowed; on the chance that n lied, and there really
814 * is enough room, ignore it. If n was telling the truth, we'll
815 * eventually run out of memory during the loop.
816 */
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 /* Run iterator to exhaustion. */
819 for (;;) {
820 PyObject *item = iternext(it);
821 if (item == NULL) {
822 if (PyErr_Occurred()) {
823 if (PyErr_ExceptionMatches(PyExc_StopIteration))
824 PyErr_Clear();
825 else
826 goto error;
827 }
828 break;
829 }
830 if (Py_SIZE(self) < self->allocated) {
831 /* steals ref */
832 PyList_SET_ITEM(self, Py_SIZE(self), item);
833 ++Py_SIZE(self);
834 }
835 else {
836 int status = app1(self, item);
837 Py_DECREF(item); /* append creates a new ref */
838 if (status < 0)
839 goto error;
840 }
841 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 /* Cut back result list if initial guess was too large. */
844 if (Py_SIZE(self) < self->allocated)
845 list_resize(self, Py_SIZE(self)); /* shrinking can't fail */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 Py_DECREF(it);
848 Py_RETURN_NONE;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000849
850 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 Py_DECREF(it);
852 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000853}
854
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000855PyObject *
856_PyList_Extend(PyListObject *self, PyObject *b)
857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 return listextend(self, b);
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000859}
860
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000861static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000862list_inplace_concat(PyListObject *self, PyObject *other)
863{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 PyObject *result;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 result = listextend(self, other);
867 if (result == NULL)
868 return result;
869 Py_DECREF(result);
870 Py_INCREF(self);
871 return (PyObject *)self;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000872}
873
874static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000875listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000876{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 Py_ssize_t i = -1;
878 PyObject *v;
879 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 if (!PyArg_ParseTuple(args, "|n:pop", &i))
882 return NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 if (Py_SIZE(self) == 0) {
885 /* Special-case most common failure cause */
886 PyErr_SetString(PyExc_IndexError, "pop from empty list");
887 return NULL;
888 }
889 if (i < 0)
890 i += Py_SIZE(self);
891 if (i < 0 || i >= Py_SIZE(self)) {
892 PyErr_SetString(PyExc_IndexError, "pop index out of range");
893 return NULL;
894 }
895 v = self->ob_item[i];
896 if (i == Py_SIZE(self) - 1) {
897 status = list_resize(self, Py_SIZE(self) - 1);
898 assert(status >= 0);
899 return v; /* and v now owns the reference the list had */
900 }
901 Py_INCREF(v);
902 status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
903 assert(status >= 0);
904 /* Use status, so that in a release build compilers don't
905 * complain about the unused name.
906 */
907 (void) status;
Brett Cannon651dd522004-08-08 21:21:18 +0000908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000910}
911
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000912/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
913static void
914reverse_slice(PyObject **lo, PyObject **hi)
915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 assert(lo && hi);
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 --hi;
919 while (lo < hi) {
920 PyObject *t = *lo;
921 *lo = *hi;
922 *hi = t;
923 ++lo;
924 --hi;
925 }
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000926}
927
Tim Petersa64dc242002-08-01 02:13:36 +0000928/* Lots of code for an adaptive, stable, natural mergesort. There are many
929 * pieces to this algorithm; read listsort.txt for overviews and details.
930 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000931
Daniel Stutzbach98338222010-12-02 21:55:33 +0000932/* A sortslice contains a pointer to an array of keys and a pointer to
933 * an array of corresponding values. In other words, keys[i]
934 * corresponds with values[i]. If values == NULL, then the keys are
935 * also the values.
936 *
937 * Several convenience routines are provided here, so that keys and
938 * values are always moved in sync.
939 */
940
941typedef struct {
942 PyObject **keys;
943 PyObject **values;
944} sortslice;
945
946Py_LOCAL_INLINE(void)
947sortslice_copy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j)
948{
949 s1->keys[i] = s2->keys[j];
950 if (s1->values != NULL)
951 s1->values[i] = s2->values[j];
952}
953
954Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +0000955sortslice_copy_incr(sortslice *dst, sortslice *src)
956{
Daniel Stutzbach98338222010-12-02 21:55:33 +0000957 *dst->keys++ = *src->keys++;
958 if (dst->values != NULL)
959 *dst->values++ = *src->values++;
960}
961
962Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +0000963sortslice_copy_decr(sortslice *dst, sortslice *src)
964{
Daniel Stutzbach98338222010-12-02 21:55:33 +0000965 *dst->keys-- = *src->keys--;
966 if (dst->values != NULL)
967 *dst->values-- = *src->values--;
968}
969
970
971Py_LOCAL_INLINE(void)
972sortslice_memcpy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +0000973 Py_ssize_t n)
974{
Daniel Stutzbach98338222010-12-02 21:55:33 +0000975 memcpy(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
976 if (s1->values != NULL)
977 memcpy(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
978}
979
980Py_LOCAL_INLINE(void)
981sortslice_memmove(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +0000982 Py_ssize_t n)
983{
Daniel Stutzbach98338222010-12-02 21:55:33 +0000984 memmove(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
985 if (s1->values != NULL)
986 memmove(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
987}
988
989Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +0000990sortslice_advance(sortslice *slice, Py_ssize_t n)
991{
Daniel Stutzbach98338222010-12-02 21:55:33 +0000992 slice->keys += n;
993 if (slice->values != NULL)
994 slice->values += n;
995}
996
Raymond Hettinger70b64fc2008-01-30 20:15:17 +0000997/* Comparison function: PyObject_RichCompareBool with Py_LT.
Tim Petersa64dc242002-08-01 02:13:36 +0000998 * Returns -1 on error, 1 if x < y, 0 if x >= y.
999 */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001000
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001001#define ISLT(X, Y) (PyObject_RichCompareBool(X, Y, Py_LT))
Tim Peters66860f62002-08-04 17:47:26 +00001002
1003/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +00001004 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
1005 started. It makes more sense in context <wink>. X and Y are PyObject*s.
1006*/
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001007#define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail; \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001009
1010/* binarysort is the best method for sorting small arrays: it does
1011 few compares, but can do data movement quadratic in the number of
1012 elements.
Guido van Rossum42812581998-06-17 14:15:44 +00001013 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +00001014 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001015 On entry, must have lo <= start <= hi, and that [lo, start) is already
1016 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +00001017 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001018 Even in case of error, the output slice will be some permutation of
1019 the input (nothing is lost or duplicated).
1020*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00001021static int
Daniel Stutzbach98338222010-12-02 21:55:33 +00001022binarysort(sortslice lo, PyObject **hi, PyObject **start)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001023{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 register Py_ssize_t k;
1025 register PyObject **l, **p, **r;
1026 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001027
Daniel Stutzbach98338222010-12-02 21:55:33 +00001028 assert(lo.keys <= start && start <= hi);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 /* assert [lo, start) is sorted */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001030 if (lo.keys == start)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 ++start;
1032 for (; start < hi; ++start) {
1033 /* set l to where *start belongs */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001034 l = lo.keys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 r = start;
1036 pivot = *r;
1037 /* Invariants:
1038 * pivot >= all in [lo, l).
1039 * pivot < all in [r, start).
1040 * The second is vacuously true at the start.
1041 */
1042 assert(l < r);
1043 do {
1044 p = l + ((r - l) >> 1);
1045 IFLT(pivot, *p)
1046 r = p;
1047 else
1048 l = p+1;
1049 } while (l < r);
1050 assert(l == r);
1051 /* The invariants still hold, so pivot >= all in [lo, l) and
1052 pivot < all in [l, start), so pivot belongs at l. Note
1053 that if there are elements equal to pivot, l points to the
1054 first slot after them -- that's why this sort is stable.
1055 Slide over to make room.
1056 Caution: using memmove is much slower under MSVC 5;
1057 we're not usually moving many slots. */
1058 for (p = start; p > l; --p)
1059 *p = *(p-1);
1060 *l = pivot;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001061 if (lo.values != NULL) {
1062 Py_ssize_t offset = lo.values - lo.keys;
1063 p = start + offset;
1064 pivot = *p;
1065 l += offset;
1066 for (p = start + offset; p > l; --p)
1067 *p = *(p-1);
1068 *l = pivot;
1069 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 }
1071 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001072
1073 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001075}
1076
Tim Petersa64dc242002-08-01 02:13:36 +00001077/*
1078Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1079is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001080
Tim Petersa64dc242002-08-01 02:13:36 +00001081 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001082
Tim Petersa64dc242002-08-01 02:13:36 +00001083or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001084
Tim Petersa64dc242002-08-01 02:13:36 +00001085 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001086
Tim Petersa64dc242002-08-01 02:13:36 +00001087Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1088For its intended use in a stable mergesort, the strictness of the defn of
1089"descending" is needed so that the caller can safely reverse a descending
1090sequence without violating stability (strict > ensures there are no equal
1091elements to get out of order).
1092
1093Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001094*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001095static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001096count_run(PyObject **lo, PyObject **hi, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 Py_ssize_t k;
1099 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 assert(lo < hi);
1102 *descending = 0;
1103 ++lo;
1104 if (lo == hi)
1105 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 n = 2;
1108 IFLT(*lo, *(lo-1)) {
1109 *descending = 1;
1110 for (lo = lo+1; lo < hi; ++lo, ++n) {
1111 IFLT(*lo, *(lo-1))
1112 ;
1113 else
1114 break;
1115 }
1116 }
1117 else {
1118 for (lo = lo+1; lo < hi; ++lo, ++n) {
1119 IFLT(*lo, *(lo-1))
1120 break;
1121 }
1122 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 return n;
Tim Petersa64dc242002-08-01 02:13:36 +00001125fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001127}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001128
Tim Petersa64dc242002-08-01 02:13:36 +00001129/*
1130Locate the proper position of key in a sorted vector; if the vector contains
1131an element equal to key, return the position immediately to the left of
1132the leftmost equal element. [gallop_right() does the same except returns
1133the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001134
Tim Petersa64dc242002-08-01 02:13:36 +00001135"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001136
Tim Petersa64dc242002-08-01 02:13:36 +00001137"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1138hint is to the final result, the faster this runs.
1139
1140The return value is the int k in 0..n such that
1141
1142 a[k-1] < key <= a[k]
1143
1144pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1145key belongs at index k; or, IOW, the first k elements of a should precede
1146key, and the last n-k should follow key.
1147
1148Returns -1 on error. See listsort.txt for info on the method.
1149*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001150static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001151gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 Py_ssize_t ofs;
1154 Py_ssize_t lastofs;
1155 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 a += hint;
1160 lastofs = 0;
1161 ofs = 1;
1162 IFLT(*a, key) {
1163 /* a[hint] < key -- gallop right, until
1164 * a[hint + lastofs] < key <= a[hint + ofs]
1165 */
1166 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1167 while (ofs < maxofs) {
1168 IFLT(a[ofs], key) {
1169 lastofs = ofs;
1170 ofs = (ofs << 1) + 1;
1171 if (ofs <= 0) /* int overflow */
1172 ofs = maxofs;
1173 }
1174 else /* key <= a[hint + ofs] */
1175 break;
1176 }
1177 if (ofs > maxofs)
1178 ofs = maxofs;
1179 /* Translate back to offsets relative to &a[0]. */
1180 lastofs += hint;
1181 ofs += hint;
1182 }
1183 else {
1184 /* key <= a[hint] -- gallop left, until
1185 * a[hint - ofs] < key <= a[hint - lastofs]
1186 */
1187 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1188 while (ofs < maxofs) {
1189 IFLT(*(a-ofs), key)
1190 break;
1191 /* key <= a[hint - ofs] */
1192 lastofs = ofs;
1193 ofs = (ofs << 1) + 1;
1194 if (ofs <= 0) /* int overflow */
1195 ofs = maxofs;
1196 }
1197 if (ofs > maxofs)
1198 ofs = maxofs;
1199 /* Translate back to positive offsets relative to &a[0]. */
1200 k = lastofs;
1201 lastofs = hint - ofs;
1202 ofs = hint - k;
1203 }
1204 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1207 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1208 * right of lastofs but no farther right than ofs. Do a binary
1209 * search, with invariant a[lastofs-1] < key <= a[ofs].
1210 */
1211 ++lastofs;
1212 while (lastofs < ofs) {
1213 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 IFLT(a[m], key)
1216 lastofs = m+1; /* a[m] < key */
1217 else
1218 ofs = m; /* key <= a[m] */
1219 }
1220 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1221 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001222
1223fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001225}
1226
1227/*
1228Exactly like gallop_left(), except that if key already exists in a[0:n],
1229finds the position immediately to the right of the rightmost equal value.
1230
1231The return value is the int k in 0..n such that
1232
1233 a[k-1] <= key < a[k]
1234
1235or -1 if error.
1236
1237The code duplication is massive, but this is enough different given that
1238we're sticking to "<" comparisons that it's much harder to follow if
1239written as one routine with yet another "left or right?" flag.
1240*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001241static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001242gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001243{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 Py_ssize_t ofs;
1245 Py_ssize_t lastofs;
1246 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 a += hint;
1251 lastofs = 0;
1252 ofs = 1;
1253 IFLT(key, *a) {
1254 /* key < a[hint] -- gallop left, until
1255 * a[hint - ofs] <= key < a[hint - lastofs]
1256 */
1257 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1258 while (ofs < maxofs) {
1259 IFLT(key, *(a-ofs)) {
1260 lastofs = ofs;
1261 ofs = (ofs << 1) + 1;
1262 if (ofs <= 0) /* int overflow */
1263 ofs = maxofs;
1264 }
1265 else /* a[hint - ofs] <= key */
1266 break;
1267 }
1268 if (ofs > maxofs)
1269 ofs = maxofs;
1270 /* Translate back to positive offsets relative to &a[0]. */
1271 k = lastofs;
1272 lastofs = hint - ofs;
1273 ofs = hint - k;
1274 }
1275 else {
1276 /* a[hint] <= key -- gallop right, until
1277 * a[hint + lastofs] <= key < a[hint + ofs]
1278 */
1279 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1280 while (ofs < maxofs) {
1281 IFLT(key, a[ofs])
1282 break;
1283 /* a[hint + ofs] <= key */
1284 lastofs = ofs;
1285 ofs = (ofs << 1) + 1;
1286 if (ofs <= 0) /* int overflow */
1287 ofs = maxofs;
1288 }
1289 if (ofs > maxofs)
1290 ofs = maxofs;
1291 /* Translate back to offsets relative to &a[0]. */
1292 lastofs += hint;
1293 ofs += hint;
1294 }
1295 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1298 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1299 * right of lastofs but no farther right than ofs. Do a binary
1300 * search, with invariant a[lastofs-1] <= key < a[ofs].
1301 */
1302 ++lastofs;
1303 while (lastofs < ofs) {
1304 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 IFLT(key, a[m])
1307 ofs = m; /* key < a[m] */
1308 else
1309 lastofs = m+1; /* a[m] <= key */
1310 }
1311 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1312 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001313
1314fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001316}
1317
1318/* The maximum number of entries in a MergeState's pending-runs stack.
1319 * This is enough to sort arrays of size up to about
1320 * 32 * phi ** MAX_MERGE_PENDING
1321 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1322 * with 2**64 elements.
1323 */
1324#define MAX_MERGE_PENDING 85
1325
Tim Peterse05f65a2002-08-10 05:21:15 +00001326/* When we get into galloping mode, we stay there until both runs win less
1327 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001328 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001329#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001330
1331/* Avoid malloc for small temp arrays. */
1332#define MERGESTATE_TEMP_SIZE 256
1333
1334/* One MergeState exists on the stack per invocation of mergesort. It's just
1335 * a convenient way to pass state around among the helper functions.
1336 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001337struct s_slice {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001338 sortslice base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 Py_ssize_t len;
Tim Peterse05f65a2002-08-10 05:21:15 +00001340};
1341
Tim Petersa64dc242002-08-01 02:13:36 +00001342typedef struct s_MergeState {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 /* This controls when we get *into* galloping mode. It's initialized
1344 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1345 * random data, and lower for highly structured data.
1346 */
1347 Py_ssize_t min_gallop;
Tim Peterse05f65a2002-08-10 05:21:15 +00001348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 /* 'a' is temp storage to help with merges. It contains room for
1350 * alloced entries.
1351 */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001352 sortslice a; /* may point to temparray below */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 Py_ssize_t alloced;
Tim Petersa64dc242002-08-01 02:13:36 +00001354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 /* A stack of n pending runs yet to be merged. Run #i starts at
1356 * address base[i] and extends for len[i] elements. It's always
1357 * true (so long as the indices are in bounds) that
1358 *
1359 * pending[i].base + pending[i].len == pending[i+1].base
1360 *
1361 * so we could cut the storage for this, but it's a minor amount,
1362 * and keeping all the info explicit simplifies the code.
1363 */
1364 int n;
1365 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 /* 'a' points to this when possible, rather than muck with malloc. */
1368 PyObject *temparray[MERGESTATE_TEMP_SIZE];
Tim Petersa64dc242002-08-01 02:13:36 +00001369} MergeState;
1370
1371/* Conceptually a MergeState's constructor. */
1372static void
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001373merge_init(MergeState *ms, Py_ssize_t list_size, int has_keyfunc)
Tim Petersa64dc242002-08-01 02:13:36 +00001374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001376 if (has_keyfunc) {
1377 /* The temporary space for merging will need at most half the list
1378 * size rounded up. Use the minimum possible space so we can use the
1379 * rest of temparray for other things. In particular, if there is
1380 * enough extra space, listsort() will use it to store the keys.
1381 */
1382 ms->alloced = (list_size + 1) / 2;
1383
1384 /* ms->alloced describes how many keys will be stored at
1385 ms->temparray, but we also need to store the values. Hence,
1386 ms->alloced is capped at half of MERGESTATE_TEMP_SIZE. */
1387 if (MERGESTATE_TEMP_SIZE / 2 < ms->alloced)
1388 ms->alloced = MERGESTATE_TEMP_SIZE / 2;
1389 ms->a.values = &ms->temparray[ms->alloced];
1390 }
1391 else {
1392 ms->alloced = MERGESTATE_TEMP_SIZE;
1393 ms->a.values = NULL;
1394 }
1395 ms->a.keys = ms->temparray;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 ms->n = 0;
1397 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001398}
1399
1400/* Free all the temp memory owned by the MergeState. This must be called
1401 * when you're done with a MergeState, and may be called before then if
1402 * you want to free the temp memory early.
1403 */
1404static void
1405merge_freemem(MergeState *ms)
1406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001408 if (ms->a.keys != ms->temparray)
1409 PyMem_Free(ms->a.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001410}
1411
1412/* Ensure enough temp memory for 'need' array slots is available.
1413 * Returns 0 on success and -1 if the memory can't be gotten.
1414 */
1415static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001416merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001417{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001418 int multiplier;
1419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 assert(ms != NULL);
1421 if (need <= ms->alloced)
1422 return 0;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001423
1424 multiplier = ms->a.values != NULL ? 2 : 1;
1425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 /* Don't realloc! That can cost cycles to copy the old data, but
1427 * we don't care what's in the block.
1428 */
1429 merge_freemem(ms);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001430 if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject*) / multiplier) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 PyErr_NoMemory();
1432 return -1;
1433 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001434 ms->a.keys = (PyObject**)PyMem_Malloc(multiplier * need
1435 * sizeof(PyObject *));
1436 if (ms->a.keys != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 ms->alloced = need;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001438 if (ms->a.values != NULL)
1439 ms->a.values = &ms->a.keys[need];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 return 0;
1441 }
1442 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001444}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1446 merge_getmem(MS, NEED))
Tim Petersa64dc242002-08-01 02:13:36 +00001447
Daniel Stutzbach98338222010-12-02 21:55:33 +00001448/* Merge the na elements starting at ssa with the nb elements starting at
1449 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1450 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1451 * should have na <= nb. See listsort.txt for more info. Return 0 if
1452 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001453 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001454static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001455merge_lo(MergeState *ms, sortslice ssa, Py_ssize_t na,
1456 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001459 sortslice dest;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 int result = -1; /* guilty until proved innocent */
1461 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001462
Daniel Stutzbach98338222010-12-02 21:55:33 +00001463 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1464 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 if (MERGE_GETMEM(ms, na) < 0)
1466 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001467 sortslice_memcpy(&ms->a, 0, &ssa, 0, na);
1468 dest = ssa;
1469 ssa = ms->a;
Tim Petersa64dc242002-08-01 02:13:36 +00001470
Daniel Stutzbach98338222010-12-02 21:55:33 +00001471 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 --nb;
1473 if (nb == 0)
1474 goto Succeed;
1475 if (na == 1)
1476 goto CopyB;
Tim Petersa64dc242002-08-01 02:13:36 +00001477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 min_gallop = ms->min_gallop;
1479 for (;;) {
1480 Py_ssize_t acount = 0; /* # of times A won in a row */
1481 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 /* Do the straightforward thing until (if ever) one run
1484 * appears to win consistently.
1485 */
1486 for (;;) {
1487 assert(na > 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001488 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 if (k) {
1490 if (k < 0)
1491 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001492 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 ++bcount;
1494 acount = 0;
1495 --nb;
1496 if (nb == 0)
1497 goto Succeed;
1498 if (bcount >= min_gallop)
1499 break;
1500 }
1501 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001502 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 ++acount;
1504 bcount = 0;
1505 --na;
1506 if (na == 1)
1507 goto CopyB;
1508 if (acount >= min_gallop)
1509 break;
1510 }
1511 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 /* One run is winning so consistently that galloping may
1514 * be a huge win. So try that, and continue galloping until
1515 * (if ever) neither run appears to be winning consistently
1516 * anymore.
1517 */
1518 ++min_gallop;
1519 do {
1520 assert(na > 1 && nb > 0);
1521 min_gallop -= min_gallop > 1;
1522 ms->min_gallop = min_gallop;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001523 k = gallop_right(ssb.keys[0], ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 acount = k;
1525 if (k) {
1526 if (k < 0)
1527 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001528 sortslice_memcpy(&dest, 0, &ssa, 0, k);
1529 sortslice_advance(&dest, k);
1530 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 na -= k;
1532 if (na == 1)
1533 goto CopyB;
1534 /* na==0 is impossible now if the comparison
1535 * function is consistent, but we can't assume
1536 * that it is.
1537 */
1538 if (na == 0)
1539 goto Succeed;
1540 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001541 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 --nb;
1543 if (nb == 0)
1544 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001545
Daniel Stutzbach98338222010-12-02 21:55:33 +00001546 k = gallop_left(ssa.keys[0], ssb.keys, nb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 bcount = k;
1548 if (k) {
1549 if (k < 0)
1550 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001551 sortslice_memmove(&dest, 0, &ssb, 0, k);
1552 sortslice_advance(&dest, k);
1553 sortslice_advance(&ssb, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 nb -= k;
1555 if (nb == 0)
1556 goto Succeed;
1557 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001558 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 --na;
1560 if (na == 1)
1561 goto CopyB;
1562 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1563 ++min_gallop; /* penalize it for leaving galloping mode */
1564 ms->min_gallop = min_gallop;
1565 }
Tim Petersa64dc242002-08-01 02:13:36 +00001566Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001568Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 if (na)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001570 sortslice_memcpy(&dest, 0, &ssa, 0, na);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001572CopyB:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 assert(na == 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001574 /* The last element of ssa belongs at the end of the merge. */
1575 sortslice_memmove(&dest, 0, &ssb, 0, nb);
1576 sortslice_copy(&dest, nb, &ssa, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001578}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001579
Daniel Stutzbach98338222010-12-02 21:55:33 +00001580/* Merge the na elements starting at pa with the nb elements starting at
1581 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1582 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1583 * should have na >= nb. See listsort.txt for more info. Return 0 if
1584 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001585 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001586static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001587merge_hi(MergeState *ms, sortslice ssa, Py_ssize_t na,
1588 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001589{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001591 sortslice dest, basea, baseb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 int result = -1; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001594
Daniel Stutzbach98338222010-12-02 21:55:33 +00001595 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1596 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 if (MERGE_GETMEM(ms, nb) < 0)
1598 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001599 dest = ssb;
1600 sortslice_advance(&dest, nb-1);
1601 sortslice_memcpy(&ms->a, 0, &ssb, 0, nb);
1602 basea = ssa;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 baseb = ms->a;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001604 ssb.keys = ms->a.keys + nb - 1;
1605 if (ssb.values != NULL)
1606 ssb.values = ms->a.values + nb - 1;
1607 sortslice_advance(&ssa, na - 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001608
Daniel Stutzbach98338222010-12-02 21:55:33 +00001609 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 --na;
1611 if (na == 0)
1612 goto Succeed;
1613 if (nb == 1)
1614 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 min_gallop = ms->min_gallop;
1617 for (;;) {
1618 Py_ssize_t acount = 0; /* # of times A won in a row */
1619 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 /* Do the straightforward thing until (if ever) one run
1622 * appears to win consistently.
1623 */
1624 for (;;) {
1625 assert(na > 0 && nb > 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001626 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 if (k) {
1628 if (k < 0)
1629 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001630 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 ++acount;
1632 bcount = 0;
1633 --na;
1634 if (na == 0)
1635 goto Succeed;
1636 if (acount >= min_gallop)
1637 break;
1638 }
1639 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001640 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 ++bcount;
1642 acount = 0;
1643 --nb;
1644 if (nb == 1)
1645 goto CopyA;
1646 if (bcount >= min_gallop)
1647 break;
1648 }
1649 }
Tim Petersa64dc242002-08-01 02:13:36 +00001650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001651 /* One run is winning so consistently that galloping may
1652 * be a huge win. So try that, and continue galloping until
1653 * (if ever) neither run appears to be winning consistently
1654 * anymore.
1655 */
1656 ++min_gallop;
1657 do {
1658 assert(na > 0 && nb > 1);
1659 min_gallop -= min_gallop > 1;
1660 ms->min_gallop = min_gallop;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001661 k = gallop_right(ssb.keys[0], basea.keys, na, na-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 if (k < 0)
1663 goto Fail;
1664 k = na - k;
1665 acount = k;
1666 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001667 sortslice_advance(&dest, -k);
1668 sortslice_advance(&ssa, -k);
1669 sortslice_memmove(&dest, 1, &ssa, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 na -= k;
1671 if (na == 0)
1672 goto Succeed;
1673 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001674 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 --nb;
1676 if (nb == 1)
1677 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001678
Daniel Stutzbach98338222010-12-02 21:55:33 +00001679 k = gallop_left(ssa.keys[0], baseb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 if (k < 0)
1681 goto Fail;
1682 k = nb - k;
1683 bcount = k;
1684 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001685 sortslice_advance(&dest, -k);
1686 sortslice_advance(&ssb, -k);
1687 sortslice_memcpy(&dest, 1, &ssb, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 nb -= k;
1689 if (nb == 1)
1690 goto CopyA;
1691 /* nb==0 is impossible now if the comparison
1692 * function is consistent, but we can't assume
1693 * that it is.
1694 */
1695 if (nb == 0)
1696 goto Succeed;
1697 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001698 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 --na;
1700 if (na == 0)
1701 goto Succeed;
1702 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1703 ++min_gallop; /* penalize it for leaving galloping mode */
1704 ms->min_gallop = min_gallop;
1705 }
Tim Petersa64dc242002-08-01 02:13:36 +00001706Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001708Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 if (nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001710 sortslice_memcpy(&dest, -(nb-1), &baseb, 0, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001712CopyA:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 assert(nb == 1 && na > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001714 /* The first element of ssb belongs at the front of the merge. */
1715 sortslice_memmove(&dest, 1-na, &ssa, 1-na, na);
1716 sortslice_advance(&dest, -na);
1717 sortslice_advance(&ssa, -na);
1718 sortslice_copy(&dest, 0, &ssb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001720}
1721
1722/* Merge the two runs at stack indices i and i+1.
1723 * Returns 0 on success, -1 on error.
1724 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001725static Py_ssize_t
1726merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001727{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001728 sortslice ssa, ssb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 Py_ssize_t na, nb;
1730 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 assert(ms != NULL);
1733 assert(ms->n >= 2);
1734 assert(i >= 0);
1735 assert(i == ms->n - 2 || i == ms->n - 3);
Tim Petersa64dc242002-08-01 02:13:36 +00001736
Daniel Stutzbach98338222010-12-02 21:55:33 +00001737 ssa = ms->pending[i].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 na = ms->pending[i].len;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001739 ssb = ms->pending[i+1].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 nb = ms->pending[i+1].len;
1741 assert(na > 0 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001742 assert(ssa.keys + na == ssb.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 /* Record the length of the combined runs; if i is the 3rd-last
1745 * run now, also slide over the last run (which isn't involved
1746 * in this merge). The current run i+1 goes away in any case.
1747 */
1748 ms->pending[i].len = na + nb;
1749 if (i == ms->n - 3)
1750 ms->pending[i+1] = ms->pending[i+2];
1751 --ms->n;
Tim Petersa64dc242002-08-01 02:13:36 +00001752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 /* Where does b start in a? Elements in a before that can be
1754 * ignored (already in place).
1755 */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001756 k = gallop_right(*ssb.keys, ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 if (k < 0)
1758 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001759 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 na -= k;
1761 if (na == 0)
1762 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 /* Where does a end in b? Elements in b after that can be
1765 * ignored (already in place).
1766 */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001767 nb = gallop_left(ssa.keys[na-1], ssb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 if (nb <= 0)
1769 return nb;
Tim Petersa64dc242002-08-01 02:13:36 +00001770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 /* Merge what remains of the runs, using a temp array with
1772 * min(na, nb) elements.
1773 */
1774 if (na <= nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001775 return merge_lo(ms, ssa, na, ssb, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 else
Daniel Stutzbach98338222010-12-02 21:55:33 +00001777 return merge_hi(ms, ssa, na, ssb, nb);
Tim Petersa64dc242002-08-01 02:13:36 +00001778}
1779
1780/* Examine the stack of runs waiting to be merged, merging adjacent runs
1781 * until the stack invariants are re-established:
1782 *
1783 * 1. len[-3] > len[-2] + len[-1]
1784 * 2. len[-2] > len[-1]
1785 *
1786 * See listsort.txt for more info.
1787 *
1788 * Returns 0 on success, -1 on error.
1789 */
1790static int
1791merge_collapse(MergeState *ms)
1792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 assert(ms);
1796 while (ms->n > 1) {
1797 Py_ssize_t n = ms->n - 2;
1798 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1799 if (p[n-1].len < p[n+1].len)
1800 --n;
1801 if (merge_at(ms, n) < 0)
1802 return -1;
1803 }
1804 else if (p[n].len <= p[n+1].len) {
1805 if (merge_at(ms, n) < 0)
1806 return -1;
1807 }
1808 else
1809 break;
1810 }
1811 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001812}
1813
1814/* Regardless of invariants, merge all runs on the stack until only one
1815 * remains. This is used at the end of the mergesort.
1816 *
1817 * Returns 0 on success, -1 on error.
1818 */
1819static int
1820merge_force_collapse(MergeState *ms)
1821{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 assert(ms);
1825 while (ms->n > 1) {
1826 Py_ssize_t n = ms->n - 2;
1827 if (n > 0 && p[n-1].len < p[n+1].len)
1828 --n;
1829 if (merge_at(ms, n) < 0)
1830 return -1;
1831 }
1832 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001833}
1834
1835/* Compute a good value for the minimum run length; natural runs shorter
1836 * than this are boosted artificially via binary insertion.
1837 *
1838 * If n < 64, return n (it's too small to bother with fancy stuff).
1839 * Else if n is an exact power of 2, return 32.
1840 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1841 * strictly less than, an exact power of 2.
1842 *
1843 * See listsort.txt for more info.
1844 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001845static Py_ssize_t
1846merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001847{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 assert(n >= 0);
1851 while (n >= 64) {
1852 r |= n & 1;
1853 n >>= 1;
1854 }
1855 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001856}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001857
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001858static void
Daniel Stutzbach98338222010-12-02 21:55:33 +00001859reverse_sortslice(sortslice *s, Py_ssize_t n)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001860{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001861 reverse_slice(s->keys, &s->keys[n]);
1862 if (s->values != NULL)
1863 reverse_slice(s->values, &s->values[n]);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001864}
1865
Tim Petersa64dc242002-08-01 02:13:36 +00001866/* An adaptive, stable, natural mergesort. See listsort.txt.
1867 * Returns Py_None on success, NULL on error. Even in case of error, the
1868 * list will be some permutation of its input state (nothing is lost or
1869 * duplicated).
1870 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001871static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001872listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001873{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 MergeState ms;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 Py_ssize_t nremaining;
1876 Py_ssize_t minrun;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001877 sortslice lo;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 Py_ssize_t saved_ob_size, saved_allocated;
1879 PyObject **saved_ob_item;
1880 PyObject **final_ob_item;
1881 PyObject *result = NULL; /* guilty until proved innocent */
1882 int reverse = 0;
1883 PyObject *keyfunc = NULL;
1884 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 static char *kwlist[] = {"key", "reverse", 0};
Daniel Stutzbach98338222010-12-02 21:55:33 +00001886 PyObject **keys;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 assert(self != NULL);
1889 assert (PyList_Check(self));
1890 if (args != NULL) {
1891 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:sort",
1892 kwlist, &keyfunc, &reverse))
1893 return NULL;
1894 if (Py_SIZE(args) > 0) {
1895 PyErr_SetString(PyExc_TypeError,
1896 "must use keyword argument for key function");
1897 return NULL;
1898 }
1899 }
1900 if (keyfunc == Py_None)
1901 keyfunc = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 /* The list is temporarily made empty, so that mutations performed
1904 * by comparison functions can't affect the slice of memory we're
1905 * sorting (allowing mutations during sorting is a core-dump
1906 * factory, since ob_item may change).
1907 */
1908 saved_ob_size = Py_SIZE(self);
1909 saved_ob_item = self->ob_item;
1910 saved_allocated = self->allocated;
1911 Py_SIZE(self) = 0;
1912 self->ob_item = NULL;
1913 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00001914
Daniel Stutzbach98338222010-12-02 21:55:33 +00001915 if (keyfunc == NULL) {
1916 keys = NULL;
1917 lo.keys = saved_ob_item;
1918 lo.values = NULL;
1919 }
1920 else {
1921 if (saved_ob_size < MERGESTATE_TEMP_SIZE/2)
1922 /* Leverage stack space we allocated but won't otherwise use */
1923 keys = &ms.temparray[saved_ob_size+1];
1924 else {
1925 keys = PyMem_MALLOC(sizeof(PyObject *) * saved_ob_size);
1926 if (keys == NULL)
1927 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001929
1930 for (i = 0; i < saved_ob_size ; i++) {
1931 keys[i] = PyObject_CallFunctionObjArgs(keyfunc, saved_ob_item[i],
1932 NULL);
1933 if (keys[i] == NULL) {
1934 for (i=i-1 ; i>=0 ; i--)
1935 Py_DECREF(keys[i]);
Daniel Stutzbacheda70b82011-05-04 12:46:28 -07001936 if (keys != &ms.temparray[saved_ob_size+1])
1937 PyMem_FREE(keys);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001938 goto keyfunc_fail;
1939 }
1940 }
1941
1942 lo.keys = keys;
1943 lo.values = saved_ob_item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001945
Daniel Stutzbach98338222010-12-02 21:55:33 +00001946 merge_init(&ms, saved_ob_size, keys != NULL);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 nremaining = saved_ob_size;
1949 if (nremaining < 2)
1950 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00001951
Benjamin Peterson05380642010-08-23 19:35:39 +00001952 /* Reverse sort stability achieved by initially reversing the list,
1953 applying a stable forward sort, then reversing the final result. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001954 if (reverse) {
1955 if (keys != NULL)
1956 reverse_slice(&keys[0], &keys[saved_ob_size]);
1957 reverse_slice(&saved_ob_item[0], &saved_ob_item[saved_ob_size]);
1958 }
Benjamin Peterson05380642010-08-23 19:35:39 +00001959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001960 /* March over the array once, left to right, finding natural runs,
1961 * and extending short natural runs to minrun elements.
1962 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 minrun = merge_compute_minrun(nremaining);
1964 do {
1965 int descending;
1966 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00001967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 /* Identify next run. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001969 n = count_run(lo.keys, lo.keys + nremaining, &descending);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 if (n < 0)
1971 goto fail;
1972 if (descending)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001973 reverse_sortslice(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001974 /* If short, extend to min(minrun, nremaining). */
1975 if (n < minrun) {
1976 const Py_ssize_t force = nremaining <= minrun ?
1977 nremaining : minrun;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001978 if (binarysort(lo, lo.keys + force, lo.keys + n) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 goto fail;
1980 n = force;
1981 }
1982 /* Push run onto pending-runs stack, and maybe merge. */
1983 assert(ms.n < MAX_MERGE_PENDING);
1984 ms.pending[ms.n].base = lo;
1985 ms.pending[ms.n].len = n;
1986 ++ms.n;
1987 if (merge_collapse(&ms) < 0)
1988 goto fail;
1989 /* Advance to find next run. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001990 sortslice_advance(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 nremaining -= n;
1992 } while (nremaining);
Tim Peters330f9e92002-07-19 07:05:44 +00001993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 if (merge_force_collapse(&ms) < 0)
1995 goto fail;
1996 assert(ms.n == 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001997 assert(keys == NULL
1998 ? ms.pending[0].base.keys == saved_ob_item
1999 : ms.pending[0].base.keys == &keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 assert(ms.pending[0].len == saved_ob_size);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002001 lo = ms.pending[0].base;
Tim Petersa64dc242002-08-01 02:13:36 +00002002
2003succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002005fail:
Daniel Stutzbach98338222010-12-02 21:55:33 +00002006 if (keys != NULL) {
2007 for (i = 0; i < saved_ob_size; i++)
2008 Py_DECREF(keys[i]);
2009 if (keys != &ms.temparray[saved_ob_size+1])
2010 PyMem_FREE(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 if (self->allocated != -1 && result != NULL) {
2014 /* The user mucked with the list during the sort,
2015 * and we don't already have another error to report.
2016 */
2017 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2018 result = NULL;
2019 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 if (reverse && saved_ob_size > 1)
2022 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 merge_freemem(&ms);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002025
Daniel Stutzbach98338222010-12-02 21:55:33 +00002026keyfunc_fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 final_ob_item = self->ob_item;
2028 i = Py_SIZE(self);
2029 Py_SIZE(self) = saved_ob_size;
2030 self->ob_item = saved_ob_item;
2031 self->allocated = saved_allocated;
2032 if (final_ob_item != NULL) {
2033 /* we cannot use list_clear() for this because it does not
2034 guarantee that the list is really empty when it returns */
2035 while (--i >= 0) {
2036 Py_XDECREF(final_ob_item[i]);
2037 }
2038 PyMem_FREE(final_ob_item);
2039 }
2040 Py_XINCREF(result);
2041 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002042}
Tim Peters330f9e92002-07-19 07:05:44 +00002043#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002044#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002045
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002046int
Fred Drakea2f55112000-07-09 15:16:51 +00002047PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002048{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 if (v == NULL || !PyList_Check(v)) {
2050 PyErr_BadInternalCall();
2051 return -1;
2052 }
2053 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
2054 if (v == NULL)
2055 return -1;
2056 Py_DECREF(v);
2057 return 0;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002058}
2059
Guido van Rossumb86c5492001-02-12 22:06:02 +00002060static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002061listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 if (Py_SIZE(self) > 1)
2064 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2065 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002066}
2067
Guido van Rossum84c76f51990-10-30 13:32:20 +00002068int
Fred Drakea2f55112000-07-09 15:16:51 +00002069PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 PyListObject *self = (PyListObject *)v;
Tim Peters6063e262002-08-08 01:06:39 +00002072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 if (v == NULL || !PyList_Check(v)) {
2074 PyErr_BadInternalCall();
2075 return -1;
2076 }
2077 if (Py_SIZE(self) > 1)
2078 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2079 return 0;
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002080}
2081
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002082PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002083PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002084{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 PyObject *w;
2086 PyObject **p, **q;
2087 Py_ssize_t n;
2088 if (v == NULL || !PyList_Check(v)) {
2089 PyErr_BadInternalCall();
2090 return NULL;
2091 }
2092 n = Py_SIZE(v);
2093 w = PyTuple_New(n);
2094 if (w == NULL)
2095 return NULL;
2096 p = ((PyTupleObject *)w)->ob_item;
2097 q = ((PyListObject *)v)->ob_item;
2098 while (--n >= 0) {
2099 Py_INCREF(*q);
2100 *p = *q;
2101 p++;
2102 q++;
2103 }
2104 return w;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002105}
2106
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002107static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002108listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002109{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 Py_ssize_t i, start=0, stop=Py_SIZE(self);
2111 PyObject *v, *format_tuple, *err_string;
2112 static PyObject *err_format = NULL;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002113
Petri Lehtinenebfaabd2011-11-06 21:02:39 +02002114 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2115 _PyEval_SliceIndex, &start,
2116 _PyEval_SliceIndex, &stop))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 return NULL;
2118 if (start < 0) {
2119 start += Py_SIZE(self);
2120 if (start < 0)
2121 start = 0;
2122 }
2123 if (stop < 0) {
2124 stop += Py_SIZE(self);
2125 if (stop < 0)
2126 stop = 0;
2127 }
2128 for (i = start; i < stop && i < Py_SIZE(self); i++) {
2129 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2130 if (cmp > 0)
2131 return PyLong_FromSsize_t(i);
2132 else if (cmp < 0)
2133 return NULL;
2134 }
2135 if (err_format == NULL) {
2136 err_format = PyUnicode_FromString("%r is not in list");
2137 if (err_format == NULL)
2138 return NULL;
2139 }
2140 format_tuple = PyTuple_Pack(1, v);
2141 if (format_tuple == NULL)
2142 return NULL;
2143 err_string = PyUnicode_Format(err_format, format_tuple);
2144 Py_DECREF(format_tuple);
2145 if (err_string == NULL)
2146 return NULL;
2147 PyErr_SetObject(PyExc_ValueError, err_string);
2148 Py_DECREF(err_string);
2149 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002150}
2151
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002152static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002153listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 Py_ssize_t count = 0;
2156 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 for (i = 0; i < Py_SIZE(self); i++) {
2159 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2160 if (cmp > 0)
2161 count++;
2162 else if (cmp < 0)
2163 return NULL;
2164 }
2165 return PyLong_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002166}
2167
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002168static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002169listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 for (i = 0; i < Py_SIZE(self); i++) {
2174 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2175 if (cmp > 0) {
2176 if (list_ass_slice(self, i, i+1,
2177 (PyObject *)NULL) == 0)
2178 Py_RETURN_NONE;
2179 return NULL;
2180 }
2181 else if (cmp < 0)
2182 return NULL;
2183 }
2184 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
2185 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002186}
2187
Jeremy Hylton8caad492000-06-23 14:18:11 +00002188static int
2189list_traverse(PyListObject *o, visitproc visit, void *arg)
2190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 for (i = Py_SIZE(o); --i >= 0; )
2194 Py_VISIT(o->ob_item[i]);
2195 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002196}
2197
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002198static PyObject *
2199list_richcompare(PyObject *v, PyObject *w, int op)
2200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 PyListObject *vl, *wl;
2202 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 if (!PyList_Check(v) || !PyList_Check(w)) {
2205 Py_INCREF(Py_NotImplemented);
2206 return Py_NotImplemented;
2207 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 vl = (PyListObject *)v;
2210 wl = (PyListObject *)w;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
2213 /* Shortcut: if the lengths differ, the lists differ */
2214 PyObject *res;
2215 if (op == Py_EQ)
2216 res = Py_False;
2217 else
2218 res = Py_True;
2219 Py_INCREF(res);
2220 return res;
2221 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 /* Search for the first index where items are different */
2224 for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
2225 int k = PyObject_RichCompareBool(vl->ob_item[i],
2226 wl->ob_item[i], Py_EQ);
2227 if (k < 0)
2228 return NULL;
2229 if (!k)
2230 break;
2231 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
2234 /* No more items to compare -- compare sizes */
2235 Py_ssize_t vs = Py_SIZE(vl);
2236 Py_ssize_t ws = Py_SIZE(wl);
2237 int cmp;
2238 PyObject *res;
2239 switch (op) {
2240 case Py_LT: cmp = vs < ws; break;
2241 case Py_LE: cmp = vs <= ws; break;
2242 case Py_EQ: cmp = vs == ws; break;
2243 case Py_NE: cmp = vs != ws; break;
2244 case Py_GT: cmp = vs > ws; break;
2245 case Py_GE: cmp = vs >= ws; break;
2246 default: return NULL; /* cannot happen */
2247 }
2248 if (cmp)
2249 res = Py_True;
2250 else
2251 res = Py_False;
2252 Py_INCREF(res);
2253 return res;
2254 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 /* We have an item that differs -- shortcuts for EQ/NE */
2257 if (op == Py_EQ) {
2258 Py_INCREF(Py_False);
2259 return Py_False;
2260 }
2261 if (op == Py_NE) {
2262 Py_INCREF(Py_True);
2263 return Py_True;
2264 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002266 /* Compare the final item again using the proper operator */
2267 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002268}
2269
Tim Peters6d6c1a32001-08-02 04:15:00 +00002270static int
2271list_init(PyListObject *self, PyObject *args, PyObject *kw)
2272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 PyObject *arg = NULL;
2274 static char *kwlist[] = {"sequence", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2277 return -1;
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 /* Verify list invariants established by PyType_GenericAlloc() */
2280 assert(0 <= Py_SIZE(self));
2281 assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
2282 assert(self->ob_item != NULL ||
2283 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 /* Empty previous contents */
2286 if (self->ob_item != NULL) {
2287 (void)list_clear(self);
2288 }
2289 if (arg != NULL) {
2290 PyObject *rv = listextend(self, arg);
2291 if (rv == NULL)
2292 return -1;
2293 Py_DECREF(rv);
2294 }
2295 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002296}
2297
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002298static PyObject *
2299list_sizeof(PyListObject *self)
2300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 res = sizeof(PyListObject) + self->allocated * sizeof(void*);
2304 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002305}
2306
Raymond Hettinger1021c442003-11-07 15:38:09 +00002307static PyObject *list_iter(PyObject *seq);
2308static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2309
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002310PyDoc_STRVAR(getitem_doc,
2311"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002312PyDoc_STRVAR(reversed_doc,
2313"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002314PyDoc_STRVAR(sizeof_doc,
2315"L.__sizeof__() -- size of L in memory, in bytes");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002316PyDoc_STRVAR(append_doc,
2317"L.append(object) -- append object to end");
2318PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002319"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002320PyDoc_STRVAR(insert_doc,
2321"L.insert(index, object) -- insert object before index");
2322PyDoc_STRVAR(pop_doc,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002323"L.pop([index]) -> item -- remove and return item at index (default last).\n"
2324"Raises IndexError if list is empty or index is out of range.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002325PyDoc_STRVAR(remove_doc,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002326"L.remove(value) -- remove first occurrence of value.\n"
2327"Raises ValueError if the value is not present.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002328PyDoc_STRVAR(index_doc,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002329"L.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
2330"Raises ValueError if the value is not present.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002331PyDoc_STRVAR(count_doc,
2332"L.count(value) -> integer -- return number of occurrences of value");
2333PyDoc_STRVAR(reverse_doc,
2334"L.reverse() -- reverse *IN PLACE*");
2335PyDoc_STRVAR(sort_doc,
Benjamin Petersoncb9a5512008-09-30 02:08:36 +00002336"L.sort(key=None, reverse=False) -- stable sort *IN PLACE*");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002337
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002338static PyObject *list_subscript(PyListObject*, PyObject*);
2339
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002340static PyMethodDef list_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
2342 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
2343 {"__sizeof__", (PyCFunction)list_sizeof, METH_NOARGS, sizeof_doc},
2344 {"append", (PyCFunction)listappend, METH_O, append_doc},
2345 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
2346 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
2347 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
2348 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
2349 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
2350 {"count", (PyCFunction)listcount, METH_O, count_doc},
2351 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
2352 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
2353 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002354};
2355
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002356static PySequenceMethods list_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 (lenfunc)list_length, /* sq_length */
2358 (binaryfunc)list_concat, /* sq_concat */
2359 (ssizeargfunc)list_repeat, /* sq_repeat */
2360 (ssizeargfunc)list_item, /* sq_item */
2361 0, /* sq_slice */
2362 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
2363 0, /* sq_ass_slice */
2364 (objobjproc)list_contains, /* sq_contains */
2365 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2366 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002367};
2368
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002369PyDoc_STRVAR(list_doc,
Ezio Melotti7f807b72010-03-01 04:08:34 +00002370"list() -> new empty list\n"
2371"list(iterable) -> new list initialized from iterable's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002372
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002373static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002374list_subscript(PyListObject* self, PyObject* item)
2375{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 if (PyIndex_Check(item)) {
2377 Py_ssize_t i;
2378 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2379 if (i == -1 && PyErr_Occurred())
2380 return NULL;
2381 if (i < 0)
2382 i += PyList_GET_SIZE(self);
2383 return list_item(self, i);
2384 }
2385 else if (PySlice_Check(item)) {
2386 Py_ssize_t start, stop, step, slicelength, cur, i;
2387 PyObject* result;
2388 PyObject* it;
2389 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002390
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002391 if (PySlice_GetIndicesEx(item, Py_SIZE(self),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 &start, &stop, &step, &slicelength) < 0) {
2393 return NULL;
2394 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 if (slicelength <= 0) {
2397 return PyList_New(0);
2398 }
2399 else if (step == 1) {
2400 return list_slice(self, start, stop);
2401 }
2402 else {
2403 result = PyList_New(slicelength);
2404 if (!result) return NULL;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 src = self->ob_item;
2407 dest = ((PyListObject *)result)->ob_item;
2408 for (cur = start, i = 0; i < slicelength;
2409 cur += step, i++) {
2410 it = src[cur];
2411 Py_INCREF(it);
2412 dest[i] = it;
2413 }
Tim Peters3b01a122002-07-19 02:35:45 +00002414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 return result;
2416 }
2417 }
2418 else {
2419 PyErr_Format(PyExc_TypeError,
2420 "list indices must be integers, not %.200s",
2421 item->ob_type->tp_name);
2422 return NULL;
2423 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002424}
2425
Tim Peters3b01a122002-07-19 02:35:45 +00002426static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002427list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 if (PyIndex_Check(item)) {
2430 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2431 if (i == -1 && PyErr_Occurred())
2432 return -1;
2433 if (i < 0)
2434 i += PyList_GET_SIZE(self);
2435 return list_ass_item(self, i, value);
2436 }
2437 else if (PySlice_Check(item)) {
2438 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002439
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002440 if (PySlice_GetIndicesEx(item, Py_SIZE(self),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 &start, &stop, &step, &slicelength) < 0) {
2442 return -1;
2443 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 if (step == 1)
2446 return list_ass_slice(self, start, stop, value);
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 /* Make sure s[5:2] = [..] inserts at the right place:
2449 before 5, not before 2. */
2450 if ((step < 0 && start < stop) ||
2451 (step > 0 && start > stop))
2452 stop = start;
Thomas Woutersed03b412007-08-28 21:37:11 +00002453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 if (value == NULL) {
2455 /* delete slice */
2456 PyObject **garbage;
2457 size_t cur;
2458 Py_ssize_t i;
Tim Peters3b01a122002-07-19 02:35:45 +00002459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 if (slicelength <= 0)
2461 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 if (step < 0) {
2464 stop = start + 1;
2465 start = stop + step*(slicelength - 1) - 1;
2466 step = -step;
2467 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 assert((size_t)slicelength <=
2470 PY_SIZE_MAX / sizeof(PyObject*));
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00002471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 garbage = (PyObject**)
2473 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2474 if (!garbage) {
2475 PyErr_NoMemory();
2476 return -1;
2477 }
Tim Peters3b01a122002-07-19 02:35:45 +00002478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 /* drawing pictures might help understand these for
2480 loops. Basically, we memmove the parts of the
2481 list that are *not* part of the slice: step-1
2482 items for each item that is part of the slice,
2483 and then tail end of the list that was not
2484 covered by the slice */
2485 for (cur = start, i = 0;
2486 cur < (size_t)stop;
2487 cur += step, i++) {
2488 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 garbage[i] = PyList_GET_ITEM(self, cur);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002492 if (cur + step >= (size_t)Py_SIZE(self)) {
2493 lim = Py_SIZE(self) - cur - 1;
2494 }
Michael W. Hudson56796f62002-07-29 14:35:04 +00002495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 memmove(self->ob_item + cur - i,
2497 self->ob_item + cur + 1,
2498 lim * sizeof(PyObject *));
2499 }
2500 cur = start + slicelength*step;
2501 if (cur < (size_t)Py_SIZE(self)) {
2502 memmove(self->ob_item + cur - slicelength,
2503 self->ob_item + cur,
2504 (Py_SIZE(self) - cur) *
2505 sizeof(PyObject *));
2506 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 Py_SIZE(self) -= slicelength;
2509 list_resize(self, Py_SIZE(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 for (i = 0; i < slicelength; i++) {
2512 Py_DECREF(garbage[i]);
2513 }
2514 PyMem_FREE(garbage);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 return 0;
2517 }
2518 else {
2519 /* assign slice */
2520 PyObject *ins, *seq;
2521 PyObject **garbage, **seqitems, **selfitems;
2522 Py_ssize_t cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002524 /* protect against a[::-1] = a */
2525 if (self == (PyListObject*)value) {
2526 seq = list_slice((PyListObject*)value, 0,
2527 PyList_GET_SIZE(value));
2528 }
2529 else {
2530 seq = PySequence_Fast(value,
2531 "must assign iterable "
2532 "to extended slice");
2533 }
2534 if (!seq)
2535 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2538 PyErr_Format(PyExc_ValueError,
2539 "attempt to assign sequence of "
2540 "size %zd to extended slice of "
2541 "size %zd",
2542 PySequence_Fast_GET_SIZE(seq),
2543 slicelength);
2544 Py_DECREF(seq);
2545 return -1;
2546 }
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 if (!slicelength) {
2549 Py_DECREF(seq);
2550 return 0;
2551 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 garbage = (PyObject**)
2554 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2555 if (!garbage) {
2556 Py_DECREF(seq);
2557 PyErr_NoMemory();
2558 return -1;
2559 }
Tim Peters3b01a122002-07-19 02:35:45 +00002560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 selfitems = self->ob_item;
2562 seqitems = PySequence_Fast_ITEMS(seq);
2563 for (cur = start, i = 0; i < slicelength;
2564 cur += step, i++) {
2565 garbage[i] = selfitems[cur];
2566 ins = seqitems[i];
2567 Py_INCREF(ins);
2568 selfitems[cur] = ins;
2569 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 for (i = 0; i < slicelength; i++) {
2572 Py_DECREF(garbage[i]);
2573 }
Tim Peters3b01a122002-07-19 02:35:45 +00002574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 PyMem_FREE(garbage);
2576 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 return 0;
2579 }
2580 }
2581 else {
2582 PyErr_Format(PyExc_TypeError,
2583 "list indices must be integers, not %.200s",
2584 item->ob_type->tp_name);
2585 return -1;
2586 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002587}
2588
2589static PyMappingMethods list_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002590 (lenfunc)list_length,
2591 (binaryfunc)list_subscript,
2592 (objobjargproc)list_ass_subscript
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002593};
2594
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002595PyTypeObject PyList_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2597 "list",
2598 sizeof(PyListObject),
2599 0,
2600 (destructor)list_dealloc, /* tp_dealloc */
2601 0, /* tp_print */
2602 0, /* tp_getattr */
2603 0, /* tp_setattr */
2604 0, /* tp_reserved */
2605 (reprfunc)list_repr, /* tp_repr */
2606 0, /* tp_as_number */
2607 &list_as_sequence, /* tp_as_sequence */
2608 &list_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00002609 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 0, /* tp_call */
2611 0, /* tp_str */
2612 PyObject_GenericGetAttr, /* tp_getattro */
2613 0, /* tp_setattro */
2614 0, /* tp_as_buffer */
2615 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2616 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
2617 list_doc, /* tp_doc */
2618 (traverseproc)list_traverse, /* tp_traverse */
2619 (inquiry)list_clear, /* tp_clear */
2620 list_richcompare, /* tp_richcompare */
2621 0, /* tp_weaklistoffset */
2622 list_iter, /* tp_iter */
2623 0, /* tp_iternext */
2624 list_methods, /* tp_methods */
2625 0, /* tp_members */
2626 0, /* tp_getset */
2627 0, /* tp_base */
2628 0, /* tp_dict */
2629 0, /* tp_descr_get */
2630 0, /* tp_descr_set */
2631 0, /* tp_dictoffset */
2632 (initproc)list_init, /* tp_init */
2633 PyType_GenericAlloc, /* tp_alloc */
2634 PyType_GenericNew, /* tp_new */
2635 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002636};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002637
2638
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002639/*********************** List Iterator **************************/
2640
2641typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 PyObject_HEAD
2643 long it_index;
2644 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002645} listiterobject;
2646
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002647static PyObject *list_iter(PyObject *);
2648static void listiter_dealloc(listiterobject *);
2649static int listiter_traverse(listiterobject *, visitproc, void *);
2650static PyObject *listiter_next(listiterobject *);
2651static PyObject *listiter_len(listiterobject *);
Raymond Hettinger435bf582004-03-18 22:43:10 +00002652
Armin Rigof5b3e362006-02-11 21:32:43 +00002653PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002654
2655static PyMethodDef listiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
2657 {NULL, NULL} /* sentinel */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002658};
2659
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002660PyTypeObject PyListIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002661 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2662 "list_iterator", /* tp_name */
2663 sizeof(listiterobject), /* tp_basicsize */
2664 0, /* tp_itemsize */
2665 /* methods */
2666 (destructor)listiter_dealloc, /* tp_dealloc */
2667 0, /* tp_print */
2668 0, /* tp_getattr */
2669 0, /* tp_setattr */
2670 0, /* tp_reserved */
2671 0, /* tp_repr */
2672 0, /* tp_as_number */
2673 0, /* tp_as_sequence */
2674 0, /* tp_as_mapping */
2675 0, /* tp_hash */
2676 0, /* tp_call */
2677 0, /* tp_str */
2678 PyObject_GenericGetAttr, /* tp_getattro */
2679 0, /* tp_setattro */
2680 0, /* tp_as_buffer */
2681 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2682 0, /* tp_doc */
2683 (traverseproc)listiter_traverse, /* tp_traverse */
2684 0, /* tp_clear */
2685 0, /* tp_richcompare */
2686 0, /* tp_weaklistoffset */
2687 PyObject_SelfIter, /* tp_iter */
2688 (iternextfunc)listiter_next, /* tp_iternext */
2689 listiter_methods, /* tp_methods */
2690 0, /* tp_members */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002691};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002692
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002693
2694static PyObject *
2695list_iter(PyObject *seq)
2696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 listiterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002699 if (!PyList_Check(seq)) {
2700 PyErr_BadInternalCall();
2701 return NULL;
2702 }
2703 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2704 if (it == NULL)
2705 return NULL;
2706 it->it_index = 0;
2707 Py_INCREF(seq);
2708 it->it_seq = (PyListObject *)seq;
2709 _PyObject_GC_TRACK(it);
2710 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002711}
2712
2713static void
2714listiter_dealloc(listiterobject *it)
2715{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 _PyObject_GC_UNTRACK(it);
2717 Py_XDECREF(it->it_seq);
2718 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002719}
2720
2721static int
2722listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002724 Py_VISIT(it->it_seq);
2725 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002726}
2727
2728static PyObject *
2729listiter_next(listiterobject *it)
2730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 PyListObject *seq;
2732 PyObject *item;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 assert(it != NULL);
2735 seq = it->it_seq;
2736 if (seq == NULL)
2737 return NULL;
2738 assert(PyList_Check(seq));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 if (it->it_index < PyList_GET_SIZE(seq)) {
2741 item = PyList_GET_ITEM(seq, it->it_index);
2742 ++it->it_index;
2743 Py_INCREF(item);
2744 return item;
2745 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002746
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002747 Py_DECREF(seq);
2748 it->it_seq = NULL;
2749 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002750}
2751
2752static PyObject *
2753listiter_len(listiterobject *it)
2754{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002755 Py_ssize_t len;
2756 if (it->it_seq) {
2757 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2758 if (len >= 0)
2759 return PyLong_FromSsize_t(len);
2760 }
2761 return PyLong_FromLong(0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002762}
Raymond Hettinger1021c442003-11-07 15:38:09 +00002763/*********************** List Reverse Iterator **************************/
2764
2765typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002766 PyObject_HEAD
2767 Py_ssize_t it_index;
2768 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002769} listreviterobject;
2770
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002771static PyObject *list_reversed(PyListObject *, PyObject *);
2772static void listreviter_dealloc(listreviterobject *);
2773static int listreviter_traverse(listreviterobject *, visitproc, void *);
2774static PyObject *listreviter_next(listreviterobject *);
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002775static PyObject *listreviter_len(listreviterobject *);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002776
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002777static PyMethodDef listreviter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc},
2779 {NULL, NULL} /* sentinel */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002780};
2781
Raymond Hettinger1021c442003-11-07 15:38:09 +00002782PyTypeObject PyListRevIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2784 "list_reverseiterator", /* tp_name */
2785 sizeof(listreviterobject), /* tp_basicsize */
2786 0, /* tp_itemsize */
2787 /* methods */
2788 (destructor)listreviter_dealloc, /* tp_dealloc */
2789 0, /* tp_print */
2790 0, /* tp_getattr */
2791 0, /* tp_setattr */
2792 0, /* tp_reserved */
2793 0, /* tp_repr */
2794 0, /* tp_as_number */
2795 0, /* tp_as_sequence */
2796 0, /* tp_as_mapping */
2797 0, /* tp_hash */
2798 0, /* tp_call */
2799 0, /* tp_str */
2800 PyObject_GenericGetAttr, /* tp_getattro */
2801 0, /* tp_setattro */
2802 0, /* tp_as_buffer */
2803 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2804 0, /* tp_doc */
2805 (traverseproc)listreviter_traverse, /* tp_traverse */
2806 0, /* tp_clear */
2807 0, /* tp_richcompare */
2808 0, /* tp_weaklistoffset */
2809 PyObject_SelfIter, /* tp_iter */
2810 (iternextfunc)listreviter_next, /* tp_iternext */
2811 listreviter_methods, /* tp_methods */
2812 0,
Raymond Hettinger1021c442003-11-07 15:38:09 +00002813};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002814
2815static PyObject *
2816list_reversed(PyListObject *seq, PyObject *unused)
2817{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002818 listreviterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002820 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2821 if (it == NULL)
2822 return NULL;
2823 assert(PyList_Check(seq));
2824 it->it_index = PyList_GET_SIZE(seq) - 1;
2825 Py_INCREF(seq);
2826 it->it_seq = seq;
2827 PyObject_GC_Track(it);
2828 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002829}
2830
2831static void
2832listreviter_dealloc(listreviterobject *it)
2833{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 PyObject_GC_UnTrack(it);
2835 Py_XDECREF(it->it_seq);
2836 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002837}
2838
2839static int
2840listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2841{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002842 Py_VISIT(it->it_seq);
2843 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002844}
2845
2846static PyObject *
2847listreviter_next(listreviterobject *it)
2848{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002849 PyObject *item;
2850 Py_ssize_t index = it->it_index;
2851 PyListObject *seq = it->it_seq;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2854 item = PyList_GET_ITEM(seq, index);
2855 it->it_index--;
2856 Py_INCREF(item);
2857 return item;
2858 }
2859 it->it_index = -1;
2860 if (seq != NULL) {
2861 it->it_seq = NULL;
2862 Py_DECREF(seq);
2863 }
2864 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002865}
2866
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002867static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002868listreviter_len(listreviterobject *it)
2869{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002870 Py_ssize_t len = it->it_index + 1;
2871 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
2872 len = 0;
2873 return PyLong_FromSsize_t(len);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002874}