blob: b9ef0d0287f42b645d6df831226441d16880fab6 [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);
1927 if (keys == NULL)
1928 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001930
1931 for (i = 0; i < saved_ob_size ; i++) {
1932 keys[i] = PyObject_CallFunctionObjArgs(keyfunc, saved_ob_item[i],
1933 NULL);
1934 if (keys[i] == NULL) {
1935 for (i=i-1 ; i>=0 ; i--)
1936 Py_DECREF(keys[i]);
Daniel Stutzbacheda70b82011-05-04 12:46:28 -07001937 if (keys != &ms.temparray[saved_ob_size+1])
1938 PyMem_FREE(keys);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001939 goto keyfunc_fail;
1940 }
1941 }
1942
1943 lo.keys = keys;
1944 lo.values = saved_ob_item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001946
Daniel Stutzbach98338222010-12-02 21:55:33 +00001947 merge_init(&ms, saved_ob_size, keys != NULL);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00001948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 nremaining = saved_ob_size;
1950 if (nremaining < 2)
1951 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00001952
Benjamin Peterson05380642010-08-23 19:35:39 +00001953 /* Reverse sort stability achieved by initially reversing the list,
1954 applying a stable forward sort, then reversing the final result. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001955 if (reverse) {
1956 if (keys != NULL)
1957 reverse_slice(&keys[0], &keys[saved_ob_size]);
1958 reverse_slice(&saved_ob_item[0], &saved_ob_item[saved_ob_size]);
1959 }
Benjamin Peterson05380642010-08-23 19:35:39 +00001960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 /* March over the array once, left to right, finding natural runs,
1962 * and extending short natural runs to minrun elements.
1963 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 minrun = merge_compute_minrun(nremaining);
1965 do {
1966 int descending;
1967 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00001968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 /* Identify next run. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001970 n = count_run(lo.keys, lo.keys + nremaining, &descending);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 if (n < 0)
1972 goto fail;
1973 if (descending)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001974 reverse_sortslice(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 /* If short, extend to min(minrun, nremaining). */
1976 if (n < minrun) {
1977 const Py_ssize_t force = nremaining <= minrun ?
1978 nremaining : minrun;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001979 if (binarysort(lo, lo.keys + force, lo.keys + n) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 goto fail;
1981 n = force;
1982 }
1983 /* Push run onto pending-runs stack, and maybe merge. */
1984 assert(ms.n < MAX_MERGE_PENDING);
1985 ms.pending[ms.n].base = lo;
1986 ms.pending[ms.n].len = n;
1987 ++ms.n;
1988 if (merge_collapse(&ms) < 0)
1989 goto fail;
1990 /* Advance to find next run. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001991 sortslice_advance(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 nremaining -= n;
1993 } while (nremaining);
Tim Peters330f9e92002-07-19 07:05:44 +00001994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 if (merge_force_collapse(&ms) < 0)
1996 goto fail;
1997 assert(ms.n == 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001998 assert(keys == NULL
1999 ? ms.pending[0].base.keys == saved_ob_item
2000 : ms.pending[0].base.keys == &keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 assert(ms.pending[0].len == saved_ob_size);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002002 lo = ms.pending[0].base;
Tim Petersa64dc242002-08-01 02:13:36 +00002003
2004succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002006fail:
Daniel Stutzbach98338222010-12-02 21:55:33 +00002007 if (keys != NULL) {
2008 for (i = 0; i < saved_ob_size; i++)
2009 Py_DECREF(keys[i]);
2010 if (keys != &ms.temparray[saved_ob_size+1])
2011 PyMem_FREE(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 if (self->allocated != -1 && result != NULL) {
2015 /* The user mucked with the list during the sort,
2016 * and we don't already have another error to report.
2017 */
2018 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2019 result = NULL;
2020 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 if (reverse && saved_ob_size > 1)
2023 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 merge_freemem(&ms);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002026
Daniel Stutzbach98338222010-12-02 21:55:33 +00002027keyfunc_fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 final_ob_item = self->ob_item;
2029 i = Py_SIZE(self);
2030 Py_SIZE(self) = saved_ob_size;
2031 self->ob_item = saved_ob_item;
2032 self->allocated = saved_allocated;
2033 if (final_ob_item != NULL) {
2034 /* we cannot use list_clear() for this because it does not
2035 guarantee that the list is really empty when it returns */
2036 while (--i >= 0) {
2037 Py_XDECREF(final_ob_item[i]);
2038 }
2039 PyMem_FREE(final_ob_item);
2040 }
2041 Py_XINCREF(result);
2042 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002043}
Tim Peters330f9e92002-07-19 07:05:44 +00002044#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002045#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002046
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002047int
Fred Drakea2f55112000-07-09 15:16:51 +00002048PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002049{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 if (v == NULL || !PyList_Check(v)) {
2051 PyErr_BadInternalCall();
2052 return -1;
2053 }
2054 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
2055 if (v == NULL)
2056 return -1;
2057 Py_DECREF(v);
2058 return 0;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002059}
2060
Guido van Rossumb86c5492001-02-12 22:06:02 +00002061static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002062listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002063{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 if (Py_SIZE(self) > 1)
2065 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2066 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002067}
2068
Guido van Rossum84c76f51990-10-30 13:32:20 +00002069int
Fred Drakea2f55112000-07-09 15:16:51 +00002070PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002071{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 PyListObject *self = (PyListObject *)v;
Tim Peters6063e262002-08-08 01:06:39 +00002073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 if (v == NULL || !PyList_Check(v)) {
2075 PyErr_BadInternalCall();
2076 return -1;
2077 }
2078 if (Py_SIZE(self) > 1)
2079 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2080 return 0;
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002081}
2082
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002083PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002084PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002085{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 PyObject *w;
2087 PyObject **p, **q;
2088 Py_ssize_t n;
2089 if (v == NULL || !PyList_Check(v)) {
2090 PyErr_BadInternalCall();
2091 return NULL;
2092 }
2093 n = Py_SIZE(v);
2094 w = PyTuple_New(n);
2095 if (w == NULL)
2096 return NULL;
2097 p = ((PyTupleObject *)w)->ob_item;
2098 q = ((PyListObject *)v)->ob_item;
2099 while (--n >= 0) {
2100 Py_INCREF(*q);
2101 *p = *q;
2102 p++;
2103 q++;
2104 }
2105 return w;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002106}
2107
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002108static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002109listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 Py_ssize_t i, start=0, stop=Py_SIZE(self);
2112 PyObject *v, *format_tuple, *err_string;
2113 static PyObject *err_format = NULL;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002114
Petri Lehtinenebfaabd2011-11-06 21:02:39 +02002115 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
2116 _PyEval_SliceIndex, &start,
2117 _PyEval_SliceIndex, &stop))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 return NULL;
2119 if (start < 0) {
2120 start += Py_SIZE(self);
2121 if (start < 0)
2122 start = 0;
2123 }
2124 if (stop < 0) {
2125 stop += Py_SIZE(self);
2126 if (stop < 0)
2127 stop = 0;
2128 }
2129 for (i = start; i < stop && i < Py_SIZE(self); i++) {
2130 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2131 if (cmp > 0)
2132 return PyLong_FromSsize_t(i);
2133 else if (cmp < 0)
2134 return NULL;
2135 }
2136 if (err_format == NULL) {
2137 err_format = PyUnicode_FromString("%r is not in list");
2138 if (err_format == NULL)
2139 return NULL;
2140 }
2141 format_tuple = PyTuple_Pack(1, v);
2142 if (format_tuple == NULL)
2143 return NULL;
2144 err_string = PyUnicode_Format(err_format, format_tuple);
2145 Py_DECREF(format_tuple);
2146 if (err_string == NULL)
2147 return NULL;
2148 PyErr_SetObject(PyExc_ValueError, err_string);
2149 Py_DECREF(err_string);
2150 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002151}
2152
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002153static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002154listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 Py_ssize_t count = 0;
2157 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 for (i = 0; i < Py_SIZE(self); i++) {
2160 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2161 if (cmp > 0)
2162 count++;
2163 else if (cmp < 0)
2164 return NULL;
2165 }
2166 return PyLong_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002167}
2168
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002169static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002170listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002171{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 for (i = 0; i < Py_SIZE(self); i++) {
2175 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2176 if (cmp > 0) {
2177 if (list_ass_slice(self, i, i+1,
2178 (PyObject *)NULL) == 0)
2179 Py_RETURN_NONE;
2180 return NULL;
2181 }
2182 else if (cmp < 0)
2183 return NULL;
2184 }
2185 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
2186 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002187}
2188
Jeremy Hylton8caad492000-06-23 14:18:11 +00002189static int
2190list_traverse(PyListObject *o, visitproc visit, void *arg)
2191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 for (i = Py_SIZE(o); --i >= 0; )
2195 Py_VISIT(o->ob_item[i]);
2196 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002197}
2198
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002199static PyObject *
2200list_richcompare(PyObject *v, PyObject *w, int op)
2201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002202 PyListObject *vl, *wl;
2203 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 if (!PyList_Check(v) || !PyList_Check(w)) {
2206 Py_INCREF(Py_NotImplemented);
2207 return Py_NotImplemented;
2208 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 vl = (PyListObject *)v;
2211 wl = (PyListObject *)w;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
2214 /* Shortcut: if the lengths differ, the lists differ */
2215 PyObject *res;
2216 if (op == Py_EQ)
2217 res = Py_False;
2218 else
2219 res = Py_True;
2220 Py_INCREF(res);
2221 return res;
2222 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 /* Search for the first index where items are different */
2225 for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
2226 int k = PyObject_RichCompareBool(vl->ob_item[i],
2227 wl->ob_item[i], Py_EQ);
2228 if (k < 0)
2229 return NULL;
2230 if (!k)
2231 break;
2232 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
2235 /* No more items to compare -- compare sizes */
2236 Py_ssize_t vs = Py_SIZE(vl);
2237 Py_ssize_t ws = Py_SIZE(wl);
2238 int cmp;
2239 PyObject *res;
2240 switch (op) {
2241 case Py_LT: cmp = vs < ws; break;
2242 case Py_LE: cmp = vs <= ws; break;
2243 case Py_EQ: cmp = vs == ws; break;
2244 case Py_NE: cmp = vs != ws; break;
2245 case Py_GT: cmp = vs > ws; break;
2246 case Py_GE: cmp = vs >= ws; break;
2247 default: return NULL; /* cannot happen */
2248 }
2249 if (cmp)
2250 res = Py_True;
2251 else
2252 res = Py_False;
2253 Py_INCREF(res);
2254 return res;
2255 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 /* We have an item that differs -- shortcuts for EQ/NE */
2258 if (op == Py_EQ) {
2259 Py_INCREF(Py_False);
2260 return Py_False;
2261 }
2262 if (op == Py_NE) {
2263 Py_INCREF(Py_True);
2264 return Py_True;
2265 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 /* Compare the final item again using the proper operator */
2268 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002269}
2270
Tim Peters6d6c1a32001-08-02 04:15:00 +00002271static int
2272list_init(PyListObject *self, PyObject *args, PyObject *kw)
2273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002274 PyObject *arg = NULL;
2275 static char *kwlist[] = {"sequence", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2278 return -1;
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002280 /* Verify list invariants established by PyType_GenericAlloc() */
2281 assert(0 <= Py_SIZE(self));
2282 assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
2283 assert(self->ob_item != NULL ||
2284 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 /* Empty previous contents */
2287 if (self->ob_item != NULL) {
2288 (void)list_clear(self);
2289 }
2290 if (arg != NULL) {
2291 PyObject *rv = listextend(self, arg);
2292 if (rv == NULL)
2293 return -1;
2294 Py_DECREF(rv);
2295 }
2296 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002297}
2298
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002299static PyObject *
2300list_sizeof(PyListObject *self)
2301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002303
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002304 res = sizeof(PyListObject) + self->allocated * sizeof(void*);
2305 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002306}
2307
Raymond Hettinger1021c442003-11-07 15:38:09 +00002308static PyObject *list_iter(PyObject *seq);
2309static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2310
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002311PyDoc_STRVAR(getitem_doc,
2312"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002313PyDoc_STRVAR(reversed_doc,
2314"L.__reversed__() -- return a reverse iterator over the list");
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002315PyDoc_STRVAR(sizeof_doc,
2316"L.__sizeof__() -- size of L in memory, in bytes");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002317PyDoc_STRVAR(append_doc,
2318"L.append(object) -- append object to end");
2319PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002320"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002321PyDoc_STRVAR(insert_doc,
2322"L.insert(index, object) -- insert object before index");
2323PyDoc_STRVAR(pop_doc,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002324"L.pop([index]) -> item -- remove and return item at index (default last).\n"
2325"Raises IndexError if list is empty or index is out of range.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002326PyDoc_STRVAR(remove_doc,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002327"L.remove(value) -- remove first occurrence of value.\n"
2328"Raises ValueError if the value is not present.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002329PyDoc_STRVAR(index_doc,
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00002330"L.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
2331"Raises ValueError if the value is not present.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002332PyDoc_STRVAR(count_doc,
2333"L.count(value) -> integer -- return number of occurrences of value");
2334PyDoc_STRVAR(reverse_doc,
2335"L.reverse() -- reverse *IN PLACE*");
2336PyDoc_STRVAR(sort_doc,
Benjamin Petersoncb9a5512008-09-30 02:08:36 +00002337"L.sort(key=None, reverse=False) -- stable sort *IN PLACE*");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002338
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002339static PyObject *list_subscript(PyListObject*, PyObject*);
2340
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002341static PyMethodDef list_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
2343 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
2344 {"__sizeof__", (PyCFunction)list_sizeof, METH_NOARGS, sizeof_doc},
2345 {"append", (PyCFunction)listappend, METH_O, append_doc},
2346 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
2347 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
2348 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
2349 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
2350 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
2351 {"count", (PyCFunction)listcount, METH_O, count_doc},
2352 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
2353 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
2354 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002355};
2356
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002357static PySequenceMethods list_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002358 (lenfunc)list_length, /* sq_length */
2359 (binaryfunc)list_concat, /* sq_concat */
2360 (ssizeargfunc)list_repeat, /* sq_repeat */
2361 (ssizeargfunc)list_item, /* sq_item */
2362 0, /* sq_slice */
2363 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
2364 0, /* sq_ass_slice */
2365 (objobjproc)list_contains, /* sq_contains */
2366 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2367 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002368};
2369
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002370PyDoc_STRVAR(list_doc,
Ezio Melotti7f807b72010-03-01 04:08:34 +00002371"list() -> new empty list\n"
2372"list(iterable) -> new list initialized from iterable's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002373
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002374static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002375list_subscript(PyListObject* self, PyObject* item)
2376{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 if (PyIndex_Check(item)) {
2378 Py_ssize_t i;
2379 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2380 if (i == -1 && PyErr_Occurred())
2381 return NULL;
2382 if (i < 0)
2383 i += PyList_GET_SIZE(self);
2384 return list_item(self, i);
2385 }
2386 else if (PySlice_Check(item)) {
2387 Py_ssize_t start, stop, step, slicelength, cur, i;
2388 PyObject* result;
2389 PyObject* it;
2390 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002391
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002392 if (PySlice_GetIndicesEx(item, Py_SIZE(self),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 &start, &stop, &step, &slicelength) < 0) {
2394 return NULL;
2395 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 if (slicelength <= 0) {
2398 return PyList_New(0);
2399 }
2400 else if (step == 1) {
2401 return list_slice(self, start, stop);
2402 }
2403 else {
2404 result = PyList_New(slicelength);
2405 if (!result) return NULL;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 src = self->ob_item;
2408 dest = ((PyListObject *)result)->ob_item;
2409 for (cur = start, i = 0; i < slicelength;
2410 cur += step, i++) {
2411 it = src[cur];
2412 Py_INCREF(it);
2413 dest[i] = it;
2414 }
Tim Peters3b01a122002-07-19 02:35:45 +00002415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 return result;
2417 }
2418 }
2419 else {
2420 PyErr_Format(PyExc_TypeError,
2421 "list indices must be integers, not %.200s",
2422 item->ob_type->tp_name);
2423 return NULL;
2424 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002425}
2426
Tim Peters3b01a122002-07-19 02:35:45 +00002427static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002428list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 if (PyIndex_Check(item)) {
2431 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2432 if (i == -1 && PyErr_Occurred())
2433 return -1;
2434 if (i < 0)
2435 i += PyList_GET_SIZE(self);
2436 return list_ass_item(self, i, value);
2437 }
2438 else if (PySlice_Check(item)) {
2439 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002440
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002441 if (PySlice_GetIndicesEx(item, Py_SIZE(self),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 &start, &stop, &step, &slicelength) < 0) {
2443 return -1;
2444 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 if (step == 1)
2447 return list_ass_slice(self, start, stop, value);
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 /* Make sure s[5:2] = [..] inserts at the right place:
2450 before 5, not before 2. */
2451 if ((step < 0 && start < stop) ||
2452 (step > 0 && start > stop))
2453 stop = start;
Thomas Woutersed03b412007-08-28 21:37:11 +00002454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 if (value == NULL) {
2456 /* delete slice */
2457 PyObject **garbage;
2458 size_t cur;
2459 Py_ssize_t i;
Tim Peters3b01a122002-07-19 02:35:45 +00002460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 if (slicelength <= 0)
2462 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 if (step < 0) {
2465 stop = start + 1;
2466 start = stop + step*(slicelength - 1) - 1;
2467 step = -step;
2468 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 assert((size_t)slicelength <=
2471 PY_SIZE_MAX / sizeof(PyObject*));
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +00002472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 garbage = (PyObject**)
2474 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2475 if (!garbage) {
2476 PyErr_NoMemory();
2477 return -1;
2478 }
Tim Peters3b01a122002-07-19 02:35:45 +00002479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002480 /* drawing pictures might help understand these for
2481 loops. Basically, we memmove the parts of the
2482 list that are *not* part of the slice: step-1
2483 items for each item that is part of the slice,
2484 and then tail end of the list that was not
2485 covered by the slice */
2486 for (cur = start, i = 0;
2487 cur < (size_t)stop;
2488 cur += step, i++) {
2489 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 garbage[i] = PyList_GET_ITEM(self, cur);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 if (cur + step >= (size_t)Py_SIZE(self)) {
2494 lim = Py_SIZE(self) - cur - 1;
2495 }
Michael W. Hudson56796f62002-07-29 14:35:04 +00002496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 memmove(self->ob_item + cur - i,
2498 self->ob_item + cur + 1,
2499 lim * sizeof(PyObject *));
2500 }
2501 cur = start + slicelength*step;
2502 if (cur < (size_t)Py_SIZE(self)) {
2503 memmove(self->ob_item + cur - slicelength,
2504 self->ob_item + cur,
2505 (Py_SIZE(self) - cur) *
2506 sizeof(PyObject *));
2507 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 Py_SIZE(self) -= slicelength;
2510 list_resize(self, Py_SIZE(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002512 for (i = 0; i < slicelength; i++) {
2513 Py_DECREF(garbage[i]);
2514 }
2515 PyMem_FREE(garbage);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 return 0;
2518 }
2519 else {
2520 /* assign slice */
2521 PyObject *ins, *seq;
2522 PyObject **garbage, **seqitems, **selfitems;
2523 Py_ssize_t cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 /* protect against a[::-1] = a */
2526 if (self == (PyListObject*)value) {
2527 seq = list_slice((PyListObject*)value, 0,
2528 PyList_GET_SIZE(value));
2529 }
2530 else {
2531 seq = PySequence_Fast(value,
2532 "must assign iterable "
2533 "to extended slice");
2534 }
2535 if (!seq)
2536 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002538 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2539 PyErr_Format(PyExc_ValueError,
2540 "attempt to assign sequence of "
2541 "size %zd to extended slice of "
2542 "size %zd",
2543 PySequence_Fast_GET_SIZE(seq),
2544 slicelength);
2545 Py_DECREF(seq);
2546 return -1;
2547 }
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 if (!slicelength) {
2550 Py_DECREF(seq);
2551 return 0;
2552 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 garbage = (PyObject**)
2555 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2556 if (!garbage) {
2557 Py_DECREF(seq);
2558 PyErr_NoMemory();
2559 return -1;
2560 }
Tim Peters3b01a122002-07-19 02:35:45 +00002561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 selfitems = self->ob_item;
2563 seqitems = PySequence_Fast_ITEMS(seq);
2564 for (cur = start, i = 0; i < slicelength;
2565 cur += step, i++) {
2566 garbage[i] = selfitems[cur];
2567 ins = seqitems[i];
2568 Py_INCREF(ins);
2569 selfitems[cur] = ins;
2570 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 for (i = 0; i < slicelength; i++) {
2573 Py_DECREF(garbage[i]);
2574 }
Tim Peters3b01a122002-07-19 02:35:45 +00002575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 PyMem_FREE(garbage);
2577 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 return 0;
2580 }
2581 }
2582 else {
2583 PyErr_Format(PyExc_TypeError,
2584 "list indices must be integers, not %.200s",
2585 item->ob_type->tp_name);
2586 return -1;
2587 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002588}
2589
2590static PyMappingMethods list_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 (lenfunc)list_length,
2592 (binaryfunc)list_subscript,
2593 (objobjargproc)list_ass_subscript
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002594};
2595
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002596PyTypeObject PyList_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2598 "list",
2599 sizeof(PyListObject),
2600 0,
2601 (destructor)list_dealloc, /* tp_dealloc */
2602 0, /* tp_print */
2603 0, /* tp_getattr */
2604 0, /* tp_setattr */
2605 0, /* tp_reserved */
2606 (reprfunc)list_repr, /* tp_repr */
2607 0, /* tp_as_number */
2608 &list_as_sequence, /* tp_as_sequence */
2609 &list_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00002610 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002611 0, /* tp_call */
2612 0, /* tp_str */
2613 PyObject_GenericGetAttr, /* tp_getattro */
2614 0, /* tp_setattro */
2615 0, /* tp_as_buffer */
2616 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2617 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
2618 list_doc, /* tp_doc */
2619 (traverseproc)list_traverse, /* tp_traverse */
2620 (inquiry)list_clear, /* tp_clear */
2621 list_richcompare, /* tp_richcompare */
2622 0, /* tp_weaklistoffset */
2623 list_iter, /* tp_iter */
2624 0, /* tp_iternext */
2625 list_methods, /* tp_methods */
2626 0, /* tp_members */
2627 0, /* tp_getset */
2628 0, /* tp_base */
2629 0, /* tp_dict */
2630 0, /* tp_descr_get */
2631 0, /* tp_descr_set */
2632 0, /* tp_dictoffset */
2633 (initproc)list_init, /* tp_init */
2634 PyType_GenericAlloc, /* tp_alloc */
2635 PyType_GenericNew, /* tp_new */
2636 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002637};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002638
2639
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002640/*********************** List Iterator **************************/
2641
2642typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002643 PyObject_HEAD
2644 long it_index;
2645 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002646} listiterobject;
2647
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002648static PyObject *list_iter(PyObject *);
2649static void listiter_dealloc(listiterobject *);
2650static int listiter_traverse(listiterobject *, visitproc, void *);
2651static PyObject *listiter_next(listiterobject *);
2652static PyObject *listiter_len(listiterobject *);
Raymond Hettinger435bf582004-03-18 22:43:10 +00002653
Armin Rigof5b3e362006-02-11 21:32:43 +00002654PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002655
2656static PyMethodDef listiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
2658 {NULL, NULL} /* sentinel */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002659};
2660
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002661PyTypeObject PyListIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2663 "list_iterator", /* tp_name */
2664 sizeof(listiterobject), /* tp_basicsize */
2665 0, /* tp_itemsize */
2666 /* methods */
2667 (destructor)listiter_dealloc, /* tp_dealloc */
2668 0, /* tp_print */
2669 0, /* tp_getattr */
2670 0, /* tp_setattr */
2671 0, /* tp_reserved */
2672 0, /* tp_repr */
2673 0, /* tp_as_number */
2674 0, /* tp_as_sequence */
2675 0, /* tp_as_mapping */
2676 0, /* tp_hash */
2677 0, /* tp_call */
2678 0, /* tp_str */
2679 PyObject_GenericGetAttr, /* tp_getattro */
2680 0, /* tp_setattro */
2681 0, /* tp_as_buffer */
2682 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2683 0, /* tp_doc */
2684 (traverseproc)listiter_traverse, /* tp_traverse */
2685 0, /* tp_clear */
2686 0, /* tp_richcompare */
2687 0, /* tp_weaklistoffset */
2688 PyObject_SelfIter, /* tp_iter */
2689 (iternextfunc)listiter_next, /* tp_iternext */
2690 listiter_methods, /* tp_methods */
2691 0, /* tp_members */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002692};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002693
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002694
2695static PyObject *
2696list_iter(PyObject *seq)
2697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 listiterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002700 if (!PyList_Check(seq)) {
2701 PyErr_BadInternalCall();
2702 return NULL;
2703 }
2704 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2705 if (it == NULL)
2706 return NULL;
2707 it->it_index = 0;
2708 Py_INCREF(seq);
2709 it->it_seq = (PyListObject *)seq;
2710 _PyObject_GC_TRACK(it);
2711 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002712}
2713
2714static void
2715listiter_dealloc(listiterobject *it)
2716{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002717 _PyObject_GC_UNTRACK(it);
2718 Py_XDECREF(it->it_seq);
2719 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002720}
2721
2722static int
2723listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 Py_VISIT(it->it_seq);
2726 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002727}
2728
2729static PyObject *
2730listiter_next(listiterobject *it)
2731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002732 PyListObject *seq;
2733 PyObject *item;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002735 assert(it != NULL);
2736 seq = it->it_seq;
2737 if (seq == NULL)
2738 return NULL;
2739 assert(PyList_Check(seq));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 if (it->it_index < PyList_GET_SIZE(seq)) {
2742 item = PyList_GET_ITEM(seq, it->it_index);
2743 ++it->it_index;
2744 Py_INCREF(item);
2745 return item;
2746 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002747
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002748 Py_DECREF(seq);
2749 it->it_seq = NULL;
2750 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002751}
2752
2753static PyObject *
2754listiter_len(listiterobject *it)
2755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002756 Py_ssize_t len;
2757 if (it->it_seq) {
2758 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2759 if (len >= 0)
2760 return PyLong_FromSsize_t(len);
2761 }
2762 return PyLong_FromLong(0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002763}
Raymond Hettinger1021c442003-11-07 15:38:09 +00002764/*********************** List Reverse Iterator **************************/
2765
2766typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002767 PyObject_HEAD
2768 Py_ssize_t it_index;
2769 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002770} listreviterobject;
2771
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002772static PyObject *list_reversed(PyListObject *, PyObject *);
2773static void listreviter_dealloc(listreviterobject *);
2774static int listreviter_traverse(listreviterobject *, visitproc, void *);
2775static PyObject *listreviter_next(listreviterobject *);
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002776static PyObject *listreviter_len(listreviterobject *);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002777
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002778static PyMethodDef listreviter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc},
2780 {NULL, NULL} /* sentinel */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002781};
2782
Raymond Hettinger1021c442003-11-07 15:38:09 +00002783PyTypeObject PyListRevIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002784 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2785 "list_reverseiterator", /* tp_name */
2786 sizeof(listreviterobject), /* tp_basicsize */
2787 0, /* tp_itemsize */
2788 /* methods */
2789 (destructor)listreviter_dealloc, /* tp_dealloc */
2790 0, /* tp_print */
2791 0, /* tp_getattr */
2792 0, /* tp_setattr */
2793 0, /* tp_reserved */
2794 0, /* tp_repr */
2795 0, /* tp_as_number */
2796 0, /* tp_as_sequence */
2797 0, /* tp_as_mapping */
2798 0, /* tp_hash */
2799 0, /* tp_call */
2800 0, /* tp_str */
2801 PyObject_GenericGetAttr, /* tp_getattro */
2802 0, /* tp_setattro */
2803 0, /* tp_as_buffer */
2804 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2805 0, /* tp_doc */
2806 (traverseproc)listreviter_traverse, /* tp_traverse */
2807 0, /* tp_clear */
2808 0, /* tp_richcompare */
2809 0, /* tp_weaklistoffset */
2810 PyObject_SelfIter, /* tp_iter */
2811 (iternextfunc)listreviter_next, /* tp_iternext */
2812 listreviter_methods, /* tp_methods */
2813 0,
Raymond Hettinger1021c442003-11-07 15:38:09 +00002814};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002815
2816static PyObject *
2817list_reversed(PyListObject *seq, PyObject *unused)
2818{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002819 listreviterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002821 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2822 if (it == NULL)
2823 return NULL;
2824 assert(PyList_Check(seq));
2825 it->it_index = PyList_GET_SIZE(seq) - 1;
2826 Py_INCREF(seq);
2827 it->it_seq = seq;
2828 PyObject_GC_Track(it);
2829 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002830}
2831
2832static void
2833listreviter_dealloc(listreviterobject *it)
2834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 PyObject_GC_UnTrack(it);
2836 Py_XDECREF(it->it_seq);
2837 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002838}
2839
2840static int
2841listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002843 Py_VISIT(it->it_seq);
2844 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002845}
2846
2847static PyObject *
2848listreviter_next(listreviterobject *it)
2849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002850 PyObject *item;
2851 Py_ssize_t index = it->it_index;
2852 PyListObject *seq = it->it_seq;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002854 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2855 item = PyList_GET_ITEM(seq, index);
2856 it->it_index--;
2857 Py_INCREF(item);
2858 return item;
2859 }
2860 it->it_index = -1;
2861 if (seq != NULL) {
2862 it->it_seq = NULL;
2863 Py_DECREF(seq);
2864 }
2865 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002866}
2867
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002868static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002869listreviter_len(listreviterobject *it)
2870{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871 Py_ssize_t len = it->it_index + 1;
2872 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
2873 len = 0;
2874 return PyLong_FromSsize_t(len);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002875}