blob: bb65e98714eea16e6094b71b2d94eb724d34fc1d [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* List object implementation */
2
Guido van Rossumc0b618a1997-05-02 03:12:38 +00003#include "Python.h"
4
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00005#ifdef STDC_HEADERS
6#include <stddef.h>
7#else
Antoine Pitrouc83ea132010-05-09 14:46:46 +00008#include <sys/types.h> /* For size_t */
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00009#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000010
Tim Peters8d9eb102004-07-31 02:24:20 +000011/* Ensure ob_item has room for at least newsize elements, and set
12 * ob_size to newsize. If newsize > ob_size on entry, the content
13 * of the new slots at exit is undefined heap trash; it's the caller's
Ezio Melottic2077b02011-03-16 12:34:31 +020014 * responsibility to overwrite them with sane values.
Tim Peters8d9eb102004-07-31 02:24:20 +000015 * The number of allocated elements may grow, shrink, or stay the same.
16 * Failure is impossible if newsize <= self.allocated on entry, although
17 * that partly relies on an assumption that the system realloc() never
18 * fails when passed a number of bytes <= the number of bytes last
19 * allocated (the C standard doesn't guarantee this, but it's hard to
20 * imagine a realloc implementation where it wouldn't be true).
21 * Note that self->ob_item may change, and even if newsize is less
22 * than ob_size on entry.
23 */
Guido van Rossuma46d51d1995-01-26 22:59:43 +000024static int
Martin v. Löwis18e16552006-02-15 17:27:45 +000025list_resize(PyListObject *self, Py_ssize_t newsize)
Guido van Rossuma46d51d1995-01-26 22:59:43 +000026{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000027 PyObject **items;
28 size_t new_allocated;
29 Py_ssize_t allocated = self->allocated;
Tim Peters65b8b842001-05-26 05:28:40 +000030
Antoine Pitrouc83ea132010-05-09 14:46:46 +000031 /* Bypass realloc() when a previous overallocation is large enough
32 to accommodate the newsize. If the newsize falls lower than half
33 the allocated size, then proceed with the realloc() to shrink the list.
34 */
35 if (allocated >= newsize && newsize >= (allocated >> 1)) {
36 assert(self->ob_item != NULL || newsize == 0);
37 Py_SIZE(self) = newsize;
38 return 0;
39 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +000040
Antoine Pitrouc83ea132010-05-09 14:46:46 +000041 /* This over-allocates proportional to the list size, making room
42 * for additional growth. The over-allocation is mild, but is
43 * enough to give linear-time amortized behavior over a long
44 * sequence of appends() in the presence of a poorly-performing
45 * system realloc().
46 * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
47 */
48 new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6);
Gregory P. Smith9d534572008-06-11 07:41:16 +000049
Antoine Pitrouc83ea132010-05-09 14:46:46 +000050 /* check for integer overflow */
51 if (new_allocated > PY_SIZE_MAX - newsize) {
52 PyErr_NoMemory();
53 return -1;
54 } else {
55 new_allocated += newsize;
56 }
Gregory P. Smith9d534572008-06-11 07:41:16 +000057
Antoine Pitrouc83ea132010-05-09 14:46:46 +000058 if (newsize == 0)
59 new_allocated = 0;
60 items = self->ob_item;
Mark Dickinson4ac5d2c2011-09-19 19:23:55 +010061 if (new_allocated <= (PY_SIZE_MAX / sizeof(PyObject *)))
Antoine Pitrouc83ea132010-05-09 14:46:46 +000062 PyMem_RESIZE(items, PyObject *, new_allocated);
63 else
64 items = NULL;
65 if (items == NULL) {
66 PyErr_NoMemory();
67 return -1;
68 }
69 self->ob_item = items;
70 Py_SIZE(self) = newsize;
71 self->allocated = new_allocated;
72 return 0;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000073}
Guido van Rossuma46d51d1995-01-26 22:59:43 +000074
Christian Heimesb4ee4a12008-02-07 17:15:30 +000075/* Debug statistic to compare allocations with reuse through the free list */
76#undef SHOW_ALLOC_COUNT
77#ifdef SHOW_ALLOC_COUNT
78static size_t count_alloc = 0;
79static size_t count_reuse = 0;
80
81static void
82show_alloc(void)
83{
Antoine Pitrouc83ea132010-05-09 14:46:46 +000084 fprintf(stderr, "List allocations: %" PY_FORMAT_SIZE_T "d\n",
85 count_alloc);
86 fprintf(stderr, "List reuse through freelist: %" PY_FORMAT_SIZE_T
87 "d\n", count_reuse);
88 fprintf(stderr, "%.2f%% reuse rate\n\n",
89 (100.0*count_reuse/(count_alloc+count_reuse)));
Christian Heimesb4ee4a12008-02-07 17:15:30 +000090}
91#endif
92
Raymond Hettinger0468e412004-05-05 05:37:53 +000093/* Empty list reuse scheme to save calls to malloc and free */
Christian Heimes5b970ad2008-02-06 13:33:44 +000094#ifndef PyList_MAXFREELIST
95#define PyList_MAXFREELIST 80
96#endif
97static PyListObject *free_list[PyList_MAXFREELIST];
98static int numfree = 0;
Raymond Hettinger0468e412004-05-05 05:37:53 +000099
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000100void
101PyList_Fini(void)
102{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000103 PyListObject *op;
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000104
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000105 while (numfree) {
106 op = free_list[--numfree];
107 assert(PyList_CheckExact(op));
108 PyObject_GC_Del(op);
109 }
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000110}
111
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000112PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000113PyList_New(Py_ssize_t size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000114{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000115 PyListObject *op;
116 size_t nbytes;
Christian Heimesb4ee4a12008-02-07 17:15:30 +0000117#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000118 static int initialized = 0;
119 if (!initialized) {
120 Py_AtExit(show_alloc);
121 initialized = 1;
122 }
Christian Heimesb4ee4a12008-02-07 17:15:30 +0000123#endif
Tim Peters3986d4e2004-07-29 02:28:42 +0000124
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000125 if (size < 0) {
126 PyErr_BadInternalCall();
127 return NULL;
128 }
129 /* Check for overflow without an actual overflow,
130 * which can cause compiler to optimise out */
131 if ((size_t)size > PY_SIZE_MAX / sizeof(PyObject *))
132 return PyErr_NoMemory();
133 nbytes = size * sizeof(PyObject *);
134 if (numfree) {
135 numfree--;
136 op = free_list[numfree];
137 _Py_NewReference((PyObject *)op);
Christian Heimesb4ee4a12008-02-07 17:15:30 +0000138#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000139 count_reuse++;
Christian Heimesb4ee4a12008-02-07 17:15:30 +0000140#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000141 } else {
142 op = PyObject_GC_New(PyListObject, &PyList_Type);
143 if (op == NULL)
144 return NULL;
Christian Heimesb4ee4a12008-02-07 17:15:30 +0000145#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000146 count_alloc++;
Christian Heimesb4ee4a12008-02-07 17:15:30 +0000147#endif
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000148 }
149 if (size <= 0)
150 op->ob_item = NULL;
151 else {
152 op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
153 if (op->ob_item == NULL) {
154 Py_DECREF(op);
155 return PyErr_NoMemory();
156 }
157 memset(op->ob_item, 0, nbytes);
158 }
159 Py_SIZE(op) = size;
160 op->allocated = size;
161 _PyObject_GC_TRACK(op);
162 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000163}
164
Martin v. Löwis18e16552006-02-15 17:27:45 +0000165Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000166PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000167{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000168 if (!PyList_Check(op)) {
169 PyErr_BadInternalCall();
170 return -1;
171 }
172 else
173 return Py_SIZE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000174}
175
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000176static PyObject *indexerr = NULL;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000177
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000178PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000179PyList_GetItem(PyObject *op, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000180{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000181 if (!PyList_Check(op)) {
182 PyErr_BadInternalCall();
183 return NULL;
184 }
185 if (i < 0 || i >= Py_SIZE(op)) {
186 if (indexerr == NULL) {
187 indexerr = PyString_FromString(
188 "list index out of range");
189 if (indexerr == NULL)
190 return NULL;
191 }
192 PyErr_SetObject(PyExc_IndexError, indexerr);
193 return NULL;
194 }
195 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000196}
197
198int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000199PyList_SetItem(register PyObject *op, register Py_ssize_t i,
Fred Drakea2f55112000-07-09 15:16:51 +0000200 register PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000201{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000202 register PyObject *olditem;
203 register PyObject **p;
204 if (!PyList_Check(op)) {
205 Py_XDECREF(newitem);
206 PyErr_BadInternalCall();
207 return -1;
208 }
209 if (i < 0 || i >= Py_SIZE(op)) {
210 Py_XDECREF(newitem);
211 PyErr_SetString(PyExc_IndexError,
212 "list assignment index out of range");
213 return -1;
214 }
215 p = ((PyListObject *)op) -> ob_item + i;
216 olditem = *p;
217 *p = newitem;
218 Py_XDECREF(olditem);
219 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000220}
221
222static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000223ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000224{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000225 Py_ssize_t i, n = Py_SIZE(self);
226 PyObject **items;
227 if (v == NULL) {
228 PyErr_BadInternalCall();
229 return -1;
230 }
231 if (n == PY_SSIZE_T_MAX) {
232 PyErr_SetString(PyExc_OverflowError,
233 "cannot add more objects to list");
234 return -1;
235 }
Tim Petersb38e2b62004-07-29 02:29:26 +0000236
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000237 if (list_resize(self, n+1) == -1)
238 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000239
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000240 if (where < 0) {
241 where += n;
242 if (where < 0)
243 where = 0;
244 }
245 if (where > n)
246 where = n;
247 items = self->ob_item;
248 for (i = n; --i >= where; )
249 items[i+1] = items[i];
250 Py_INCREF(v);
251 items[where] = v;
252 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000253}
254
255int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000256PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000257{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000258 if (!PyList_Check(op)) {
259 PyErr_BadInternalCall();
260 return -1;
261 }
262 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000263}
264
Raymond Hettinger40a03822004-04-12 13:05:09 +0000265static int
266app1(PyListObject *self, PyObject *v)
267{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000268 Py_ssize_t n = PyList_GET_SIZE(self);
Raymond Hettinger40a03822004-04-12 13:05:09 +0000269
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000270 assert (v != NULL);
271 if (n == PY_SSIZE_T_MAX) {
272 PyErr_SetString(PyExc_OverflowError,
273 "cannot add more objects to list");
274 return -1;
275 }
Raymond Hettinger40a03822004-04-12 13:05:09 +0000276
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000277 if (list_resize(self, n+1) == -1)
278 return -1;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000279
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000280 Py_INCREF(v);
281 PyList_SET_ITEM(self, n, v);
282 return 0;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000283}
284
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000285int
Fred Drakea2f55112000-07-09 15:16:51 +0000286PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000287{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000288 if (PyList_Check(op) && (newitem != NULL))
289 return app1((PyListObject *)op, newitem);
290 PyErr_BadInternalCall();
291 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000292}
293
294/* Methods */
295
296static void
Fred Drakea2f55112000-07-09 15:16:51 +0000297list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000298{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000299 Py_ssize_t i;
300 PyObject_GC_UnTrack(op);
301 Py_TRASHCAN_SAFE_BEGIN(op)
302 if (op->ob_item != NULL) {
303 /* Do it backwards, for Christian Tismer.
304 There's a simple test case where somehow this reduces
305 thrashing when a *very* large list is created and
306 immediately deleted. */
307 i = Py_SIZE(op);
308 while (--i >= 0) {
309 Py_XDECREF(op->ob_item[i]);
310 }
311 PyMem_FREE(op->ob_item);
312 }
313 if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op))
314 free_list[numfree++] = op;
315 else
316 Py_TYPE(op)->tp_free((PyObject *)op);
317 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000318}
319
Guido van Rossum90933611991-06-07 16:10:43 +0000320static int
Fred Drakea2f55112000-07-09 15:16:51 +0000321list_print(PyListObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000322{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000323 int rc;
324 Py_ssize_t i;
325 PyObject *item;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000326
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000327 rc = Py_ReprEnter((PyObject*)op);
328 if (rc != 0) {
329 if (rc < 0)
330 return rc;
331 Py_BEGIN_ALLOW_THREADS
332 fprintf(fp, "[...]");
333 Py_END_ALLOW_THREADS
334 return 0;
335 }
336 Py_BEGIN_ALLOW_THREADS
337 fprintf(fp, "[");
338 Py_END_ALLOW_THREADS
339 for (i = 0; i < Py_SIZE(op); i++) {
340 item = op->ob_item[i];
341 Py_INCREF(item);
342 if (i > 0) {
343 Py_BEGIN_ALLOW_THREADS
344 fprintf(fp, ", ");
345 Py_END_ALLOW_THREADS
346 }
347 if (PyObject_Print(item, fp, 0) != 0) {
348 Py_DECREF(item);
349 Py_ReprLeave((PyObject *)op);
350 return -1;
351 }
352 Py_DECREF(item);
353 }
354 Py_BEGIN_ALLOW_THREADS
355 fprintf(fp, "]");
356 Py_END_ALLOW_THREADS
357 Py_ReprLeave((PyObject *)op);
358 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000359}
360
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000361static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000362list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000363{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000364 Py_ssize_t i;
365 PyObject *s, *temp;
366 PyObject *pieces = NULL, *result = NULL;
Guido van Rossumfb376de1998-04-10 22:47:27 +0000367
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000368 i = Py_ReprEnter((PyObject*)v);
369 if (i != 0) {
370 return i > 0 ? PyString_FromString("[...]") : NULL;
371 }
Tim Petersa7259592001-06-16 05:11:17 +0000372
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000373 if (Py_SIZE(v) == 0) {
374 result = PyString_FromString("[]");
375 goto Done;
376 }
Tim Petersa7259592001-06-16 05:11:17 +0000377
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000378 pieces = PyList_New(0);
379 if (pieces == NULL)
380 goto Done;
Tim Petersa7259592001-06-16 05:11:17 +0000381
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000382 /* Do repr() on each element. Note that this may mutate the list,
383 so must refetch the list size on each iteration. */
384 for (i = 0; i < Py_SIZE(v); ++i) {
385 int status;
386 if (Py_EnterRecursiveCall(" while getting the repr of a list"))
387 goto Done;
388 s = PyObject_Repr(v->ob_item[i]);
389 Py_LeaveRecursiveCall();
390 if (s == NULL)
391 goto Done;
392 status = PyList_Append(pieces, s);
393 Py_DECREF(s); /* append created a new ref */
394 if (status < 0)
395 goto Done;
396 }
Tim Petersa7259592001-06-16 05:11:17 +0000397
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000398 /* Add "[]" decorations to the first and last items. */
399 assert(PyList_GET_SIZE(pieces) > 0);
400 s = PyString_FromString("[");
401 if (s == NULL)
402 goto Done;
403 temp = PyList_GET_ITEM(pieces, 0);
404 PyString_ConcatAndDel(&s, temp);
405 PyList_SET_ITEM(pieces, 0, s);
406 if (s == NULL)
407 goto Done;
Tim Petersa7259592001-06-16 05:11:17 +0000408
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000409 s = PyString_FromString("]");
410 if (s == NULL)
411 goto Done;
412 temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
413 PyString_ConcatAndDel(&temp, s);
414 PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
415 if (temp == NULL)
416 goto Done;
Tim Petersa7259592001-06-16 05:11:17 +0000417
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000418 /* Paste them all together with ", " between. */
419 s = PyString_FromString(", ");
420 if (s == NULL)
421 goto Done;
422 result = _PyString_Join(s, pieces);
423 Py_DECREF(s);
Tim Petersa7259592001-06-16 05:11:17 +0000424
425Done:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000426 Py_XDECREF(pieces);
427 Py_ReprLeave((PyObject *)v);
428 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000429}
430
Martin v. Löwis18e16552006-02-15 17:27:45 +0000431static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000432list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000433{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000434 return Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000435}
436
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000437static int
Fred Drakea2f55112000-07-09 15:16:51 +0000438list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000439{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000440 Py_ssize_t i;
441 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000442
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000443 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
444 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
445 Py_EQ);
446 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000447}
448
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000449static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000450list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000451{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000452 if (i < 0 || i >= Py_SIZE(a)) {
453 if (indexerr == NULL) {
454 indexerr = PyString_FromString(
455 "list index out of range");
456 if (indexerr == NULL)
457 return NULL;
458 }
459 PyErr_SetObject(PyExc_IndexError, indexerr);
460 return NULL;
461 }
462 Py_INCREF(a->ob_item[i]);
463 return a->ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000464}
465
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000466static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000467list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000468{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000469 PyListObject *np;
470 PyObject **src, **dest;
471 Py_ssize_t i, len;
472 if (ilow < 0)
473 ilow = 0;
474 else if (ilow > Py_SIZE(a))
475 ilow = Py_SIZE(a);
476 if (ihigh < ilow)
477 ihigh = ilow;
478 else if (ihigh > Py_SIZE(a))
479 ihigh = Py_SIZE(a);
480 len = ihigh - ilow;
481 np = (PyListObject *) PyList_New(len);
482 if (np == NULL)
483 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000484
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000485 src = a->ob_item + ilow;
486 dest = np->ob_item;
487 for (i = 0; i < len; i++) {
488 PyObject *v = src[i];
489 Py_INCREF(v);
490 dest[i] = v;
491 }
492 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000493}
494
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000495PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000496PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000497{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000498 if (!PyList_Check(a)) {
499 PyErr_BadInternalCall();
500 return NULL;
501 }
502 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000503}
504
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000505static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000506list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000507{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000508 Py_ssize_t size;
509 Py_ssize_t i;
510 PyObject **src, **dest;
511 PyListObject *np;
512 if (!PyList_Check(bb)) {
513 PyErr_Format(PyExc_TypeError,
514 "can only concatenate list (not \"%.200s\") to list",
515 bb->ob_type->tp_name);
516 return NULL;
517 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000518#define b ((PyListObject *)bb)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000519 size = Py_SIZE(a) + Py_SIZE(b);
520 if (size < 0)
521 return PyErr_NoMemory();
522 np = (PyListObject *) PyList_New(size);
523 if (np == NULL) {
524 return NULL;
525 }
526 src = a->ob_item;
527 dest = np->ob_item;
528 for (i = 0; i < Py_SIZE(a); i++) {
529 PyObject *v = src[i];
530 Py_INCREF(v);
531 dest[i] = v;
532 }
533 src = b->ob_item;
534 dest = np->ob_item + Py_SIZE(a);
535 for (i = 0; i < Py_SIZE(b); i++) {
536 PyObject *v = src[i];
537 Py_INCREF(v);
538 dest[i] = v;
539 }
540 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000541#undef b
542}
543
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000544static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000545list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000546{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000547 Py_ssize_t i, j;
548 Py_ssize_t size;
549 PyListObject *np;
550 PyObject **p, **items;
551 PyObject *elem;
552 if (n < 0)
553 n = 0;
Mark Dickinson4ac5d2c2011-09-19 19:23:55 +0100554 if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000555 return PyErr_NoMemory();
Mark Dickinson4ac5d2c2011-09-19 19:23:55 +0100556 size = Py_SIZE(a) * n;
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000557 if (size == 0)
558 return PyList_New(0);
559 np = (PyListObject *) PyList_New(size);
560 if (np == NULL)
561 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000562
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000563 items = np->ob_item;
564 if (Py_SIZE(a) == 1) {
565 elem = a->ob_item[0];
566 for (i = 0; i < n; i++) {
567 items[i] = elem;
568 Py_INCREF(elem);
569 }
570 return (PyObject *) np;
571 }
572 p = np->ob_item;
573 items = a->ob_item;
574 for (i = 0; i < n; i++) {
575 for (j = 0; j < Py_SIZE(a); j++) {
576 *p = items[j];
577 Py_INCREF(*p);
578 p++;
579 }
580 }
581 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000582}
583
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000584static int
Armin Rigo93677f02004-07-29 12:40:23 +0000585list_clear(PyListObject *a)
586{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000587 Py_ssize_t i;
588 PyObject **item = a->ob_item;
589 if (item != NULL) {
590 /* Because XDECREF can recursively invoke operations on
591 this list, we make it empty first. */
592 i = Py_SIZE(a);
593 Py_SIZE(a) = 0;
594 a->ob_item = NULL;
595 a->allocated = 0;
596 while (--i >= 0) {
597 Py_XDECREF(item[i]);
598 }
599 PyMem_FREE(item);
600 }
601 /* Never fails; the return value can be ignored.
602 Note that there is no guarantee that the list is actually empty
603 at this point, because XDECREF may have populated it again! */
604 return 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000605}
606
Tim Peters8fc4a912004-07-31 21:53:19 +0000607/* a[ilow:ihigh] = v if v != NULL.
608 * del a[ilow:ihigh] if v == NULL.
609 *
610 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
611 * guaranteed the call cannot fail.
612 */
Armin Rigo93677f02004-07-29 12:40:23 +0000613static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000614list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000615{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000616 /* Because [X]DECREF can recursively invoke list operations on
617 this list, we must postpone all [X]DECREF activity until
618 after the list is back in its canonical shape. Therefore
619 we must allocate an additional array, 'recycle', into which
620 we temporarily copy the items that are deleted from the
621 list. :-( */
622 PyObject *recycle_on_stack[8];
623 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
624 PyObject **item;
625 PyObject **vitem = NULL;
626 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
627 Py_ssize_t n; /* # of elements in replacement list */
628 Py_ssize_t norig; /* # of elements in list getting replaced */
629 Py_ssize_t d; /* Change in size */
630 Py_ssize_t k;
631 size_t s;
632 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000633#define b ((PyListObject *)v)
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000634 if (v == NULL)
635 n = 0;
636 else {
637 if (a == b) {
638 /* Special case "a[i:j] = a" -- copy b first */
639 v = list_slice(b, 0, Py_SIZE(b));
640 if (v == NULL)
641 return result;
642 result = list_ass_slice(a, ilow, ihigh, v);
643 Py_DECREF(v);
644 return result;
645 }
646 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
647 if(v_as_SF == NULL)
648 goto Error;
649 n = PySequence_Fast_GET_SIZE(v_as_SF);
650 vitem = PySequence_Fast_ITEMS(v_as_SF);
651 }
652 if (ilow < 0)
653 ilow = 0;
654 else if (ilow > Py_SIZE(a))
655 ilow = Py_SIZE(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000656
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000657 if (ihigh < ilow)
658 ihigh = ilow;
659 else if (ihigh > Py_SIZE(a))
660 ihigh = Py_SIZE(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000661
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000662 norig = ihigh - ilow;
663 assert(norig >= 0);
664 d = n - norig;
665 if (Py_SIZE(a) + d == 0) {
666 Py_XDECREF(v_as_SF);
667 return list_clear(a);
668 }
669 item = a->ob_item;
670 /* recycle the items that we are about to remove */
671 s = norig * sizeof(PyObject *);
Benjamin Petersond4d79002016-09-06 17:58:25 -0700672 /* If norig == 0, item might be NULL, in which case we may not memcpy from it. */
673 if (s) {
674 if (s > sizeof(recycle_on_stack)) {
675 recycle = (PyObject **)PyMem_MALLOC(s);
676 if (recycle == NULL) {
677 PyErr_NoMemory();
678 goto Error;
679 }
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000680 }
Benjamin Petersond4d79002016-09-06 17:58:25 -0700681 memcpy(recycle, &item[ilow], s);
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000682 }
Tim Peters8d9eb102004-07-31 02:24:20 +0000683
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000684 if (d < 0) { /* Delete -d items */
685 memmove(&item[ihigh+d], &item[ihigh],
686 (Py_SIZE(a) - ihigh)*sizeof(PyObject *));
687 list_resize(a, Py_SIZE(a) + d);
688 item = a->ob_item;
689 }
690 else if (d > 0) { /* Insert d items */
691 k = Py_SIZE(a);
692 if (list_resize(a, k+d) < 0)
693 goto Error;
694 item = a->ob_item;
695 memmove(&item[ihigh+d], &item[ihigh],
696 (k - ihigh)*sizeof(PyObject *));
697 }
698 for (k = 0; k < n; k++, ilow++) {
699 PyObject *w = vitem[k];
700 Py_XINCREF(w);
701 item[ilow] = w;
702 }
703 for (k = norig - 1; k >= 0; --k)
704 Py_XDECREF(recycle[k]);
705 result = 0;
Tim Peters8d9eb102004-07-31 02:24:20 +0000706 Error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000707 if (recycle != recycle_on_stack)
708 PyMem_FREE(recycle);
709 Py_XDECREF(v_as_SF);
710 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000711#undef b
712}
713
Guido van Rossum234f9421993-06-17 12:35:49 +0000714int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000715PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000716{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000717 if (!PyList_Check(a)) {
718 PyErr_BadInternalCall();
719 return -1;
720 }
721 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000722}
723
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000724static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000725list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000726{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000727 PyObject **items;
728 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000729
730
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000731 size = PyList_GET_SIZE(self);
732 if (size == 0 || n == 1) {
733 Py_INCREF(self);
734 return (PyObject *)self;
735 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000736
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000737 if (n < 1) {
738 (void)list_clear(self);
739 Py_INCREF(self);
740 return (PyObject *)self;
741 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000742
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000743 if (size > PY_SSIZE_T_MAX / n) {
744 return PyErr_NoMemory();
745 }
Guido van Rossum8d5cf4e2008-01-25 19:50:26 +0000746
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000747 if (list_resize(self, size*n) == -1)
748 return NULL;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000749
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000750 p = size;
751 items = self->ob_item;
752 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
753 for (j = 0; j < size; j++) {
754 PyObject *o = items[j];
755 Py_INCREF(o);
756 items[p++] = o;
757 }
758 }
759 Py_INCREF(self);
760 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000761}
762
Guido van Rossum4a450d01991-04-03 19:05:18 +0000763static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000764list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000765{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000766 PyObject *old_value;
767 if (i < 0 || i >= Py_SIZE(a)) {
768 PyErr_SetString(PyExc_IndexError,
769 "list assignment index out of range");
770 return -1;
771 }
772 if (v == NULL)
773 return list_ass_slice(a, i, i+1, v);
774 Py_INCREF(v);
775 old_value = a->ob_item[i];
776 a->ob_item[i] = v;
777 Py_DECREF(old_value);
778 return 0;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000779}
780
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000781static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000782listinsert(PyListObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000783{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000784 Py_ssize_t i;
785 PyObject *v;
786 if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
787 return NULL;
788 if (ins1(self, i, v) == 0)
789 Py_RETURN_NONE;
790 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000791}
792
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000793static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000794listappend(PyListObject *self, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000795{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000796 if (app1(self, v) == 0)
797 Py_RETURN_NONE;
798 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000799}
800
Barry Warsawdedf6d61998-10-09 16:37:25 +0000801static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000802listextend(PyListObject *self, PyObject *b)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000803{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000804 PyObject *it; /* iter(v) */
805 Py_ssize_t m; /* size of self */
806 Py_ssize_t n; /* guess for size of b */
807 Py_ssize_t mn; /* m + n */
808 Py_ssize_t i;
809 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000810
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000811 /* Special cases:
812 1) lists and tuples which can use PySequence_Fast ops
813 2) extending self to self requires making a copy first
814 */
815 if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
816 PyObject **src, **dest;
817 b = PySequence_Fast(b, "argument must be iterable");
818 if (!b)
819 return NULL;
820 n = PySequence_Fast_GET_SIZE(b);
821 if (n == 0) {
822 /* short circuit when b is empty */
823 Py_DECREF(b);
824 Py_RETURN_NONE;
825 }
826 m = Py_SIZE(self);
827 if (list_resize(self, m + n) == -1) {
828 Py_DECREF(b);
829 return NULL;
830 }
831 /* note that we may still have self == b here for the
832 * situation a.extend(a), but the following code works
833 * in that case too. Just make sure to resize self
834 * before calling PySequence_Fast_ITEMS.
835 */
836 /* populate the end of self with b's items */
837 src = PySequence_Fast_ITEMS(b);
838 dest = self->ob_item + m;
839 for (i = 0; i < n; i++) {
840 PyObject *o = src[i];
841 Py_INCREF(o);
842 dest[i] = o;
843 }
844 Py_DECREF(b);
845 Py_RETURN_NONE;
846 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000847
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000848 it = PyObject_GetIter(b);
849 if (it == NULL)
850 return NULL;
851 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000852
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000853 /* Guess a result list size. */
854 n = _PyObject_LengthHint(b, 8);
855 if (n == -1) {
856 Py_DECREF(it);
857 return NULL;
858 }
859 m = Py_SIZE(self);
860 mn = m + n;
861 if (mn >= m) {
862 /* Make room. */
863 if (list_resize(self, mn) == -1)
864 goto error;
865 /* Make the list sane again. */
866 Py_SIZE(self) = m;
867 }
868 /* Else m + n overflowed; on the chance that n lied, and there really
869 * is enough room, ignore it. If n was telling the truth, we'll
870 * eventually run out of memory during the loop.
871 */
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000872
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000873 /* Run iterator to exhaustion. */
874 for (;;) {
875 PyObject *item = iternext(it);
876 if (item == NULL) {
877 if (PyErr_Occurred()) {
878 if (PyErr_ExceptionMatches(PyExc_StopIteration))
879 PyErr_Clear();
880 else
881 goto error;
882 }
883 break;
884 }
885 if (Py_SIZE(self) < self->allocated) {
886 /* steals ref */
887 PyList_SET_ITEM(self, Py_SIZE(self), item);
888 ++Py_SIZE(self);
889 }
890 else {
891 int status = app1(self, item);
892 Py_DECREF(item); /* append creates a new ref */
893 if (status < 0)
894 goto error;
895 }
896 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000897
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000898 /* Cut back result list if initial guess was too large. */
899 if (Py_SIZE(self) < self->allocated)
900 list_resize(self, Py_SIZE(self)); /* shrinking can't fail */
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000901
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000902 Py_DECREF(it);
903 Py_RETURN_NONE;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000904
905 error:
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000906 Py_DECREF(it);
907 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000908}
909
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000910PyObject *
911_PyList_Extend(PyListObject *self, PyObject *b)
912{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000913 return listextend(self, b);
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000914}
915
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000916static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000917list_inplace_concat(PyListObject *self, PyObject *other)
918{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000919 PyObject *result;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000920
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000921 result = listextend(self, other);
922 if (result == NULL)
923 return result;
924 Py_DECREF(result);
925 Py_INCREF(self);
926 return (PyObject *)self;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000927}
928
929static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000930listpop(PyListObject *self, PyObject *args)
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000931{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000932 Py_ssize_t i = -1;
933 PyObject *v;
934 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000935
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000936 if (!PyArg_ParseTuple(args, "|n:pop", &i))
937 return NULL;
Armin Rigo7ccbca92006-10-04 12:17:45 +0000938
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000939 if (Py_SIZE(self) == 0) {
940 /* Special-case most common failure cause */
941 PyErr_SetString(PyExc_IndexError, "pop from empty list");
942 return NULL;
943 }
944 if (i < 0)
945 i += Py_SIZE(self);
946 if (i < 0 || i >= Py_SIZE(self)) {
947 PyErr_SetString(PyExc_IndexError, "pop index out of range");
948 return NULL;
949 }
950 v = self->ob_item[i];
951 if (i == Py_SIZE(self) - 1) {
952 status = list_resize(self, Py_SIZE(self) - 1);
953 assert(status >= 0);
954 return v; /* and v now owns the reference the list had */
955 }
956 Py_INCREF(v);
957 status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
958 assert(status >= 0);
959 /* Use status, so that in a release build compilers don't
960 * complain about the unused name.
961 */
962 (void) status;
Brett Cannon651dd522004-08-08 21:21:18 +0000963
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000964 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000965}
966
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000967/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
968static void
969reverse_slice(PyObject **lo, PyObject **hi)
970{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000971 assert(lo && hi);
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000972
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000973 --hi;
974 while (lo < hi) {
975 PyObject *t = *lo;
976 *lo = *hi;
977 *hi = t;
978 ++lo;
979 --hi;
980 }
Tim Peters8e2e7ca2002-07-19 02:33:08 +0000981}
982
Tim Petersa64dc242002-08-01 02:13:36 +0000983/* Lots of code for an adaptive, stable, natural mergesort. There are many
984 * pieces to this algorithm; read listsort.txt for overviews and details.
985 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000986
Guido van Rossum3f236de1996-12-10 23:55:39 +0000987/* Comparison function. Takes care of calling a user-supplied
Tim Peters66860f62002-08-04 17:47:26 +0000988 * comparison function (any callable Python object), which must not be
989 * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool
990 * with Py_LT if you know it's NULL).
Tim Petersa64dc242002-08-01 02:13:36 +0000991 * Returns -1 on error, 1 if x < y, 0 if x >= y.
992 */
Guido van Rossum3f236de1996-12-10 23:55:39 +0000993static int
Tim Petersa8c974c2002-07-19 03:30:57 +0000994islt(PyObject *x, PyObject *y, PyObject *compare)
Guido van Rossum3f236de1996-12-10 23:55:39 +0000995{
Antoine Pitrouc83ea132010-05-09 14:46:46 +0000996 PyObject *res;
997 PyObject *args;
998 Py_ssize_t i;
Guido van Rossum3f236de1996-12-10 23:55:39 +0000999
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001000 assert(compare != NULL);
1001 /* Call the user's comparison function and translate the 3-way
1002 * result into true or false (or error).
1003 */
1004 args = PyTuple_New(2);
1005 if (args == NULL)
1006 return -1;
1007 Py_INCREF(x);
1008 Py_INCREF(y);
1009 PyTuple_SET_ITEM(args, 0, x);
1010 PyTuple_SET_ITEM(args, 1, y);
1011 res = PyObject_Call(compare, args, NULL);
1012 Py_DECREF(args);
1013 if (res == NULL)
1014 return -1;
1015 if (!PyInt_Check(res)) {
1016 PyErr_Format(PyExc_TypeError,
1017 "comparison function must return int, not %.200s",
1018 res->ob_type->tp_name);
1019 Py_DECREF(res);
1020 return -1;
1021 }
1022 i = PyInt_AsLong(res);
1023 Py_DECREF(res);
1024 return i < 0;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001025}
1026
Tim Peters66860f62002-08-04 17:47:26 +00001027/* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
1028 * islt. This avoids a layer of function call in the usual case, and
1029 * sorting does many comparisons.
1030 * Returns -1 on error, 1 if x < y, 0 if x >= y.
1031 */
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001032#define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
1033 PyObject_RichCompareBool(X, Y, Py_LT) : \
1034 islt(X, Y, COMPARE))
Tim Peters66860f62002-08-04 17:47:26 +00001035
1036/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +00001037 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
1038 started. It makes more sense in context <wink>. X and Y are PyObject*s.
1039*/
Tim Peters66860f62002-08-04 17:47:26 +00001040#define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001041 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001042
1043/* binarysort is the best method for sorting small arrays: it does
1044 few compares, but can do data movement quadratic in the number of
1045 elements.
Guido van Rossum42812581998-06-17 14:15:44 +00001046 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +00001047 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001048 On entry, must have lo <= start <= hi, and that [lo, start) is already
1049 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +00001050 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001051 Even in case of error, the output slice will be some permutation of
1052 the input (nothing is lost or duplicated).
1053*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00001054static int
Fred Drakea2f55112000-07-09 15:16:51 +00001055binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
1056 /* compare -- comparison function object, or NULL for default */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001057{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001058 register Py_ssize_t k;
1059 register PyObject **l, **p, **r;
1060 register PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001061
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001062 assert(lo <= start && start <= hi);
1063 /* assert [lo, start) is sorted */
1064 if (lo == start)
1065 ++start;
1066 for (; start < hi; ++start) {
1067 /* set l to where *start belongs */
1068 l = lo;
1069 r = start;
1070 pivot = *r;
1071 /* Invariants:
1072 * pivot >= all in [lo, l).
1073 * pivot < all in [r, start).
1074 * The second is vacuously true at the start.
1075 */
1076 assert(l < r);
1077 do {
1078 p = l + ((r - l) >> 1);
1079 IFLT(pivot, *p)
1080 r = p;
1081 else
1082 l = p+1;
1083 } while (l < r);
1084 assert(l == r);
1085 /* The invariants still hold, so pivot >= all in [lo, l) and
1086 pivot < all in [l, start), so pivot belongs at l. Note
1087 that if there are elements equal to pivot, l points to the
1088 first slot after them -- that's why this sort is stable.
1089 Slide over to make room.
1090 Caution: using memmove is much slower under MSVC 5;
1091 we're not usually moving many slots. */
1092 for (p = start; p > l; --p)
1093 *p = *(p-1);
1094 *l = pivot;
1095 }
1096 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001097
1098 fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001099 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001100}
1101
Tim Petersa64dc242002-08-01 02:13:36 +00001102/*
1103Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1104is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001105
Tim Petersa64dc242002-08-01 02:13:36 +00001106 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001107
Tim Petersa64dc242002-08-01 02:13:36 +00001108or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001109
Tim Petersa64dc242002-08-01 02:13:36 +00001110 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001111
Tim Petersa64dc242002-08-01 02:13:36 +00001112Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1113For its intended use in a stable mergesort, the strictness of the defn of
1114"descending" is needed so that the caller can safely reverse a descending
1115sequence without violating stability (strict > ensures there are no equal
1116elements to get out of order).
1117
1118Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001119*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001120static Py_ssize_t
Tim Petersa64dc242002-08-01 02:13:36 +00001121count_run(PyObject **lo, PyObject **hi, PyObject *compare, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001122{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001123 Py_ssize_t k;
1124 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001125
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001126 assert(lo < hi);
1127 *descending = 0;
1128 ++lo;
1129 if (lo == hi)
1130 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001131
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001132 n = 2;
1133 IFLT(*lo, *(lo-1)) {
1134 *descending = 1;
1135 for (lo = lo+1; lo < hi; ++lo, ++n) {
1136 IFLT(*lo, *(lo-1))
1137 ;
1138 else
1139 break;
1140 }
1141 }
1142 else {
1143 for (lo = lo+1; lo < hi; ++lo, ++n) {
1144 IFLT(*lo, *(lo-1))
1145 break;
1146 }
1147 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001148
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001149 return n;
Tim Petersa64dc242002-08-01 02:13:36 +00001150fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001151 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001152}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001153
Tim Petersa64dc242002-08-01 02:13:36 +00001154/*
1155Locate the proper position of key in a sorted vector; if the vector contains
1156an element equal to key, return the position immediately to the left of
1157the leftmost equal element. [gallop_right() does the same except returns
1158the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001159
Tim Petersa64dc242002-08-01 02:13:36 +00001160"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001161
Tim Petersa64dc242002-08-01 02:13:36 +00001162"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1163hint is to the final result, the faster this runs.
1164
1165The return value is the int k in 0..n such that
1166
1167 a[k-1] < key <= a[k]
1168
1169pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1170key belongs at index k; or, IOW, the first k elements of a should precede
1171key, and the last n-k should follow key.
1172
1173Returns -1 on error. See listsort.txt for info on the method.
1174*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001175static Py_ssize_t
1176gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
Tim Petersa64dc242002-08-01 02:13:36 +00001177{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001178 Py_ssize_t ofs;
1179 Py_ssize_t lastofs;
1180 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001181
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001182 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001183
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001184 a += hint;
1185 lastofs = 0;
1186 ofs = 1;
1187 IFLT(*a, key) {
1188 /* a[hint] < key -- gallop right, until
1189 * a[hint + lastofs] < key <= a[hint + ofs]
1190 */
1191 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1192 while (ofs < maxofs) {
1193 IFLT(a[ofs], key) {
1194 lastofs = ofs;
1195 ofs = (ofs << 1) + 1;
1196 if (ofs <= 0) /* int overflow */
1197 ofs = maxofs;
1198 }
1199 else /* key <= a[hint + ofs] */
1200 break;
1201 }
1202 if (ofs > maxofs)
1203 ofs = maxofs;
1204 /* Translate back to offsets relative to &a[0]. */
1205 lastofs += hint;
1206 ofs += hint;
1207 }
1208 else {
1209 /* key <= a[hint] -- gallop left, until
1210 * a[hint - ofs] < key <= a[hint - lastofs]
1211 */
1212 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1213 while (ofs < maxofs) {
1214 IFLT(*(a-ofs), key)
1215 break;
1216 /* key <= a[hint - ofs] */
1217 lastofs = ofs;
1218 ofs = (ofs << 1) + 1;
1219 if (ofs <= 0) /* int overflow */
1220 ofs = maxofs;
1221 }
1222 if (ofs > maxofs)
1223 ofs = maxofs;
1224 /* Translate back to positive offsets relative to &a[0]. */
1225 k = lastofs;
1226 lastofs = hint - ofs;
1227 ofs = hint - k;
1228 }
1229 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001230
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001231 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1232 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1233 * right of lastofs but no farther right than ofs. Do a binary
1234 * search, with invariant a[lastofs-1] < key <= a[ofs].
1235 */
1236 ++lastofs;
1237 while (lastofs < ofs) {
1238 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001239
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001240 IFLT(a[m], key)
1241 lastofs = m+1; /* a[m] < key */
1242 else
1243 ofs = m; /* key <= a[m] */
1244 }
1245 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1246 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001247
1248fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001249 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001250}
1251
1252/*
1253Exactly like gallop_left(), except that if key already exists in a[0:n],
1254finds the position immediately to the right of the rightmost equal value.
1255
1256The return value is the int k in 0..n such that
1257
1258 a[k-1] <= key < a[k]
1259
1260or -1 if error.
1261
1262The code duplication is massive, but this is enough different given that
1263we're sticking to "<" comparisons that it's much harder to follow if
1264written as one routine with yet another "left or right?" flag.
1265*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001266static Py_ssize_t
1267gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
Tim Petersa64dc242002-08-01 02:13:36 +00001268{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001269 Py_ssize_t ofs;
1270 Py_ssize_t lastofs;
1271 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001272
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001273 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001274
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001275 a += hint;
1276 lastofs = 0;
1277 ofs = 1;
1278 IFLT(key, *a) {
1279 /* key < a[hint] -- gallop left, until
1280 * a[hint - ofs] <= key < a[hint - lastofs]
1281 */
1282 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1283 while (ofs < maxofs) {
1284 IFLT(key, *(a-ofs)) {
1285 lastofs = ofs;
1286 ofs = (ofs << 1) + 1;
1287 if (ofs <= 0) /* int overflow */
1288 ofs = maxofs;
1289 }
1290 else /* a[hint - ofs] <= key */
1291 break;
1292 }
1293 if (ofs > maxofs)
1294 ofs = maxofs;
1295 /* Translate back to positive offsets relative to &a[0]. */
1296 k = lastofs;
1297 lastofs = hint - ofs;
1298 ofs = hint - k;
1299 }
1300 else {
1301 /* a[hint] <= key -- gallop right, until
1302 * a[hint + lastofs] <= key < a[hint + ofs]
1303 */
1304 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1305 while (ofs < maxofs) {
1306 IFLT(key, a[ofs])
1307 break;
1308 /* a[hint + ofs] <= key */
1309 lastofs = ofs;
1310 ofs = (ofs << 1) + 1;
1311 if (ofs <= 0) /* int overflow */
1312 ofs = maxofs;
1313 }
1314 if (ofs > maxofs)
1315 ofs = maxofs;
1316 /* Translate back to offsets relative to &a[0]. */
1317 lastofs += hint;
1318 ofs += hint;
1319 }
1320 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001321
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001322 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1323 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1324 * right of lastofs but no farther right than ofs. Do a binary
1325 * search, with invariant a[lastofs-1] <= key < a[ofs].
1326 */
1327 ++lastofs;
1328 while (lastofs < ofs) {
1329 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001330
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001331 IFLT(key, a[m])
1332 ofs = m; /* key < a[m] */
1333 else
1334 lastofs = m+1; /* a[m] <= key */
1335 }
1336 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1337 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001338
1339fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001340 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001341}
1342
1343/* The maximum number of entries in a MergeState's pending-runs stack.
1344 * This is enough to sort arrays of size up to about
1345 * 32 * phi ** MAX_MERGE_PENDING
1346 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1347 * with 2**64 elements.
1348 */
1349#define MAX_MERGE_PENDING 85
1350
Tim Peterse05f65a2002-08-10 05:21:15 +00001351/* When we get into galloping mode, we stay there until both runs win less
1352 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001353 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001354#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001355
1356/* Avoid malloc for small temp arrays. */
1357#define MERGESTATE_TEMP_SIZE 256
1358
1359/* One MergeState exists on the stack per invocation of mergesort. It's just
1360 * a convenient way to pass state around among the helper functions.
1361 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001362struct s_slice {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001363 PyObject **base;
1364 Py_ssize_t len;
Tim Peterse05f65a2002-08-10 05:21:15 +00001365};
1366
Tim Petersa64dc242002-08-01 02:13:36 +00001367typedef struct s_MergeState {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001368 /* The user-supplied comparison function. or NULL if none given. */
1369 PyObject *compare;
Tim Petersa64dc242002-08-01 02:13:36 +00001370
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001371 /* This controls when we get *into* galloping mode. It's initialized
1372 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1373 * random data, and lower for highly structured data.
1374 */
1375 Py_ssize_t min_gallop;
Tim Peterse05f65a2002-08-10 05:21:15 +00001376
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001377 /* 'a' is temp storage to help with merges. It contains room for
1378 * alloced entries.
1379 */
1380 PyObject **a; /* may point to temparray below */
1381 Py_ssize_t alloced;
Tim Petersa64dc242002-08-01 02:13:36 +00001382
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001383 /* A stack of n pending runs yet to be merged. Run #i starts at
1384 * address base[i] and extends for len[i] elements. It's always
1385 * true (so long as the indices are in bounds) that
1386 *
1387 * pending[i].base + pending[i].len == pending[i+1].base
1388 *
1389 * so we could cut the storage for this, but it's a minor amount,
1390 * and keeping all the info explicit simplifies the code.
1391 */
1392 int n;
1393 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001394
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001395 /* 'a' points to this when possible, rather than muck with malloc. */
1396 PyObject *temparray[MERGESTATE_TEMP_SIZE];
Tim Petersa64dc242002-08-01 02:13:36 +00001397} MergeState;
1398
1399/* Conceptually a MergeState's constructor. */
1400static void
1401merge_init(MergeState *ms, PyObject *compare)
1402{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001403 assert(ms != NULL);
1404 ms->compare = compare;
1405 ms->a = ms->temparray;
1406 ms->alloced = MERGESTATE_TEMP_SIZE;
1407 ms->n = 0;
1408 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001409}
1410
1411/* Free all the temp memory owned by the MergeState. This must be called
1412 * when you're done with a MergeState, and may be called before then if
1413 * you want to free the temp memory early.
1414 */
1415static void
1416merge_freemem(MergeState *ms)
1417{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001418 assert(ms != NULL);
1419 if (ms->a != ms->temparray)
1420 PyMem_Free(ms->a);
1421 ms->a = ms->temparray;
1422 ms->alloced = MERGESTATE_TEMP_SIZE;
Tim Petersa64dc242002-08-01 02:13:36 +00001423}
1424
1425/* Ensure enough temp memory for 'need' array slots is available.
1426 * Returns 0 on success and -1 if the memory can't be gotten.
1427 */
1428static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001429merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001430{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001431 assert(ms != NULL);
1432 if (need <= ms->alloced)
1433 return 0;
1434 /* Don't realloc! That can cost cycles to copy the old data, but
1435 * we don't care what's in the block.
1436 */
1437 merge_freemem(ms);
1438 if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject*)) {
1439 PyErr_NoMemory();
1440 return -1;
1441 }
1442 ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
1443 if (ms->a) {
1444 ms->alloced = need;
1445 return 0;
1446 }
1447 PyErr_NoMemory();
1448 merge_freemem(ms); /* reset to sane state */
1449 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001450}
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001451#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1452 merge_getmem(MS, NEED))
Tim Petersa64dc242002-08-01 02:13:36 +00001453
1454/* Merge the na elements starting at pa with the nb elements starting at pb
1455 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1456 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1457 * merge, and should have na <= nb. See listsort.txt for more info.
1458 * Return 0 if successful, -1 if error.
1459 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001460static Py_ssize_t
1461merge_lo(MergeState *ms, PyObject **pa, Py_ssize_t na,
1462 PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001463{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001464 Py_ssize_t k;
1465 PyObject *compare;
1466 PyObject **dest;
1467 int result = -1; /* guilty until proved innocent */
1468 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001469
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001470 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1471 if (MERGE_GETMEM(ms, na) < 0)
1472 return -1;
1473 memcpy(ms->a, pa, na * sizeof(PyObject*));
1474 dest = pa;
1475 pa = ms->a;
Tim Petersa64dc242002-08-01 02:13:36 +00001476
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001477 *dest++ = *pb++;
1478 --nb;
1479 if (nb == 0)
1480 goto Succeed;
1481 if (na == 1)
1482 goto CopyB;
Tim Petersa64dc242002-08-01 02:13:36 +00001483
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001484 min_gallop = ms->min_gallop;
1485 compare = ms->compare;
1486 for (;;) {
1487 Py_ssize_t acount = 0; /* # of times A won in a row */
1488 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001489
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001490 /* Do the straightforward thing until (if ever) one run
1491 * appears to win consistently.
1492 */
1493 for (;;) {
1494 assert(na > 1 && nb > 0);
1495 k = ISLT(*pb, *pa, compare);
1496 if (k) {
1497 if (k < 0)
1498 goto Fail;
1499 *dest++ = *pb++;
1500 ++bcount;
1501 acount = 0;
1502 --nb;
1503 if (nb == 0)
1504 goto Succeed;
1505 if (bcount >= min_gallop)
1506 break;
1507 }
1508 else {
1509 *dest++ = *pa++;
1510 ++acount;
1511 bcount = 0;
1512 --na;
1513 if (na == 1)
1514 goto CopyB;
1515 if (acount >= min_gallop)
1516 break;
1517 }
1518 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001519
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001520 /* One run is winning so consistently that galloping may
1521 * be a huge win. So try that, and continue galloping until
1522 * (if ever) neither run appears to be winning consistently
1523 * anymore.
1524 */
1525 ++min_gallop;
1526 do {
1527 assert(na > 1 && nb > 0);
1528 min_gallop -= min_gallop > 1;
1529 ms->min_gallop = min_gallop;
1530 k = gallop_right(*pb, pa, na, 0, compare);
1531 acount = k;
1532 if (k) {
1533 if (k < 0)
1534 goto Fail;
1535 memcpy(dest, pa, k * sizeof(PyObject *));
1536 dest += k;
1537 pa += k;
1538 na -= k;
1539 if (na == 1)
1540 goto CopyB;
1541 /* na==0 is impossible now if the comparison
1542 * function is consistent, but we can't assume
1543 * that it is.
1544 */
1545 if (na == 0)
1546 goto Succeed;
1547 }
1548 *dest++ = *pb++;
1549 --nb;
1550 if (nb == 0)
1551 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001552
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001553 k = gallop_left(*pa, pb, nb, 0, compare);
1554 bcount = k;
1555 if (k) {
1556 if (k < 0)
1557 goto Fail;
1558 memmove(dest, pb, k * sizeof(PyObject *));
1559 dest += k;
1560 pb += k;
1561 nb -= k;
1562 if (nb == 0)
1563 goto Succeed;
1564 }
1565 *dest++ = *pa++;
1566 --na;
1567 if (na == 1)
1568 goto CopyB;
1569 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1570 ++min_gallop; /* penalize it for leaving galloping mode */
1571 ms->min_gallop = min_gallop;
1572 }
Tim Petersa64dc242002-08-01 02:13:36 +00001573Succeed:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001574 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001575Fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001576 if (na)
1577 memcpy(dest, pa, na * sizeof(PyObject*));
1578 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001579CopyB:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001580 assert(na == 1 && nb > 0);
1581 /* The last element of pa belongs at the end of the merge. */
1582 memmove(dest, pb, nb * sizeof(PyObject *));
1583 dest[nb] = *pa;
1584 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001585}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001586
Tim Petersa64dc242002-08-01 02:13:36 +00001587/* Merge the na elements starting at pa with the nb elements starting at pb
1588 * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
1589 * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
1590 * merge, and should have na >= nb. See listsort.txt for more info.
1591 * Return 0 if successful, -1 if error.
1592 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001593static Py_ssize_t
1594merge_hi(MergeState *ms, PyObject **pa, Py_ssize_t na, PyObject **pb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001595{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001596 Py_ssize_t k;
1597 PyObject *compare;
1598 PyObject **dest;
1599 int result = -1; /* guilty until proved innocent */
1600 PyObject **basea;
1601 PyObject **baseb;
1602 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001603
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001604 assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
1605 if (MERGE_GETMEM(ms, nb) < 0)
1606 return -1;
1607 dest = pb + nb - 1;
1608 memcpy(ms->a, pb, nb * sizeof(PyObject*));
1609 basea = pa;
1610 baseb = ms->a;
1611 pb = ms->a + nb - 1;
1612 pa += na - 1;
Tim Petersa64dc242002-08-01 02:13:36 +00001613
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001614 *dest-- = *pa--;
1615 --na;
1616 if (na == 0)
1617 goto Succeed;
1618 if (nb == 1)
1619 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001620
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001621 min_gallop = ms->min_gallop;
1622 compare = ms->compare;
1623 for (;;) {
1624 Py_ssize_t acount = 0; /* # of times A won in a row */
1625 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001626
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001627 /* Do the straightforward thing until (if ever) one run
1628 * appears to win consistently.
1629 */
1630 for (;;) {
1631 assert(na > 0 && nb > 1);
1632 k = ISLT(*pb, *pa, compare);
1633 if (k) {
1634 if (k < 0)
1635 goto Fail;
1636 *dest-- = *pa--;
1637 ++acount;
1638 bcount = 0;
1639 --na;
1640 if (na == 0)
1641 goto Succeed;
1642 if (acount >= min_gallop)
1643 break;
1644 }
1645 else {
1646 *dest-- = *pb--;
1647 ++bcount;
1648 acount = 0;
1649 --nb;
1650 if (nb == 1)
1651 goto CopyA;
1652 if (bcount >= min_gallop)
1653 break;
1654 }
1655 }
Tim Petersa64dc242002-08-01 02:13:36 +00001656
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001657 /* One run is winning so consistently that galloping may
1658 * be a huge win. So try that, and continue galloping until
1659 * (if ever) neither run appears to be winning consistently
1660 * anymore.
1661 */
1662 ++min_gallop;
1663 do {
1664 assert(na > 0 && nb > 1);
1665 min_gallop -= min_gallop > 1;
1666 ms->min_gallop = min_gallop;
1667 k = gallop_right(*pb, basea, na, na-1, compare);
1668 if (k < 0)
1669 goto Fail;
1670 k = na - k;
1671 acount = k;
1672 if (k) {
1673 dest -= k;
1674 pa -= k;
1675 memmove(dest+1, pa+1, k * sizeof(PyObject *));
1676 na -= k;
1677 if (na == 0)
1678 goto Succeed;
1679 }
1680 *dest-- = *pb--;
1681 --nb;
1682 if (nb == 1)
1683 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001684
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001685 k = gallop_left(*pa, baseb, nb, nb-1, compare);
1686 if (k < 0)
1687 goto Fail;
1688 k = nb - k;
1689 bcount = k;
1690 if (k) {
1691 dest -= k;
1692 pb -= k;
1693 memcpy(dest+1, pb+1, k * sizeof(PyObject *));
1694 nb -= k;
1695 if (nb == 1)
1696 goto CopyA;
1697 /* nb==0 is impossible now if the comparison
1698 * function is consistent, but we can't assume
1699 * that it is.
1700 */
1701 if (nb == 0)
1702 goto Succeed;
1703 }
1704 *dest-- = *pa--;
1705 --na;
1706 if (na == 0)
1707 goto Succeed;
1708 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1709 ++min_gallop; /* penalize it for leaving galloping mode */
1710 ms->min_gallop = min_gallop;
1711 }
Tim Petersa64dc242002-08-01 02:13:36 +00001712Succeed:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001713 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001714Fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001715 if (nb)
1716 memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
1717 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001718CopyA:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001719 assert(nb == 1 && na > 0);
1720 /* The first element of pb belongs at the front of the merge. */
1721 dest -= na;
1722 pa -= na;
1723 memmove(dest+1, pa+1, na * sizeof(PyObject *));
1724 *dest = *pb;
1725 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001726}
1727
1728/* Merge the two runs at stack indices i and i+1.
1729 * Returns 0 on success, -1 on error.
1730 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001731static Py_ssize_t
1732merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001733{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001734 PyObject **pa, **pb;
1735 Py_ssize_t na, nb;
1736 Py_ssize_t k;
1737 PyObject *compare;
Tim Petersa64dc242002-08-01 02:13:36 +00001738
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001739 assert(ms != NULL);
1740 assert(ms->n >= 2);
1741 assert(i >= 0);
1742 assert(i == ms->n - 2 || i == ms->n - 3);
Tim Petersa64dc242002-08-01 02:13:36 +00001743
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001744 pa = ms->pending[i].base;
1745 na = ms->pending[i].len;
1746 pb = ms->pending[i+1].base;
1747 nb = ms->pending[i+1].len;
1748 assert(na > 0 && nb > 0);
1749 assert(pa + na == pb);
Tim Petersa64dc242002-08-01 02:13:36 +00001750
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001751 /* Record the length of the combined runs; if i is the 3rd-last
1752 * run now, also slide over the last run (which isn't involved
1753 * in this merge). The current run i+1 goes away in any case.
1754 */
1755 ms->pending[i].len = na + nb;
1756 if (i == ms->n - 3)
1757 ms->pending[i+1] = ms->pending[i+2];
1758 --ms->n;
Tim Petersa64dc242002-08-01 02:13:36 +00001759
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001760 /* Where does b start in a? Elements in a before that can be
1761 * ignored (already in place).
1762 */
1763 compare = ms->compare;
1764 k = gallop_right(*pb, pa, na, 0, compare);
1765 if (k < 0)
1766 return -1;
1767 pa += k;
1768 na -= k;
1769 if (na == 0)
1770 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001771
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001772 /* Where does a end in b? Elements in b after that can be
1773 * ignored (already in place).
1774 */
1775 nb = gallop_left(pa[na-1], pb, nb, nb-1, compare);
1776 if (nb <= 0)
1777 return nb;
Tim Petersa64dc242002-08-01 02:13:36 +00001778
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001779 /* Merge what remains of the runs, using a temp array with
1780 * min(na, nb) elements.
1781 */
1782 if (na <= nb)
1783 return merge_lo(ms, pa, na, pb, nb);
1784 else
1785 return merge_hi(ms, pa, na, pb, nb);
Tim Petersa64dc242002-08-01 02:13:36 +00001786}
1787
1788/* Examine the stack of runs waiting to be merged, merging adjacent runs
1789 * until the stack invariants are re-established:
1790 *
1791 * 1. len[-3] > len[-2] + len[-1]
1792 * 2. len[-2] > len[-1]
1793 *
1794 * See listsort.txt for more info.
1795 *
1796 * Returns 0 on success, -1 on error.
1797 */
1798static int
1799merge_collapse(MergeState *ms)
1800{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001801 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001802
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001803 assert(ms);
1804 while (ms->n > 1) {
1805 Py_ssize_t n = ms->n - 2;
Benjamin Peterson082a9602015-02-25 10:12:26 -05001806 if ((n > 0 && p[n-1].len <= p[n].len + p[n+1].len) ||
1807 (n > 1 && p[n-2].len <= p[n-1].len + p[n].len)) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001808 if (p[n-1].len < p[n+1].len)
1809 --n;
1810 if (merge_at(ms, n) < 0)
1811 return -1;
1812 }
1813 else if (p[n].len <= p[n+1].len) {
1814 if (merge_at(ms, n) < 0)
1815 return -1;
1816 }
1817 else
1818 break;
1819 }
1820 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001821}
1822
1823/* Regardless of invariants, merge all runs on the stack until only one
1824 * remains. This is used at the end of the mergesort.
1825 *
1826 * Returns 0 on success, -1 on error.
1827 */
1828static int
1829merge_force_collapse(MergeState *ms)
1830{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001831 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001832
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001833 assert(ms);
1834 while (ms->n > 1) {
1835 Py_ssize_t n = ms->n - 2;
1836 if (n > 0 && p[n-1].len < p[n+1].len)
1837 --n;
1838 if (merge_at(ms, n) < 0)
1839 return -1;
1840 }
1841 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001842}
1843
1844/* Compute a good value for the minimum run length; natural runs shorter
1845 * than this are boosted artificially via binary insertion.
1846 *
1847 * If n < 64, return n (it's too small to bother with fancy stuff).
1848 * Else if n is an exact power of 2, return 32.
1849 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1850 * strictly less than, an exact power of 2.
1851 *
1852 * See listsort.txt for more info.
1853 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001854static Py_ssize_t
1855merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001856{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001857 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001858
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001859 assert(n >= 0);
1860 while (n >= 64) {
1861 r |= n & 1;
1862 n >>= 1;
1863 }
1864 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001865}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001866
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001867/* Special wrapper to support stable sorting using the decorate-sort-undecorate
Andrew M. Kuchling55be9ea2004-09-10 12:59:54 +00001868 pattern. Holds a key which is used for comparisons and the original record
Tim Petersb38e2b62004-07-29 02:29:26 +00001869 which is returned during the undecorate phase. By exposing only the key
1870 during comparisons, the underlying sort stability characteristics are left
1871 unchanged. Also, if a custom comparison function is used, it will only see
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001872 the key instead of a full record. */
1873
1874typedef struct {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001875 PyObject_HEAD
1876 PyObject *key;
1877 PyObject *value;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001878} sortwrapperobject;
1879
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001880PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
Anthony Baxter377be112006-04-11 06:54:30 +00001881static PyObject *
1882sortwrapper_richcompare(sortwrapperobject *, sortwrapperobject *, int);
1883static void
1884sortwrapper_dealloc(sortwrapperobject *);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001885
1886static PyTypeObject sortwrapper_type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001887 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1888 "sortwrapper", /* tp_name */
1889 sizeof(sortwrapperobject), /* tp_basicsize */
1890 0, /* tp_itemsize */
1891 /* methods */
1892 (destructor)sortwrapper_dealloc, /* tp_dealloc */
1893 0, /* tp_print */
1894 0, /* tp_getattr */
1895 0, /* tp_setattr */
1896 0, /* tp_compare */
1897 0, /* tp_repr */
1898 0, /* tp_as_number */
1899 0, /* tp_as_sequence */
1900 0, /* tp_as_mapping */
1901 0, /* tp_hash */
1902 0, /* tp_call */
1903 0, /* tp_str */
1904 PyObject_GenericGetAttr, /* tp_getattro */
1905 0, /* tp_setattro */
1906 0, /* tp_as_buffer */
1907 Py_TPFLAGS_DEFAULT |
1908 Py_TPFLAGS_HAVE_RICHCOMPARE, /* tp_flags */
1909 sortwrapper_doc, /* tp_doc */
1910 0, /* tp_traverse */
1911 0, /* tp_clear */
1912 (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001913};
1914
Anthony Baxter377be112006-04-11 06:54:30 +00001915
1916static PyObject *
1917sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
1918{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001919 if (!PyObject_TypeCheck(b, &sortwrapper_type)) {
1920 PyErr_SetString(PyExc_TypeError,
1921 "expected a sortwrapperobject");
1922 return NULL;
1923 }
1924 return PyObject_RichCompare(a->key, b->key, op);
Anthony Baxter377be112006-04-11 06:54:30 +00001925}
1926
1927static void
1928sortwrapper_dealloc(sortwrapperobject *so)
1929{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001930 Py_XDECREF(so->key);
1931 Py_XDECREF(so->value);
1932 PyObject_Del(so);
Anthony Baxter377be112006-04-11 06:54:30 +00001933}
1934
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001935/* Returns a new reference to a sortwrapper.
1936 Consumes the references to the two underlying objects. */
1937
1938static PyObject *
1939build_sortwrapper(PyObject *key, PyObject *value)
1940{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001941 sortwrapperobject *so;
Tim Petersb38e2b62004-07-29 02:29:26 +00001942
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001943 so = PyObject_New(sortwrapperobject, &sortwrapper_type);
1944 if (so == NULL)
1945 return NULL;
1946 so->key = key;
1947 so->value = value;
1948 return (PyObject *)so;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001949}
1950
1951/* Returns a new reference to the value underlying the wrapper. */
1952static PyObject *
1953sortwrapper_getvalue(PyObject *so)
1954{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001955 PyObject *value;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001956
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001957 if (!PyObject_TypeCheck(so, &sortwrapper_type)) {
1958 PyErr_SetString(PyExc_TypeError,
1959 "expected a sortwrapperobject");
1960 return NULL;
1961 }
1962 value = ((sortwrapperobject *)so)->value;
1963 Py_INCREF(value);
1964 return value;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001965}
1966
1967/* Wrapper for user specified cmp functions in combination with a
1968 specified key function. Makes sure the cmp function is presented
1969 with the actual key instead of the sortwrapper */
1970
1971typedef struct {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001972 PyObject_HEAD
1973 PyObject *func;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001974} cmpwrapperobject;
1975
1976static void
1977cmpwrapper_dealloc(cmpwrapperobject *co)
1978{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001979 Py_XDECREF(co->func);
1980 PyObject_Del(co);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001981}
1982
1983static PyObject *
1984cmpwrapper_call(cmpwrapperobject *co, PyObject *args, PyObject *kwds)
1985{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001986 PyObject *x, *y, *xx, *yy;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001987
Antoine Pitrouc83ea132010-05-09 14:46:46 +00001988 if (!PyArg_UnpackTuple(args, "", 2, 2, &x, &y))
1989 return NULL;
1990 if (!PyObject_TypeCheck(x, &sortwrapper_type) ||
1991 !PyObject_TypeCheck(y, &sortwrapper_type)) {
1992 PyErr_SetString(PyExc_TypeError,
1993 "expected a sortwrapperobject");
1994 return NULL;
1995 }
1996 xx = ((sortwrapperobject *)x)->key;
1997 yy = ((sortwrapperobject *)y)->key;
1998 return PyObject_CallFunctionObjArgs(co->func, xx, yy, NULL);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001999}
2000
2001PyDoc_STRVAR(cmpwrapper_doc, "cmp() wrapper for sort with custom keys.");
2002
2003static PyTypeObject cmpwrapper_type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002004 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2005 "cmpwrapper", /* tp_name */
2006 sizeof(cmpwrapperobject), /* tp_basicsize */
2007 0, /* tp_itemsize */
2008 /* methods */
2009 (destructor)cmpwrapper_dealloc, /* tp_dealloc */
2010 0, /* tp_print */
2011 0, /* tp_getattr */
2012 0, /* tp_setattr */
2013 0, /* tp_compare */
2014 0, /* tp_repr */
2015 0, /* tp_as_number */
2016 0, /* tp_as_sequence */
2017 0, /* tp_as_mapping */
2018 0, /* tp_hash */
2019 (ternaryfunc)cmpwrapper_call, /* tp_call */
2020 0, /* tp_str */
2021 PyObject_GenericGetAttr, /* tp_getattro */
2022 0, /* tp_setattro */
2023 0, /* tp_as_buffer */
2024 Py_TPFLAGS_DEFAULT, /* tp_flags */
2025 cmpwrapper_doc, /* tp_doc */
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002026};
2027
2028static PyObject *
2029build_cmpwrapper(PyObject *cmpfunc)
2030{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002031 cmpwrapperobject *co;
Tim Petersb38e2b62004-07-29 02:29:26 +00002032
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002033 co = PyObject_New(cmpwrapperobject, &cmpwrapper_type);
2034 if (co == NULL)
2035 return NULL;
2036 Py_INCREF(cmpfunc);
2037 co->func = cmpfunc;
2038 return (PyObject *)co;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002039}
2040
Tim Petersa64dc242002-08-01 02:13:36 +00002041/* An adaptive, stable, natural mergesort. See listsort.txt.
2042 * Returns Py_None on success, NULL on error. Even in case of error, the
2043 * list will be some permutation of its input state (nothing is lost or
2044 * duplicated).
2045 */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002046static PyObject *
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002047listsort(PyListObject *self, PyObject *args, PyObject *kwds)
Guido van Rossum3f236de1996-12-10 23:55:39 +00002048{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002049 MergeState ms;
2050 PyObject **lo, **hi;
2051 Py_ssize_t nremaining;
2052 Py_ssize_t minrun;
2053 Py_ssize_t saved_ob_size, saved_allocated;
2054 PyObject **saved_ob_item;
2055 PyObject **final_ob_item;
2056 PyObject *compare = NULL;
2057 PyObject *result = NULL; /* guilty until proved innocent */
2058 int reverse = 0;
2059 PyObject *keyfunc = NULL;
2060 Py_ssize_t i;
2061 PyObject *key, *value, *kvpair;
2062 static char *kwlist[] = {"cmp", "key", "reverse", 0};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002063
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002064 assert(self != NULL);
2065 assert (PyList_Check(self));
2066 if (args != NULL) {
2067 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:sort",
2068 kwlist, &compare, &keyfunc, &reverse))
2069 return NULL;
2070 }
2071 if (compare == Py_None)
2072 compare = NULL;
2073 if (compare != NULL &&
2074 PyErr_WarnPy3k("the cmp argument is not supported in 3.x", 1) < 0)
2075 return NULL;
2076 if (keyfunc == Py_None)
2077 keyfunc = NULL;
2078 if (compare != NULL && keyfunc != NULL) {
2079 compare = build_cmpwrapper(compare);
2080 if (compare == NULL)
2081 return NULL;
2082 } else
2083 Py_XINCREF(compare);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002084
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002085 /* The list is temporarily made empty, so that mutations performed
2086 * by comparison functions can't affect the slice of memory we're
2087 * sorting (allowing mutations during sorting is a core-dump
2088 * factory, since ob_item may change).
2089 */
2090 saved_ob_size = Py_SIZE(self);
2091 saved_ob_item = self->ob_item;
2092 saved_allocated = self->allocated;
2093 Py_SIZE(self) = 0;
2094 self->ob_item = NULL;
2095 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00002096
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002097 if (keyfunc != NULL) {
2098 for (i=0 ; i < saved_ob_size ; i++) {
2099 value = saved_ob_item[i];
2100 key = PyObject_CallFunctionObjArgs(keyfunc, value,
2101 NULL);
2102 if (key == NULL) {
2103 for (i=i-1 ; i>=0 ; i--) {
2104 kvpair = saved_ob_item[i];
2105 value = sortwrapper_getvalue(kvpair);
2106 saved_ob_item[i] = value;
2107 Py_DECREF(kvpair);
2108 }
2109 goto dsu_fail;
2110 }
2111 kvpair = build_sortwrapper(key, value);
2112 if (kvpair == NULL)
2113 goto dsu_fail;
2114 saved_ob_item[i] = kvpair;
2115 }
2116 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002117
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002118 /* Reverse sort stability achieved by initially reversing the list,
2119 applying a stable forward sort, then reversing the final result. */
2120 if (reverse && saved_ob_size > 1)
2121 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002122
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002123 merge_init(&ms, compare);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002124
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002125 nremaining = saved_ob_size;
2126 if (nremaining < 2)
2127 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00002128
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002129 /* March over the array once, left to right, finding natural runs,
2130 * and extending short natural runs to minrun elements.
2131 */
2132 lo = saved_ob_item;
2133 hi = lo + nremaining;
2134 minrun = merge_compute_minrun(nremaining);
2135 do {
2136 int descending;
2137 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00002138
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002139 /* Identify next run. */
2140 n = count_run(lo, hi, compare, &descending);
2141 if (n < 0)
2142 goto fail;
2143 if (descending)
2144 reverse_slice(lo, lo + n);
2145 /* If short, extend to min(minrun, nremaining). */
2146 if (n < minrun) {
2147 const Py_ssize_t force = nremaining <= minrun ?
2148 nremaining : minrun;
2149 if (binarysort(lo, lo + force, lo + n, compare) < 0)
2150 goto fail;
2151 n = force;
2152 }
2153 /* Push run onto pending-runs stack, and maybe merge. */
2154 assert(ms.n < MAX_MERGE_PENDING);
2155 ms.pending[ms.n].base = lo;
2156 ms.pending[ms.n].len = n;
2157 ++ms.n;
2158 if (merge_collapse(&ms) < 0)
2159 goto fail;
2160 /* Advance to find next run. */
2161 lo += n;
2162 nremaining -= n;
2163 } while (nremaining);
2164 assert(lo == hi);
Tim Peters330f9e92002-07-19 07:05:44 +00002165
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002166 if (merge_force_collapse(&ms) < 0)
2167 goto fail;
2168 assert(ms.n == 1);
2169 assert(ms.pending[0].base == saved_ob_item);
2170 assert(ms.pending[0].len == saved_ob_size);
Tim Petersa64dc242002-08-01 02:13:36 +00002171
2172succeed:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002173 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002174fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002175 if (keyfunc != NULL) {
2176 for (i=0 ; i < saved_ob_size ; i++) {
2177 kvpair = saved_ob_item[i];
2178 value = sortwrapper_getvalue(kvpair);
2179 saved_ob_item[i] = value;
2180 Py_DECREF(kvpair);
2181 }
2182 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002183
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002184 if (self->allocated != -1 && result != NULL) {
2185 /* The user mucked with the list during the sort,
2186 * and we don't already have another error to report.
2187 */
2188 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2189 result = NULL;
2190 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002191
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002192 if (reverse && saved_ob_size > 1)
2193 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002194
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002195 merge_freemem(&ms);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002196
2197dsu_fail:
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002198 final_ob_item = self->ob_item;
2199 i = Py_SIZE(self);
2200 Py_SIZE(self) = saved_ob_size;
2201 self->ob_item = saved_ob_item;
2202 self->allocated = saved_allocated;
2203 if (final_ob_item != NULL) {
2204 /* we cannot use list_clear() for this because it does not
2205 guarantee that the list is really empty when it returns */
2206 while (--i >= 0) {
2207 Py_XDECREF(final_ob_item[i]);
2208 }
2209 PyMem_FREE(final_ob_item);
2210 }
2211 Py_XDECREF(compare);
2212 Py_XINCREF(result);
2213 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002214}
Tim Peters330f9e92002-07-19 07:05:44 +00002215#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002216#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002217
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002218int
Fred Drakea2f55112000-07-09 15:16:51 +00002219PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002220{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002221 if (v == NULL || !PyList_Check(v)) {
2222 PyErr_BadInternalCall();
2223 return -1;
2224 }
2225 v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
2226 if (v == NULL)
2227 return -1;
2228 Py_DECREF(v);
2229 return 0;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002230}
2231
Guido van Rossumb86c5492001-02-12 22:06:02 +00002232static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002233listreverse(PyListObject *self)
Guido van Rossumb86c5492001-02-12 22:06:02 +00002234{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002235 if (Py_SIZE(self) > 1)
2236 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2237 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002238}
2239
Guido van Rossum84c76f51990-10-30 13:32:20 +00002240int
Fred Drakea2f55112000-07-09 15:16:51 +00002241PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002242{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002243 PyListObject *self = (PyListObject *)v;
Tim Peters6063e262002-08-08 01:06:39 +00002244
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002245 if (v == NULL || !PyList_Check(v)) {
2246 PyErr_BadInternalCall();
2247 return -1;
2248 }
2249 if (Py_SIZE(self) > 1)
2250 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2251 return 0;
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002252}
2253
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002254PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002255PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002256{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002257 PyObject *w;
2258 PyObject **p, **q;
2259 Py_ssize_t n;
2260 if (v == NULL || !PyList_Check(v)) {
2261 PyErr_BadInternalCall();
2262 return NULL;
2263 }
2264 n = Py_SIZE(v);
2265 w = PyTuple_New(n);
2266 if (w == NULL)
2267 return NULL;
2268 p = ((PyTupleObject *)w)->ob_item;
2269 q = ((PyListObject *)v)->ob_item;
2270 while (--n >= 0) {
2271 Py_INCREF(*q);
2272 *p = *q;
2273 p++;
2274 q++;
2275 }
2276 return w;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002277}
2278
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002279static PyObject *
Raymond Hettingerd05abde2003-06-17 05:05:49 +00002280listindex(PyListObject *self, PyObject *args)
Guido van Rossumed98d481991-03-06 13:07:53 +00002281{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002282 Py_ssize_t i, start=0, stop=Py_SIZE(self);
2283 PyObject *v, *format_tuple, *err_string;
2284 static PyObject *err_format = NULL;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002285
Petri Lehtinen3b9d92a2011-11-06 20:58:50 +02002286 if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
Serhiy Storchaka079f21f2017-03-30 20:32:18 +03002287 _PyEval_SliceIndexNotNone, &start,
2288 _PyEval_SliceIndexNotNone, &stop))
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002289 return NULL;
2290 if (start < 0) {
2291 start += Py_SIZE(self);
2292 if (start < 0)
2293 start = 0;
2294 }
2295 if (stop < 0) {
2296 stop += Py_SIZE(self);
2297 if (stop < 0)
2298 stop = 0;
2299 }
2300 for (i = start; i < stop && i < Py_SIZE(self); i++) {
2301 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2302 if (cmp > 0)
2303 return PyInt_FromSsize_t(i);
2304 else if (cmp < 0)
2305 return NULL;
2306 }
2307 if (err_format == NULL) {
2308 err_format = PyString_FromString("%r is not in list");
2309 if (err_format == NULL)
2310 return NULL;
2311 }
2312 format_tuple = PyTuple_Pack(1, v);
2313 if (format_tuple == NULL)
2314 return NULL;
2315 err_string = PyString_Format(err_format, format_tuple);
2316 Py_DECREF(format_tuple);
2317 if (err_string == NULL)
2318 return NULL;
2319 PyErr_SetObject(PyExc_ValueError, err_string);
2320 Py_DECREF(err_string);
2321 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002322}
2323
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002324static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002325listcount(PyListObject *self, PyObject *v)
Guido van Rossume6f7d181991-10-20 20:20:40 +00002326{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002327 Py_ssize_t count = 0;
2328 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002329
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002330 for (i = 0; i < Py_SIZE(self); i++) {
2331 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2332 if (cmp > 0)
2333 count++;
2334 else if (cmp < 0)
2335 return NULL;
2336 }
2337 return PyInt_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002338}
2339
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002340static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00002341listremove(PyListObject *self, PyObject *v)
Guido van Rossumed98d481991-03-06 13:07:53 +00002342{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002343 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002344
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002345 for (i = 0; i < Py_SIZE(self); i++) {
2346 int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
2347 if (cmp > 0) {
2348 if (list_ass_slice(self, i, i+1,
2349 (PyObject *)NULL) == 0)
2350 Py_RETURN_NONE;
2351 return NULL;
2352 }
2353 else if (cmp < 0)
2354 return NULL;
2355 }
2356 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
2357 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002358}
2359
Jeremy Hylton8caad492000-06-23 14:18:11 +00002360static int
2361list_traverse(PyListObject *o, visitproc visit, void *arg)
2362{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002363 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002364
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002365 for (i = Py_SIZE(o); --i >= 0; )
2366 Py_VISIT(o->ob_item[i]);
2367 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002368}
2369
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002370static PyObject *
2371list_richcompare(PyObject *v, PyObject *w, int op)
2372{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002373 PyListObject *vl, *wl;
2374 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002375
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002376 if (!PyList_Check(v) || !PyList_Check(w)) {
2377 Py_INCREF(Py_NotImplemented);
2378 return Py_NotImplemented;
2379 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002380
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002381 vl = (PyListObject *)v;
2382 wl = (PyListObject *)w;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002383
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002384 if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
2385 /* Shortcut: if the lengths differ, the lists differ */
2386 PyObject *res;
2387 if (op == Py_EQ)
2388 res = Py_False;
2389 else
2390 res = Py_True;
2391 Py_INCREF(res);
2392 return res;
2393 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002394
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002395 /* Search for the first index where items are different */
2396 for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
2397 int k = PyObject_RichCompareBool(vl->ob_item[i],
2398 wl->ob_item[i], Py_EQ);
2399 if (k < 0)
2400 return NULL;
2401 if (!k)
2402 break;
2403 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002404
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002405 if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
2406 /* No more items to compare -- compare sizes */
2407 Py_ssize_t vs = Py_SIZE(vl);
2408 Py_ssize_t ws = Py_SIZE(wl);
2409 int cmp;
2410 PyObject *res;
2411 switch (op) {
2412 case Py_LT: cmp = vs < ws; break;
2413 case Py_LE: cmp = vs <= ws; break;
2414 case Py_EQ: cmp = vs == ws; break;
2415 case Py_NE: cmp = vs != ws; break;
2416 case Py_GT: cmp = vs > ws; break;
2417 case Py_GE: cmp = vs >= ws; break;
2418 default: return NULL; /* cannot happen */
2419 }
2420 if (cmp)
2421 res = Py_True;
2422 else
2423 res = Py_False;
2424 Py_INCREF(res);
2425 return res;
2426 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002427
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002428 /* We have an item that differs -- shortcuts for EQ/NE */
2429 if (op == Py_EQ) {
2430 Py_INCREF(Py_False);
2431 return Py_False;
2432 }
2433 if (op == Py_NE) {
2434 Py_INCREF(Py_True);
2435 return Py_True;
2436 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002437
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002438 /* Compare the final item again using the proper operator */
2439 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002440}
2441
Tim Peters6d6c1a32001-08-02 04:15:00 +00002442static int
2443list_init(PyListObject *self, PyObject *args, PyObject *kw)
2444{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002445 PyObject *arg = NULL;
2446 static char *kwlist[] = {"sequence", 0};
Tim Peters6d6c1a32001-08-02 04:15:00 +00002447
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002448 if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
2449 return -1;
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002450
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002451 /* Verify list invariants established by PyType_GenericAlloc() */
2452 assert(0 <= Py_SIZE(self));
2453 assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
2454 assert(self->ob_item != NULL ||
2455 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002456
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002457 /* Empty previous contents */
2458 if (self->ob_item != NULL) {
2459 (void)list_clear(self);
2460 }
2461 if (arg != NULL) {
2462 PyObject *rv = listextend(self, arg);
2463 if (rv == NULL)
2464 return -1;
2465 Py_DECREF(rv);
2466 }
2467 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002468}
2469
Robert Schuppenies51df0642008-06-01 16:16:17 +00002470static PyObject *
2471list_sizeof(PyListObject *self)
2472{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002473 Py_ssize_t res;
Robert Schuppenies51df0642008-06-01 16:16:17 +00002474
Serhiy Storchakac06a6d02015-12-19 20:07:48 +02002475 res = _PyObject_SIZE(Py_TYPE(self)) + self->allocated * sizeof(void*);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002476 return PyInt_FromSsize_t(res);
Robert Schuppenies51df0642008-06-01 16:16:17 +00002477}
2478
Raymond Hettinger1021c442003-11-07 15:38:09 +00002479static PyObject *list_iter(PyObject *seq);
2480static PyObject *list_reversed(PyListObject* seq, PyObject* unused);
2481
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002482PyDoc_STRVAR(getitem_doc,
2483"x.__getitem__(y) <==> x[y]");
Raymond Hettinger1021c442003-11-07 15:38:09 +00002484PyDoc_STRVAR(reversed_doc,
2485"L.__reversed__() -- return a reverse iterator over the list");
Robert Schuppenies51df0642008-06-01 16:16:17 +00002486PyDoc_STRVAR(sizeof_doc,
Georg Brandl7a6de8b2008-06-01 16:42:16 +00002487"L.__sizeof__() -- size of L in memory, in bytes");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002488PyDoc_STRVAR(append_doc,
2489"L.append(object) -- append object to end");
2490PyDoc_STRVAR(extend_doc,
Raymond Hettingerf8bcfb12002-12-29 05:49:09 +00002491"L.extend(iterable) -- extend list by appending elements from the iterable");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002492PyDoc_STRVAR(insert_doc,
2493"L.insert(index, object) -- insert object before index");
2494PyDoc_STRVAR(pop_doc,
Andrew M. Kuchlingd810cdf2008-10-04 01:04:24 +00002495"L.pop([index]) -> item -- remove and return item at index (default last).\n"
2496"Raises IndexError if list is empty or index is out of range.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002497PyDoc_STRVAR(remove_doc,
Andrew M. Kuchlingd810cdf2008-10-04 01:04:24 +00002498"L.remove(value) -- remove first occurrence of value.\n"
2499"Raises ValueError if the value is not present.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002500PyDoc_STRVAR(index_doc,
Andrew M. Kuchlingd810cdf2008-10-04 01:04:24 +00002501"L.index(value, [start, [stop]]) -> integer -- return first index of value.\n"
2502"Raises ValueError if the value is not present.");
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002503PyDoc_STRVAR(count_doc,
2504"L.count(value) -> integer -- return number of occurrences of value");
2505PyDoc_STRVAR(reverse_doc,
2506"L.reverse() -- reverse *IN PLACE*");
2507PyDoc_STRVAR(sort_doc,
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00002508"L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\n\
2509cmp(x, y) -> -1, 0, 1");
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00002510
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002511static PyObject *list_subscript(PyListObject*, PyObject*);
2512
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002513static PyMethodDef list_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002514 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
2515 {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
2516 {"__sizeof__", (PyCFunction)list_sizeof, METH_NOARGS, sizeof_doc},
2517 {"append", (PyCFunction)listappend, METH_O, append_doc},
2518 {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
2519 {"extend", (PyCFunction)listextend, METH_O, extend_doc},
2520 {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
2521 {"remove", (PyCFunction)listremove, METH_O, remove_doc},
2522 {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
2523 {"count", (PyCFunction)listcount, METH_O, count_doc},
2524 {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
2525 {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
2526 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002527};
2528
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002529static PySequenceMethods list_as_sequence = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002530 (lenfunc)list_length, /* sq_length */
2531 (binaryfunc)list_concat, /* sq_concat */
2532 (ssizeargfunc)list_repeat, /* sq_repeat */
2533 (ssizeargfunc)list_item, /* sq_item */
2534 (ssizessizeargfunc)list_slice, /* sq_slice */
2535 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
2536 (ssizessizeobjargproc)list_ass_slice, /* sq_ass_slice */
2537 (objobjproc)list_contains, /* sq_contains */
2538 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2539 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002540};
2541
Neal Norwitz2c2e8272002-06-14 02:04:18 +00002542PyDoc_STRVAR(list_doc,
Ezio Melottifb501122010-02-28 23:59:00 +00002543"list() -> new empty list\n"
Georg Brandlbca11692010-02-28 18:19:17 +00002544"list(iterable) -> new list initialized from iterable's items");
Tim Peters6d6c1a32001-08-02 04:15:00 +00002545
Guido van Rossum38fff8c2006-03-07 18:50:55 +00002546
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002547static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002548list_subscript(PyListObject* self, PyObject* item)
2549{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002550 if (PyIndex_Check(item)) {
2551 Py_ssize_t i;
2552 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2553 if (i == -1 && PyErr_Occurred())
2554 return NULL;
2555 if (i < 0)
2556 i += PyList_GET_SIZE(self);
2557 return list_item(self, i);
2558 }
2559 else if (PySlice_Check(item)) {
2560 Py_ssize_t start, stop, step, slicelength, cur, i;
2561 PyObject* result;
2562 PyObject* it;
2563 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002564
Serhiy Storchaka5e793212017-04-15 20:11:12 +03002565 if (_PySlice_Unpack(item, &start, &stop, &step) < 0) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002566 return NULL;
2567 }
Serhiy Storchakae41390a2017-04-08 11:48:57 +03002568 slicelength = _PySlice_AdjustIndices(Py_SIZE(self), &start, &stop,
2569 step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002570
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002571 if (slicelength <= 0) {
2572 return PyList_New(0);
2573 }
2574 else if (step == 1) {
2575 return list_slice(self, start, stop);
2576 }
2577 else {
2578 result = PyList_New(slicelength);
2579 if (!result) return NULL;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002580
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002581 src = self->ob_item;
2582 dest = ((PyListObject *)result)->ob_item;
2583 for (cur = start, i = 0; i < slicelength;
2584 cur += step, i++) {
2585 it = src[cur];
2586 Py_INCREF(it);
2587 dest[i] = it;
2588 }
Tim Peters3b01a122002-07-19 02:35:45 +00002589
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002590 return result;
2591 }
2592 }
2593 else {
2594 PyErr_Format(PyExc_TypeError,
2595 "list indices must be integers, not %.200s",
2596 item->ob_type->tp_name);
2597 return NULL;
2598 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002599}
2600
Tim Peters3b01a122002-07-19 02:35:45 +00002601static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002602list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2603{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002604 if (PyIndex_Check(item)) {
2605 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2606 if (i == -1 && PyErr_Occurred())
2607 return -1;
2608 if (i < 0)
2609 i += PyList_GET_SIZE(self);
2610 return list_ass_item(self, i, value);
2611 }
2612 else if (PySlice_Check(item)) {
2613 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002614
Serhiy Storchaka5e793212017-04-15 20:11:12 +03002615 if (_PySlice_Unpack(item, &start, &stop, &step) < 0) {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002616 return -1;
2617 }
Serhiy Storchakae41390a2017-04-08 11:48:57 +03002618 slicelength = _PySlice_AdjustIndices(Py_SIZE(self), &start, &stop,
2619 step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002620
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002621 if (step == 1)
2622 return list_ass_slice(self, start, stop, value);
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002623
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002624 /* Make sure s[5:2] = [..] inserts at the right place:
2625 before 5, not before 2. */
2626 if ((step < 0 && start < stop) ||
2627 (step > 0 && start > stop))
2628 stop = start;
Thomas Wouters3ccec682007-08-28 15:28:19 +00002629
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002630 if (value == NULL) {
2631 /* delete slice */
2632 PyObject **garbage;
2633 size_t cur;
2634 Py_ssize_t i;
Tim Peters3b01a122002-07-19 02:35:45 +00002635
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002636 if (slicelength <= 0)
2637 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002638
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002639 if (step < 0) {
2640 stop = start + 1;
2641 start = stop + step*(slicelength - 1) - 1;
2642 step = -step;
2643 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002644
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002645 assert((size_t)slicelength <=
2646 PY_SIZE_MAX / sizeof(PyObject*));
Gregory P. Smith9d534572008-06-11 07:41:16 +00002647
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002648 garbage = (PyObject**)
2649 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2650 if (!garbage) {
2651 PyErr_NoMemory();
2652 return -1;
2653 }
Tim Peters3b01a122002-07-19 02:35:45 +00002654
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002655 /* drawing pictures might help understand these for
2656 loops. Basically, we memmove the parts of the
2657 list that are *not* part of the slice: step-1
2658 items for each item that is part of the slice,
2659 and then tail end of the list that was not
2660 covered by the slice */
2661 for (cur = start, i = 0;
2662 cur < (size_t)stop;
2663 cur += step, i++) {
2664 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002665
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002666 garbage[i] = PyList_GET_ITEM(self, cur);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002667
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002668 if (cur + step >= (size_t)Py_SIZE(self)) {
2669 lim = Py_SIZE(self) - cur - 1;
2670 }
Michael W. Hudson56796f62002-07-29 14:35:04 +00002671
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002672 memmove(self->ob_item + cur - i,
2673 self->ob_item + cur + 1,
2674 lim * sizeof(PyObject *));
2675 }
2676 cur = start + slicelength*step;
2677 if (cur < (size_t)Py_SIZE(self)) {
2678 memmove(self->ob_item + cur - slicelength,
2679 self->ob_item + cur,
2680 (Py_SIZE(self) - cur) *
2681 sizeof(PyObject *));
2682 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002683
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002684 Py_SIZE(self) -= slicelength;
2685 list_resize(self, Py_SIZE(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002686
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002687 for (i = 0; i < slicelength; i++) {
2688 Py_DECREF(garbage[i]);
2689 }
2690 PyMem_FREE(garbage);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002691
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002692 return 0;
2693 }
2694 else {
2695 /* assign slice */
2696 PyObject *ins, *seq;
2697 PyObject **garbage, **seqitems, **selfitems;
2698 Py_ssize_t cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002699
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002700 /* protect against a[::-1] = a */
2701 if (self == (PyListObject*)value) {
2702 seq = list_slice((PyListObject*)value, 0,
2703 PyList_GET_SIZE(value));
2704 }
2705 else {
2706 seq = PySequence_Fast(value,
2707 "must assign iterable "
2708 "to extended slice");
2709 }
2710 if (!seq)
2711 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002712
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002713 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2714 PyErr_Format(PyExc_ValueError,
2715 "attempt to assign sequence of "
2716 "size %zd to extended slice of "
2717 "size %zd",
2718 PySequence_Fast_GET_SIZE(seq),
2719 slicelength);
2720 Py_DECREF(seq);
2721 return -1;
2722 }
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002723
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002724 if (!slicelength) {
2725 Py_DECREF(seq);
2726 return 0;
2727 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002728
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002729 garbage = (PyObject**)
2730 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2731 if (!garbage) {
2732 Py_DECREF(seq);
2733 PyErr_NoMemory();
2734 return -1;
2735 }
Tim Peters3b01a122002-07-19 02:35:45 +00002736
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002737 selfitems = self->ob_item;
2738 seqitems = PySequence_Fast_ITEMS(seq);
2739 for (cur = start, i = 0; i < slicelength;
2740 cur += step, i++) {
2741 garbage[i] = selfitems[cur];
2742 ins = seqitems[i];
2743 Py_INCREF(ins);
2744 selfitems[cur] = ins;
2745 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002746
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002747 for (i = 0; i < slicelength; i++) {
2748 Py_DECREF(garbage[i]);
2749 }
Tim Peters3b01a122002-07-19 02:35:45 +00002750
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002751 PyMem_FREE(garbage);
2752 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002753
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002754 return 0;
2755 }
2756 }
2757 else {
2758 PyErr_Format(PyExc_TypeError,
2759 "list indices must be integers, not %.200s",
2760 item->ob_type->tp_name);
2761 return -1;
2762 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002763}
2764
2765static PyMappingMethods list_as_mapping = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002766 (lenfunc)list_length,
2767 (binaryfunc)list_subscript,
2768 (objobjargproc)list_ass_subscript
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002769};
2770
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002771PyTypeObject PyList_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002772 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2773 "list",
2774 sizeof(PyListObject),
2775 0,
2776 (destructor)list_dealloc, /* tp_dealloc */
2777 (printfunc)list_print, /* tp_print */
2778 0, /* tp_getattr */
2779 0, /* tp_setattr */
2780 0, /* tp_compare */
2781 (reprfunc)list_repr, /* tp_repr */
2782 0, /* tp_as_number */
2783 &list_as_sequence, /* tp_as_sequence */
2784 &list_as_mapping, /* tp_as_mapping */
2785 (hashfunc)PyObject_HashNotImplemented, /* tp_hash */
2786 0, /* tp_call */
2787 0, /* tp_str */
2788 PyObject_GenericGetAttr, /* tp_getattro */
2789 0, /* tp_setattro */
2790 0, /* tp_as_buffer */
2791 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
2792 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
2793 list_doc, /* tp_doc */
2794 (traverseproc)list_traverse, /* tp_traverse */
2795 (inquiry)list_clear, /* tp_clear */
2796 list_richcompare, /* tp_richcompare */
2797 0, /* tp_weaklistoffset */
2798 list_iter, /* tp_iter */
2799 0, /* tp_iternext */
2800 list_methods, /* tp_methods */
2801 0, /* tp_members */
2802 0, /* tp_getset */
2803 0, /* tp_base */
2804 0, /* tp_dict */
2805 0, /* tp_descr_get */
2806 0, /* tp_descr_set */
2807 0, /* tp_dictoffset */
2808 (initproc)list_init, /* tp_init */
2809 PyType_GenericAlloc, /* tp_alloc */
2810 PyType_GenericNew, /* tp_new */
2811 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002812};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002813
2814
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002815/*********************** List Iterator **************************/
2816
2817typedef struct {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002818 PyObject_HEAD
2819 long it_index;
2820 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002821} listiterobject;
2822
Anthony Baxter377be112006-04-11 06:54:30 +00002823static PyObject *list_iter(PyObject *);
2824static void listiter_dealloc(listiterobject *);
2825static int listiter_traverse(listiterobject *, visitproc, void *);
2826static PyObject *listiter_next(listiterobject *);
2827static PyObject *listiter_len(listiterobject *);
2828
2829PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
2830
2831static PyMethodDef listiter_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002832 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
2833 {NULL, NULL} /* sentinel */
Anthony Baxter377be112006-04-11 06:54:30 +00002834};
2835
2836PyTypeObject PyListIter_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002837 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2838 "listiterator", /* tp_name */
2839 sizeof(listiterobject), /* tp_basicsize */
2840 0, /* tp_itemsize */
2841 /* methods */
2842 (destructor)listiter_dealloc, /* tp_dealloc */
2843 0, /* tp_print */
2844 0, /* tp_getattr */
2845 0, /* tp_setattr */
2846 0, /* tp_compare */
2847 0, /* tp_repr */
2848 0, /* tp_as_number */
2849 0, /* tp_as_sequence */
2850 0, /* tp_as_mapping */
2851 0, /* tp_hash */
2852 0, /* tp_call */
2853 0, /* tp_str */
2854 PyObject_GenericGetAttr, /* tp_getattro */
2855 0, /* tp_setattro */
2856 0, /* tp_as_buffer */
2857 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2858 0, /* tp_doc */
2859 (traverseproc)listiter_traverse, /* tp_traverse */
2860 0, /* tp_clear */
2861 0, /* tp_richcompare */
2862 0, /* tp_weaklistoffset */
2863 PyObject_SelfIter, /* tp_iter */
2864 (iternextfunc)listiter_next, /* tp_iternext */
2865 listiter_methods, /* tp_methods */
2866 0, /* tp_members */
Anthony Baxter377be112006-04-11 06:54:30 +00002867};
2868
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002869
Guido van Rossum5086e492002-07-16 15:56:52 +00002870static PyObject *
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002871list_iter(PyObject *seq)
2872{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002873 listiterobject *it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002874
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002875 if (!PyList_Check(seq)) {
2876 PyErr_BadInternalCall();
2877 return NULL;
2878 }
2879 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2880 if (it == NULL)
2881 return NULL;
2882 it->it_index = 0;
2883 Py_INCREF(seq);
2884 it->it_seq = (PyListObject *)seq;
2885 _PyObject_GC_TRACK(it);
2886 return (PyObject *)it;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002887}
2888
2889static void
2890listiter_dealloc(listiterobject *it)
2891{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002892 _PyObject_GC_UNTRACK(it);
2893 Py_XDECREF(it->it_seq);
2894 PyObject_GC_Del(it);
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002895}
2896
2897static int
2898listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2899{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002900 Py_VISIT(it->it_seq);
2901 return 0;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002902}
2903
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002904static PyObject *
Tim Peters93b2cc42002-06-01 05:22:55 +00002905listiter_next(listiterobject *it)
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002906{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002907 PyListObject *seq;
2908 PyObject *item;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002909
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002910 assert(it != NULL);
2911 seq = it->it_seq;
2912 if (seq == NULL)
2913 return NULL;
2914 assert(PyList_Check(seq));
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002915
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002916 if (it->it_index < PyList_GET_SIZE(seq)) {
2917 item = PyList_GET_ITEM(seq, it->it_index);
2918 ++it->it_index;
2919 Py_INCREF(item);
2920 return item;
2921 }
Guido van Rossum86103ae2002-07-16 20:07:32 +00002922
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002923 it->it_seq = NULL;
Serhiy Storchaka14a7d632016-03-30 20:43:06 +03002924 Py_DECREF(seq);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002925 return NULL;
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002926}
2927
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002928static PyObject *
Raymond Hettinger435bf582004-03-18 22:43:10 +00002929listiter_len(listiterobject *it)
2930{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002931 Py_ssize_t len;
2932 if (it->it_seq) {
2933 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2934 if (len >= 0)
2935 return PyInt_FromSsize_t(len);
2936 }
2937 return PyInt_FromLong(0);
Raymond Hettinger435bf582004-03-18 22:43:10 +00002938}
Anthony Baxter377be112006-04-11 06:54:30 +00002939/*********************** List Reverse Iterator **************************/
Raymond Hettinger435bf582004-03-18 22:43:10 +00002940
Anthony Baxter377be112006-04-11 06:54:30 +00002941typedef struct {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002942 PyObject_HEAD
2943 Py_ssize_t it_index;
2944 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Anthony Baxter377be112006-04-11 06:54:30 +00002945} listreviterobject;
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002946
Anthony Baxter377be112006-04-11 06:54:30 +00002947static PyObject *list_reversed(PyListObject *, PyObject *);
2948static void listreviter_dealloc(listreviterobject *);
2949static int listreviter_traverse(listreviterobject *, visitproc, void *);
2950static PyObject *listreviter_next(listreviterobject *);
Raymond Hettinger7989a4d2008-12-03 15:42:10 +00002951static PyObject *listreviter_len(listreviterobject *);
Anthony Baxter377be112006-04-11 06:54:30 +00002952
Raymond Hettinger7989a4d2008-12-03 15:42:10 +00002953static PyMethodDef listreviter_methods[] = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002954 {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc},
2955 {NULL, NULL} /* sentinel */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002956};
2957
Anthony Baxter377be112006-04-11 06:54:30 +00002958PyTypeObject PyListRevIter_Type = {
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002959 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2960 "listreverseiterator", /* tp_name */
2961 sizeof(listreviterobject), /* tp_basicsize */
2962 0, /* tp_itemsize */
2963 /* methods */
2964 (destructor)listreviter_dealloc, /* tp_dealloc */
2965 0, /* tp_print */
2966 0, /* tp_getattr */
2967 0, /* tp_setattr */
2968 0, /* tp_compare */
2969 0, /* tp_repr */
2970 0, /* tp_as_number */
2971 0, /* tp_as_sequence */
2972 0, /* tp_as_mapping */
2973 0, /* tp_hash */
2974 0, /* tp_call */
2975 0, /* tp_str */
2976 PyObject_GenericGetAttr, /* tp_getattro */
2977 0, /* tp_setattro */
2978 0, /* tp_as_buffer */
2979 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2980 0, /* tp_doc */
2981 (traverseproc)listreviter_traverse, /* tp_traverse */
2982 0, /* tp_clear */
2983 0, /* tp_richcompare */
2984 0, /* tp_weaklistoffset */
2985 PyObject_SelfIter, /* tp_iter */
2986 (iternextfunc)listreviter_next, /* tp_iternext */
2987 listreviter_methods, /* tp_methods */
2988 0,
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002989};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002990
Raymond Hettinger1021c442003-11-07 15:38:09 +00002991static PyObject *
2992list_reversed(PyListObject *seq, PyObject *unused)
2993{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002994 listreviterobject *it;
Raymond Hettinger1021c442003-11-07 15:38:09 +00002995
Antoine Pitrouc83ea132010-05-09 14:46:46 +00002996 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2997 if (it == NULL)
2998 return NULL;
2999 assert(PyList_Check(seq));
3000 it->it_index = PyList_GET_SIZE(seq) - 1;
3001 Py_INCREF(seq);
3002 it->it_seq = seq;
3003 PyObject_GC_Track(it);
3004 return (PyObject *)it;
Raymond Hettinger1021c442003-11-07 15:38:09 +00003005}
3006
3007static void
3008listreviter_dealloc(listreviterobject *it)
3009{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003010 PyObject_GC_UnTrack(it);
3011 Py_XDECREF(it->it_seq);
3012 PyObject_GC_Del(it);
Raymond Hettinger1021c442003-11-07 15:38:09 +00003013}
3014
3015static int
3016listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
3017{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003018 Py_VISIT(it->it_seq);
3019 return 0;
Raymond Hettinger1021c442003-11-07 15:38:09 +00003020}
3021
3022static PyObject *
3023listreviter_next(listreviterobject *it)
3024{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003025 PyObject *item;
Serhiy Storchaka14a7d632016-03-30 20:43:06 +03003026 Py_ssize_t index;
3027 PyListObject *seq;
Raymond Hettinger1021c442003-11-07 15:38:09 +00003028
Serhiy Storchaka14a7d632016-03-30 20:43:06 +03003029 assert(it != NULL);
3030 seq = it->it_seq;
3031 if (seq == NULL) {
3032 return NULL;
3033 }
3034 assert(PyList_Check(seq));
3035
3036 index = it->it_index;
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003037 if (index>=0 && index < PyList_GET_SIZE(seq)) {
3038 item = PyList_GET_ITEM(seq, index);
3039 it->it_index--;
3040 Py_INCREF(item);
3041 return item;
3042 }
3043 it->it_index = -1;
Serhiy Storchaka14a7d632016-03-30 20:43:06 +03003044 it->it_seq = NULL;
3045 Py_DECREF(seq);
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003046 return NULL;
Raymond Hettinger1021c442003-11-07 15:38:09 +00003047}
3048
Raymond Hettinger7989a4d2008-12-03 15:42:10 +00003049static PyObject *
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003050listreviter_len(listreviterobject *it)
3051{
Antoine Pitrouc83ea132010-05-09 14:46:46 +00003052 Py_ssize_t len = it->it_index + 1;
3053 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
3054 len = 0;
3055 return PyLong_FromSsize_t(len);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00003056}