blob: 3642b39dd132f6402f0ffe30c0e91bd01f8540ec [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"
Antoine Pitrou0197ff92012-03-22 14:38:16 +01004#include "accu.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00005
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00006#ifdef STDC_HEADERS
7#include <stddef.h>
8#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00009#include <sys/types.h> /* For size_t */
Guido van Rossum6cd2fe01994-08-29 12:45:32 +000010#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011
Tim Peters8d9eb102004-07-31 02:24:20 +000012/* Ensure ob_item has room for at least newsize elements, and set
13 * ob_size to newsize. If newsize > ob_size on entry, the content
14 * of the new slots at exit is undefined heap trash; it's the caller's
Ezio Melotti13925002011-03-16 11:05:33 +020015 * responsibility to overwrite them with sane values.
Tim Peters8d9eb102004-07-31 02:24:20 +000016 * The number of allocated elements may grow, shrink, or stay the same.
17 * Failure is impossible if newsize <= self.allocated on entry, although
18 * that partly relies on an assumption that the system realloc() never
19 * fails when passed a number of bytes <= the number of bytes last
20 * allocated (the C standard doesn't guarantee this, but it's hard to
21 * imagine a realloc implementation where it wouldn't be true).
22 * Note that self->ob_item may change, and even if newsize is less
23 * than ob_size on entry.
24 */
Guido van Rossuma46d51d1995-01-26 22:59:43 +000025static int
Martin v. Löwis18e16552006-02-15 17:27:45 +000026list_resize(PyListObject *self, Py_ssize_t newsize)
Guido van Rossuma46d51d1995-01-26 22:59:43 +000027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000028 PyObject **items;
29 size_t new_allocated;
30 Py_ssize_t allocated = self->allocated;
Tim Peters65b8b842001-05-26 05:28:40 +000031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000032 /* Bypass realloc() when a previous overallocation is large enough
33 to accommodate the newsize. If the newsize falls lower than half
34 the allocated size, then proceed with the realloc() to shrink the list.
35 */
36 if (allocated >= newsize && newsize >= (allocated >> 1)) {
37 assert(self->ob_item != NULL || newsize == 0);
38 Py_SIZE(self) = newsize;
39 return 0;
40 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +000041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000042 /* This over-allocates proportional to the list size, making room
43 * for additional growth. The over-allocation is mild, but is
44 * enough to give linear-time amortized behavior over a long
45 * sequence of appends() in the presence of a poorly-performing
46 * system realloc().
47 * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
48 */
49 new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6);
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +000050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051 /* check for integer overflow */
52 if (new_allocated > PY_SIZE_MAX - newsize) {
53 PyErr_NoMemory();
54 return -1;
55 } else {
56 new_allocated += newsize;
57 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +000058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000059 if (newsize == 0)
60 new_allocated = 0;
61 items = self->ob_item;
Mark Dickinsonc0420fd2011-09-19 19:18:37 +010062 if (new_allocated <= (PY_SIZE_MAX / sizeof(PyObject *)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 PyMem_RESIZE(items, PyObject *, new_allocated);
64 else
65 items = NULL;
66 if (items == NULL) {
67 PyErr_NoMemory();
68 return -1;
69 }
70 self->ob_item = items;
71 Py_SIZE(self) = newsize;
72 self->allocated = new_allocated;
73 return 0;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000074}
Guido van Rossuma46d51d1995-01-26 22:59:43 +000075
Christian Heimes77c02eb2008-02-09 02:18:51 +000076/* Debug statistic to compare allocations with reuse through the free list */
77#undef SHOW_ALLOC_COUNT
78#ifdef SHOW_ALLOC_COUNT
79static size_t count_alloc = 0;
80static size_t count_reuse = 0;
81
82static void
83show_alloc(void)
84{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000085 fprintf(stderr, "List allocations: %" PY_FORMAT_SIZE_T "d\n",
86 count_alloc);
87 fprintf(stderr, "List reuse through freelist: %" PY_FORMAT_SIZE_T
88 "d\n", count_reuse);
89 fprintf(stderr, "%.2f%% reuse rate\n\n",
90 (100.0*count_reuse/(count_alloc+count_reuse)));
Christian Heimes77c02eb2008-02-09 02:18:51 +000091}
92#endif
93
Raymond Hettinger0468e412004-05-05 05:37:53 +000094/* Empty list reuse scheme to save calls to malloc and free */
Christian Heimes2202f872008-02-06 14:31:34 +000095#ifndef PyList_MAXFREELIST
96#define PyList_MAXFREELIST 80
97#endif
98static PyListObject *free_list[PyList_MAXFREELIST];
99static int numfree = 0;
Raymond Hettinger0468e412004-05-05 05:37:53 +0000100
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000101void
102PyList_Fini(void)
103{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 PyListObject *op;
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 while (numfree) {
107 op = free_list[--numfree];
108 assert(PyList_CheckExact(op));
109 PyObject_GC_Del(op);
110 }
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000111}
112
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000113PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000114PyList_New(Py_ssize_t size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000115{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 PyListObject *op;
117 size_t nbytes;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000118#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 static int initialized = 0;
120 if (!initialized) {
121 Py_AtExit(show_alloc);
122 initialized = 1;
123 }
Christian Heimes77c02eb2008-02-09 02:18:51 +0000124#endif
Tim Peters3986d4e2004-07-29 02:28:42 +0000125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 if (size < 0) {
127 PyErr_BadInternalCall();
128 return NULL;
129 }
130 /* Check for overflow without an actual overflow,
131 * which can cause compiler to optimise out */
132 if ((size_t)size > PY_SIZE_MAX / sizeof(PyObject *))
133 return PyErr_NoMemory();
134 nbytes = size * sizeof(PyObject *);
135 if (numfree) {
136 numfree--;
137 op = free_list[numfree];
138 _Py_NewReference((PyObject *)op);
Christian Heimes77c02eb2008-02-09 02:18:51 +0000139#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 count_reuse++;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000141#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 } else {
143 op = PyObject_GC_New(PyListObject, &PyList_Type);
144 if (op == NULL)
145 return NULL;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000146#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 count_alloc++;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000148#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 }
150 if (size <= 0)
151 op->ob_item = NULL;
152 else {
153 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
154 if (op->ob_item == NULL) {
155 Py_DECREF(op);
156 return PyErr_NoMemory();
157 }
158 memset(op->ob_item, 0, nbytes);
159 }
160 Py_SIZE(op) = size;
161 op->allocated = size;
162 _PyObject_GC_TRACK(op);
163 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000164}
165
Martin v. Löwis18e16552006-02-15 17:27:45 +0000166Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000167PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000168{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 if (!PyList_Check(op)) {
170 PyErr_BadInternalCall();
171 return -1;
172 }
173 else
174 return Py_SIZE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000175}
176
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000177static PyObject *indexerr = NULL;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000178
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000179PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000180PyList_GetItem(PyObject *op, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 if (!PyList_Check(op)) {
183 PyErr_BadInternalCall();
184 return NULL;
185 }
186 if (i < 0 || i >= Py_SIZE(op)) {
187 if (indexerr == NULL) {
188 indexerr = PyUnicode_FromString(
189 "list index out of range");
190 if (indexerr == NULL)
191 return NULL;
192 }
193 PyErr_SetObject(PyExc_IndexError, indexerr);
194 return NULL;
195 }
196 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000197}
198
199int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000200PyList_SetItem(register PyObject *op, register Py_ssize_t i,
Fred Drakea2f55112000-07-09 15:16:51 +0000201 register PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000202{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 register PyObject *olditem;
204 register PyObject **p;
205 if (!PyList_Check(op)) {
206 Py_XDECREF(newitem);
207 PyErr_BadInternalCall();
208 return -1;
209 }
210 if (i < 0 || i >= Py_SIZE(op)) {
211 Py_XDECREF(newitem);
212 PyErr_SetString(PyExc_IndexError,
213 "list assignment index out of range");
214 return -1;
215 }
216 p = ((PyListObject *)op) -> ob_item + i;
217 olditem = *p;
218 *p = newitem;
219 Py_XDECREF(olditem);
220 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000221}
222
223static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000224ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 Py_ssize_t i, n = Py_SIZE(self);
227 PyObject **items;
228 if (v == NULL) {
229 PyErr_BadInternalCall();
230 return -1;
231 }
232 if (n == PY_SSIZE_T_MAX) {
233 PyErr_SetString(PyExc_OverflowError,
234 "cannot add more objects to list");
235 return -1;
236 }
Tim Petersb38e2b62004-07-29 02:29:26 +0000237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 if (list_resize(self, n+1) == -1)
239 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 if (where < 0) {
242 where += n;
243 if (where < 0)
244 where = 0;
245 }
246 if (where > n)
247 where = n;
248 items = self->ob_item;
249 for (i = n; --i >= where; )
250 items[i+1] = items[i];
251 Py_INCREF(v);
252 items[where] = v;
253 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000254}
255
256int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000257PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 if (!PyList_Check(op)) {
260 PyErr_BadInternalCall();
261 return -1;
262 }
263 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000264}
265
Raymond Hettinger40a03822004-04-12 13:05:09 +0000266static int
267app1(PyListObject *self, PyObject *v)
268{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 Py_ssize_t n = PyList_GET_SIZE(self);
Raymond Hettinger40a03822004-04-12 13:05:09 +0000270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 assert (v != NULL);
272 if (n == PY_SSIZE_T_MAX) {
273 PyErr_SetString(PyExc_OverflowError,
274 "cannot add more objects to list");
275 return -1;
276 }
Raymond Hettinger40a03822004-04-12 13:05:09 +0000277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 if (list_resize(self, n+1) == -1)
279 return -1;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 Py_INCREF(v);
282 PyList_SET_ITEM(self, n, v);
283 return 0;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000284}
285
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000286int
Fred Drakea2f55112000-07-09 15:16:51 +0000287PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 if (PyList_Check(op) && (newitem != NULL))
290 return app1((PyListObject *)op, newitem);
291 PyErr_BadInternalCall();
292 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000293}
294
295/* Methods */
296
297static void
Fred Drakea2f55112000-07-09 15:16:51 +0000298list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000299{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 Py_ssize_t i;
301 PyObject_GC_UnTrack(op);
302 Py_TRASHCAN_SAFE_BEGIN(op)
303 if (op->ob_item != NULL) {
304 /* Do it backwards, for Christian Tismer.
305 There's a simple test case where somehow this reduces
306 thrashing when a *very* large list is created and
307 immediately deleted. */
308 i = Py_SIZE(op);
309 while (--i >= 0) {
310 Py_XDECREF(op->ob_item[i]);
311 }
312 PyMem_FREE(op->ob_item);
313 }
314 if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op))
315 free_list[numfree++] = op;
316 else
317 Py_TYPE(op)->tp_free((PyObject *)op);
318 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000319}
320
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000321static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000322list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 Py_ssize_t i;
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200325 PyObject *s = NULL;
326 _PyAccu acc;
327 static PyObject *sep = NULL;
328
329 if (Py_SIZE(v) == 0) {
330 return PyUnicode_FromString("[]");
331 }
332
333 if (sep == NULL) {
334 sep = PyUnicode_FromString(", ");
335 if (sep == NULL)
336 return NULL;
337 }
Guido van Rossumfb376de1998-04-10 22:47:27 +0000338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 i = Py_ReprEnter((PyObject*)v);
340 if (i != 0) {
341 return i > 0 ? PyUnicode_FromString("[...]") : NULL;
342 }
Tim Petersa7259592001-06-16 05:11:17 +0000343
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200344 if (_PyAccu_Init(&acc))
345 goto error;
Tim Petersa7259592001-06-16 05:11:17 +0000346
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200347 s = PyUnicode_FromString("[");
348 if (s == NULL || _PyAccu_Accumulate(&acc, s))
349 goto error;
350 Py_CLEAR(s);
Tim Petersa7259592001-06-16 05:11:17 +0000351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 /* Do repr() on each element. Note that this may mutate the list,
353 so must refetch the list size on each iteration. */
354 for (i = 0; i < Py_SIZE(v); ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 if (Py_EnterRecursiveCall(" while getting the repr of a list"))
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200356 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 s = PyObject_Repr(v->ob_item[i]);
358 Py_LeaveRecursiveCall();
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200359 if (i > 0 && _PyAccu_Accumulate(&acc, sep))
360 goto error;
361 if (s == NULL || _PyAccu_Accumulate(&acc, s))
362 goto error;
363 Py_CLEAR(s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 s = PyUnicode_FromString("]");
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200366 if (s == NULL || _PyAccu_Accumulate(&acc, s))
367 goto error;
368 Py_CLEAR(s);
Tim Petersa7259592001-06-16 05:11:17 +0000369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 Py_ReprLeave((PyObject *)v);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200371 return _PyAccu_Finish(&acc);
372
373error:
374 _PyAccu_Destroy(&acc);
375 Py_XDECREF(s);
376 Py_ReprLeave((PyObject *)v);
377 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000378}
379
Martin v. Löwis18e16552006-02-15 17:27:45 +0000380static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000381list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 return Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000384}
385
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000386static int
Fred Drakea2f55112000-07-09 15:16:51 +0000387list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 Py_ssize_t i;
390 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
393 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
394 Py_EQ);
395 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000396}
397
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000398static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000399list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 if (i < 0 || i >= Py_SIZE(a)) {
402 if (indexerr == NULL) {
403 indexerr = PyUnicode_FromString(
404 "list index out of range");
405 if (indexerr == NULL)
406 return NULL;
407 }
408 PyErr_SetObject(PyExc_IndexError, indexerr);
409 return NULL;
410 }
411 Py_INCREF(a->ob_item[i]);
412 return a->ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000413}
414
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000415static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000416list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 PyListObject *np;
419 PyObject **src, **dest;
420 Py_ssize_t i, len;
421 if (ilow < 0)
422 ilow = 0;
423 else if (ilow > Py_SIZE(a))
424 ilow = Py_SIZE(a);
425 if (ihigh < ilow)
426 ihigh = ilow;
427 else if (ihigh > Py_SIZE(a))
428 ihigh = Py_SIZE(a);
429 len = ihigh - ilow;
430 np = (PyListObject *) PyList_New(len);
431 if (np == NULL)
432 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 src = a->ob_item + ilow;
435 dest = np->ob_item;
436 for (i = 0; i < len; i++) {
437 PyObject *v = src[i];
438 Py_INCREF(v);
439 dest[i] = v;
440 }
441 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000442}
443
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000444PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000445PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000446{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 if (!PyList_Check(a)) {
448 PyErr_BadInternalCall();
449 return NULL;
450 }
451 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000452}
453
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000454static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000455list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000456{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 Py_ssize_t size;
458 Py_ssize_t i;
459 PyObject **src, **dest;
460 PyListObject *np;
461 if (!PyList_Check(bb)) {
462 PyErr_Format(PyExc_TypeError,
463 "can only concatenate list (not \"%.200s\") to list",
464 bb->ob_type->tp_name);
465 return NULL;
466 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000467#define b ((PyListObject *)bb)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 size = Py_SIZE(a) + Py_SIZE(b);
469 if (size < 0)
470 return PyErr_NoMemory();
471 np = (PyListObject *) PyList_New(size);
472 if (np == NULL) {
473 return NULL;
474 }
475 src = a->ob_item;
476 dest = np->ob_item;
477 for (i = 0; i < Py_SIZE(a); i++) {
478 PyObject *v = src[i];
479 Py_INCREF(v);
480 dest[i] = v;
481 }
482 src = b->ob_item;
483 dest = np->ob_item + Py_SIZE(a);
484 for (i = 0; i < Py_SIZE(b); i++) {
485 PyObject *v = src[i];
486 Py_INCREF(v);
487 dest[i] = v;
488 }
489 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000490#undef b
491}
492
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000493static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000494list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000495{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 Py_ssize_t i, j;
497 Py_ssize_t size;
498 PyListObject *np;
499 PyObject **p, **items;
500 PyObject *elem;
501 if (n < 0)
502 n = 0;
Mark Dickinsonc0420fd2011-09-19 19:18:37 +0100503 if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 return PyErr_NoMemory();
Mark Dickinsonc0420fd2011-09-19 19:18:37 +0100505 size = Py_SIZE(a) * n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 if (size == 0)
507 return PyList_New(0);
508 np = (PyListObject *) PyList_New(size);
509 if (np == NULL)
510 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 items = np->ob_item;
513 if (Py_SIZE(a) == 1) {
514 elem = a->ob_item[0];
515 for (i = 0; i < n; i++) {
516 items[i] = elem;
517 Py_INCREF(elem);
518 }
519 return (PyObject *) np;
520 }
521 p = np->ob_item;
522 items = a->ob_item;
523 for (i = 0; i < n; i++) {
524 for (j = 0; j < Py_SIZE(a); j++) {
525 *p = items[j];
526 Py_INCREF(*p);
527 p++;
528 }
529 }
530 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000531}
532
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000533static int
Armin Rigo93677f02004-07-29 12:40:23 +0000534list_clear(PyListObject *a)
535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 Py_ssize_t i;
537 PyObject **item = a->ob_item;
538 if (item != NULL) {
539 /* Because XDECREF can recursively invoke operations on
540 this list, we make it empty first. */
541 i = Py_SIZE(a);
542 Py_SIZE(a) = 0;
543 a->ob_item = NULL;
544 a->allocated = 0;
545 while (--i >= 0) {
546 Py_XDECREF(item[i]);
547 }
548 PyMem_FREE(item);
549 }
550 /* Never fails; the return value can be ignored.
551 Note that there is no guarantee that the list is actually empty
552 at this point, because XDECREF may have populated it again! */
553 return 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000554}
555
Tim Peters8fc4a912004-07-31 21:53:19 +0000556/* a[ilow:ihigh] = v if v != NULL.
557 * del a[ilow:ihigh] if v == NULL.
558 *
559 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
560 * guaranteed the call cannot fail.
561 */
Armin Rigo93677f02004-07-29 12:40:23 +0000562static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000563list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 /* Because [X]DECREF can recursively invoke list operations on
566 this list, we must postpone all [X]DECREF activity until
567 after the list is back in its canonical shape. Therefore
568 we must allocate an additional array, 'recycle', into which
569 we temporarily copy the items that are deleted from the
570 list. :-( */
571 PyObject *recycle_on_stack[8];
572 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
573 PyObject **item;
574 PyObject **vitem = NULL;
575 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
576 Py_ssize_t n; /* # of elements in replacement list */
577 Py_ssize_t norig; /* # of elements in list getting replaced */
578 Py_ssize_t d; /* Change in size */
579 Py_ssize_t k;
580 size_t s;
581 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000582#define b ((PyListObject *)v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 if (v == NULL)
584 n = 0;
585 else {
586 if (a == b) {
587 /* Special case "a[i:j] = a" -- copy b first */
588 v = list_slice(b, 0, Py_SIZE(b));
589 if (v == NULL)
590 return result;
591 result = list_ass_slice(a, ilow, ihigh, v);
592 Py_DECREF(v);
593 return result;
594 }
595 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
596 if(v_as_SF == NULL)
597 goto Error;
598 n = PySequence_Fast_GET_SIZE(v_as_SF);
599 vitem = PySequence_Fast_ITEMS(v_as_SF);
600 }
601 if (ilow < 0)
602 ilow = 0;
603 else if (ilow > Py_SIZE(a))
604 ilow = Py_SIZE(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 if (ihigh < ilow)
607 ihigh = ilow;
608 else if (ihigh > Py_SIZE(a))
609 ihigh = Py_SIZE(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 norig = ihigh - ilow;
612 assert(norig >= 0);
613 d = n - norig;
614 if (Py_SIZE(a) + d == 0) {
615 Py_XDECREF(v_as_SF);
616 return list_clear(a);
617 }
618 item = a->ob_item;
619 /* recycle the items that we are about to remove */
620 s = norig * sizeof(PyObject *);
621 if (s > sizeof(recycle_on_stack)) {
622 recycle = (PyObject **)PyMem_MALLOC(s);
623 if (recycle == NULL) {
624 PyErr_NoMemory();
625 goto Error;
626 }
627 }
628 memcpy(recycle, &item[ilow], s);
Tim Peters8d9eb102004-07-31 02:24:20 +0000629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 if (d < 0) { /* Delete -d items */
631 memmove(&item[ihigh+d], &item[ihigh],
632 (Py_SIZE(a) - ihigh)*sizeof(PyObject *));
633 list_resize(a, Py_SIZE(a) + d);
634 item = a->ob_item;
635 }
636 else if (d > 0) { /* Insert d items */
637 k = Py_SIZE(a);
638 if (list_resize(a, k+d) < 0)
639 goto Error;
640 item = a->ob_item;
641 memmove(&item[ihigh+d], &item[ihigh],
642 (k - ihigh)*sizeof(PyObject *));
643 }
644 for (k = 0; k < n; k++, ilow++) {
645 PyObject *w = vitem[k];
646 Py_XINCREF(w);
647 item[ilow] = w;
648 }
649 for (k = norig - 1; k >= 0; --k)
650 Py_XDECREF(recycle[k]);
651 result = 0;
Tim Peters8d9eb102004-07-31 02:24:20 +0000652 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 if (recycle != recycle_on_stack)
654 PyMem_FREE(recycle);
655 Py_XDECREF(v_as_SF);
656 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000657#undef b
658}
659
Guido van Rossum234f9421993-06-17 12:35:49 +0000660int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000661PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 if (!PyList_Check(a)) {
664 PyErr_BadInternalCall();
665 return -1;
666 }
667 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000668}
669
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000670static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000671list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000672{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 PyObject **items;
674 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000675
676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 size = PyList_GET_SIZE(self);
678 if (size == 0 || n == 1) {
679 Py_INCREF(self);
680 return (PyObject *)self;
681 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000682
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 if (n < 1) {
684 (void)list_clear(self);
685 Py_INCREF(self);
686 return (PyObject *)self;
687 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 if (size > PY_SSIZE_T_MAX / n) {
690 return PyErr_NoMemory();
691 }
Christian Heimesaf98da12008-01-27 15:18:18 +0000692
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 if (list_resize(self, size*n) == -1)
694 return NULL;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 p = size;
697 items = self->ob_item;
698 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
699 for (j = 0; j < size; j++) {
700 PyObject *o = items[j];
701 Py_INCREF(o);
702 items[p++] = o;
703 }
704 }
705 Py_INCREF(self);
706 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000707}
708
Guido van Rossum4a450d01991-04-03 19:05:18 +0000709static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000710list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 PyObject *old_value;
713 if (i < 0 || i >= Py_SIZE(a)) {
714 PyErr_SetString(PyExc_IndexError,
715 "list assignment index out of range");
716 return -1;
717 }
718 if (v == NULL)
719 return list_ass_slice(a, i, i+1, v);
720 Py_INCREF(v);
721 old_value = a->ob_item[i];
722 a->ob_item[i] = v;
723 Py_DECREF(old_value);
724 return 0;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000725}
726
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000727static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000728listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000729{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 Py_ssize_t i;
731 PyObject *v;
732 if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
733 return NULL;
734 if (ins1(self, i, v) == 0)
735 Py_RETURN_NONE;
736 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000737}
738
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000739static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000740listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000741{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 if (app1(self, v) == 0)
743 Py_RETURN_NONE;
744 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000745}
746
Barry Warsawdedf6d61998-10-09 16:37:25 +0000747static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000748listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 PyObject *it; /* iter(v) */
751 Py_ssize_t m; /* size of self */
752 Py_ssize_t n; /* guess for size of b */
753 Py_ssize_t mn; /* m + n */
754 Py_ssize_t i;
755 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 /* Special cases:
758 1) lists and tuples which can use PySequence_Fast ops
759 2) extending self to self requires making a copy first
760 */
761 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
762 PyObject **src, **dest;
763 b = PySequence_Fast(b, "argument must be iterable");
764 if (!b)
765 return NULL;
766 n = PySequence_Fast_GET_SIZE(b);
767 if (n == 0) {
768 /* short circuit when b is empty */
769 Py_DECREF(b);
770 Py_RETURN_NONE;
771 }
772 m = Py_SIZE(self);
773 if (list_resize(self, m + n) == -1) {
774 Py_DECREF(b);
775 return NULL;
776 }
777 /* note that we may still have self == b here for the
778 * situation a.extend(a), but the following code works
779 * in that case too. Just make sure to resize self
780 * before calling PySequence_Fast_ITEMS.
781 */
782 /* populate the end of self with b's items */
783 src = PySequence_Fast_ITEMS(b);
784 dest = self->ob_item + m;
785 for (i = 0; i < n; i++) {
786 PyObject *o = src[i];
787 Py_INCREF(o);
788 dest[i] = o;
789 }
790 Py_DECREF(b);
791 Py_RETURN_NONE;
792 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 it = PyObject_GetIter(b);
795 if (it == NULL)
796 return NULL;
797 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 /* Guess a result list size. */
800 n = _PyObject_LengthHint(b, 8);
801 if (n == -1) {
802 Py_DECREF(it);
803 return NULL;
804 }
805 m = Py_SIZE(self);
806 mn = m + n;
807 if (mn >= m) {
808 /* Make room. */
809 if (list_resize(self, mn) == -1)
810 goto error;
811 /* Make the list sane again. */
812 Py_SIZE(self) = m;
813 }
814 /* Else m + n overflowed; on the chance that n lied, and there really
815 * is enough room, ignore it. If n was telling the truth, we'll
816 * eventually run out of memory during the loop.
817 */
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 /* Run iterator to exhaustion. */
820 for (;;) {
821 PyObject *item = iternext(it);
822 if (item == NULL) {
823 if (PyErr_Occurred()) {
824 if (PyErr_ExceptionMatches(PyExc_StopIteration))
825 PyErr_Clear();
826 else
827 goto error;
828 }
829 break;
830 }
831 if (Py_SIZE(self) < self->allocated) {
832 /* steals ref */
833 PyList_SET_ITEM(self, Py_SIZE(self), item);
834 ++Py_SIZE(self);
835 }
836 else {
837 int status = app1(self, item);
838 Py_DECREF(item); /* append creates a new ref */
839 if (status < 0)
840 goto error;
841 }
842 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 /* Cut back result list if initial guess was too large. */
845 if (Py_SIZE(self) < self->allocated)
846 list_resize(self, Py_SIZE(self)); /* shrinking can't fail */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 Py_DECREF(it);
849 Py_RETURN_NONE;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000850
851 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 Py_DECREF(it);
853 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000854}
855
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000856PyObject *
857_PyList_Extend(PyListObject *self, PyObject *b)
858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 return listextend(self, b);
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000860}
861
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000862static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000863list_inplace_concat(PyListObject *self, PyObject *other)
864{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 PyObject *result;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 result = listextend(self, other);
868 if (result == NULL)
869 return result;
870 Py_DECREF(result);
871 Py_INCREF(self);
872 return (PyObject *)self;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000873}
874
875static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000876listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000877{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 Py_ssize_t i = -1;
879 PyObject *v;
880 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 if (!PyArg_ParseTuple(args, "|n:pop", &i))
883 return NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 if (Py_SIZE(self) == 0) {
886 /* Special-case most common failure cause */
887 PyErr_SetString(PyExc_IndexError, "pop from empty list");
888 return NULL;
889 }
890 if (i < 0)
891 i += Py_SIZE(self);
892 if (i < 0 || i >= Py_SIZE(self)) {
893 PyErr_SetString(PyExc_IndexError, "pop index out of range");
894 return NULL;
895 }
896 v = self->ob_item[i];
897 if (i == Py_SIZE(self) - 1) {
898 status = list_resize(self, Py_SIZE(self) - 1);
899 assert(status >= 0);
900 return v; /* and v now owns the reference the list had */
901 }
902 Py_INCREF(v);
903 status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
904 assert(status >= 0);
905 /* Use status, so that in a release build compilers don't
906 * complain about the unused name.
907 */
908 (void) status;
Brett Cannon651dd522004-08-08 21:21:18 +0000909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000911}
912
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000913/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
914static void
915reverse_slice(PyObject **lo, PyObject **hi)
916{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 assert(lo && hi);
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 --hi;
920 while (lo < hi) {
921 PyObject *t = *lo;
922 *lo = *hi;
923 *hi = t;
924 ++lo;
925 --hi;
926 }
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000927}
928
Tim Petersa64dc242002-08-01 02:13:36 +0000929/* Lots of code for an adaptive, stable, natural mergesort. There are many
930 * pieces to this algorithm; read listsort.txt for overviews and details.
931 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000932
Daniel Stutzbach98338222010-12-02 21:55:33 +0000933/* A sortslice contains a pointer to an array of keys and a pointer to
934 * an array of corresponding values. In other words, keys[i]
935 * corresponds with values[i]. If values == NULL, then the keys are
936 * also the values.
937 *
938 * Several convenience routines are provided here, so that keys and
939 * values are always moved in sync.
940 */
941
942typedef struct {
943 PyObject **keys;
944 PyObject **values;
945} sortslice;
946
947Py_LOCAL_INLINE(void)
948sortslice_copy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j)
949{
950 s1->keys[i] = s2->keys[j];
951 if (s1->values != NULL)
952 s1->values[i] = s2->values[j];
953}
954
955Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +0000956sortslice_copy_incr(sortslice *dst, sortslice *src)
957{
Daniel Stutzbach98338222010-12-02 21:55:33 +0000958 *dst->keys++ = *src->keys++;
959 if (dst->values != NULL)
960 *dst->values++ = *src->values++;
961}
962
963Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +0000964sortslice_copy_decr(sortslice *dst, sortslice *src)
965{
Daniel Stutzbach98338222010-12-02 21:55:33 +0000966 *dst->keys-- = *src->keys--;
967 if (dst->values != NULL)
968 *dst->values-- = *src->values--;
969}
970
971
972Py_LOCAL_INLINE(void)
973sortslice_memcpy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +0000974 Py_ssize_t n)
975{
Daniel Stutzbach98338222010-12-02 21:55:33 +0000976 memcpy(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
977 if (s1->values != NULL)
978 memcpy(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
979}
980
981Py_LOCAL_INLINE(void)
982sortslice_memmove(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +0000983 Py_ssize_t n)
984{
Daniel Stutzbach98338222010-12-02 21:55:33 +0000985 memmove(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
986 if (s1->values != NULL)
987 memmove(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
988}
989
990Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +0000991sortslice_advance(sortslice *slice, Py_ssize_t n)
992{
Daniel Stutzbach98338222010-12-02 21:55:33 +0000993 slice->keys += n;
994 if (slice->values != NULL)
995 slice->values += n;
996}
997
Raymond Hettinger70b64fc2008-01-30 20:15:17 +0000998/* Comparison function: PyObject_RichCompareBool with Py_LT.
Tim Petersa64dc242002-08-01 02:13:36 +0000999 * Returns -1 on error, 1 if x < y, 0 if x >= y.
1000 */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001001
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001002#define ISLT(X, Y) (PyObject_RichCompareBool(X, Y, Py_LT))
Tim Peters66860f62002-08-04 17:47:26 +00001003
1004/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +00001005 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
1006 started. It makes more sense in context <wink>. X and Y are PyObject*s.
1007*/
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001008#define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail; \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001010
1011/* binarysort is the best method for sorting small arrays: it does
1012 few compares, but can do data movement quadratic in the number of
1013 elements.
Guido van Rossum42812581998-06-17 14:15:44 +00001014 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +00001015 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001016 On entry, must have lo <= start <= hi, and that [lo, start) is already
1017 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +00001018 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001019 Even in case of error, the output slice will be some permutation of
1020 the input (nothing is lost or duplicated).
1021*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00001022static int
Daniel Stutzbach98338222010-12-02 21:55:33 +00001023binarysort(sortslice lo, PyObject **hi, PyObject **start)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 register Py_ssize_t k;
1026 register PyObject **l, **p, **r;
1027 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001028
Daniel Stutzbach98338222010-12-02 21:55:33 +00001029 assert(lo.keys <= start && start <= hi);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 /* assert [lo, start) is sorted */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001031 if (lo.keys == start)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 ++start;
1033 for (; start < hi; ++start) {
1034 /* set l to where *start belongs */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001035 l = lo.keys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 r = start;
1037 pivot = *r;
1038 /* Invariants:
1039 * pivot >= all in [lo, l).
1040 * pivot < all in [r, start).
1041 * The second is vacuously true at the start.
1042 */
1043 assert(l < r);
1044 do {
1045 p = l + ((r - l) >> 1);
1046 IFLT(pivot, *p)
1047 r = p;
1048 else
1049 l = p+1;
1050 } while (l < r);
1051 assert(l == r);
1052 /* The invariants still hold, so pivot >= all in [lo, l) and
1053 pivot < all in [l, start), so pivot belongs at l. Note
1054 that if there are elements equal to pivot, l points to the
1055 first slot after them -- that's why this sort is stable.
1056 Slide over to make room.
1057 Caution: using memmove is much slower under MSVC 5;
1058 we're not usually moving many slots. */
1059 for (p = start; p > l; --p)
1060 *p = *(p-1);
1061 *l = pivot;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001062 if (lo.values != NULL) {
1063 Py_ssize_t offset = lo.values - lo.keys;
1064 p = start + offset;
1065 pivot = *p;
1066 l += offset;
1067 for (p = start + offset; p > l; --p)
1068 *p = *(p-1);
1069 *l = pivot;
1070 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 }
1072 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001073
1074 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001076}
1077
Tim Petersa64dc242002-08-01 02:13:36 +00001078/*
1079Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1080is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001081
Tim Petersa64dc242002-08-01 02:13:36 +00001082 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001083
Tim Petersa64dc242002-08-01 02:13:36 +00001084or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001085
Tim Petersa64dc242002-08-01 02:13:36 +00001086 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001087
Tim Petersa64dc242002-08-01 02:13:36 +00001088Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1089For its intended use in a stable mergesort, the strictness of the defn of
1090"descending" is needed so that the caller can safely reverse a descending
1091sequence without violating stability (strict > ensures there are no equal
1092elements to get out of order).
1093
1094Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001095*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001096static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001097count_run(PyObject **lo, PyObject **hi, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 Py_ssize_t k;
1100 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 assert(lo < hi);
1103 *descending = 0;
1104 ++lo;
1105 if (lo == hi)
1106 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 n = 2;
1109 IFLT(*lo, *(lo-1)) {
1110 *descending = 1;
1111 for (lo = lo+1; lo < hi; ++lo, ++n) {
1112 IFLT(*lo, *(lo-1))
1113 ;
1114 else
1115 break;
1116 }
1117 }
1118 else {
1119 for (lo = lo+1; lo < hi; ++lo, ++n) {
1120 IFLT(*lo, *(lo-1))
1121 break;
1122 }
1123 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 return n;
Tim Petersa64dc242002-08-01 02:13:36 +00001126fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001128}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001129
Tim Petersa64dc242002-08-01 02:13:36 +00001130/*
1131Locate the proper position of key in a sorted vector; if the vector contains
1132an element equal to key, return the position immediately to the left of
1133the leftmost equal element. [gallop_right() does the same except returns
1134the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001135
Tim Petersa64dc242002-08-01 02:13:36 +00001136"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001137
Tim Petersa64dc242002-08-01 02:13:36 +00001138"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1139hint is to the final result, the faster this runs.
1140
1141The return value is the int k in 0..n such that
1142
1143 a[k-1] < key <= a[k]
1144
1145pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1146key belongs at index k; or, IOW, the first k elements of a should precede
1147key, and the last n-k should follow key.
1148
1149Returns -1 on error. See listsort.txt for info on the method.
1150*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001151static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001152gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 Py_ssize_t ofs;
1155 Py_ssize_t lastofs;
1156 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 a += hint;
1161 lastofs = 0;
1162 ofs = 1;
1163 IFLT(*a, key) {
1164 /* a[hint] < key -- gallop right, until
1165 * a[hint + lastofs] < key <= a[hint + ofs]
1166 */
1167 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1168 while (ofs < maxofs) {
1169 IFLT(a[ofs], key) {
1170 lastofs = ofs;
1171 ofs = (ofs << 1) + 1;
1172 if (ofs <= 0) /* int overflow */
1173 ofs = maxofs;
1174 }
1175 else /* key <= a[hint + ofs] */
1176 break;
1177 }
1178 if (ofs > maxofs)
1179 ofs = maxofs;
1180 /* Translate back to offsets relative to &a[0]. */
1181 lastofs += hint;
1182 ofs += hint;
1183 }
1184 else {
1185 /* key <= a[hint] -- gallop left, until
1186 * a[hint - ofs] < key <= a[hint - lastofs]
1187 */
1188 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1189 while (ofs < maxofs) {
1190 IFLT(*(a-ofs), key)
1191 break;
1192 /* key <= a[hint - ofs] */
1193 lastofs = ofs;
1194 ofs = (ofs << 1) + 1;
1195 if (ofs <= 0) /* int overflow */
1196 ofs = maxofs;
1197 }
1198 if (ofs > maxofs)
1199 ofs = maxofs;
1200 /* Translate back to positive offsets relative to &a[0]. */
1201 k = lastofs;
1202 lastofs = hint - ofs;
1203 ofs = hint - k;
1204 }
1205 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1208 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1209 * right of lastofs but no farther right than ofs. Do a binary
1210 * search, with invariant a[lastofs-1] < key <= a[ofs].
1211 */
1212 ++lastofs;
1213 while (lastofs < ofs) {
1214 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 IFLT(a[m], key)
1217 lastofs = m+1; /* a[m] < key */
1218 else
1219 ofs = m; /* key <= a[m] */
1220 }
1221 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1222 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001223
1224fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001226}
1227
1228/*
1229Exactly like gallop_left(), except that if key already exists in a[0:n],
1230finds the position immediately to the right of the rightmost equal value.
1231
1232The return value is the int k in 0..n such that
1233
1234 a[k-1] <= key < a[k]
1235
1236or -1 if error.
1237
1238The code duplication is massive, but this is enough different given that
1239we're sticking to "<" comparisons that it's much harder to follow if
1240written as one routine with yet another "left or right?" flag.
1241*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001242static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001243gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 Py_ssize_t ofs;
1246 Py_ssize_t lastofs;
1247 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 a += hint;
1252 lastofs = 0;
1253 ofs = 1;
1254 IFLT(key, *a) {
1255 /* key < a[hint] -- gallop left, until
1256 * a[hint - ofs] <= key < a[hint - lastofs]
1257 */
1258 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1259 while (ofs < maxofs) {
1260 IFLT(key, *(a-ofs)) {
1261 lastofs = ofs;
1262 ofs = (ofs << 1) + 1;
1263 if (ofs <= 0) /* int overflow */
1264 ofs = maxofs;
1265 }
1266 else /* a[hint - ofs] <= key */
1267 break;
1268 }
1269 if (ofs > maxofs)
1270 ofs = maxofs;
1271 /* Translate back to positive offsets relative to &a[0]. */
1272 k = lastofs;
1273 lastofs = hint - ofs;
1274 ofs = hint - k;
1275 }
1276 else {
1277 /* a[hint] <= key -- gallop right, until
1278 * a[hint + lastofs] <= key < a[hint + ofs]
1279 */
1280 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1281 while (ofs < maxofs) {
1282 IFLT(key, a[ofs])
1283 break;
1284 /* a[hint + ofs] <= key */
1285 lastofs = ofs;
1286 ofs = (ofs << 1) + 1;
1287 if (ofs <= 0) /* int overflow */
1288 ofs = maxofs;
1289 }
1290 if (ofs > maxofs)
1291 ofs = maxofs;
1292 /* Translate back to offsets relative to &a[0]. */
1293 lastofs += hint;
1294 ofs += hint;
1295 }
1296 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1299 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1300 * right of lastofs but no farther right than ofs. Do a binary
1301 * search, with invariant a[lastofs-1] <= key < a[ofs].
1302 */
1303 ++lastofs;
1304 while (lastofs < ofs) {
1305 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 IFLT(key, a[m])
1308 ofs = m; /* key < a[m] */
1309 else
1310 lastofs = m+1; /* a[m] <= key */
1311 }
1312 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1313 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001314
1315fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001317}
1318
1319/* The maximum number of entries in a MergeState's pending-runs stack.
1320 * This is enough to sort arrays of size up to about
1321 * 32 * phi ** MAX_MERGE_PENDING
1322 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1323 * with 2**64 elements.
1324 */
1325#define MAX_MERGE_PENDING 85
1326
Tim Peterse05f65a2002-08-10 05:21:15 +00001327/* When we get into galloping mode, we stay there until both runs win less
1328 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001329 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001330#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001331
1332/* Avoid malloc for small temp arrays. */
1333#define MERGESTATE_TEMP_SIZE 256
1334
1335/* One MergeState exists on the stack per invocation of mergesort. It's just
1336 * a convenient way to pass state around among the helper functions.
1337 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001338struct s_slice {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001339 sortslice base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 Py_ssize_t len;
Tim Peterse05f65a2002-08-10 05:21:15 +00001341};
1342
Tim Petersa64dc242002-08-01 02:13:36 +00001343typedef struct s_MergeState {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 /* This controls when we get *into* galloping mode. It's initialized
1345 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1346 * random data, and lower for highly structured data.
1347 */
1348 Py_ssize_t min_gallop;
Tim Peterse05f65a2002-08-10 05:21:15 +00001349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 /* 'a' is temp storage to help with merges. It contains room for
1351 * alloced entries.
1352 */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001353 sortslice a; /* may point to temparray below */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 Py_ssize_t alloced;
Tim Petersa64dc242002-08-01 02:13:36 +00001355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 /* A stack of n pending runs yet to be merged. Run #i starts at
1357 * address base[i] and extends for len[i] elements. It's always
1358 * true (so long as the indices are in bounds) that
1359 *
1360 * pending[i].base + pending[i].len == pending[i+1].base
1361 *
1362 * so we could cut the storage for this, but it's a minor amount,
1363 * and keeping all the info explicit simplifies the code.
1364 */
1365 int n;
1366 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 /* 'a' points to this when possible, rather than muck with malloc. */
1369 PyObject *temparray[MERGESTATE_TEMP_SIZE];
Tim Petersa64dc242002-08-01 02:13:36 +00001370} MergeState;
1371
1372/* Conceptually a MergeState's constructor. */
1373static void
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001374merge_init(MergeState *ms, Py_ssize_t list_size, int has_keyfunc)
Tim Petersa64dc242002-08-01 02:13:36 +00001375{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001377 if (has_keyfunc) {
1378 /* The temporary space for merging will need at most half the list
1379 * size rounded up. Use the minimum possible space so we can use the
1380 * rest of temparray for other things. In particular, if there is
1381 * enough extra space, listsort() will use it to store the keys.
1382 */
1383 ms->alloced = (list_size + 1) / 2;
1384
1385 /* ms->alloced describes how many keys will be stored at
1386 ms->temparray, but we also need to store the values. Hence,
1387 ms->alloced is capped at half of MERGESTATE_TEMP_SIZE. */
1388 if (MERGESTATE_TEMP_SIZE / 2 < ms->alloced)
1389 ms->alloced = MERGESTATE_TEMP_SIZE / 2;
1390 ms->a.values = &ms->temparray[ms->alloced];
1391 }
1392 else {
1393 ms->alloced = MERGESTATE_TEMP_SIZE;
1394 ms->a.values = NULL;
1395 }
1396 ms->a.keys = ms->temparray;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 ms->n = 0;
1398 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001399}
1400
1401/* Free all the temp memory owned by the MergeState. This must be called
1402 * when you're done with a MergeState, and may be called before then if
1403 * you want to free the temp memory early.
1404 */
1405static void
1406merge_freemem(MergeState *ms)
1407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001409 if (ms->a.keys != ms->temparray)
1410 PyMem_Free(ms->a.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001411}
1412
1413/* Ensure enough temp memory for 'need' array slots is available.
1414 * Returns 0 on success and -1 if the memory can't be gotten.
1415 */
1416static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001417merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001418{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001419 int multiplier;
1420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 assert(ms != NULL);
1422 if (need <= ms->alloced)
1423 return 0;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001424
1425 multiplier = ms->a.values != NULL ? 2 : 1;
1426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 /* Don't realloc! That can cost cycles to copy the old data, but
1428 * we don't care what's in the block.
1429 */
1430 merge_freemem(ms);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001431 if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject*) / multiplier) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 PyErr_NoMemory();
1433 return -1;
1434 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001435 ms->a.keys = (PyObject**)PyMem_Malloc(multiplier * need
1436 * sizeof(PyObject *));
1437 if (ms->a.keys != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 ms->alloced = need;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001439 if (ms->a.values != NULL)
1440 ms->a.values = &ms->a.keys[need];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 return 0;
1442 }
1443 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001445}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1447 merge_getmem(MS, NEED))
Tim Petersa64dc242002-08-01 02:13:36 +00001448
Daniel Stutzbach98338222010-12-02 21:55:33 +00001449/* Merge the na elements starting at ssa with the nb elements starting at
1450 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1451 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1452 * should have na <= nb. See listsort.txt for more info. Return 0 if
1453 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001454 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001455static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001456merge_lo(MergeState *ms, sortslice ssa, Py_ssize_t na,
1457 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001460 sortslice dest;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 int result = -1; /* guilty until proved innocent */
1462 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001463
Daniel Stutzbach98338222010-12-02 21:55:33 +00001464 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1465 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 if (MERGE_GETMEM(ms, na) < 0)
1467 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001468 sortslice_memcpy(&ms->a, 0, &ssa, 0, na);
1469 dest = ssa;
1470 ssa = ms->a;
Tim Petersa64dc242002-08-01 02:13:36 +00001471
Daniel Stutzbach98338222010-12-02 21:55:33 +00001472 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 --nb;
1474 if (nb == 0)
1475 goto Succeed;
1476 if (na == 1)
1477 goto CopyB;
Tim Petersa64dc242002-08-01 02:13:36 +00001478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 min_gallop = ms->min_gallop;
1480 for (;;) {
1481 Py_ssize_t acount = 0; /* # of times A won in a row */
1482 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 /* Do the straightforward thing until (if ever) one run
1485 * appears to win consistently.
1486 */
1487 for (;;) {
1488 assert(na > 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001489 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 if (k) {
1491 if (k < 0)
1492 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001493 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 ++bcount;
1495 acount = 0;
1496 --nb;
1497 if (nb == 0)
1498 goto Succeed;
1499 if (bcount >= min_gallop)
1500 break;
1501 }
1502 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001503 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 ++acount;
1505 bcount = 0;
1506 --na;
1507 if (na == 1)
1508 goto CopyB;
1509 if (acount >= min_gallop)
1510 break;
1511 }
1512 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 /* One run is winning so consistently that galloping may
1515 * be a huge win. So try that, and continue galloping until
1516 * (if ever) neither run appears to be winning consistently
1517 * anymore.
1518 */
1519 ++min_gallop;
1520 do {
1521 assert(na > 1 && nb > 0);
1522 min_gallop -= min_gallop > 1;
1523 ms->min_gallop = min_gallop;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001524 k = gallop_right(ssb.keys[0], ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 acount = k;
1526 if (k) {
1527 if (k < 0)
1528 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001529 sortslice_memcpy(&dest, 0, &ssa, 0, k);
1530 sortslice_advance(&dest, k);
1531 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 na -= k;
1533 if (na == 1)
1534 goto CopyB;
1535 /* na==0 is impossible now if the comparison
1536 * function is consistent, but we can't assume
1537 * that it is.
1538 */
1539 if (na == 0)
1540 goto Succeed;
1541 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001542 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 --nb;
1544 if (nb == 0)
1545 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001546
Daniel Stutzbach98338222010-12-02 21:55:33 +00001547 k = gallop_left(ssa.keys[0], ssb.keys, nb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 bcount = k;
1549 if (k) {
1550 if (k < 0)
1551 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001552 sortslice_memmove(&dest, 0, &ssb, 0, k);
1553 sortslice_advance(&dest, k);
1554 sortslice_advance(&ssb, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 nb -= k;
1556 if (nb == 0)
1557 goto Succeed;
1558 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001559 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 --na;
1561 if (na == 1)
1562 goto CopyB;
1563 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1564 ++min_gallop; /* penalize it for leaving galloping mode */
1565 ms->min_gallop = min_gallop;
1566 }
Tim Petersa64dc242002-08-01 02:13:36 +00001567Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001569Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 if (na)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001571 sortslice_memcpy(&dest, 0, &ssa, 0, na);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001573CopyB:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 assert(na == 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001575 /* The last element of ssa belongs at the end of the merge. */
1576 sortslice_memmove(&dest, 0, &ssb, 0, nb);
1577 sortslice_copy(&dest, nb, &ssa, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001579}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001580
Daniel Stutzbach98338222010-12-02 21:55:33 +00001581/* Merge the na elements starting at pa with the nb elements starting at
1582 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1583 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1584 * should have na >= nb. See listsort.txt for more info. Return 0 if
1585 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001586 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001587static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001588merge_hi(MergeState *ms, sortslice ssa, Py_ssize_t na,
1589 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001592 sortslice dest, basea, baseb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 int result = -1; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001595
Daniel Stutzbach98338222010-12-02 21:55:33 +00001596 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1597 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 if (MERGE_GETMEM(ms, nb) < 0)
1599 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001600 dest = ssb;
1601 sortslice_advance(&dest, nb-1);
1602 sortslice_memcpy(&ms->a, 0, &ssb, 0, nb);
1603 basea = ssa;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 baseb = ms->a;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001605 ssb.keys = ms->a.keys + nb - 1;
1606 if (ssb.values != NULL)
1607 ssb.values = ms->a.values + nb - 1;
1608 sortslice_advance(&ssa, na - 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001609
Daniel Stutzbach98338222010-12-02 21:55:33 +00001610 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 --na;
1612 if (na == 0)
1613 goto Succeed;
1614 if (nb == 1)
1615 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 min_gallop = ms->min_gallop;
1618 for (;;) {
1619 Py_ssize_t acount = 0; /* # of times A won in a row */
1620 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 /* Do the straightforward thing until (if ever) one run
1623 * appears to win consistently.
1624 */
1625 for (;;) {
1626 assert(na > 0 && nb > 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001627 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 if (k) {
1629 if (k < 0)
1630 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001631 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 ++acount;
1633 bcount = 0;
1634 --na;
1635 if (na == 0)
1636 goto Succeed;
1637 if (acount >= min_gallop)
1638 break;
1639 }
1640 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001641 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 ++bcount;
1643 acount = 0;
1644 --nb;
1645 if (nb == 1)
1646 goto CopyA;
1647 if (bcount >= min_gallop)
1648 break;
1649 }
1650 }
Tim Petersa64dc242002-08-01 02:13:36 +00001651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 /* One run is winning so consistently that galloping may
1653 * be a huge win. So try that, and continue galloping until
1654 * (if ever) neither run appears to be winning consistently
1655 * anymore.
1656 */
1657 ++min_gallop;
1658 do {
1659 assert(na > 0 && nb > 1);
1660 min_gallop -= min_gallop > 1;
1661 ms->min_gallop = min_gallop;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001662 k = gallop_right(ssb.keys[0], basea.keys, na, na-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 if (k < 0)
1664 goto Fail;
1665 k = na - k;
1666 acount = k;
1667 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001668 sortslice_advance(&dest, -k);
1669 sortslice_advance(&ssa, -k);
1670 sortslice_memmove(&dest, 1, &ssa, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 na -= k;
1672 if (na == 0)
1673 goto Succeed;
1674 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001675 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 --nb;
1677 if (nb == 1)
1678 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001679
Daniel Stutzbach98338222010-12-02 21:55:33 +00001680 k = gallop_left(ssa.keys[0], baseb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 if (k < 0)
1682 goto Fail;
1683 k = nb - k;
1684 bcount = k;
1685 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001686 sortslice_advance(&dest, -k);
1687 sortslice_advance(&ssb, -k);
1688 sortslice_memcpy(&dest, 1, &ssb, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 nb -= k;
1690 if (nb == 1)
1691 goto CopyA;
1692 /* nb==0 is impossible now if the comparison
1693 * function is consistent, but we can't assume
1694 * that it is.
1695 */
1696 if (nb == 0)
1697 goto Succeed;
1698 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001699 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 --na;
1701 if (na == 0)
1702 goto Succeed;
1703 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1704 ++min_gallop; /* penalize it for leaving galloping mode */
1705 ms->min_gallop = min_gallop;
1706 }
Tim Petersa64dc242002-08-01 02:13:36 +00001707Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001709Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 if (nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001711 sortslice_memcpy(&dest, -(nb-1), &baseb, 0, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001713CopyA:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 assert(nb == 1 && na > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001715 /* The first element of ssb belongs at the front of the merge. */
1716 sortslice_memmove(&dest, 1-na, &ssa, 1-na, na);
1717 sortslice_advance(&dest, -na);
1718 sortslice_advance(&ssa, -na);
1719 sortslice_copy(&dest, 0, &ssb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001721}
1722
1723/* Merge the two runs at stack indices i and i+1.
1724 * Returns 0 on success, -1 on error.
1725 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001726static Py_ssize_t
1727merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001728{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001729 sortslice ssa, ssb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 Py_ssize_t na, nb;
1731 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 assert(ms != NULL);
1734 assert(ms->n >= 2);
1735 assert(i >= 0);
1736 assert(i == ms->n - 2 || i == ms->n - 3);
Tim Petersa64dc242002-08-01 02:13:36 +00001737
Daniel Stutzbach98338222010-12-02 21:55:33 +00001738 ssa = ms->pending[i].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 na = ms->pending[i].len;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001740 ssb = ms->pending[i+1].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 nb = ms->pending[i+1].len;
1742 assert(na > 0 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001743 assert(ssa.keys + na == ssb.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 /* Record the length of the combined runs; if i is the 3rd-last
1746 * run now, also slide over the last run (which isn't involved
1747 * in this merge). The current run i+1 goes away in any case.
1748 */
1749 ms->pending[i].len = na + nb;
1750 if (i == ms->n - 3)
1751 ms->pending[i+1] = ms->pending[i+2];
1752 --ms->n;
Tim Petersa64dc242002-08-01 02:13:36 +00001753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 /* Where does b start in a? Elements in a before that can be
1755 * ignored (already in place).
1756 */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001757 k = gallop_right(*ssb.keys, ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 if (k < 0)
1759 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001760 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 na -= k;
1762 if (na == 0)
1763 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 /* Where does a end in b? Elements in b after that can be
1766 * ignored (already in place).
1767 */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001768 nb = gallop_left(ssa.keys[na-1], ssb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 if (nb <= 0)
1770 return nb;
Tim Petersa64dc242002-08-01 02:13:36 +00001771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 /* Merge what remains of the runs, using a temp array with
1773 * min(na, nb) elements.
1774 */
1775 if (na <= nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001776 return merge_lo(ms, ssa, na, ssb, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 else
Daniel Stutzbach98338222010-12-02 21:55:33 +00001778 return merge_hi(ms, ssa, na, ssb, nb);
Tim Petersa64dc242002-08-01 02:13:36 +00001779}
1780
1781/* Examine the stack of runs waiting to be merged, merging adjacent runs
1782 * until the stack invariants are re-established:
1783 *
1784 * 1. len[-3] > len[-2] + len[-1]
1785 * 2. len[-2] > len[-1]
1786 *
1787 * See listsort.txt for more info.
1788 *
1789 * Returns 0 on success, -1 on error.
1790 */
1791static int
1792merge_collapse(MergeState *ms)
1793{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 assert(ms);
1797 while (ms->n > 1) {
1798 Py_ssize_t n = ms->n - 2;
1799 if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
1800 if (p[n-1].len < p[n+1].len)
1801 --n;
1802 if (merge_at(ms, n) < 0)
1803 return -1;
1804 }
1805 else if (p[n].len <= p[n+1].len) {
1806 if (merge_at(ms, n) < 0)
1807 return -1;
1808 }
1809 else
1810 break;
1811 }
1812 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001813}
1814
1815/* Regardless of invariants, merge all runs on the stack until only one
1816 * remains. This is used at the end of the mergesort.
1817 *
1818 * Returns 0 on success, -1 on error.
1819 */
1820static int
1821merge_force_collapse(MergeState *ms)
1822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 assert(ms);
1826 while (ms->n > 1) {
1827 Py_ssize_t n = ms->n - 2;
1828 if (n > 0 && p[n-1].len < p[n+1].len)
1829 --n;
1830 if (merge_at(ms, n) < 0)
1831 return -1;
1832 }
1833 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001834}
1835
1836/* Compute a good value for the minimum run length; natural runs shorter
1837 * than this are boosted artificially via binary insertion.
1838 *
1839 * If n < 64, return n (it's too small to bother with fancy stuff).
1840 * Else if n is an exact power of 2, return 32.
1841 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1842 * strictly less than, an exact power of 2.
1843 *
1844 * See listsort.txt for more info.
1845 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001846static Py_ssize_t
1847merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001848{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 assert(n >= 0);
1852 while (n >= 64) {
1853 r |= n & 1;
1854 n >>= 1;
1855 }
1856 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001857}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001858
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001859static void
Daniel Stutzbach98338222010-12-02 21:55:33 +00001860reverse_sortslice(sortslice *s, Py_ssize_t n)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001861{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001862 reverse_slice(s->keys, &s->keys[n]);
1863 if (s->values != NULL)
1864 reverse_slice(s->values, &s->values[n]);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001865}
1866
Tim Petersa64dc242002-08-01 02:13:36 +00001867/* An adaptive, stable, natural mergesort. See listsort.txt.
1868 * Returns Py_None on success, NULL on error. Even in case of error, the
1869 * list will be some permutation of its input state (nothing is lost or
1870 * duplicated).
1871 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001872static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001873listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001874{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001875 MergeState ms;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 Py_ssize_t nremaining;
1877 Py_ssize_t minrun;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001878 sortslice lo;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 Py_ssize_t saved_ob_size, saved_allocated;
1880 PyObject **saved_ob_item;
1881 PyObject **final_ob_item;
1882 PyObject *result = NULL; /* guilty until proved innocent */
1883 int reverse = 0;
1884 PyObject *keyfunc = NULL;
1885 Py_ssize_t i;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 static char *kwlist[] = {"key", "reverse", 0};
Daniel Stutzbach98338222010-12-02 21:55:33 +00001887 PyObject **keys;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 assert(self != NULL);
1890 assert (PyList_Check(self));
1891 if (args != NULL) {
1892 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:sort",
1893 kwlist, &keyfunc, &reverse))
1894 return NULL;
1895 if (Py_SIZE(args) > 0) {
1896 PyErr_SetString(PyExc_TypeError,
1897 "must use keyword argument for key function");
1898 return NULL;
1899 }
1900 }
1901 if (keyfunc == Py_None)
1902 keyfunc = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 /* The list is temporarily made empty, so that mutations performed
1905 * by comparison functions can't affect the slice of memory we're
1906 * sorting (allowing mutations during sorting is a core-dump
1907 * factory, since ob_item may change).
1908 */
1909 saved_ob_size = Py_SIZE(self);
1910 saved_ob_item = self->ob_item;
1911 saved_allocated = self->allocated;
1912 Py_SIZE(self) = 0;
1913 self->ob_item = NULL;
1914 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00001915
Daniel Stutzbach98338222010-12-02 21:55:33 +00001916 if (keyfunc == NULL) {
1917 keys = NULL;
1918 lo.keys = saved_ob_item;
1919 lo.values = NULL;
1920 }
1921 else {
1922 if (saved_ob_size < MERGESTATE_TEMP_SIZE/2)
1923 /* Leverage stack space we allocated but won't otherwise use */
1924 keys = &ms.temparray[saved_ob_size+1];
1925 else {
1926 keys = PyMem_MALLOC(sizeof(PyObject *) * saved_ob_size);
Benjamin Peterson0823ffb2015-04-23 17:04:36 -04001927 if (keys == NULL) {
1928 PyErr_NoMemory();
1929 goto keyfunc_fail;
1930 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001932
1933 for (i = 0; i < saved_ob_size ; i++) {
1934 keys[i] = PyObject_CallFunctionObjArgs(keyfunc, saved_ob_item[i],
1935 NULL);
1936 if (keys[i] == NULL) {
1937 for (i=i-1 ; i>=0 ; i--)
1938 Py_DECREF(keys[i]);
Daniel Stutzbacheda70b82011-05-04 12:46:28 -07001939 if (keys != &ms.temparray[saved_ob_size+1])
1940 PyMem_FREE(keys);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001941 goto keyfunc_fail;
1942 }
1943 }
1944
1945 lo.keys = keys;
1946 lo.values = saved_ob_item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001948
Daniel Stutzbach98338222010-12-02 21:55:33 +00001949 merge_init(&ms, saved_ob_size, keys != NULL);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 nremaining = saved_ob_size;
1952 if (nremaining < 2)
1953 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00001954
Benjamin Peterson05380642010-08-23 19:35:39 +00001955 /* Reverse sort stability achieved by initially reversing the list,
1956 applying a stable forward sort, then reversing the final result. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001957 if (reverse) {
1958 if (keys != NULL)
1959 reverse_slice(&keys[0], &keys[saved_ob_size]);
1960 reverse_slice(&saved_ob_item[0], &saved_ob_item[saved_ob_size]);
1961 }
Benjamin Peterson05380642010-08-23 19:35:39 +00001962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 /* March over the array once, left to right, finding natural runs,
1964 * and extending short natural runs to minrun elements.
1965 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 minrun = merge_compute_minrun(nremaining);
1967 do {
1968 int descending;
1969 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00001970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 /* Identify next run. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001972 n = count_run(lo.keys, lo.keys + nremaining, &descending);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 if (n < 0)
1974 goto fail;
1975 if (descending)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001976 reverse_sortslice(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 /* If short, extend to min(minrun, nremaining). */
1978 if (n < minrun) {
1979 const Py_ssize_t force = nremaining <= minrun ?
1980 nremaining : minrun;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001981 if (binarysort(lo, lo.keys + force, lo.keys + n) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 goto fail;
1983 n = force;
1984 }
1985 /* Push run onto pending-runs stack, and maybe merge. */
1986 assert(ms.n < MAX_MERGE_PENDING);
1987 ms.pending[ms.n].base = lo;
1988 ms.pending[ms.n].len = n;
1989 ++ms.n;
1990 if (merge_collapse(&ms) < 0)
1991 goto fail;
1992 /* Advance to find next run. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001993 sortslice_advance(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 nremaining -= n;
1995 } while (nremaining);
Tim Peters330f9e92002-07-19 07:05:44 +00001996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 if (merge_force_collapse(&ms) < 0)
1998 goto fail;
1999 assert(ms.n == 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002000 assert(keys == NULL
2001 ? ms.pending[0].base.keys == saved_ob_item
2002 : ms.pending[0].base.keys == &keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 assert(ms.pending[0].len == saved_ob_size);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002004 lo = ms.pending[0].base;
Tim Petersa64dc242002-08-01 02:13:36 +00002005
2006succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002008fail:
Daniel Stutzbach98338222010-12-02 21:55:33 +00002009 if (keys != NULL) {
2010 for (i = 0; i < saved_ob_size; i++)
2011 Py_DECREF(keys[i]);
2012 if (keys != &ms.temparray[saved_ob_size+1])
2013 PyMem_FREE(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 if (self->allocated != -1 && result != NULL) {
2017 /* The user mucked with the list during the sort,
2018 * and we don't already have another error to report.
2019 */
2020 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2021 result = NULL;
2022 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 if (reverse && saved_ob_size > 1)
2025 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 merge_freemem(&ms);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002028
Daniel Stutzbach98338222010-12-02 21:55:33 +00002029keyfunc_fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 final_ob_item = self->ob_item;
2031 i = Py_SIZE(self);
2032 Py_SIZE(self) = saved_ob_size;
2033 self->ob_item = saved_ob_item;
2034 self->allocated = saved_allocated;
2035 if (final_ob_item != NULL) {
2036 /* we cannot use list_clear() for this because it does not
2037 guarantee that the list is really empty when it returns */
2038 while (--i >= 0) {
2039 Py_XDECREF(final_ob_item[i]);
2040 }
2041 PyMem_FREE(final_ob_item);
2042 }
2043 Py_XINCREF(result);
2044 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002045}
Tim Peters330f9e92002-07-19 07:05:44 +00002046#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002047#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002048
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002049int
Fred Drakea2f55112000-07-09 15:16:51 +00002050PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002051{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 if (v == NULL || !PyList_Check(v)) {
2053 PyErr_BadInternalCall();
2054 return -1;
2055 }
2056 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
2057 if (v == NULL)
2058 return -1;
2059 Py_DECREF(v);
2060 return 0;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002061}
2062
Guido van Rossumb86c5492001-02-12 22:06:02 +00002063static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002064listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002065{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 if (Py_SIZE(self) > 1)
2067 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2068 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002069}
2070
Guido van Rossum84c76f51990-10-30 13:32:20 +00002071int
Fred Drakea2f55112000-07-09 15:16:51 +00002072PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002073{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 PyListObject *self = (PyListObject *)v;
Tim Peters6063e262002-08-08 01:06:39 +00002075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 if (v == NULL || !PyList_Check(v)) {
2077 PyErr_BadInternalCall();
2078 return -1;
2079 }
2080 if (Py_SIZE(self) > 1)
2081 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2082 return 0;
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002083}
2084
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002085PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002086PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 PyObject *w;
2089 PyObject **p, **q;
2090 Py_ssize_t n;
2091 if (v == NULL || !PyList_Check(v)) {
2092 PyErr_BadInternalCall();
2093 return NULL;
2094 }
2095 n = Py_SIZE(v);
2096 w = PyTuple_New(n);
2097 if (w == NULL)
2098 return NULL;
2099 p = ((PyTupleObject *)w)->ob_item;
2100 q = ((PyListObject *)v)->ob_item;
2101 while (--n >= 0) {
2102 Py_INCREF(*q);
2103 *p = *q;
2104 p++;
2105 q++;
2106 }
2107 return w;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002108}
2109
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002110static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002111listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 Py_ssize_t i, start=0, stop=Py_SIZE(self);
2114 PyObject *v, *format_tuple, *err_string;
2115 static PyObject *err_format = NULL;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002116
Petri Lehtinenebfaabd2011-11-06 21:02:39 +02002117 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2118 _PyEval_SliceIndex, &start,
2119 _PyEval_SliceIndex, &stop))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 return NULL;
2121 if (start < 0) {
2122 start += Py_SIZE(self);
2123 if (start < 0)
2124 start = 0;
2125 }
2126 if (stop < 0) {
2127 stop += Py_SIZE(self);
2128 if (stop < 0)
2129 stop = 0;
2130 }
2131 for (i = start; i < stop && i < Py_SIZE(self); i++) {
2132 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2133 if (cmp > 0)
2134 return PyLong_FromSsize_t(i);
2135 else if (cmp < 0)
2136 return NULL;
2137 }
2138 if (err_format == NULL) {
2139 err_format = PyUnicode_FromString("%r is not in list");
2140 if (err_format == NULL)
2141 return NULL;
2142 }
2143 format_tuple = PyTuple_Pack(1, v);
2144 if (format_tuple == NULL)
2145 return NULL;
2146 err_string = PyUnicode_Format(err_format, format_tuple);
2147 Py_DECREF(format_tuple);
2148 if (err_string == NULL)
2149 return NULL;
2150 PyErr_SetObject(PyExc_ValueError, err_string);
2151 Py_DECREF(err_string);
2152 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002153}
2154
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002155static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002156listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 Py_ssize_t count = 0;
2159 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 for (i = 0; i < Py_SIZE(self); i++) {
2162 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2163 if (cmp > 0)
2164 count++;
2165 else if (cmp < 0)
2166 return NULL;
2167 }
2168 return PyLong_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002169}
2170
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002171static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002172listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 for (i = 0; i < Py_SIZE(self); i++) {
2177 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2178 if (cmp > 0) {
2179 if (list_ass_slice(self, i, i+1,
2180 (PyObject *)NULL) == 0)
2181 Py_RETURN_NONE;
2182 return NULL;
2183 }
2184 else if (cmp < 0)
2185 return NULL;
2186 }
2187 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
2188 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002189}
2190
Jeremy Hylton8caad492000-06-23 14:18:11 +00002191static int
2192list_traverse(PyListObject *o, visitproc visit, void *arg)
2193{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 for (i = Py_SIZE(o); --i >= 0; )
2197 Py_VISIT(o->ob_item[i]);
2198 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002199}
2200
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002201static PyObject *
2202list_richcompare(PyObject *v, PyObject *w, int op)
2203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 PyListObject *vl, *wl;
2205 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 if (!PyList_Check(v) || !PyList_Check(w)) {
2208 Py_INCREF(Py_NotImplemented);
2209 return Py_NotImplemented;
2210 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 vl = (PyListObject *)v;
2213 wl = (PyListObject *)w;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
2216 /* Shortcut: if the lengths differ, the lists differ */
2217 PyObject *res;
2218 if (op == Py_EQ)
2219 res = Py_False;
2220 else
2221 res = Py_True;
2222 Py_INCREF(res);
2223 return res;
2224 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 /* Search for the first index where items are different */
2227 for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
2228 int k = PyObject_RichCompareBool(vl->ob_item[i],
2229 wl->ob_item[i], Py_EQ);
2230 if (k < 0)
2231 return NULL;
2232 if (!k)
2233 break;
2234 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
2237 /* No more items to compare -- compare sizes */
2238 Py_ssize_t vs = Py_SIZE(vl);
2239 Py_ssize_t ws = Py_SIZE(wl);
2240 int cmp;
2241 PyObject *res;
2242 switch (op) {
2243 case Py_LT: cmp = vs < ws; break;
2244 case Py_LE: cmp = vs <= ws; break;
2245 case Py_EQ: cmp = vs == ws; break;
2246 case Py_NE: cmp = vs != ws; break;
2247 case Py_GT: cmp = vs > ws; break;
2248 case Py_GE: cmp = vs >= ws; break;
2249 default: return NULL; /* cannot happen */
2250 }
2251 if (cmp)
2252 res = Py_True;
2253 else
2254 res = Py_False;
2255 Py_INCREF(res);
2256 return res;
2257 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 /* We have an item that differs -- shortcuts for EQ/NE */
2260 if (op == Py_EQ) {
2261 Py_INCREF(Py_False);
2262 return Py_False;
2263 }
2264 if (op == Py_NE) {
2265 Py_INCREF(Py_True);
2266 return Py_True;
2267 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 /* Compare the final item again using the proper operator */
2270 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002271}
2272
Tim Peters6d6c1a32001-08-02 04:15:00 +00002273static int
2274list_init(PyListObject *self, PyObject *args, PyObject *kw)
2275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002276 PyObject *arg = NULL;
2277 static char *kwlist[] = {"sequence", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2280 return -1;
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 /* Verify list invariants established by PyType_GenericAlloc() */
2283 assert(0 <= Py_SIZE(self));
2284 assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
2285 assert(self->ob_item != NULL ||
2286 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 /* Empty previous contents */
2289 if (self->ob_item != NULL) {
2290 (void)list_clear(self);
2291 }
2292 if (arg != NULL) {
2293 PyObject *rv = listextend(self, arg);
2294 if (rv == NULL)
2295 return -1;
2296 Py_DECREF(rv);
2297 }
2298 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002299}
2300
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002301static PyObject *
2302list_sizeof(PyListObject *self)
2303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 res = sizeof(PyListObject) + self->allocated * sizeof(void*);
2307 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002308}
2309
Raymond Hettinger1021c442003-11-07 15:38:09 +00002310static PyObject *list_iter(PyObject *seq);
2311static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2312
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002313PyDoc_STRVAR(getitem_doc,
2314"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002315PyDoc_STRVAR(reversed_doc,
2316"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002317PyDoc_STRVAR(sizeof_doc,
2318"L.__sizeof__() -- size of L in memory, in bytes");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002319PyDoc_STRVAR(append_doc,
2320"L.append(object) -- append object to end");
2321PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002322"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002323PyDoc_STRVAR(insert_doc,
2324"L.insert(index, object) -- insert object before index");
2325PyDoc_STRVAR(pop_doc,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002326"L.pop([index]) -> item -- remove and return item at index (default last).\n"
2327"Raises IndexError if list is empty or index is out of range.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002328PyDoc_STRVAR(remove_doc,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002329"L.remove(value) -- remove first occurrence of value.\n"
2330"Raises ValueError if the value is not present.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002331PyDoc_STRVAR(index_doc,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002332"L.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
2333"Raises ValueError if the value is not present.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002334PyDoc_STRVAR(count_doc,
2335"L.count(value) -> integer -- return number of occurrences of value");
2336PyDoc_STRVAR(reverse_doc,
2337"L.reverse() -- reverse *IN PLACE*");
2338PyDoc_STRVAR(sort_doc,
Benjamin Petersoncb9a5512008-09-30 02:08:36 +00002339"L.sort(key=None, reverse=False) -- stable sort *IN PLACE*");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002340
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002341static PyObject *list_subscript(PyListObject*, PyObject*);
2342
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002343static PyMethodDef list_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
2345 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
2346 {"__sizeof__", (PyCFunction)list_sizeof, METH_NOARGS, sizeof_doc},
2347 {"append", (PyCFunction)listappend, METH_O, append_doc},
2348 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
2349 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
2350 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
2351 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
2352 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
2353 {"count", (PyCFunction)listcount, METH_O, count_doc},
2354 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
2355 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
2356 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002357};
2358
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002359static PySequenceMethods list_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 (lenfunc)list_length, /* sq_length */
2361 (binaryfunc)list_concat, /* sq_concat */
2362 (ssizeargfunc)list_repeat, /* sq_repeat */
2363 (ssizeargfunc)list_item, /* sq_item */
2364 0, /* sq_slice */
2365 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
2366 0, /* sq_ass_slice */
2367 (objobjproc)list_contains, /* sq_contains */
2368 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2369 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002370};
2371
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002372PyDoc_STRVAR(list_doc,
Ezio Melotti7f807b72010-03-01 04:08:34 +00002373"list() -> new empty list\n"
2374"list(iterable) -> new list initialized from iterable's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002375
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002376static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002377list_subscript(PyListObject* self, PyObject* item)
2378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 if (PyIndex_Check(item)) {
2380 Py_ssize_t i;
2381 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2382 if (i == -1 && PyErr_Occurred())
2383 return NULL;
2384 if (i < 0)
2385 i += PyList_GET_SIZE(self);
2386 return list_item(self, i);
2387 }
2388 else if (PySlice_Check(item)) {
2389 Py_ssize_t start, stop, step, slicelength, cur, i;
2390 PyObject* result;
2391 PyObject* it;
2392 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002393
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002394 if (PySlice_GetIndicesEx(item, Py_SIZE(self),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 &start, &stop, &step, &slicelength) < 0) {
2396 return NULL;
2397 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 if (slicelength <= 0) {
2400 return PyList_New(0);
2401 }
2402 else if (step == 1) {
2403 return list_slice(self, start, stop);
2404 }
2405 else {
2406 result = PyList_New(slicelength);
2407 if (!result) return NULL;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 src = self->ob_item;
2410 dest = ((PyListObject *)result)->ob_item;
2411 for (cur = start, i = 0; i < slicelength;
2412 cur += step, i++) {
2413 it = src[cur];
2414 Py_INCREF(it);
2415 dest[i] = it;
2416 }
Tim Peters3b01a122002-07-19 02:35:45 +00002417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 return result;
2419 }
2420 }
2421 else {
2422 PyErr_Format(PyExc_TypeError,
2423 "list indices must be integers, not %.200s",
2424 item->ob_type->tp_name);
2425 return NULL;
2426 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002427}
2428
Tim Peters3b01a122002-07-19 02:35:45 +00002429static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002430list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 if (PyIndex_Check(item)) {
2433 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2434 if (i == -1 && PyErr_Occurred())
2435 return -1;
2436 if (i < 0)
2437 i += PyList_GET_SIZE(self);
2438 return list_ass_item(self, i, value);
2439 }
2440 else if (PySlice_Check(item)) {
2441 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002442
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002443 if (PySlice_GetIndicesEx(item, Py_SIZE(self),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 &start, &stop, &step, &slicelength) < 0) {
2445 return -1;
2446 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 if (step == 1)
2449 return list_ass_slice(self, start, stop, value);
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 /* Make sure s[5:2] = [..] inserts at the right place:
2452 before 5, not before 2. */
2453 if ((step < 0 && start < stop) ||
2454 (step > 0 && start > stop))
2455 stop = start;
Thomas Woutersed03b412007-08-28 21:37:11 +00002456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 if (value == NULL) {
2458 /* delete slice */
2459 PyObject **garbage;
2460 size_t cur;
2461 Py_ssize_t i;
Tim Peters3b01a122002-07-19 02:35:45 +00002462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 if (slicelength <= 0)
2464 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 if (step < 0) {
2467 stop = start + 1;
2468 start = stop + step*(slicelength - 1) - 1;
2469 step = -step;
2470 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 assert((size_t)slicelength <=
2473 PY_SIZE_MAX / sizeof(PyObject*));
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00002474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 garbage = (PyObject**)
2476 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2477 if (!garbage) {
2478 PyErr_NoMemory();
2479 return -1;
2480 }
Tim Peters3b01a122002-07-19 02:35:45 +00002481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 /* drawing pictures might help understand these for
2483 loops. Basically, we memmove the parts of the
2484 list that are *not* part of the slice: step-1
2485 items for each item that is part of the slice,
2486 and then tail end of the list that was not
2487 covered by the slice */
2488 for (cur = start, i = 0;
2489 cur < (size_t)stop;
2490 cur += step, i++) {
2491 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 garbage[i] = PyList_GET_ITEM(self, cur);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 if (cur + step >= (size_t)Py_SIZE(self)) {
2496 lim = Py_SIZE(self) - cur - 1;
2497 }
Michael W. Hudson56796f62002-07-29 14:35:04 +00002498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 memmove(self->ob_item + cur - i,
2500 self->ob_item + cur + 1,
2501 lim * sizeof(PyObject *));
2502 }
2503 cur = start + slicelength*step;
2504 if (cur < (size_t)Py_SIZE(self)) {
2505 memmove(self->ob_item + cur - slicelength,
2506 self->ob_item + cur,
2507 (Py_SIZE(self) - cur) *
2508 sizeof(PyObject *));
2509 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002511 Py_SIZE(self) -= slicelength;
2512 list_resize(self, Py_SIZE(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 for (i = 0; i < slicelength; i++) {
2515 Py_DECREF(garbage[i]);
2516 }
2517 PyMem_FREE(garbage);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 return 0;
2520 }
2521 else {
2522 /* assign slice */
2523 PyObject *ins, *seq;
2524 PyObject **garbage, **seqitems, **selfitems;
2525 Py_ssize_t cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002527 /* protect against a[::-1] = a */
2528 if (self == (PyListObject*)value) {
2529 seq = list_slice((PyListObject*)value, 0,
2530 PyList_GET_SIZE(value));
2531 }
2532 else {
2533 seq = PySequence_Fast(value,
2534 "must assign iterable "
2535 "to extended slice");
2536 }
2537 if (!seq)
2538 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002540 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2541 PyErr_Format(PyExc_ValueError,
2542 "attempt to assign sequence of "
2543 "size %zd to extended slice of "
2544 "size %zd",
2545 PySequence_Fast_GET_SIZE(seq),
2546 slicelength);
2547 Py_DECREF(seq);
2548 return -1;
2549 }
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 if (!slicelength) {
2552 Py_DECREF(seq);
2553 return 0;
2554 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 garbage = (PyObject**)
2557 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2558 if (!garbage) {
2559 Py_DECREF(seq);
2560 PyErr_NoMemory();
2561 return -1;
2562 }
Tim Peters3b01a122002-07-19 02:35:45 +00002563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 selfitems = self->ob_item;
2565 seqitems = PySequence_Fast_ITEMS(seq);
2566 for (cur = start, i = 0; i < slicelength;
2567 cur += step, i++) {
2568 garbage[i] = selfitems[cur];
2569 ins = seqitems[i];
2570 Py_INCREF(ins);
2571 selfitems[cur] = ins;
2572 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 for (i = 0; i < slicelength; i++) {
2575 Py_DECREF(garbage[i]);
2576 }
Tim Peters3b01a122002-07-19 02:35:45 +00002577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578 PyMem_FREE(garbage);
2579 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 return 0;
2582 }
2583 }
2584 else {
2585 PyErr_Format(PyExc_TypeError,
2586 "list indices must be integers, not %.200s",
2587 item->ob_type->tp_name);
2588 return -1;
2589 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002590}
2591
2592static PyMappingMethods list_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 (lenfunc)list_length,
2594 (binaryfunc)list_subscript,
2595 (objobjargproc)list_ass_subscript
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002596};
2597
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002598PyTypeObject PyList_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2600 "list",
2601 sizeof(PyListObject),
2602 0,
2603 (destructor)list_dealloc, /* tp_dealloc */
2604 0, /* tp_print */
2605 0, /* tp_getattr */
2606 0, /* tp_setattr */
2607 0, /* tp_reserved */
2608 (reprfunc)list_repr, /* tp_repr */
2609 0, /* tp_as_number */
2610 &list_as_sequence, /* tp_as_sequence */
2611 &list_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00002612 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 0, /* tp_call */
2614 0, /* tp_str */
2615 PyObject_GenericGetAttr, /* tp_getattro */
2616 0, /* tp_setattro */
2617 0, /* tp_as_buffer */
2618 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2619 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
2620 list_doc, /* tp_doc */
2621 (traverseproc)list_traverse, /* tp_traverse */
2622 (inquiry)list_clear, /* tp_clear */
2623 list_richcompare, /* tp_richcompare */
2624 0, /* tp_weaklistoffset */
2625 list_iter, /* tp_iter */
2626 0, /* tp_iternext */
2627 list_methods, /* tp_methods */
2628 0, /* tp_members */
2629 0, /* tp_getset */
2630 0, /* tp_base */
2631 0, /* tp_dict */
2632 0, /* tp_descr_get */
2633 0, /* tp_descr_set */
2634 0, /* tp_dictoffset */
2635 (initproc)list_init, /* tp_init */
2636 PyType_GenericAlloc, /* tp_alloc */
2637 PyType_GenericNew, /* tp_new */
2638 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002639};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002640
2641
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002642/*********************** List Iterator **************************/
2643
2644typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 PyObject_HEAD
2646 long it_index;
2647 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002648} listiterobject;
2649
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002650static PyObject *list_iter(PyObject *);
2651static void listiter_dealloc(listiterobject *);
2652static int listiter_traverse(listiterobject *, visitproc, void *);
2653static PyObject *listiter_next(listiterobject *);
2654static PyObject *listiter_len(listiterobject *);
Raymond Hettinger435bf582004-03-18 22:43:10 +00002655
Armin Rigof5b3e362006-02-11 21:32:43 +00002656PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002657
2658static PyMethodDef listiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002659 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
2660 {NULL, NULL} /* sentinel */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002661};
2662
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002663PyTypeObject PyListIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002664 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2665 "list_iterator", /* tp_name */
2666 sizeof(listiterobject), /* tp_basicsize */
2667 0, /* tp_itemsize */
2668 /* methods */
2669 (destructor)listiter_dealloc, /* tp_dealloc */
2670 0, /* tp_print */
2671 0, /* tp_getattr */
2672 0, /* tp_setattr */
2673 0, /* tp_reserved */
2674 0, /* tp_repr */
2675 0, /* tp_as_number */
2676 0, /* tp_as_sequence */
2677 0, /* tp_as_mapping */
2678 0, /* tp_hash */
2679 0, /* tp_call */
2680 0, /* tp_str */
2681 PyObject_GenericGetAttr, /* tp_getattro */
2682 0, /* tp_setattro */
2683 0, /* tp_as_buffer */
2684 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2685 0, /* tp_doc */
2686 (traverseproc)listiter_traverse, /* tp_traverse */
2687 0, /* tp_clear */
2688 0, /* tp_richcompare */
2689 0, /* tp_weaklistoffset */
2690 PyObject_SelfIter, /* tp_iter */
2691 (iternextfunc)listiter_next, /* tp_iternext */
2692 listiter_methods, /* tp_methods */
2693 0, /* tp_members */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002694};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002695
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002696
2697static PyObject *
2698list_iter(PyObject *seq)
2699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002700 listiterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002702 if (!PyList_Check(seq)) {
2703 PyErr_BadInternalCall();
2704 return NULL;
2705 }
2706 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2707 if (it == NULL)
2708 return NULL;
2709 it->it_index = 0;
2710 Py_INCREF(seq);
2711 it->it_seq = (PyListObject *)seq;
2712 _PyObject_GC_TRACK(it);
2713 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002714}
2715
2716static void
2717listiter_dealloc(listiterobject *it)
2718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 _PyObject_GC_UNTRACK(it);
2720 Py_XDECREF(it->it_seq);
2721 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002722}
2723
2724static int
2725listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2726{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002727 Py_VISIT(it->it_seq);
2728 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002729}
2730
2731static PyObject *
2732listiter_next(listiterobject *it)
2733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 PyListObject *seq;
2735 PyObject *item;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 assert(it != NULL);
2738 seq = it->it_seq;
2739 if (seq == NULL)
2740 return NULL;
2741 assert(PyList_Check(seq));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002743 if (it->it_index < PyList_GET_SIZE(seq)) {
2744 item = PyList_GET_ITEM(seq, it->it_index);
2745 ++it->it_index;
2746 Py_INCREF(item);
2747 return item;
2748 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002750 Py_DECREF(seq);
2751 it->it_seq = NULL;
2752 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002753}
2754
2755static PyObject *
2756listiter_len(listiterobject *it)
2757{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002758 Py_ssize_t len;
2759 if (it->it_seq) {
2760 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2761 if (len >= 0)
2762 return PyLong_FromSsize_t(len);
2763 }
2764 return PyLong_FromLong(0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002765}
Raymond Hettinger1021c442003-11-07 15:38:09 +00002766/*********************** List Reverse Iterator **************************/
2767
2768typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 PyObject_HEAD
2770 Py_ssize_t it_index;
2771 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002772} listreviterobject;
2773
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002774static PyObject *list_reversed(PyListObject *, PyObject *);
2775static void listreviter_dealloc(listreviterobject *);
2776static int listreviter_traverse(listreviterobject *, visitproc, void *);
2777static PyObject *listreviter_next(listreviterobject *);
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002778static PyObject *listreviter_len(listreviterobject *);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002779
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002780static PyMethodDef listreviter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc},
2782 {NULL, NULL} /* sentinel */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002783};
2784
Raymond Hettinger1021c442003-11-07 15:38:09 +00002785PyTypeObject PyListRevIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2787 "list_reverseiterator", /* tp_name */
2788 sizeof(listreviterobject), /* tp_basicsize */
2789 0, /* tp_itemsize */
2790 /* methods */
2791 (destructor)listreviter_dealloc, /* tp_dealloc */
2792 0, /* tp_print */
2793 0, /* tp_getattr */
2794 0, /* tp_setattr */
2795 0, /* tp_reserved */
2796 0, /* tp_repr */
2797 0, /* tp_as_number */
2798 0, /* tp_as_sequence */
2799 0, /* tp_as_mapping */
2800 0, /* tp_hash */
2801 0, /* tp_call */
2802 0, /* tp_str */
2803 PyObject_GenericGetAttr, /* tp_getattro */
2804 0, /* tp_setattro */
2805 0, /* tp_as_buffer */
2806 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2807 0, /* tp_doc */
2808 (traverseproc)listreviter_traverse, /* tp_traverse */
2809 0, /* tp_clear */
2810 0, /* tp_richcompare */
2811 0, /* tp_weaklistoffset */
2812 PyObject_SelfIter, /* tp_iter */
2813 (iternextfunc)listreviter_next, /* tp_iternext */
2814 listreviter_methods, /* tp_methods */
2815 0,
Raymond Hettinger1021c442003-11-07 15:38:09 +00002816};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002817
2818static PyObject *
2819list_reversed(PyListObject *seq, PyObject *unused)
2820{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002821 listreviterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002823 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2824 if (it == NULL)
2825 return NULL;
2826 assert(PyList_Check(seq));
2827 it->it_index = PyList_GET_SIZE(seq) - 1;
2828 Py_INCREF(seq);
2829 it->it_seq = seq;
2830 PyObject_GC_Track(it);
2831 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002832}
2833
2834static void
2835listreviter_dealloc(listreviterobject *it)
2836{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002837 PyObject_GC_UnTrack(it);
2838 Py_XDECREF(it->it_seq);
2839 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002840}
2841
2842static int
2843listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002845 Py_VISIT(it->it_seq);
2846 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002847}
2848
2849static PyObject *
2850listreviter_next(listreviterobject *it)
2851{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002852 PyObject *item;
2853 Py_ssize_t index = it->it_index;
2854 PyListObject *seq = it->it_seq;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002856 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2857 item = PyList_GET_ITEM(seq, index);
2858 it->it_index--;
2859 Py_INCREF(item);
2860 return item;
2861 }
2862 it->it_index = -1;
2863 if (seq != NULL) {
2864 it->it_seq = NULL;
2865 Py_DECREF(seq);
2866 }
2867 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002868}
2869
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002870static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002871listreviter_len(listreviterobject *it)
2872{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002873 Py_ssize_t len = it->it_index + 1;
2874 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
2875 len = 0;
2876 return PyLong_FromSsize_t(len);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002877}