blob: 8576b7ae6837a9057a4f514892a59536c21dfe77 [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"
Eric Snow2ebc5ce2017-09-07 23:51:28 -06004#include "internal/pystate.h"
Antoine Pitrou0197ff92012-03-22 14:38:16 +01005#include "accu.h"
Guido van Rossumc0b618a1997-05-02 03:12:38 +00006
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00007#ifdef STDC_HEADERS
8#include <stddef.h>
9#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000010#include <sys/types.h> /* For size_t */
Guido van Rossum6cd2fe01994-08-29 12:45:32 +000011#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000012
Serhiy Storchakafdd42c42017-03-11 09:19:20 +020013/*[clinic input]
14class list "PyListObject *" "&PyList_Type"
15[clinic start generated code]*/
16/*[clinic end generated code: output=da39a3ee5e6b4b0d input=f9b222678f9f71e0]*/
17
18#include "clinic/listobject.c.h"
19
Tim Peters8d9eb102004-07-31 02:24:20 +000020/* Ensure ob_item has room for at least newsize elements, and set
21 * ob_size to newsize. If newsize > ob_size on entry, the content
22 * of the new slots at exit is undefined heap trash; it's the caller's
Ezio Melotti13925002011-03-16 11:05:33 +020023 * responsibility to overwrite them with sane values.
Tim Peters8d9eb102004-07-31 02:24:20 +000024 * The number of allocated elements may grow, shrink, or stay the same.
25 * Failure is impossible if newsize <= self.allocated on entry, although
26 * that partly relies on an assumption that the system realloc() never
27 * fails when passed a number of bytes <= the number of bytes last
28 * allocated (the C standard doesn't guarantee this, but it's hard to
29 * imagine a realloc implementation where it wouldn't be true).
30 * Note that self->ob_item may change, and even if newsize is less
31 * than ob_size on entry.
32 */
Guido van Rossuma46d51d1995-01-26 22:59:43 +000033static int
Martin v. Löwis18e16552006-02-15 17:27:45 +000034list_resize(PyListObject *self, Py_ssize_t newsize)
Guido van Rossuma46d51d1995-01-26 22:59:43 +000035{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000036 PyObject **items;
Xiang Zhang4cee0492017-02-22 12:32:30 +080037 size_t new_allocated, num_allocated_bytes;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000038 Py_ssize_t allocated = self->allocated;
Tim Peters65b8b842001-05-26 05:28:40 +000039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000040 /* Bypass realloc() when a previous overallocation is large enough
41 to accommodate the newsize. If the newsize falls lower than half
42 the allocated size, then proceed with the realloc() to shrink the list.
43 */
44 if (allocated >= newsize && newsize >= (allocated >> 1)) {
45 assert(self->ob_item != NULL || newsize == 0);
46 Py_SIZE(self) = newsize;
47 return 0;
48 }
Raymond Hettinger4bb95402004-02-13 11:36:39 +000049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000050 /* This over-allocates proportional to the list size, making room
51 * for additional growth. The over-allocation is mild, but is
52 * enough to give linear-time amortized behavior over a long
53 * sequence of appends() in the presence of a poorly-performing
54 * system realloc().
55 * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
Xiang Zhang4cee0492017-02-22 12:32:30 +080056 * Note: new_allocated won't overflow because the largest possible value
57 * is PY_SSIZE_T_MAX * (9 / 8) + 6 which always fits in a size_t.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 */
Xiang Zhang4cee0492017-02-22 12:32:30 +080059 new_allocated = (size_t)newsize + (newsize >> 3) + (newsize < 9 ? 3 : 6);
60 if (new_allocated > (size_t)PY_SSIZE_T_MAX / sizeof(PyObject *)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 PyErr_NoMemory();
62 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 }
Amaury Forgeot d'Arc9c74b142008-06-18 00:47:36 +000064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 if (newsize == 0)
66 new_allocated = 0;
Xiang Zhang4cee0492017-02-22 12:32:30 +080067 num_allocated_bytes = new_allocated * sizeof(PyObject *);
68 items = (PyObject **)PyMem_Realloc(self->ob_item, num_allocated_bytes);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000069 if (items == NULL) {
70 PyErr_NoMemory();
71 return -1;
72 }
73 self->ob_item = items;
74 Py_SIZE(self) = newsize;
75 self->allocated = new_allocated;
76 return 0;
Raymond Hettinger4bb95402004-02-13 11:36:39 +000077}
Guido van Rossuma46d51d1995-01-26 22:59:43 +000078
Christian Heimes77c02eb2008-02-09 02:18:51 +000079/* Debug statistic to compare allocations with reuse through the free list */
80#undef SHOW_ALLOC_COUNT
81#ifdef SHOW_ALLOC_COUNT
82static size_t count_alloc = 0;
83static size_t count_reuse = 0;
84
85static void
86show_alloc(void)
87{
Victor Stinner25420fe2017-11-20 18:12:22 -080088 PyInterpreterState *interp = PyThreadState_GET()->interp;
89 if (!inter->core_config.show_alloc_count) {
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +030090 return;
Victor Stinner25420fe2017-11-20 18:12:22 -080091 }
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +030092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093 fprintf(stderr, "List allocations: %" PY_FORMAT_SIZE_T "d\n",
94 count_alloc);
95 fprintf(stderr, "List reuse through freelist: %" PY_FORMAT_SIZE_T
96 "d\n", count_reuse);
97 fprintf(stderr, "%.2f%% reuse rate\n\n",
98 (100.0*count_reuse/(count_alloc+count_reuse)));
Christian Heimes77c02eb2008-02-09 02:18:51 +000099}
100#endif
101
Raymond Hettinger0468e412004-05-05 05:37:53 +0000102/* Empty list reuse scheme to save calls to malloc and free */
Christian Heimes2202f872008-02-06 14:31:34 +0000103#ifndef PyList_MAXFREELIST
104#define PyList_MAXFREELIST 80
105#endif
106static PyListObject *free_list[PyList_MAXFREELIST];
107static int numfree = 0;
Raymond Hettinger0468e412004-05-05 05:37:53 +0000108
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100109int
110PyList_ClearFreeList(void)
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000111{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 PyListObject *op;
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100113 int ret = numfree;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 while (numfree) {
115 op = free_list[--numfree];
116 assert(PyList_CheckExact(op));
117 PyObject_GC_Del(op);
118 }
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100119 return ret;
120}
121
122void
123PyList_Fini(void)
124{
125 PyList_ClearFreeList();
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000126}
127
David Malcolm49526f42012-06-22 14:55:41 -0400128/* Print summary info about the state of the optimized allocator */
129void
130_PyList_DebugMallocStats(FILE *out)
131{
132 _PyDebugAllocatorStats(out,
133 "free PyListObject",
134 numfree, sizeof(PyListObject));
135}
136
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000137PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000138PyList_New(Py_ssize_t size)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 PyListObject *op;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000141#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 static int initialized = 0;
143 if (!initialized) {
144 Py_AtExit(show_alloc);
145 initialized = 1;
146 }
Christian Heimes77c02eb2008-02-09 02:18:51 +0000147#endif
Tim Peters3986d4e2004-07-29 02:28:42 +0000148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 if (size < 0) {
150 PyErr_BadInternalCall();
151 return NULL;
152 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 if (numfree) {
154 numfree--;
155 op = free_list[numfree];
156 _Py_NewReference((PyObject *)op);
Christian Heimes77c02eb2008-02-09 02:18:51 +0000157#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 count_reuse++;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000159#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 } else {
161 op = PyObject_GC_New(PyListObject, &PyList_Type);
162 if (op == NULL)
163 return NULL;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000164#ifdef SHOW_ALLOC_COUNT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 count_alloc++;
Christian Heimes77c02eb2008-02-09 02:18:51 +0000166#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 }
168 if (size <= 0)
169 op->ob_item = NULL;
170 else {
Mark Dickinson5d132382016-08-21 08:55:15 +0100171 op->ob_item = (PyObject **) PyMem_Calloc(size, sizeof(PyObject *));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 if (op->ob_item == NULL) {
173 Py_DECREF(op);
174 return PyErr_NoMemory();
175 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 }
177 Py_SIZE(op) = size;
178 op->allocated = size;
179 _PyObject_GC_TRACK(op);
180 return (PyObject *) op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000181}
182
Martin v. Löwis18e16552006-02-15 17:27:45 +0000183Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000184PyList_Size(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 if (!PyList_Check(op)) {
187 PyErr_BadInternalCall();
188 return -1;
189 }
190 else
191 return Py_SIZE(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000192}
193
Raymond Hettingerfdfe6182004-05-05 06:28:16 +0000194static PyObject *indexerr = NULL;
Guido van Rossum929f1b81996-08-09 20:51:27 +0000195
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000196PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000197PyList_GetItem(PyObject *op, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 if (!PyList_Check(op)) {
200 PyErr_BadInternalCall();
201 return NULL;
202 }
203 if (i < 0 || i >= Py_SIZE(op)) {
204 if (indexerr == NULL) {
205 indexerr = PyUnicode_FromString(
206 "list index out of range");
207 if (indexerr == NULL)
208 return NULL;
209 }
210 PyErr_SetObject(PyExc_IndexError, indexerr);
211 return NULL;
212 }
213 return ((PyListObject *)op) -> ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000214}
215
216int
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200217PyList_SetItem(PyObject *op, Py_ssize_t i,
218 PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000219{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200220 PyObject **p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 if (!PyList_Check(op)) {
222 Py_XDECREF(newitem);
223 PyErr_BadInternalCall();
224 return -1;
225 }
226 if (i < 0 || i >= Py_SIZE(op)) {
227 Py_XDECREF(newitem);
228 PyErr_SetString(PyExc_IndexError,
229 "list assignment index out of range");
230 return -1;
231 }
232 p = ((PyListObject *)op) -> ob_item + i;
Serhiy Storchakaec397562016-04-06 09:50:03 +0300233 Py_XSETREF(*p, newitem);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000235}
236
237static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000238ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 Py_ssize_t i, n = Py_SIZE(self);
241 PyObject **items;
242 if (v == NULL) {
243 PyErr_BadInternalCall();
244 return -1;
245 }
246 if (n == PY_SSIZE_T_MAX) {
247 PyErr_SetString(PyExc_OverflowError,
248 "cannot add more objects to list");
249 return -1;
250 }
Tim Petersb38e2b62004-07-29 02:29:26 +0000251
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800252 if (list_resize(self, n+1) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 return -1;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 if (where < 0) {
256 where += n;
257 if (where < 0)
258 where = 0;
259 }
260 if (where > n)
261 where = n;
262 items = self->ob_item;
263 for (i = n; --i >= where; )
264 items[i+1] = items[i];
265 Py_INCREF(v);
266 items[where] = v;
267 return 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000268}
269
270int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000271PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000272{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 if (!PyList_Check(op)) {
274 PyErr_BadInternalCall();
275 return -1;
276 }
277 return ins1((PyListObject *)op, where, newitem);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000278}
279
Raymond Hettinger40a03822004-04-12 13:05:09 +0000280static int
281app1(PyListObject *self, PyObject *v)
282{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 Py_ssize_t n = PyList_GET_SIZE(self);
Raymond Hettinger40a03822004-04-12 13:05:09 +0000284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 assert (v != NULL);
286 if (n == PY_SSIZE_T_MAX) {
287 PyErr_SetString(PyExc_OverflowError,
288 "cannot add more objects to list");
289 return -1;
290 }
Raymond Hettinger40a03822004-04-12 13:05:09 +0000291
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800292 if (list_resize(self, n+1) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 return -1;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 Py_INCREF(v);
296 PyList_SET_ITEM(self, n, v);
297 return 0;
Raymond Hettinger40a03822004-04-12 13:05:09 +0000298}
299
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000300int
Fred Drakea2f55112000-07-09 15:16:51 +0000301PyList_Append(PyObject *op, PyObject *newitem)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 if (PyList_Check(op) && (newitem != NULL))
304 return app1((PyListObject *)op, newitem);
305 PyErr_BadInternalCall();
306 return -1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000307}
308
309/* Methods */
310
311static void
Fred Drakea2f55112000-07-09 15:16:51 +0000312list_dealloc(PyListObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 Py_ssize_t i;
315 PyObject_GC_UnTrack(op);
316 Py_TRASHCAN_SAFE_BEGIN(op)
317 if (op->ob_item != NULL) {
318 /* Do it backwards, for Christian Tismer.
319 There's a simple test case where somehow this reduces
320 thrashing when a *very* large list is created and
321 immediately deleted. */
322 i = Py_SIZE(op);
323 while (--i >= 0) {
324 Py_XDECREF(op->ob_item[i]);
325 }
326 PyMem_FREE(op->ob_item);
327 }
328 if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op))
329 free_list[numfree++] = op;
330 else
331 Py_TYPE(op)->tp_free((PyObject *)op);
332 Py_TRASHCAN_SAFE_END(op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000333}
334
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000335static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000336list_repr(PyListObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 Py_ssize_t i;
Victor Stinner5c733472013-11-18 21:11:57 +0100339 PyObject *s;
Victor Stinner5c733472013-11-18 21:11:57 +0100340 _PyUnicodeWriter writer;
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200341
342 if (Py_SIZE(v) == 0) {
343 return PyUnicode_FromString("[]");
344 }
345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 i = Py_ReprEnter((PyObject*)v);
347 if (i != 0) {
348 return i > 0 ? PyUnicode_FromString("[...]") : NULL;
349 }
Tim Petersa7259592001-06-16 05:11:17 +0000350
Victor Stinner5c733472013-11-18 21:11:57 +0100351 _PyUnicodeWriter_Init(&writer);
352 writer.overallocate = 1;
Victor Stinnerb8fb1972013-11-18 22:15:44 +0100353 /* "[" + "1" + ", 2" * (len - 1) + "]" */
354 writer.min_length = 1 + 1 + (2 + 1) * (Py_SIZE(v) - 1) + 1;
Tim Petersa7259592001-06-16 05:11:17 +0000355
Victor Stinner5c733472013-11-18 21:11:57 +0100356 if (_PyUnicodeWriter_WriteChar(&writer, '[') < 0)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200357 goto error;
Tim Petersa7259592001-06-16 05:11:17 +0000358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 /* Do repr() on each element. Note that this may mutate the list,
360 so must refetch the list size on each iteration. */
361 for (i = 0; i < Py_SIZE(v); ++i) {
Victor Stinner5c733472013-11-18 21:11:57 +0100362 if (i > 0) {
Victor Stinner4a587072013-11-19 12:54:53 +0100363 if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
Victor Stinner5c733472013-11-18 21:11:57 +0100364 goto error;
365 }
366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 if (Py_EnterRecursiveCall(" while getting the repr of a list"))
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200368 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 s = PyObject_Repr(v->ob_item[i]);
370 Py_LeaveRecursiveCall();
Victor Stinner5c733472013-11-18 21:11:57 +0100371 if (s == NULL)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200372 goto error;
Victor Stinner5c733472013-11-18 21:11:57 +0100373
374 if (_PyUnicodeWriter_WriteStr(&writer, s) < 0) {
375 Py_DECREF(s);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200376 goto error;
Victor Stinner5c733472013-11-18 21:11:57 +0100377 }
378 Py_DECREF(s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 }
Victor Stinner5c733472013-11-18 21:11:57 +0100380
Victor Stinner4d3f1092013-11-19 12:09:00 +0100381 writer.overallocate = 0;
Victor Stinner5c733472013-11-18 21:11:57 +0100382 if (_PyUnicodeWriter_WriteChar(&writer, ']') < 0)
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200383 goto error;
Tim Petersa7259592001-06-16 05:11:17 +0000384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 Py_ReprLeave((PyObject *)v);
Victor Stinner5c733472013-11-18 21:11:57 +0100386 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200387
388error:
Victor Stinner5c733472013-11-18 21:11:57 +0100389 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitroueeb7eea2011-10-06 18:57:27 +0200390 Py_ReprLeave((PyObject *)v);
391 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000392}
393
Martin v. Löwis18e16552006-02-15 17:27:45 +0000394static Py_ssize_t
Fred Drakea2f55112000-07-09 15:16:51 +0000395list_length(PyListObject *a)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000396{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 return Py_SIZE(a);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000398}
399
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000400static int
Fred Drakea2f55112000-07-09 15:16:51 +0000401list_contains(PyListObject *a, PyObject *el)
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 Py_ssize_t i;
404 int cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
407 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
408 Py_EQ);
409 return cmp;
Jeremy Hylton37b1a262000-04-27 21:41:03 +0000410}
411
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000412static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000413list_item(PyListObject *a, Py_ssize_t i)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 if (i < 0 || i >= Py_SIZE(a)) {
416 if (indexerr == NULL) {
417 indexerr = PyUnicode_FromString(
418 "list index out of range");
419 if (indexerr == NULL)
420 return NULL;
421 }
422 PyErr_SetObject(PyExc_IndexError, indexerr);
423 return NULL;
424 }
425 Py_INCREF(a->ob_item[i]);
426 return a->ob_item[i];
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000427}
428
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000429static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000430list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 PyListObject *np;
433 PyObject **src, **dest;
434 Py_ssize_t i, len;
435 if (ilow < 0)
436 ilow = 0;
437 else if (ilow > Py_SIZE(a))
438 ilow = Py_SIZE(a);
439 if (ihigh < ilow)
440 ihigh = ilow;
441 else if (ihigh > Py_SIZE(a))
442 ihigh = Py_SIZE(a);
443 len = ihigh - ilow;
444 np = (PyListObject *) PyList_New(len);
445 if (np == NULL)
446 return NULL;
Raymond Hettinger99842b62004-03-08 05:56:15 +0000447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 src = a->ob_item + ilow;
449 dest = np->ob_item;
450 for (i = 0; i < len; i++) {
451 PyObject *v = src[i];
452 Py_INCREF(v);
453 dest[i] = v;
454 }
455 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000456}
457
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000458PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000459PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
Guido van Rossum234f9421993-06-17 12:35:49 +0000460{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 if (!PyList_Check(a)) {
462 PyErr_BadInternalCall();
463 return NULL;
464 }
465 return list_slice((PyListObject *)a, ilow, ihigh);
Guido van Rossum234f9421993-06-17 12:35:49 +0000466}
467
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000468static PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +0000469list_concat(PyListObject *a, PyObject *bb)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 Py_ssize_t size;
472 Py_ssize_t i;
473 PyObject **src, **dest;
474 PyListObject *np;
475 if (!PyList_Check(bb)) {
476 PyErr_Format(PyExc_TypeError,
477 "can only concatenate list (not \"%.200s\") to list",
478 bb->ob_type->tp_name);
479 return NULL;
480 }
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000481#define b ((PyListObject *)bb)
Martin Panterb93d8632016-07-25 02:39:20 +0000482 if (Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 return PyErr_NoMemory();
Martin Panterb93d8632016-07-25 02:39:20 +0000484 size = Py_SIZE(a) + Py_SIZE(b);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 np = (PyListObject *) PyList_New(size);
486 if (np == NULL) {
487 return NULL;
488 }
489 src = a->ob_item;
490 dest = np->ob_item;
491 for (i = 0; i < Py_SIZE(a); i++) {
492 PyObject *v = src[i];
493 Py_INCREF(v);
494 dest[i] = v;
495 }
496 src = b->ob_item;
497 dest = np->ob_item + Py_SIZE(a);
498 for (i = 0; i < Py_SIZE(b); i++) {
499 PyObject *v = src[i];
500 Py_INCREF(v);
501 dest[i] = v;
502 }
503 return (PyObject *)np;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000504#undef b
505}
506
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000507static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000508list_repeat(PyListObject *a, Py_ssize_t n)
Guido van Rossumed98d481991-03-06 13:07:53 +0000509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 Py_ssize_t i, j;
511 Py_ssize_t size;
512 PyListObject *np;
513 PyObject **p, **items;
514 PyObject *elem;
515 if (n < 0)
516 n = 0;
Mark Dickinsonc0420fd2011-09-19 19:18:37 +0100517 if (n > 0 && Py_SIZE(a) > PY_SSIZE_T_MAX / n)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 return PyErr_NoMemory();
Mark Dickinsonc0420fd2011-09-19 19:18:37 +0100519 size = Py_SIZE(a) * n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 if (size == 0)
521 return PyList_New(0);
522 np = (PyListObject *) PyList_New(size);
523 if (np == NULL)
524 return NULL;
Raymond Hettinger6624e682003-05-21 05:58:46 +0000525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 items = np->ob_item;
527 if (Py_SIZE(a) == 1) {
528 elem = a->ob_item[0];
529 for (i = 0; i < n; i++) {
530 items[i] = elem;
531 Py_INCREF(elem);
532 }
533 return (PyObject *) np;
534 }
535 p = np->ob_item;
536 items = a->ob_item;
537 for (i = 0; i < n; i++) {
538 for (j = 0; j < Py_SIZE(a); j++) {
539 *p = items[j];
540 Py_INCREF(*p);
541 p++;
542 }
543 }
544 return (PyObject *) np;
Guido van Rossumed98d481991-03-06 13:07:53 +0000545}
546
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000547static int
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200548_list_clear(PyListObject *a)
Armin Rigo93677f02004-07-29 12:40:23 +0000549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 Py_ssize_t i;
551 PyObject **item = a->ob_item;
552 if (item != NULL) {
553 /* Because XDECREF can recursively invoke operations on
554 this list, we make it empty first. */
555 i = Py_SIZE(a);
556 Py_SIZE(a) = 0;
557 a->ob_item = NULL;
558 a->allocated = 0;
559 while (--i >= 0) {
560 Py_XDECREF(item[i]);
561 }
562 PyMem_FREE(item);
563 }
564 /* Never fails; the return value can be ignored.
565 Note that there is no guarantee that the list is actually empty
566 at this point, because XDECREF may have populated it again! */
567 return 0;
Armin Rigo93677f02004-07-29 12:40:23 +0000568}
569
Tim Peters8fc4a912004-07-31 21:53:19 +0000570/* a[ilow:ihigh] = v if v != NULL.
571 * del a[ilow:ihigh] if v == NULL.
572 *
573 * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
574 * guaranteed the call cannot fail.
575 */
Armin Rigo93677f02004-07-29 12:40:23 +0000576static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000577list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000578{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 /* Because [X]DECREF can recursively invoke list operations on
580 this list, we must postpone all [X]DECREF activity until
581 after the list is back in its canonical shape. Therefore
582 we must allocate an additional array, 'recycle', into which
583 we temporarily copy the items that are deleted from the
584 list. :-( */
585 PyObject *recycle_on_stack[8];
586 PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
587 PyObject **item;
588 PyObject **vitem = NULL;
589 PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
590 Py_ssize_t n; /* # of elements in replacement list */
591 Py_ssize_t norig; /* # of elements in list getting replaced */
592 Py_ssize_t d; /* Change in size */
593 Py_ssize_t k;
594 size_t s;
595 int result = -1; /* guilty until proved innocent */
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000596#define b ((PyListObject *)v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 if (v == NULL)
598 n = 0;
599 else {
600 if (a == b) {
601 /* Special case "a[i:j] = a" -- copy b first */
602 v = list_slice(b, 0, Py_SIZE(b));
603 if (v == NULL)
604 return result;
605 result = list_ass_slice(a, ilow, ihigh, v);
606 Py_DECREF(v);
607 return result;
608 }
609 v_as_SF = PySequence_Fast(v, "can only assign an iterable");
610 if(v_as_SF == NULL)
611 goto Error;
612 n = PySequence_Fast_GET_SIZE(v_as_SF);
613 vitem = PySequence_Fast_ITEMS(v_as_SF);
614 }
615 if (ilow < 0)
616 ilow = 0;
617 else if (ilow > Py_SIZE(a))
618 ilow = Py_SIZE(a);
Tim Peters8d9eb102004-07-31 02:24:20 +0000619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 if (ihigh < ilow)
621 ihigh = ilow;
622 else if (ihigh > Py_SIZE(a))
623 ihigh = Py_SIZE(a);
Armin Rigo93677f02004-07-29 12:40:23 +0000624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 norig = ihigh - ilow;
626 assert(norig >= 0);
627 d = n - norig;
628 if (Py_SIZE(a) + d == 0) {
629 Py_XDECREF(v_as_SF);
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200630 return _list_clear(a);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 }
632 item = a->ob_item;
633 /* recycle the items that we are about to remove */
634 s = norig * sizeof(PyObject *);
Benjamin Peterson5a7d9232016-09-06 17:58:25 -0700635 /* If norig == 0, item might be NULL, in which case we may not memcpy from it. */
636 if (s) {
637 if (s > sizeof(recycle_on_stack)) {
638 recycle = (PyObject **)PyMem_MALLOC(s);
639 if (recycle == NULL) {
640 PyErr_NoMemory();
641 goto Error;
642 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 }
Benjamin Peterson5a7d9232016-09-06 17:58:25 -0700644 memcpy(recycle, &item[ilow], s);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 }
Tim Peters8d9eb102004-07-31 02:24:20 +0000646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 if (d < 0) { /* Delete -d items */
Victor Stinner2c40f642013-07-19 23:06:21 +0200648 Py_ssize_t tail;
649 tail = (Py_SIZE(a) - ihigh) * sizeof(PyObject *);
650 memmove(&item[ihigh+d], &item[ihigh], tail);
651 if (list_resize(a, Py_SIZE(a) + d) < 0) {
652 memmove(&item[ihigh], &item[ihigh+d], tail);
653 memcpy(&item[ilow], recycle, s);
654 goto Error;
655 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 item = a->ob_item;
657 }
658 else if (d > 0) { /* Insert d items */
659 k = Py_SIZE(a);
660 if (list_resize(a, k+d) < 0)
661 goto Error;
662 item = a->ob_item;
663 memmove(&item[ihigh+d], &item[ihigh],
664 (k - ihigh)*sizeof(PyObject *));
665 }
666 for (k = 0; k < n; k++, ilow++) {
667 PyObject *w = vitem[k];
668 Py_XINCREF(w);
669 item[ilow] = w;
670 }
671 for (k = norig - 1; k >= 0; --k)
672 Py_XDECREF(recycle[k]);
673 result = 0;
Tim Peters8d9eb102004-07-31 02:24:20 +0000674 Error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 if (recycle != recycle_on_stack)
676 PyMem_FREE(recycle);
677 Py_XDECREF(v_as_SF);
678 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000679#undef b
680}
681
Guido van Rossum234f9421993-06-17 12:35:49 +0000682int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000683PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
Guido van Rossum234f9421993-06-17 12:35:49 +0000684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 if (!PyList_Check(a)) {
686 PyErr_BadInternalCall();
687 return -1;
688 }
689 return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
Guido van Rossum234f9421993-06-17 12:35:49 +0000690}
691
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000692static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000693list_inplace_repeat(PyListObject *self, Py_ssize_t n)
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 PyObject **items;
696 Py_ssize_t size, i, j, p;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000697
698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 size = PyList_GET_SIZE(self);
700 if (size == 0 || n == 1) {
701 Py_INCREF(self);
702 return (PyObject *)self;
703 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 if (n < 1) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200706 (void)_list_clear(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 Py_INCREF(self);
708 return (PyObject *)self;
709 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 if (size > PY_SSIZE_T_MAX / n) {
712 return PyErr_NoMemory();
713 }
Christian Heimesaf98da12008-01-27 15:18:18 +0000714
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800715 if (list_resize(self, size*n) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 return NULL;
Raymond Hettinger4bb95402004-02-13 11:36:39 +0000717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 p = size;
719 items = self->ob_item;
720 for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
721 for (j = 0; j < size; j++) {
722 PyObject *o = items[j];
723 Py_INCREF(o);
724 items[p++] = o;
725 }
726 }
727 Py_INCREF(self);
728 return (PyObject *)self;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000729}
730
Guido van Rossum4a450d01991-04-03 19:05:18 +0000731static int
Martin v. Löwis18e16552006-02-15 17:27:45 +0000732list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
Guido van Rossum4a450d01991-04-03 19:05:18 +0000733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 if (i < 0 || i >= Py_SIZE(a)) {
735 PyErr_SetString(PyExc_IndexError,
736 "list assignment index out of range");
737 return -1;
738 }
739 if (v == NULL)
740 return list_ass_slice(a, i, i+1, v);
741 Py_INCREF(v);
Serhiy Storchakaf01e4082016-04-10 18:12:01 +0300742 Py_SETREF(a->ob_item[i], v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 return 0;
Guido van Rossum4a450d01991-04-03 19:05:18 +0000744}
745
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200746/*[clinic input]
747list.insert
748
749 index: Py_ssize_t
750 object: object
751 /
752
753Insert object before index.
754[clinic start generated code]*/
755
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000756static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200757list_insert_impl(PyListObject *self, Py_ssize_t index, PyObject *object)
758/*[clinic end generated code: output=7f35e32f60c8cb78 input=858514cf894c7eab]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000759{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200760 if (ins1(self, index, object) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 Py_RETURN_NONE;
762 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000763}
764
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200765/*[clinic input]
766list.clear
767
768Remove all items from list.
769[clinic start generated code]*/
770
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000771static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200772list_clear_impl(PyListObject *self)
773/*[clinic end generated code: output=67a1896c01f74362 input=ca3c1646856742f6]*/
Eli Benderskycbbaa962011-02-25 05:47:53 +0000774{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200775 _list_clear(self);
Eli Benderskycbbaa962011-02-25 05:47:53 +0000776 Py_RETURN_NONE;
777}
778
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200779/*[clinic input]
780list.copy
781
782Return a shallow copy of the list.
783[clinic start generated code]*/
784
Eli Benderskycbbaa962011-02-25 05:47:53 +0000785static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200786list_copy_impl(PyListObject *self)
787/*[clinic end generated code: output=ec6b72d6209d418e input=6453ab159e84771f]*/
Eli Benderskycbbaa962011-02-25 05:47:53 +0000788{
789 return list_slice(self, 0, Py_SIZE(self));
790}
791
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200792/*[clinic input]
793list.append
794
795 object: object
796 /
797
798Append object to the end of the list.
799[clinic start generated code]*/
800
Eli Benderskycbbaa962011-02-25 05:47:53 +0000801static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200802list_append(PyListObject *self, PyObject *object)
803/*[clinic end generated code: output=7c096003a29c0eae input=43a3fe48a7066e91]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000804{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200805 if (app1(self, object) == 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 Py_RETURN_NONE;
807 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000808}
809
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200810/*[clinic input]
811list.extend
812
813 iterable: object
814 /
815
816Extend list by appending elements from the iterable.
817[clinic start generated code]*/
818
Barry Warsawdedf6d61998-10-09 16:37:25 +0000819static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200820list_extend(PyListObject *self, PyObject *iterable)
821/*[clinic end generated code: output=630fb3bca0c8e789 input=9ec5ba3a81be3a4d]*/
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000822{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 PyObject *it; /* iter(v) */
824 Py_ssize_t m; /* size of self */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200825 Py_ssize_t n; /* guess for size of iterable */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 Py_ssize_t mn; /* m + n */
827 Py_ssize_t i;
828 PyObject *(*iternext)(PyObject *);
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 /* Special cases:
831 1) lists and tuples which can use PySequence_Fast ops
832 2) extending self to self requires making a copy first
833 */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200834 if (PyList_CheckExact(iterable) || PyTuple_CheckExact(iterable) ||
835 (PyObject *)self == iterable) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 PyObject **src, **dest;
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200837 iterable = PySequence_Fast(iterable, "argument must be iterable");
838 if (!iterable)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 return NULL;
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200840 n = PySequence_Fast_GET_SIZE(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 if (n == 0) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200842 /* short circuit when iterable is empty */
843 Py_DECREF(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 Py_RETURN_NONE;
845 }
846 m = Py_SIZE(self);
Martin Panter94b39ce2017-01-14 06:30:37 +0000847 /* It should not be possible to allocate a list large enough to cause
848 an overflow on any relevant platform */
849 assert(m < PY_SSIZE_T_MAX - n);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800850 if (list_resize(self, m + n) < 0) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200851 Py_DECREF(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 return NULL;
853 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200854 /* note that we may still have self == iterable here for the
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 * situation a.extend(a), but the following code works
856 * in that case too. Just make sure to resize self
857 * before calling PySequence_Fast_ITEMS.
858 */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200859 /* populate the end of self with iterable's items */
860 src = PySequence_Fast_ITEMS(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 dest = self->ob_item + m;
862 for (i = 0; i < n; i++) {
863 PyObject *o = src[i];
864 Py_INCREF(o);
865 dest[i] = o;
866 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200867 Py_DECREF(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 Py_RETURN_NONE;
869 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000870
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200871 it = PyObject_GetIter(iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 if (it == NULL)
873 return NULL;
874 iternext = *it->ob_type->tp_iternext;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 /* Guess a result list size. */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200877 n = PyObject_LengthHint(iterable, 8);
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800878 if (n < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 Py_DECREF(it);
880 return NULL;
881 }
882 m = Py_SIZE(self);
Martin Panterb93d8632016-07-25 02:39:20 +0000883 if (m > PY_SSIZE_T_MAX - n) {
884 /* m + n overflowed; on the chance that n lied, and there really
885 * is enough room, ignore it. If n was telling the truth, we'll
886 * eventually run out of memory during the loop.
887 */
888 }
889 else {
890 mn = m + n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 /* Make room. */
Raymond Hettinger0dceb912016-01-25 10:33:30 -0800892 if (list_resize(self, mn) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 goto error;
894 /* Make the list sane again. */
895 Py_SIZE(self) = m;
896 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 /* Run iterator to exhaustion. */
899 for (;;) {
900 PyObject *item = iternext(it);
901 if (item == NULL) {
902 if (PyErr_Occurred()) {
903 if (PyErr_ExceptionMatches(PyExc_StopIteration))
904 PyErr_Clear();
905 else
906 goto error;
907 }
908 break;
909 }
910 if (Py_SIZE(self) < self->allocated) {
911 /* steals ref */
912 PyList_SET_ITEM(self, Py_SIZE(self), item);
913 ++Py_SIZE(self);
914 }
915 else {
916 int status = app1(self, item);
917 Py_DECREF(item); /* append creates a new ref */
918 if (status < 0)
919 goto error;
920 }
921 }
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 /* Cut back result list if initial guess was too large. */
Victor Stinner32fd6ea2013-07-16 21:45:58 +0200924 if (Py_SIZE(self) < self->allocated) {
925 if (list_resize(self, Py_SIZE(self)) < 0)
926 goto error;
927 }
Raymond Hettingeraa241e02004-09-26 19:24:20 +0000928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 Py_DECREF(it);
930 Py_RETURN_NONE;
Raymond Hettinger90a39bf2004-02-15 03:57:00 +0000931
932 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 Py_DECREF(it);
934 return NULL;
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000935}
936
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000937PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200938_PyList_Extend(PyListObject *self, PyObject *iterable)
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000939{
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200940 return list_extend(self, iterable);
Raymond Hettinger8ca92ae2004-03-11 09:13:12 +0000941}
942
Thomas Wouterse289e0b2000-08-24 20:08:19 +0000943static PyObject *
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000944list_inplace_concat(PyListObject *self, PyObject *other)
945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 PyObject *result;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000947
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200948 result = list_extend(self, other);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 if (result == NULL)
950 return result;
951 Py_DECREF(result);
952 Py_INCREF(self);
953 return (PyObject *)self;
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000954}
955
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200956/*[clinic input]
957list.pop
958
959 index: Py_ssize_t = -1
960 /
961
962Remove and return item at index (default last).
963
964Raises IndexError if list is empty or index is out of range.
965[clinic start generated code]*/
966
Raymond Hettinger97bc6182004-03-11 07:34:19 +0000967static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200968list_pop_impl(PyListObject *self, Py_ssize_t index)
969/*[clinic end generated code: output=6bd69dcb3f17eca8 input=b83675976f329e6f]*/
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +0000970{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 PyObject *v;
972 int status;
Raymond Hettinger9eb86b32004-02-17 11:36:16 +0000973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 if (Py_SIZE(self) == 0) {
975 /* Special-case most common failure cause */
976 PyErr_SetString(PyExc_IndexError, "pop from empty list");
977 return NULL;
978 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200979 if (index < 0)
980 index += Py_SIZE(self);
981 if (index < 0 || index >= Py_SIZE(self)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 PyErr_SetString(PyExc_IndexError, "pop index out of range");
983 return NULL;
984 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200985 v = self->ob_item[index];
986 if (index == Py_SIZE(self) - 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 status = list_resize(self, Py_SIZE(self) - 1);
Victor Stinnerb27cd3e2013-07-08 22:20:44 +0200988 if (status >= 0)
989 return v; /* and v now owns the reference the list had */
990 else
991 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 }
993 Py_INCREF(v);
Serhiy Storchakafdd42c42017-03-11 09:19:20 +0200994 status = list_ass_slice(self, index, index+1, (PyObject *)NULL);
Victor Stinner095d99f2013-07-17 21:58:01 +0200995 if (status < 0) {
996 Py_DECREF(v);
997 return NULL;
998 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 return v;
Guido van Rossum3dd7f3f1998-06-30 15:36:32 +00001000}
1001
Tim Peters8e2e7ca2002-07-19 02:33:08 +00001002/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
1003static void
1004reverse_slice(PyObject **lo, PyObject **hi)
1005{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 assert(lo && hi);
Tim Peters8e2e7ca2002-07-19 02:33:08 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 --hi;
1009 while (lo < hi) {
1010 PyObject *t = *lo;
1011 *lo = *hi;
1012 *hi = t;
1013 ++lo;
1014 --hi;
1015 }
Tim Peters8e2e7ca2002-07-19 02:33:08 +00001016}
1017
Tim Petersa64dc242002-08-01 02:13:36 +00001018/* Lots of code for an adaptive, stable, natural mergesort. There are many
1019 * pieces to this algorithm; read listsort.txt for overviews and details.
1020 */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001021
Daniel Stutzbach98338222010-12-02 21:55:33 +00001022/* A sortslice contains a pointer to an array of keys and a pointer to
1023 * an array of corresponding values. In other words, keys[i]
1024 * corresponds with values[i]. If values == NULL, then the keys are
1025 * also the values.
1026 *
1027 * Several convenience routines are provided here, so that keys and
1028 * values are always moved in sync.
1029 */
1030
1031typedef struct {
1032 PyObject **keys;
1033 PyObject **values;
1034} sortslice;
1035
1036Py_LOCAL_INLINE(void)
1037sortslice_copy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j)
1038{
1039 s1->keys[i] = s2->keys[j];
1040 if (s1->values != NULL)
1041 s1->values[i] = s2->values[j];
1042}
1043
1044Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001045sortslice_copy_incr(sortslice *dst, sortslice *src)
1046{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001047 *dst->keys++ = *src->keys++;
1048 if (dst->values != NULL)
1049 *dst->values++ = *src->values++;
1050}
1051
1052Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001053sortslice_copy_decr(sortslice *dst, sortslice *src)
1054{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001055 *dst->keys-- = *src->keys--;
1056 if (dst->values != NULL)
1057 *dst->values-- = *src->values--;
1058}
1059
1060
1061Py_LOCAL_INLINE(void)
1062sortslice_memcpy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001063 Py_ssize_t n)
1064{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001065 memcpy(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1066 if (s1->values != NULL)
1067 memcpy(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1068}
1069
1070Py_LOCAL_INLINE(void)
1071sortslice_memmove(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001072 Py_ssize_t n)
1073{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001074 memmove(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
1075 if (s1->values != NULL)
1076 memmove(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
1077}
1078
1079Py_LOCAL_INLINE(void)
Benjamin Peterson9efdcca2010-12-03 01:44:10 +00001080sortslice_advance(sortslice *slice, Py_ssize_t n)
1081{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001082 slice->keys += n;
1083 if (slice->values != NULL)
1084 slice->values += n;
1085}
1086
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001087/* Comparison function: PyObject_RichCompareBool with Py_LT.
Tim Petersa64dc242002-08-01 02:13:36 +00001088 * Returns -1 on error, 1 if x < y, 0 if x >= y.
1089 */
Guido van Rossum3f236de1996-12-10 23:55:39 +00001090
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001091#define ISLT(X, Y) (PyObject_RichCompareBool(X, Y, Py_LT))
Tim Peters66860f62002-08-04 17:47:26 +00001092
1093/* Compare X to Y via "<". Goto "fail" if the comparison raises an
Tim Petersa8c974c2002-07-19 03:30:57 +00001094 error. Else "k" is set to true iff X<Y, and an "if (k)" block is
1095 started. It makes more sense in context <wink>. X and Y are PyObject*s.
1096*/
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001097#define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail; \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 if (k)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001099
1100/* binarysort is the best method for sorting small arrays: it does
1101 few compares, but can do data movement quadratic in the number of
1102 elements.
Guido van Rossum42812581998-06-17 14:15:44 +00001103 [lo, hi) is a contiguous slice of a list, and is sorted via
Tim Petersa8c974c2002-07-19 03:30:57 +00001104 binary insertion. This sort is stable.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001105 On entry, must have lo <= start <= hi, and that [lo, start) is already
1106 sorted (pass start == lo if you don't know!).
Tim Petersa8c974c2002-07-19 03:30:57 +00001107 If islt() complains return -1, else 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001108 Even in case of error, the output slice will be some permutation of
1109 the input (nothing is lost or duplicated).
1110*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00001111static int
Daniel Stutzbach98338222010-12-02 21:55:33 +00001112binarysort(sortslice lo, PyObject **hi, PyObject **start)
Guido van Rossum3f236de1996-12-10 23:55:39 +00001113{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001114 Py_ssize_t k;
1115 PyObject **l, **p, **r;
1116 PyObject *pivot;
Guido van Rossum3f236de1996-12-10 23:55:39 +00001117
Daniel Stutzbach98338222010-12-02 21:55:33 +00001118 assert(lo.keys <= start && start <= hi);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 /* assert [lo, start) is sorted */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001120 if (lo.keys == start)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 ++start;
1122 for (; start < hi; ++start) {
1123 /* set l to where *start belongs */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001124 l = lo.keys;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 r = start;
1126 pivot = *r;
1127 /* Invariants:
1128 * pivot >= all in [lo, l).
1129 * pivot < all in [r, start).
1130 * The second is vacuously true at the start.
1131 */
1132 assert(l < r);
1133 do {
1134 p = l + ((r - l) >> 1);
1135 IFLT(pivot, *p)
1136 r = p;
1137 else
1138 l = p+1;
1139 } while (l < r);
1140 assert(l == r);
1141 /* The invariants still hold, so pivot >= all in [lo, l) and
1142 pivot < all in [l, start), so pivot belongs at l. Note
1143 that if there are elements equal to pivot, l points to the
1144 first slot after them -- that's why this sort is stable.
1145 Slide over to make room.
1146 Caution: using memmove is much slower under MSVC 5;
1147 we're not usually moving many slots. */
1148 for (p = start; p > l; --p)
1149 *p = *(p-1);
1150 *l = pivot;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001151 if (lo.values != NULL) {
1152 Py_ssize_t offset = lo.values - lo.keys;
1153 p = start + offset;
1154 pivot = *p;
1155 l += offset;
1156 for (p = start + offset; p > l; --p)
1157 *p = *(p-1);
1158 *l = pivot;
1159 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 }
1161 return 0;
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001162
1163 fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 return -1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001165}
1166
Tim Petersa64dc242002-08-01 02:13:36 +00001167/*
1168Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
1169is required on entry. "A run" is the longest ascending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001170
Tim Petersa64dc242002-08-01 02:13:36 +00001171 lo[0] <= lo[1] <= lo[2] <= ...
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001172
Tim Petersa64dc242002-08-01 02:13:36 +00001173or the longest descending sequence, with
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001174
Tim Petersa64dc242002-08-01 02:13:36 +00001175 lo[0] > lo[1] > lo[2] > ...
Tim Peters3b01a122002-07-19 02:35:45 +00001176
Tim Petersa64dc242002-08-01 02:13:36 +00001177Boolean *descending is set to 0 in the former case, or to 1 in the latter.
1178For its intended use in a stable mergesort, the strictness of the defn of
1179"descending" is needed so that the caller can safely reverse a descending
1180sequence without violating stability (strict > ensures there are no equal
1181elements to get out of order).
1182
1183Returns -1 in case of error.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001184*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001185static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001186count_run(PyObject **lo, PyObject **hi, int *descending)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 Py_ssize_t k;
1189 Py_ssize_t n;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 assert(lo < hi);
1192 *descending = 0;
1193 ++lo;
1194 if (lo == hi)
1195 return 1;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 n = 2;
1198 IFLT(*lo, *(lo-1)) {
1199 *descending = 1;
1200 for (lo = lo+1; lo < hi; ++lo, ++n) {
1201 IFLT(*lo, *(lo-1))
1202 ;
1203 else
1204 break;
1205 }
1206 }
1207 else {
1208 for (lo = lo+1; lo < hi; ++lo, ++n) {
1209 IFLT(*lo, *(lo-1))
1210 break;
1211 }
1212 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 return n;
Tim Petersa64dc242002-08-01 02:13:36 +00001215fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001217}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001218
Tim Petersa64dc242002-08-01 02:13:36 +00001219/*
1220Locate the proper position of key in a sorted vector; if the vector contains
1221an element equal to key, return the position immediately to the left of
1222the leftmost equal element. [gallop_right() does the same except returns
1223the position to the right of the rightmost equal element (if any).]
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001224
Tim Petersa64dc242002-08-01 02:13:36 +00001225"a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001226
Tim Petersa64dc242002-08-01 02:13:36 +00001227"hint" is an index at which to begin the search, 0 <= hint < n. The closer
1228hint is to the final result, the faster this runs.
1229
1230The return value is the int k in 0..n such that
1231
1232 a[k-1] < key <= a[k]
1233
1234pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
1235key belongs at index k; or, IOW, the first k elements of a should precede
1236key, and the last n-k should follow key.
1237
1238Returns -1 on error. See listsort.txt for info on the method.
1239*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001240static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001241gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 Py_ssize_t ofs;
1244 Py_ssize_t lastofs;
1245 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 a += hint;
1250 lastofs = 0;
1251 ofs = 1;
1252 IFLT(*a, key) {
1253 /* a[hint] < key -- gallop right, until
1254 * a[hint + lastofs] < key <= a[hint + ofs]
1255 */
1256 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1257 while (ofs < maxofs) {
1258 IFLT(a[ofs], key) {
1259 lastofs = ofs;
1260 ofs = (ofs << 1) + 1;
1261 if (ofs <= 0) /* int overflow */
1262 ofs = maxofs;
1263 }
1264 else /* key <= a[hint + ofs] */
1265 break;
1266 }
1267 if (ofs > maxofs)
1268 ofs = maxofs;
1269 /* Translate back to offsets relative to &a[0]. */
1270 lastofs += hint;
1271 ofs += hint;
1272 }
1273 else {
1274 /* key <= a[hint] -- gallop left, until
1275 * a[hint - ofs] < key <= a[hint - lastofs]
1276 */
1277 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1278 while (ofs < maxofs) {
1279 IFLT(*(a-ofs), key)
1280 break;
1281 /* key <= a[hint - ofs] */
1282 lastofs = ofs;
1283 ofs = (ofs << 1) + 1;
1284 if (ofs <= 0) /* int overflow */
1285 ofs = maxofs;
1286 }
1287 if (ofs > maxofs)
1288 ofs = maxofs;
1289 /* Translate back to positive offsets relative to &a[0]. */
1290 k = lastofs;
1291 lastofs = hint - ofs;
1292 ofs = hint - k;
1293 }
1294 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1297 /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
1298 * right of lastofs but no farther right than ofs. Do a binary
1299 * search, with invariant a[lastofs-1] < key <= a[ofs].
1300 */
1301 ++lastofs;
1302 while (lastofs < ofs) {
1303 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 IFLT(a[m], key)
1306 lastofs = m+1; /* a[m] < key */
1307 else
1308 ofs = m; /* key <= a[m] */
1309 }
1310 assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
1311 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001312
1313fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001315}
1316
1317/*
1318Exactly like gallop_left(), except that if key already exists in a[0:n],
1319finds the position immediately to the right of the rightmost equal value.
1320
1321The return value is the int k in 0..n such that
1322
1323 a[k-1] <= key < a[k]
1324
1325or -1 if error.
1326
1327The code duplication is massive, but this is enough different given that
1328we're sticking to "<" comparisons that it's much harder to follow if
1329written as one routine with yet another "left or right?" flag.
1330*/
Martin v. Löwis18e16552006-02-15 17:27:45 +00001331static Py_ssize_t
Raymond Hettinger70b64fc2008-01-30 20:15:17 +00001332gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
Tim Petersa64dc242002-08-01 02:13:36 +00001333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 Py_ssize_t ofs;
1335 Py_ssize_t lastofs;
1336 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 assert(key && a && n > 0 && hint >= 0 && hint < n);
Tim Petersa64dc242002-08-01 02:13:36 +00001339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 a += hint;
1341 lastofs = 0;
1342 ofs = 1;
1343 IFLT(key, *a) {
1344 /* key < a[hint] -- gallop left, until
1345 * a[hint - ofs] <= key < a[hint - lastofs]
1346 */
1347 const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
1348 while (ofs < maxofs) {
1349 IFLT(key, *(a-ofs)) {
1350 lastofs = ofs;
1351 ofs = (ofs << 1) + 1;
1352 if (ofs <= 0) /* int overflow */
1353 ofs = maxofs;
1354 }
1355 else /* a[hint - ofs] <= key */
1356 break;
1357 }
1358 if (ofs > maxofs)
1359 ofs = maxofs;
1360 /* Translate back to positive offsets relative to &a[0]. */
1361 k = lastofs;
1362 lastofs = hint - ofs;
1363 ofs = hint - k;
1364 }
1365 else {
1366 /* a[hint] <= key -- gallop right, until
1367 * a[hint + lastofs] <= key < a[hint + ofs]
1368 */
1369 const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
1370 while (ofs < maxofs) {
1371 IFLT(key, a[ofs])
1372 break;
1373 /* a[hint + ofs] <= key */
1374 lastofs = ofs;
1375 ofs = (ofs << 1) + 1;
1376 if (ofs <= 0) /* int overflow */
1377 ofs = maxofs;
1378 }
1379 if (ofs > maxofs)
1380 ofs = maxofs;
1381 /* Translate back to offsets relative to &a[0]. */
1382 lastofs += hint;
1383 ofs += hint;
1384 }
1385 a -= hint;
Tim Petersa64dc242002-08-01 02:13:36 +00001386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
1388 /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
1389 * right of lastofs but no farther right than ofs. Do a binary
1390 * search, with invariant a[lastofs-1] <= key < a[ofs].
1391 */
1392 ++lastofs;
1393 while (lastofs < ofs) {
1394 Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 IFLT(key, a[m])
1397 ofs = m; /* key < a[m] */
1398 else
1399 lastofs = m+1; /* a[m] <= key */
1400 }
1401 assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
1402 return ofs;
Tim Petersa64dc242002-08-01 02:13:36 +00001403
1404fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001406}
1407
1408/* The maximum number of entries in a MergeState's pending-runs stack.
1409 * This is enough to sort arrays of size up to about
1410 * 32 * phi ** MAX_MERGE_PENDING
1411 * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
1412 * with 2**64 elements.
1413 */
1414#define MAX_MERGE_PENDING 85
1415
Tim Peterse05f65a2002-08-10 05:21:15 +00001416/* When we get into galloping mode, we stay there until both runs win less
1417 * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
Tim Petersa64dc242002-08-01 02:13:36 +00001418 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001419#define MIN_GALLOP 7
Tim Petersa64dc242002-08-01 02:13:36 +00001420
1421/* Avoid malloc for small temp arrays. */
1422#define MERGESTATE_TEMP_SIZE 256
1423
1424/* One MergeState exists on the stack per invocation of mergesort. It's just
1425 * a convenient way to pass state around among the helper functions.
1426 */
Tim Peterse05f65a2002-08-10 05:21:15 +00001427struct s_slice {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001428 sortslice base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 Py_ssize_t len;
Tim Peterse05f65a2002-08-10 05:21:15 +00001430};
1431
Tim Petersa64dc242002-08-01 02:13:36 +00001432typedef struct s_MergeState {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 /* This controls when we get *into* galloping mode. It's initialized
1434 * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
1435 * random data, and lower for highly structured data.
1436 */
1437 Py_ssize_t min_gallop;
Tim Peterse05f65a2002-08-10 05:21:15 +00001438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 /* 'a' is temp storage to help with merges. It contains room for
1440 * alloced entries.
1441 */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001442 sortslice a; /* may point to temparray below */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 Py_ssize_t alloced;
Tim Petersa64dc242002-08-01 02:13:36 +00001444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 /* A stack of n pending runs yet to be merged. Run #i starts at
1446 * address base[i] and extends for len[i] elements. It's always
1447 * true (so long as the indices are in bounds) that
1448 *
1449 * pending[i].base + pending[i].len == pending[i+1].base
1450 *
1451 * so we could cut the storage for this, but it's a minor amount,
1452 * and keeping all the info explicit simplifies the code.
1453 */
1454 int n;
1455 struct s_slice pending[MAX_MERGE_PENDING];
Tim Petersa64dc242002-08-01 02:13:36 +00001456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 /* 'a' points to this when possible, rather than muck with malloc. */
1458 PyObject *temparray[MERGESTATE_TEMP_SIZE];
Tim Petersa64dc242002-08-01 02:13:36 +00001459} MergeState;
1460
1461/* Conceptually a MergeState's constructor. */
1462static void
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001463merge_init(MergeState *ms, Py_ssize_t list_size, int has_keyfunc)
Tim Petersa64dc242002-08-01 02:13:36 +00001464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001466 if (has_keyfunc) {
1467 /* The temporary space for merging will need at most half the list
1468 * size rounded up. Use the minimum possible space so we can use the
1469 * rest of temparray for other things. In particular, if there is
1470 * enough extra space, listsort() will use it to store the keys.
1471 */
1472 ms->alloced = (list_size + 1) / 2;
1473
1474 /* ms->alloced describes how many keys will be stored at
1475 ms->temparray, but we also need to store the values. Hence,
1476 ms->alloced is capped at half of MERGESTATE_TEMP_SIZE. */
1477 if (MERGESTATE_TEMP_SIZE / 2 < ms->alloced)
1478 ms->alloced = MERGESTATE_TEMP_SIZE / 2;
1479 ms->a.values = &ms->temparray[ms->alloced];
1480 }
1481 else {
1482 ms->alloced = MERGESTATE_TEMP_SIZE;
1483 ms->a.values = NULL;
1484 }
1485 ms->a.keys = ms->temparray;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 ms->n = 0;
1487 ms->min_gallop = MIN_GALLOP;
Tim Petersa64dc242002-08-01 02:13:36 +00001488}
1489
1490/* Free all the temp memory owned by the MergeState. This must be called
1491 * when you're done with a MergeState, and may be called before then if
1492 * you want to free the temp memory early.
1493 */
1494static void
1495merge_freemem(MergeState *ms)
1496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 assert(ms != NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001498 if (ms->a.keys != ms->temparray)
1499 PyMem_Free(ms->a.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001500}
1501
1502/* Ensure enough temp memory for 'need' array slots is available.
1503 * Returns 0 on success and -1 if the memory can't be gotten.
1504 */
1505static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001506merge_getmem(MergeState *ms, Py_ssize_t need)
Tim Petersa64dc242002-08-01 02:13:36 +00001507{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001508 int multiplier;
1509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 assert(ms != NULL);
1511 if (need <= ms->alloced)
1512 return 0;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001513
1514 multiplier = ms->a.values != NULL ? 2 : 1;
1515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 /* Don't realloc! That can cost cycles to copy the old data, but
1517 * we don't care what's in the block.
1518 */
1519 merge_freemem(ms);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001520 if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject*) / multiplier) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 PyErr_NoMemory();
1522 return -1;
1523 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001524 ms->a.keys = (PyObject**)PyMem_Malloc(multiplier * need
1525 * sizeof(PyObject *));
1526 if (ms->a.keys != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 ms->alloced = need;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001528 if (ms->a.values != NULL)
1529 ms->a.values = &ms->a.keys[need];
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 return 0;
1531 }
1532 PyErr_NoMemory();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 return -1;
Tim Petersa64dc242002-08-01 02:13:36 +00001534}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
1536 merge_getmem(MS, NEED))
Tim Petersa64dc242002-08-01 02:13:36 +00001537
Daniel Stutzbach98338222010-12-02 21:55:33 +00001538/* Merge the na elements starting at ssa with the nb elements starting at
1539 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1540 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1541 * should have na <= nb. See listsort.txt for more info. Return 0 if
1542 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001543 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001544static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001545merge_lo(MergeState *ms, sortslice ssa, Py_ssize_t na,
1546 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001549 sortslice dest;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 int result = -1; /* guilty until proved innocent */
1551 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001552
Daniel Stutzbach98338222010-12-02 21:55:33 +00001553 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1554 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 if (MERGE_GETMEM(ms, na) < 0)
1556 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001557 sortslice_memcpy(&ms->a, 0, &ssa, 0, na);
1558 dest = ssa;
1559 ssa = ms->a;
Tim Petersa64dc242002-08-01 02:13:36 +00001560
Daniel Stutzbach98338222010-12-02 21:55:33 +00001561 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 --nb;
1563 if (nb == 0)
1564 goto Succeed;
1565 if (na == 1)
1566 goto CopyB;
Tim Petersa64dc242002-08-01 02:13:36 +00001567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 min_gallop = ms->min_gallop;
1569 for (;;) {
1570 Py_ssize_t acount = 0; /* # of times A won in a row */
1571 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 /* Do the straightforward thing until (if ever) one run
1574 * appears to win consistently.
1575 */
1576 for (;;) {
1577 assert(na > 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001578 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 if (k) {
1580 if (k < 0)
1581 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001582 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 ++bcount;
1584 acount = 0;
1585 --nb;
1586 if (nb == 0)
1587 goto Succeed;
1588 if (bcount >= min_gallop)
1589 break;
1590 }
1591 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001592 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 ++acount;
1594 bcount = 0;
1595 --na;
1596 if (na == 1)
1597 goto CopyB;
1598 if (acount >= min_gallop)
1599 break;
1600 }
1601 }
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 /* One run is winning so consistently that galloping may
1604 * be a huge win. So try that, and continue galloping until
1605 * (if ever) neither run appears to be winning consistently
1606 * anymore.
1607 */
1608 ++min_gallop;
1609 do {
1610 assert(na > 1 && nb > 0);
1611 min_gallop -= min_gallop > 1;
1612 ms->min_gallop = min_gallop;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001613 k = gallop_right(ssb.keys[0], ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 acount = k;
1615 if (k) {
1616 if (k < 0)
1617 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001618 sortslice_memcpy(&dest, 0, &ssa, 0, k);
1619 sortslice_advance(&dest, k);
1620 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 na -= k;
1622 if (na == 1)
1623 goto CopyB;
1624 /* na==0 is impossible now if the comparison
1625 * function is consistent, but we can't assume
1626 * that it is.
1627 */
1628 if (na == 0)
1629 goto Succeed;
1630 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001631 sortslice_copy_incr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 --nb;
1633 if (nb == 0)
1634 goto Succeed;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001635
Daniel Stutzbach98338222010-12-02 21:55:33 +00001636 k = gallop_left(ssa.keys[0], ssb.keys, nb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 bcount = k;
1638 if (k) {
1639 if (k < 0)
1640 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001641 sortslice_memmove(&dest, 0, &ssb, 0, k);
1642 sortslice_advance(&dest, k);
1643 sortslice_advance(&ssb, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001644 nb -= k;
1645 if (nb == 0)
1646 goto Succeed;
1647 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001648 sortslice_copy_incr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 --na;
1650 if (na == 1)
1651 goto CopyB;
1652 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1653 ++min_gallop; /* penalize it for leaving galloping mode */
1654 ms->min_gallop = min_gallop;
1655 }
Tim Petersa64dc242002-08-01 02:13:36 +00001656Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001658Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 if (na)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001660 sortslice_memcpy(&dest, 0, &ssa, 0, na);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001662CopyB:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 assert(na == 1 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001664 /* The last element of ssa belongs at the end of the merge. */
1665 sortslice_memmove(&dest, 0, &ssb, 0, nb);
1666 sortslice_copy(&dest, nb, &ssa, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001668}
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001669
Daniel Stutzbach98338222010-12-02 21:55:33 +00001670/* Merge the na elements starting at pa with the nb elements starting at
1671 * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
1672 * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
1673 * should have na >= nb. See listsort.txt for more info. Return 0 if
1674 * successful, -1 if error.
Tim Petersa64dc242002-08-01 02:13:36 +00001675 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001676static Py_ssize_t
Daniel Stutzbach98338222010-12-02 21:55:33 +00001677merge_hi(MergeState *ms, sortslice ssa, Py_ssize_t na,
1678 sortslice ssb, Py_ssize_t nb)
Tim Petersa64dc242002-08-01 02:13:36 +00001679{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 Py_ssize_t k;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001681 sortslice dest, basea, baseb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 int result = -1; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 Py_ssize_t min_gallop;
Tim Petersa64dc242002-08-01 02:13:36 +00001684
Daniel Stutzbach98338222010-12-02 21:55:33 +00001685 assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
1686 assert(ssa.keys + na == ssb.keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 if (MERGE_GETMEM(ms, nb) < 0)
1688 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001689 dest = ssb;
1690 sortslice_advance(&dest, nb-1);
1691 sortslice_memcpy(&ms->a, 0, &ssb, 0, nb);
1692 basea = ssa;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 baseb = ms->a;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001694 ssb.keys = ms->a.keys + nb - 1;
1695 if (ssb.values != NULL)
1696 ssb.values = ms->a.values + nb - 1;
1697 sortslice_advance(&ssa, na - 1);
Tim Petersa64dc242002-08-01 02:13:36 +00001698
Daniel Stutzbach98338222010-12-02 21:55:33 +00001699 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 --na;
1701 if (na == 0)
1702 goto Succeed;
1703 if (nb == 1)
1704 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 min_gallop = ms->min_gallop;
1707 for (;;) {
1708 Py_ssize_t acount = 0; /* # of times A won in a row */
1709 Py_ssize_t bcount = 0; /* # of times B won in a row */
Tim Petersa64dc242002-08-01 02:13:36 +00001710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 /* Do the straightforward thing until (if ever) one run
1712 * appears to win consistently.
1713 */
1714 for (;;) {
1715 assert(na > 0 && nb > 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001716 k = ISLT(ssb.keys[0], ssa.keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 if (k) {
1718 if (k < 0)
1719 goto Fail;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001720 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 ++acount;
1722 bcount = 0;
1723 --na;
1724 if (na == 0)
1725 goto Succeed;
1726 if (acount >= min_gallop)
1727 break;
1728 }
1729 else {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001730 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 ++bcount;
1732 acount = 0;
1733 --nb;
1734 if (nb == 1)
1735 goto CopyA;
1736 if (bcount >= min_gallop)
1737 break;
1738 }
1739 }
Tim Petersa64dc242002-08-01 02:13:36 +00001740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 /* One run is winning so consistently that galloping may
1742 * be a huge win. So try that, and continue galloping until
1743 * (if ever) neither run appears to be winning consistently
1744 * anymore.
1745 */
1746 ++min_gallop;
1747 do {
1748 assert(na > 0 && nb > 1);
1749 min_gallop -= min_gallop > 1;
1750 ms->min_gallop = min_gallop;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001751 k = gallop_right(ssb.keys[0], basea.keys, na, na-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 if (k < 0)
1753 goto Fail;
1754 k = na - k;
1755 acount = k;
1756 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001757 sortslice_advance(&dest, -k);
1758 sortslice_advance(&ssa, -k);
1759 sortslice_memmove(&dest, 1, &ssa, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 na -= k;
1761 if (na == 0)
1762 goto Succeed;
1763 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001764 sortslice_copy_decr(&dest, &ssb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 --nb;
1766 if (nb == 1)
1767 goto CopyA;
Tim Petersa64dc242002-08-01 02:13:36 +00001768
Daniel Stutzbach98338222010-12-02 21:55:33 +00001769 k = gallop_left(ssa.keys[0], baseb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 if (k < 0)
1771 goto Fail;
1772 k = nb - k;
1773 bcount = k;
1774 if (k) {
Daniel Stutzbach98338222010-12-02 21:55:33 +00001775 sortslice_advance(&dest, -k);
1776 sortslice_advance(&ssb, -k);
1777 sortslice_memcpy(&dest, 1, &ssb, 1, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 nb -= k;
1779 if (nb == 1)
1780 goto CopyA;
1781 /* nb==0 is impossible now if the comparison
1782 * function is consistent, but we can't assume
1783 * that it is.
1784 */
1785 if (nb == 0)
1786 goto Succeed;
1787 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00001788 sortslice_copy_decr(&dest, &ssa);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 --na;
1790 if (na == 0)
1791 goto Succeed;
1792 } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
1793 ++min_gallop; /* penalize it for leaving galloping mode */
1794 ms->min_gallop = min_gallop;
1795 }
Tim Petersa64dc242002-08-01 02:13:36 +00001796Succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 result = 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001798Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 if (nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001800 sortslice_memcpy(&dest, -(nb-1), &baseb, 0, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 return result;
Tim Petersa64dc242002-08-01 02:13:36 +00001802CopyA:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 assert(nb == 1 && na > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001804 /* The first element of ssb belongs at the front of the merge. */
1805 sortslice_memmove(&dest, 1-na, &ssa, 1-na, na);
1806 sortslice_advance(&dest, -na);
1807 sortslice_advance(&ssa, -na);
1808 sortslice_copy(&dest, 0, &ssb, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001810}
1811
1812/* Merge the two runs at stack indices i and i+1.
1813 * Returns 0 on success, -1 on error.
1814 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001815static Py_ssize_t
1816merge_at(MergeState *ms, Py_ssize_t i)
Tim Petersa64dc242002-08-01 02:13:36 +00001817{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001818 sortslice ssa, ssb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 Py_ssize_t na, nb;
1820 Py_ssize_t k;
Tim Petersa64dc242002-08-01 02:13:36 +00001821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 assert(ms != NULL);
1823 assert(ms->n >= 2);
1824 assert(i >= 0);
1825 assert(i == ms->n - 2 || i == ms->n - 3);
Tim Petersa64dc242002-08-01 02:13:36 +00001826
Daniel Stutzbach98338222010-12-02 21:55:33 +00001827 ssa = ms->pending[i].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 na = ms->pending[i].len;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001829 ssb = ms->pending[i+1].base;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 nb = ms->pending[i+1].len;
1831 assert(na > 0 && nb > 0);
Daniel Stutzbach98338222010-12-02 21:55:33 +00001832 assert(ssa.keys + na == ssb.keys);
Tim Petersa64dc242002-08-01 02:13:36 +00001833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 /* Record the length of the combined runs; if i is the 3rd-last
1835 * run now, also slide over the last run (which isn't involved
1836 * in this merge). The current run i+1 goes away in any case.
1837 */
1838 ms->pending[i].len = na + nb;
1839 if (i == ms->n - 3)
1840 ms->pending[i+1] = ms->pending[i+2];
1841 --ms->n;
Tim Petersa64dc242002-08-01 02:13:36 +00001842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 /* Where does b start in a? Elements in a before that can be
1844 * ignored (already in place).
1845 */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001846 k = gallop_right(*ssb.keys, ssa.keys, na, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 if (k < 0)
1848 return -1;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001849 sortslice_advance(&ssa, k);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001850 na -= k;
1851 if (na == 0)
1852 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 /* Where does a end in b? Elements in b after that can be
1855 * ignored (already in place).
1856 */
Daniel Stutzbach98338222010-12-02 21:55:33 +00001857 nb = gallop_left(ssa.keys[na-1], ssb.keys, nb, nb-1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 if (nb <= 0)
1859 return nb;
Tim Petersa64dc242002-08-01 02:13:36 +00001860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 /* Merge what remains of the runs, using a temp array with
1862 * min(na, nb) elements.
1863 */
1864 if (na <= nb)
Daniel Stutzbach98338222010-12-02 21:55:33 +00001865 return merge_lo(ms, ssa, na, ssb, nb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 else
Daniel Stutzbach98338222010-12-02 21:55:33 +00001867 return merge_hi(ms, ssa, na, ssb, nb);
Tim Petersa64dc242002-08-01 02:13:36 +00001868}
1869
1870/* Examine the stack of runs waiting to be merged, merging adjacent runs
1871 * until the stack invariants are re-established:
1872 *
1873 * 1. len[-3] > len[-2] + len[-1]
1874 * 2. len[-2] > len[-1]
1875 *
1876 * See listsort.txt for more info.
1877 *
1878 * Returns 0 on success, -1 on error.
1879 */
1880static int
1881merge_collapse(MergeState *ms)
1882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 assert(ms);
1886 while (ms->n > 1) {
1887 Py_ssize_t n = ms->n - 2;
Benjamin Petersonb808d592015-02-25 10:12:26 -05001888 if ((n > 0 && p[n-1].len <= p[n].len + p[n+1].len) ||
1889 (n > 1 && p[n-2].len <= p[n-1].len + p[n].len)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 if (p[n-1].len < p[n+1].len)
1891 --n;
1892 if (merge_at(ms, n) < 0)
1893 return -1;
1894 }
1895 else if (p[n].len <= p[n+1].len) {
1896 if (merge_at(ms, n) < 0)
1897 return -1;
1898 }
1899 else
1900 break;
1901 }
1902 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001903}
1904
1905/* Regardless of invariants, merge all runs on the stack until only one
1906 * remains. This is used at the end of the mergesort.
1907 *
1908 * Returns 0 on success, -1 on error.
1909 */
1910static int
1911merge_force_collapse(MergeState *ms)
1912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 struct s_slice *p = ms->pending;
Tim Petersa64dc242002-08-01 02:13:36 +00001914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 assert(ms);
1916 while (ms->n > 1) {
1917 Py_ssize_t n = ms->n - 2;
1918 if (n > 0 && p[n-1].len < p[n+1].len)
1919 --n;
1920 if (merge_at(ms, n) < 0)
1921 return -1;
1922 }
1923 return 0;
Tim Petersa64dc242002-08-01 02:13:36 +00001924}
1925
1926/* Compute a good value for the minimum run length; natural runs shorter
1927 * than this are boosted artificially via binary insertion.
1928 *
1929 * If n < 64, return n (it's too small to bother with fancy stuff).
1930 * Else if n is an exact power of 2, return 32.
1931 * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
1932 * strictly less than, an exact power of 2.
1933 *
1934 * See listsort.txt for more info.
1935 */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001936static Py_ssize_t
1937merge_compute_minrun(Py_ssize_t n)
Tim Petersa64dc242002-08-01 02:13:36 +00001938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
Tim Petersa64dc242002-08-01 02:13:36 +00001940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 assert(n >= 0);
1942 while (n >= 64) {
1943 r |= n & 1;
1944 n >>= 1;
1945 }
1946 return n + r;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001947}
Guido van Rossuma119c0d1998-05-29 17:56:32 +00001948
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001949static void
Daniel Stutzbach98338222010-12-02 21:55:33 +00001950reverse_sortslice(sortslice *s, Py_ssize_t n)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001951{
Daniel Stutzbach98338222010-12-02 21:55:33 +00001952 reverse_slice(s->keys, &s->keys[n]);
1953 if (s->values != NULL)
1954 reverse_slice(s->values, &s->values[n]);
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001955}
1956
Tim Petersa64dc242002-08-01 02:13:36 +00001957/* An adaptive, stable, natural mergesort. See listsort.txt.
1958 * Returns Py_None on success, NULL on error. Even in case of error, the
1959 * list will be some permutation of its input state (nothing is lost or
1960 * duplicated).
1961 */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02001962/*[clinic input]
1963list.sort
1964
1965 *
1966 key as keyfunc: object = None
Serhiy Storchaka202fda52017-03-12 10:10:47 +02001967 reverse: bool(accept={int}) = False
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02001968
1969Stable sort *IN PLACE*.
1970[clinic start generated code]*/
1971
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001972static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02001973list_sort_impl(PyListObject *self, PyObject *keyfunc, int reverse)
Serhiy Storchaka202fda52017-03-12 10:10:47 +02001974/*[clinic end generated code: output=57b9f9c5e23fbe42 input=b0fcf743982c5b90]*/
Guido van Rossum3f236de1996-12-10 23:55:39 +00001975{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 MergeState ms;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 Py_ssize_t nremaining;
1978 Py_ssize_t minrun;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001979 sortslice lo;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 Py_ssize_t saved_ob_size, saved_allocated;
1981 PyObject **saved_ob_item;
1982 PyObject **final_ob_item;
1983 PyObject *result = NULL; /* guilty until proved innocent */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 Py_ssize_t i;
Daniel Stutzbach98338222010-12-02 21:55:33 +00001985 PyObject **keys;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00001986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 assert(self != NULL);
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02001988 assert(PyList_Check(self));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 if (keyfunc == Py_None)
1990 keyfunc = NULL;
Raymond Hettinger42b1ba32003-10-16 03:41:09 +00001991
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 /* The list is temporarily made empty, so that mutations performed
1993 * by comparison functions can't affect the slice of memory we're
1994 * sorting (allowing mutations during sorting is a core-dump
1995 * factory, since ob_item may change).
1996 */
1997 saved_ob_size = Py_SIZE(self);
1998 saved_ob_item = self->ob_item;
1999 saved_allocated = self->allocated;
2000 Py_SIZE(self) = 0;
2001 self->ob_item = NULL;
2002 self->allocated = -1; /* any operation will reset it to >= 0 */
Tim Peters330f9e92002-07-19 07:05:44 +00002003
Daniel Stutzbach98338222010-12-02 21:55:33 +00002004 if (keyfunc == NULL) {
2005 keys = NULL;
2006 lo.keys = saved_ob_item;
2007 lo.values = NULL;
2008 }
2009 else {
2010 if (saved_ob_size < MERGESTATE_TEMP_SIZE/2)
2011 /* Leverage stack space we allocated but won't otherwise use */
2012 keys = &ms.temparray[saved_ob_size+1];
2013 else {
2014 keys = PyMem_MALLOC(sizeof(PyObject *) * saved_ob_size);
Benjamin Peterson0823ffb2015-04-23 17:04:36 -04002015 if (keys == NULL) {
2016 PyErr_NoMemory();
2017 goto keyfunc_fail;
2018 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 }
Daniel Stutzbach98338222010-12-02 21:55:33 +00002020
2021 for (i = 0; i < saved_ob_size ; i++) {
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01002022 keys[i] = PyObject_CallFunctionObjArgs(keyfunc, saved_ob_item[i],
2023 NULL);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002024 if (keys[i] == NULL) {
2025 for (i=i-1 ; i>=0 ; i--)
2026 Py_DECREF(keys[i]);
Benjamin Peterson4a42cd42014-03-15 12:21:28 -05002027 if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
Daniel Stutzbach8eda5f72011-03-02 23:37:50 +00002028 PyMem_FREE(keys);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002029 goto keyfunc_fail;
2030 }
2031 }
2032
2033 lo.keys = keys;
2034 lo.values = saved_ob_item;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002036
Daniel Stutzbach98338222010-12-02 21:55:33 +00002037 merge_init(&ms, saved_ob_size, keys != NULL);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 nremaining = saved_ob_size;
2040 if (nremaining < 2)
2041 goto succeed;
Tim Peters330f9e92002-07-19 07:05:44 +00002042
Benjamin Peterson05380642010-08-23 19:35:39 +00002043 /* Reverse sort stability achieved by initially reversing the list,
2044 applying a stable forward sort, then reversing the final result. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002045 if (reverse) {
2046 if (keys != NULL)
2047 reverse_slice(&keys[0], &keys[saved_ob_size]);
2048 reverse_slice(&saved_ob_item[0], &saved_ob_item[saved_ob_size]);
2049 }
Benjamin Peterson05380642010-08-23 19:35:39 +00002050
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 /* March over the array once, left to right, finding natural runs,
2052 * and extending short natural runs to minrun elements.
2053 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 minrun = merge_compute_minrun(nremaining);
2055 do {
2056 int descending;
2057 Py_ssize_t n;
Tim Peters330f9e92002-07-19 07:05:44 +00002058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 /* Identify next run. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002060 n = count_run(lo.keys, lo.keys + nremaining, &descending);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 if (n < 0)
2062 goto fail;
2063 if (descending)
Daniel Stutzbach98338222010-12-02 21:55:33 +00002064 reverse_sortslice(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 /* If short, extend to min(minrun, nremaining). */
2066 if (n < minrun) {
2067 const Py_ssize_t force = nremaining <= minrun ?
2068 nremaining : minrun;
Daniel Stutzbach98338222010-12-02 21:55:33 +00002069 if (binarysort(lo, lo.keys + force, lo.keys + n) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 goto fail;
2071 n = force;
2072 }
2073 /* Push run onto pending-runs stack, and maybe merge. */
2074 assert(ms.n < MAX_MERGE_PENDING);
2075 ms.pending[ms.n].base = lo;
2076 ms.pending[ms.n].len = n;
2077 ++ms.n;
2078 if (merge_collapse(&ms) < 0)
2079 goto fail;
2080 /* Advance to find next run. */
Daniel Stutzbach98338222010-12-02 21:55:33 +00002081 sortslice_advance(&lo, n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 nremaining -= n;
2083 } while (nremaining);
Tim Peters330f9e92002-07-19 07:05:44 +00002084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 if (merge_force_collapse(&ms) < 0)
2086 goto fail;
2087 assert(ms.n == 1);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002088 assert(keys == NULL
2089 ? ms.pending[0].base.keys == saved_ob_item
2090 : ms.pending[0].base.keys == &keys[0]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 assert(ms.pending[0].len == saved_ob_size);
Daniel Stutzbach98338222010-12-02 21:55:33 +00002092 lo = ms.pending[0].base;
Tim Petersa64dc242002-08-01 02:13:36 +00002093
2094succeed:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 result = Py_None;
Tim Peters330f9e92002-07-19 07:05:44 +00002096fail:
Daniel Stutzbach98338222010-12-02 21:55:33 +00002097 if (keys != NULL) {
2098 for (i = 0; i < saved_ob_size; i++)
2099 Py_DECREF(keys[i]);
Benjamin Petersonef87f8c2014-03-14 21:54:31 -05002100 if (saved_ob_size >= MERGESTATE_TEMP_SIZE/2)
Daniel Stutzbach98338222010-12-02 21:55:33 +00002101 PyMem_FREE(keys);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 if (self->allocated != -1 && result != NULL) {
2105 /* The user mucked with the list during the sort,
2106 * and we don't already have another error to report.
2107 */
2108 PyErr_SetString(PyExc_ValueError, "list modified during sort");
2109 result = NULL;
2110 }
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 if (reverse && saved_ob_size > 1)
2113 reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 merge_freemem(&ms);
Michael W. Hudson1df0f652003-12-04 11:25:46 +00002116
Daniel Stutzbach98338222010-12-02 21:55:33 +00002117keyfunc_fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 final_ob_item = self->ob_item;
2119 i = Py_SIZE(self);
2120 Py_SIZE(self) = saved_ob_size;
2121 self->ob_item = saved_ob_item;
2122 self->allocated = saved_allocated;
2123 if (final_ob_item != NULL) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002124 /* we cannot use _list_clear() for this because it does not
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 guarantee that the list is really empty when it returns */
2126 while (--i >= 0) {
2127 Py_XDECREF(final_ob_item[i]);
2128 }
2129 PyMem_FREE(final_ob_item);
2130 }
2131 Py_XINCREF(result);
2132 return result;
Guido van Rossum3f236de1996-12-10 23:55:39 +00002133}
Tim Peters330f9e92002-07-19 07:05:44 +00002134#undef IFLT
Tim Peters66860f62002-08-04 17:47:26 +00002135#undef ISLT
Tim Peters330f9e92002-07-19 07:05:44 +00002136
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002137int
Fred Drakea2f55112000-07-09 15:16:51 +00002138PyList_Sort(PyObject *v)
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 if (v == NULL || !PyList_Check(v)) {
2141 PyErr_BadInternalCall();
2142 return -1;
2143 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002144 v = list_sort_impl((PyListObject *)v, NULL, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 if (v == NULL)
2146 return -1;
2147 Py_DECREF(v);
2148 return 0;
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002149}
2150
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002151/*[clinic input]
2152list.reverse
2153
2154Reverse *IN PLACE*.
2155[clinic start generated code]*/
2156
Guido van Rossumb86c5492001-02-12 22:06:02 +00002157static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002158list_reverse_impl(PyListObject *self)
2159/*[clinic end generated code: output=482544fc451abea9 input=eefd4c3ae1bc9887]*/
Guido van Rossumb86c5492001-02-12 22:06:02 +00002160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 if (Py_SIZE(self) > 1)
2162 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2163 Py_RETURN_NONE;
Guido van Rossumed98d481991-03-06 13:07:53 +00002164}
2165
Guido van Rossum84c76f51990-10-30 13:32:20 +00002166int
Fred Drakea2f55112000-07-09 15:16:51 +00002167PyList_Reverse(PyObject *v)
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002168{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 PyListObject *self = (PyListObject *)v;
Tim Peters6063e262002-08-08 01:06:39 +00002170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 if (v == NULL || !PyList_Check(v)) {
2172 PyErr_BadInternalCall();
2173 return -1;
2174 }
2175 if (Py_SIZE(self) > 1)
2176 reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
2177 return 0;
Guido van Rossumb0fe3a91995-01-17 16:34:45 +00002178}
2179
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002180PyObject *
Fred Drakea2f55112000-07-09 15:16:51 +00002181PyList_AsTuple(PyObject *v)
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002182{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 PyObject *w;
2184 PyObject **p, **q;
2185 Py_ssize_t n;
2186 if (v == NULL || !PyList_Check(v)) {
2187 PyErr_BadInternalCall();
2188 return NULL;
2189 }
2190 n = Py_SIZE(v);
2191 w = PyTuple_New(n);
2192 if (w == NULL)
2193 return NULL;
2194 p = ((PyTupleObject *)w)->ob_item;
2195 q = ((PyListObject *)v)->ob_item;
2196 while (--n >= 0) {
2197 Py_INCREF(*q);
2198 *p = *q;
2199 p++;
2200 q++;
2201 }
2202 return w;
Guido van Rossum6cd2fe01994-08-29 12:45:32 +00002203}
2204
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002205/*[clinic input]
2206list.index
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002207
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002208 value: object
Serhiy Storchaka80ec8362017-03-19 19:37:40 +02002209 start: slice_index(accept={int}) = 0
2210 stop: slice_index(accept={int}, c_default="PY_SSIZE_T_MAX") = sys.maxsize
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002211 /
2212
2213Return first index of value.
2214
2215Raises ValueError if the value is not present.
2216[clinic start generated code]*/
2217
2218static PyObject *
2219list_index_impl(PyListObject *self, PyObject *value, Py_ssize_t start,
2220 Py_ssize_t stop)
Serhiy Storchaka80ec8362017-03-19 19:37:40 +02002221/*[clinic end generated code: output=ec51b88787e4e481 input=40ec5826303a0eb1]*/
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002222{
2223 Py_ssize_t i;
2224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 if (start < 0) {
2226 start += Py_SIZE(self);
2227 if (start < 0)
2228 start = 0;
2229 }
2230 if (stop < 0) {
2231 stop += Py_SIZE(self);
2232 if (stop < 0)
2233 stop = 0;
2234 }
2235 for (i = start; i < stop && i < Py_SIZE(self); i++) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002236 int cmp = PyObject_RichCompareBool(self->ob_item[i], value, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 if (cmp > 0)
2238 return PyLong_FromSsize_t(i);
2239 else if (cmp < 0)
2240 return NULL;
2241 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002242 PyErr_Format(PyExc_ValueError, "%R is not in list", value);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002244}
2245
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002246/*[clinic input]
2247list.count
2248
2249 value: object
2250 /
2251
2252Return number of occurrences of value.
2253[clinic start generated code]*/
2254
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002255static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002256list_count(PyListObject *self, PyObject *value)
2257/*[clinic end generated code: output=b1f5d284205ae714 input=3bdc3a5e6f749565]*/
Guido van Rossume6f7d181991-10-20 20:20:40 +00002258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 Py_ssize_t count = 0;
2260 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 for (i = 0; i < Py_SIZE(self); i++) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002263 int cmp = PyObject_RichCompareBool(self->ob_item[i], value, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 if (cmp > 0)
2265 count++;
2266 else if (cmp < 0)
2267 return NULL;
2268 }
2269 return PyLong_FromSsize_t(count);
Guido van Rossume6f7d181991-10-20 20:20:40 +00002270}
2271
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002272/*[clinic input]
2273list.remove
2274
2275 value: object
2276 /
2277
2278Remove first occurrence of value.
2279
2280Raises ValueError if the value is not present.
2281[clinic start generated code]*/
2282
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002283static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002284list_remove(PyListObject *self, PyObject *value)
2285/*[clinic end generated code: output=f087e1951a5e30d1 input=2dc2ba5bb2fb1f82]*/
Guido van Rossumed98d481991-03-06 13:07:53 +00002286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 Py_ssize_t i;
Guido van Rossum4aa24f92000-02-24 15:23:03 +00002288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 for (i = 0; i < Py_SIZE(self); i++) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002290 int cmp = PyObject_RichCompareBool(self->ob_item[i], value, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 if (cmp > 0) {
2292 if (list_ass_slice(self, i, i+1,
2293 (PyObject *)NULL) == 0)
2294 Py_RETURN_NONE;
2295 return NULL;
2296 }
2297 else if (cmp < 0)
2298 return NULL;
2299 }
2300 PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
2301 return NULL;
Guido van Rossumed98d481991-03-06 13:07:53 +00002302}
2303
Jeremy Hylton8caad492000-06-23 14:18:11 +00002304static int
2305list_traverse(PyListObject *o, visitproc visit, void *arg)
2306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 Py_ssize_t i;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 for (i = Py_SIZE(o); --i >= 0; )
2310 Py_VISIT(o->ob_item[i]);
2311 return 0;
Jeremy Hylton8caad492000-06-23 14:18:11 +00002312}
2313
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002314static PyObject *
2315list_richcompare(PyObject *v, PyObject *w, int op)
2316{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 PyListObject *vl, *wl;
2318 Py_ssize_t i;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002319
Brian Curtindfc80e32011-08-10 20:28:54 -05002320 if (!PyList_Check(v) || !PyList_Check(w))
2321 Py_RETURN_NOTIMPLEMENTED;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 vl = (PyListObject *)v;
2324 wl = (PyListObject *)w;
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
2327 /* Shortcut: if the lengths differ, the lists differ */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 if (op == Py_EQ)
stratakise8b19652017-11-02 11:32:54 +01002329 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 else
stratakise8b19652017-11-02 11:32:54 +01002331 Py_RETURN_TRUE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002332 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 /* Search for the first index where items are different */
2335 for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
2336 int k = PyObject_RichCompareBool(vl->ob_item[i],
2337 wl->ob_item[i], Py_EQ);
2338 if (k < 0)
2339 return NULL;
2340 if (!k)
2341 break;
2342 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
2345 /* No more items to compare -- compare sizes */
stratakise8b19652017-11-02 11:32:54 +01002346 Py_RETURN_RICHCOMPARE(Py_SIZE(vl), Py_SIZE(wl), op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 /* We have an item that differs -- shortcuts for EQ/NE */
2350 if (op == Py_EQ) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002351 Py_RETURN_FALSE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 }
2353 if (op == Py_NE) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02002354 Py_RETURN_TRUE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 }
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 /* Compare the final item again using the proper operator */
2358 return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
Guido van Rossum65e1cea2001-01-17 22:11:59 +00002359}
2360
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002361/*[clinic input]
2362list.__init__
2363
2364 iterable: object(c_default="NULL") = ()
2365 /
2366
2367Built-in mutable sequence.
2368
2369If no argument is given, the constructor creates a new empty list.
2370The argument must be an iterable if specified.
2371[clinic start generated code]*/
2372
Tim Peters6d6c1a32001-08-02 04:15:00 +00002373static int
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002374list___init___impl(PyListObject *self, PyObject *iterable)
2375/*[clinic end generated code: output=0f3c21379d01de48 input=b3f3fe7206af8f6b]*/
Tim Peters6d6c1a32001-08-02 04:15:00 +00002376{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 /* Verify list invariants established by PyType_GenericAlloc() */
2378 assert(0 <= Py_SIZE(self));
2379 assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
2380 assert(self->ob_item != NULL ||
2381 self->allocated == 0 || self->allocated == -1);
Raymond Hettingerc0aaa2d2004-07-29 23:31:29 +00002382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 /* Empty previous contents */
2384 if (self->ob_item != NULL) {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002385 (void)_list_clear(self);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 }
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002387 if (iterable != NULL) {
2388 PyObject *rv = list_extend(self, iterable);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 if (rv == NULL)
2390 return -1;
2391 Py_DECREF(rv);
2392 }
2393 return 0;
Tim Peters6d6c1a32001-08-02 04:15:00 +00002394}
2395
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002396/*[clinic input]
2397list.__sizeof__
2398
2399Return the size of the list in memory, in bytes.
2400[clinic start generated code]*/
2401
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002402static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002403list___sizeof___impl(PyListObject *self)
2404/*[clinic end generated code: output=3417541f95f9a53e input=b8030a5d5ce8a187]*/
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 Py_ssize_t res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002407
Serhiy Storchaka5c4064e2015-12-19 20:05:25 +02002408 res = _PyObject_SIZE(Py_TYPE(self)) + self->allocated * sizeof(void*);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 return PyLong_FromSsize_t(res);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002410}
2411
Raymond Hettinger1021c442003-11-07 15:38:09 +00002412static PyObject *list_iter(PyObject *seq);
Raymond Hettinger8f5cdaa2003-12-13 11:26:12 +00002413static PyObject *list_subscript(PyListObject*, PyObject*);
2414
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002415static PyMethodDef list_methods[] = {
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002416 {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, "x.__getitem__(y) <==> x[y]"},
2417 LIST___REVERSED___METHODDEF
2418 LIST___SIZEOF___METHODDEF
2419 LIST_CLEAR_METHODDEF
2420 LIST_COPY_METHODDEF
2421 LIST_APPEND_METHODDEF
2422 LIST_INSERT_METHODDEF
2423 LIST_EXTEND_METHODDEF
2424 LIST_POP_METHODDEF
2425 LIST_REMOVE_METHODDEF
2426 LIST_INDEX_METHODDEF
2427 LIST_COUNT_METHODDEF
2428 LIST_REVERSE_METHODDEF
2429 LIST_SORT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 {NULL, NULL} /* sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002431};
2432
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002433static PySequenceMethods list_as_sequence = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 (lenfunc)list_length, /* sq_length */
2435 (binaryfunc)list_concat, /* sq_concat */
2436 (ssizeargfunc)list_repeat, /* sq_repeat */
2437 (ssizeargfunc)list_item, /* sq_item */
2438 0, /* sq_slice */
2439 (ssizeobjargproc)list_ass_item, /* sq_ass_item */
2440 0, /* sq_ass_slice */
2441 (objobjproc)list_contains, /* sq_contains */
2442 (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
2443 (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002444};
2445
Jeremy Hyltona4b4c3b2002-07-13 03:51:17 +00002446static PyObject *
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002447list_subscript(PyListObject* self, PyObject* item)
2448{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 if (PyIndex_Check(item)) {
2450 Py_ssize_t i;
2451 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2452 if (i == -1 && PyErr_Occurred())
2453 return NULL;
2454 if (i < 0)
2455 i += PyList_GET_SIZE(self);
2456 return list_item(self, i);
2457 }
2458 else if (PySlice_Check(item)) {
2459 Py_ssize_t start, stop, step, slicelength, cur, i;
2460 PyObject* result;
2461 PyObject* it;
2462 PyObject **src, **dest;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002463
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002464 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 return NULL;
2466 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002467 slicelength = PySlice_AdjustIndices(Py_SIZE(self), &start, &stop,
2468 step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 if (slicelength <= 0) {
2471 return PyList_New(0);
2472 }
2473 else if (step == 1) {
2474 return list_slice(self, start, stop);
2475 }
2476 else {
2477 result = PyList_New(slicelength);
2478 if (!result) return NULL;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002480 src = self->ob_item;
2481 dest = ((PyListObject *)result)->ob_item;
2482 for (cur = start, i = 0; i < slicelength;
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002483 cur += (size_t)step, i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 it = src[cur];
2485 Py_INCREF(it);
2486 dest[i] = it;
2487 }
Tim Peters3b01a122002-07-19 02:35:45 +00002488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 return result;
2490 }
2491 }
2492 else {
2493 PyErr_Format(PyExc_TypeError,
Terry Jan Reedyffff1442014-08-02 01:30:37 -04002494 "list indices must be integers or slices, not %.200s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 item->ob_type->tp_name);
2496 return NULL;
2497 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002498}
2499
Tim Peters3b01a122002-07-19 02:35:45 +00002500static int
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002501list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
2502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 if (PyIndex_Check(item)) {
2504 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
2505 if (i == -1 && PyErr_Occurred())
2506 return -1;
2507 if (i < 0)
2508 i += PyList_GET_SIZE(self);
2509 return list_ass_item(self, i, value);
2510 }
2511 else if (PySlice_Check(item)) {
2512 Py_ssize_t start, stop, step, slicelength;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002513
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002514 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002515 return -1;
2516 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +03002517 slicelength = PySlice_AdjustIndices(Py_SIZE(self), &start, &stop,
2518 step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002520 if (step == 1)
2521 return list_ass_slice(self, start, stop, value);
Michael W. Hudson9c14bad2002-06-19 15:44:15 +00002522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 /* Make sure s[5:2] = [..] inserts at the right place:
2524 before 5, not before 2. */
2525 if ((step < 0 && start < stop) ||
2526 (step > 0 && start > stop))
2527 stop = start;
Thomas Woutersed03b412007-08-28 21:37:11 +00002528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 if (value == NULL) {
2530 /* delete slice */
2531 PyObject **garbage;
2532 size_t cur;
2533 Py_ssize_t i;
Victor Stinner35f28032013-11-21 12:16:35 +01002534 int res;
Tim Peters3b01a122002-07-19 02:35:45 +00002535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 if (slicelength <= 0)
2537 return 0;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 if (step < 0) {
2540 stop = start + 1;
2541 start = stop + step*(slicelength - 1) - 1;
2542 step = -step;
2543 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 garbage = (PyObject**)
2546 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2547 if (!garbage) {
2548 PyErr_NoMemory();
2549 return -1;
2550 }
Tim Peters3b01a122002-07-19 02:35:45 +00002551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002552 /* drawing pictures might help understand these for
2553 loops. Basically, we memmove the parts of the
2554 list that are *not* part of the slice: step-1
2555 items for each item that is part of the slice,
2556 and then tail end of the list that was not
2557 covered by the slice */
2558 for (cur = start, i = 0;
2559 cur < (size_t)stop;
2560 cur += step, i++) {
2561 Py_ssize_t lim = step - 1;
Michael W. Hudson56796f62002-07-29 14:35:04 +00002562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 garbage[i] = PyList_GET_ITEM(self, cur);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 if (cur + step >= (size_t)Py_SIZE(self)) {
2566 lim = Py_SIZE(self) - cur - 1;
2567 }
Michael W. Hudson56796f62002-07-29 14:35:04 +00002568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002569 memmove(self->ob_item + cur - i,
2570 self->ob_item + cur + 1,
2571 lim * sizeof(PyObject *));
2572 }
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002573 cur = start + (size_t)slicelength * step;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 if (cur < (size_t)Py_SIZE(self)) {
2575 memmove(self->ob_item + cur - slicelength,
2576 self->ob_item + cur,
2577 (Py_SIZE(self) - cur) *
2578 sizeof(PyObject *));
2579 }
Raymond Hettingera6366fe2004-03-09 13:05:22 +00002580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 Py_SIZE(self) -= slicelength;
Victor Stinner35f28032013-11-21 12:16:35 +01002582 res = list_resize(self, Py_SIZE(self));
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002584 for (i = 0; i < slicelength; i++) {
2585 Py_DECREF(garbage[i]);
2586 }
2587 PyMem_FREE(garbage);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002588
Victor Stinner35f28032013-11-21 12:16:35 +01002589 return res;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002590 }
2591 else {
2592 /* assign slice */
2593 PyObject *ins, *seq;
2594 PyObject **garbage, **seqitems, **selfitems;
2595 Py_ssize_t cur, i;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 /* protect against a[::-1] = a */
2598 if (self == (PyListObject*)value) {
2599 seq = list_slice((PyListObject*)value, 0,
2600 PyList_GET_SIZE(value));
2601 }
2602 else {
2603 seq = PySequence_Fast(value,
2604 "must assign iterable "
2605 "to extended slice");
2606 }
2607 if (!seq)
2608 return -1;
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
2611 PyErr_Format(PyExc_ValueError,
2612 "attempt to assign sequence of "
2613 "size %zd to extended slice of "
2614 "size %zd",
2615 PySequence_Fast_GET_SIZE(seq),
2616 slicelength);
2617 Py_DECREF(seq);
2618 return -1;
2619 }
Michael W. Hudsona69c0302002-12-05 21:32:32 +00002620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 if (!slicelength) {
2622 Py_DECREF(seq);
2623 return 0;
2624 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 garbage = (PyObject**)
2627 PyMem_MALLOC(slicelength*sizeof(PyObject*));
2628 if (!garbage) {
2629 Py_DECREF(seq);
2630 PyErr_NoMemory();
2631 return -1;
2632 }
Tim Peters3b01a122002-07-19 02:35:45 +00002633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634 selfitems = self->ob_item;
2635 seqitems = PySequence_Fast_ITEMS(seq);
2636 for (cur = start, i = 0; i < slicelength;
Mark Dickinsonc7d93b72011-09-25 15:34:32 +01002637 cur += (size_t)step, i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 garbage[i] = selfitems[cur];
2639 ins = seqitems[i];
2640 Py_INCREF(ins);
2641 selfitems[cur] = ins;
2642 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002644 for (i = 0; i < slicelength; i++) {
2645 Py_DECREF(garbage[i]);
2646 }
Tim Peters3b01a122002-07-19 02:35:45 +00002647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 PyMem_FREE(garbage);
2649 Py_DECREF(seq);
Tim Peters3b01a122002-07-19 02:35:45 +00002650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 return 0;
2652 }
2653 }
2654 else {
2655 PyErr_Format(PyExc_TypeError,
Terry Jan Reedyffff1442014-08-02 01:30:37 -04002656 "list indices must be integers or slices, not %.200s",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 item->ob_type->tp_name);
2658 return -1;
2659 }
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002660}
2661
2662static PyMappingMethods list_as_mapping = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 (lenfunc)list_length,
2664 (binaryfunc)list_subscript,
2665 (objobjargproc)list_ass_subscript
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +00002666};
2667
Guido van Rossumc0b618a1997-05-02 03:12:38 +00002668PyTypeObject PyList_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002669 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2670 "list",
2671 sizeof(PyListObject),
2672 0,
2673 (destructor)list_dealloc, /* tp_dealloc */
2674 0, /* tp_print */
2675 0, /* tp_getattr */
2676 0, /* tp_setattr */
2677 0, /* tp_reserved */
2678 (reprfunc)list_repr, /* tp_repr */
2679 0, /* tp_as_number */
2680 &list_as_sequence, /* tp_as_sequence */
2681 &list_as_mapping, /* tp_as_mapping */
Georg Brandl00da4e02010-10-18 07:32:48 +00002682 PyObject_HashNotImplemented, /* tp_hash */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002683 0, /* tp_call */
2684 0, /* tp_str */
2685 PyObject_GenericGetAttr, /* tp_getattro */
2686 0, /* tp_setattro */
2687 0, /* tp_as_buffer */
2688 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002689 Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
2690 list___init____doc__, /* tp_doc */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 (traverseproc)list_traverse, /* tp_traverse */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002692 (inquiry)_list_clear, /* tp_clear */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 list_richcompare, /* tp_richcompare */
2694 0, /* tp_weaklistoffset */
2695 list_iter, /* tp_iter */
2696 0, /* tp_iternext */
2697 list_methods, /* tp_methods */
2698 0, /* tp_members */
2699 0, /* tp_getset */
2700 0, /* tp_base */
2701 0, /* tp_dict */
2702 0, /* tp_descr_get */
2703 0, /* tp_descr_set */
2704 0, /* tp_dictoffset */
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002705 (initproc)list___init__, /* tp_init */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002706 PyType_GenericAlloc, /* tp_alloc */
2707 PyType_GenericNew, /* tp_new */
2708 PyObject_GC_Del, /* tp_free */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002709};
Guido van Rossum4c4e7df1998-06-16 15:18:28 +00002710
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002711/*********************** List Iterator **************************/
2712
2713typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002714 PyObject_HEAD
Victor Stinner7660b882013-06-24 23:59:24 +02002715 Py_ssize_t it_index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002717} listiterobject;
2718
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002719static void listiter_dealloc(listiterobject *);
2720static int listiter_traverse(listiterobject *, visitproc, void *);
2721static PyObject *listiter_next(listiterobject *);
2722static PyObject *listiter_len(listiterobject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002723static PyObject *listiter_reduce_general(void *_it, int forward);
2724static PyObject *listiter_reduce(listiterobject *);
2725static PyObject *listiter_setstate(listiterobject *, PyObject *state);
Raymond Hettinger435bf582004-03-18 22:43:10 +00002726
Armin Rigof5b3e362006-02-11 21:32:43 +00002727PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002728PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
2729PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00002730
2731static PyMethodDef listiter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002732 {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002733 {"__reduce__", (PyCFunction)listiter_reduce, METH_NOARGS, reduce_doc},
2734 {"__setstate__", (PyCFunction)listiter_setstate, METH_O, setstate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002735 {NULL, NULL} /* sentinel */
Raymond Hettinger435bf582004-03-18 22:43:10 +00002736};
2737
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002738PyTypeObject PyListIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2740 "list_iterator", /* tp_name */
2741 sizeof(listiterobject), /* tp_basicsize */
2742 0, /* tp_itemsize */
2743 /* methods */
2744 (destructor)listiter_dealloc, /* tp_dealloc */
2745 0, /* tp_print */
2746 0, /* tp_getattr */
2747 0, /* tp_setattr */
2748 0, /* tp_reserved */
2749 0, /* tp_repr */
2750 0, /* tp_as_number */
2751 0, /* tp_as_sequence */
2752 0, /* tp_as_mapping */
2753 0, /* tp_hash */
2754 0, /* tp_call */
2755 0, /* tp_str */
2756 PyObject_GenericGetAttr, /* tp_getattro */
2757 0, /* tp_setattro */
2758 0, /* tp_as_buffer */
2759 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2760 0, /* tp_doc */
2761 (traverseproc)listiter_traverse, /* tp_traverse */
2762 0, /* tp_clear */
2763 0, /* tp_richcompare */
2764 0, /* tp_weaklistoffset */
2765 PyObject_SelfIter, /* tp_iter */
2766 (iternextfunc)listiter_next, /* tp_iternext */
2767 listiter_methods, /* tp_methods */
2768 0, /* tp_members */
Raymond Hettinger14bd6de2002-05-31 21:40:38 +00002769};
Raymond Hettinger1021c442003-11-07 15:38:09 +00002770
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002771
2772static PyObject *
2773list_iter(PyObject *seq)
2774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775 listiterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 if (!PyList_Check(seq)) {
2778 PyErr_BadInternalCall();
2779 return NULL;
2780 }
2781 it = PyObject_GC_New(listiterobject, &PyListIter_Type);
2782 if (it == NULL)
2783 return NULL;
2784 it->it_index = 0;
2785 Py_INCREF(seq);
2786 it->it_seq = (PyListObject *)seq;
2787 _PyObject_GC_TRACK(it);
2788 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002789}
2790
2791static void
2792listiter_dealloc(listiterobject *it)
2793{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002794 _PyObject_GC_UNTRACK(it);
2795 Py_XDECREF(it->it_seq);
2796 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002797}
2798
2799static int
2800listiter_traverse(listiterobject *it, visitproc visit, void *arg)
2801{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002802 Py_VISIT(it->it_seq);
2803 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002804}
2805
2806static PyObject *
2807listiter_next(listiterobject *it)
2808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002809 PyListObject *seq;
2810 PyObject *item;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812 assert(it != NULL);
2813 seq = it->it_seq;
2814 if (seq == NULL)
2815 return NULL;
2816 assert(PyList_Check(seq));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002818 if (it->it_index < PyList_GET_SIZE(seq)) {
2819 item = PyList_GET_ITEM(seq, it->it_index);
2820 ++it->it_index;
2821 Py_INCREF(item);
2822 return item;
2823 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03002826 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002828}
2829
2830static PyObject *
2831listiter_len(listiterobject *it)
2832{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002833 Py_ssize_t len;
2834 if (it->it_seq) {
2835 len = PyList_GET_SIZE(it->it_seq) - it->it_index;
2836 if (len >= 0)
2837 return PyLong_FromSsize_t(len);
2838 }
2839 return PyLong_FromLong(0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002840}
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002841
2842static PyObject *
2843listiter_reduce(listiterobject *it)
2844{
2845 return listiter_reduce_general(it, 1);
2846}
2847
2848static PyObject *
2849listiter_setstate(listiterobject *it, PyObject *state)
2850{
Victor Stinner7660b882013-06-24 23:59:24 +02002851 Py_ssize_t index = PyLong_AsSsize_t(state);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002852 if (index == -1 && PyErr_Occurred())
2853 return NULL;
2854 if (it->it_seq != NULL) {
2855 if (index < 0)
2856 index = 0;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +00002857 else if (index > PyList_GET_SIZE(it->it_seq))
2858 index = PyList_GET_SIZE(it->it_seq); /* iterator exhausted */
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002859 it->it_index = index;
2860 }
2861 Py_RETURN_NONE;
2862}
2863
Raymond Hettinger1021c442003-11-07 15:38:09 +00002864/*********************** List Reverse Iterator **************************/
2865
2866typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 PyObject_HEAD
2868 Py_ssize_t it_index;
2869 PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
Raymond Hettinger1021c442003-11-07 15:38:09 +00002870} listreviterobject;
2871
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002872static void listreviter_dealloc(listreviterobject *);
2873static int listreviter_traverse(listreviterobject *, visitproc, void *);
2874static PyObject *listreviter_next(listreviterobject *);
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002875static PyObject *listreviter_len(listreviterobject *);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002876static PyObject *listreviter_reduce(listreviterobject *);
2877static PyObject *listreviter_setstate(listreviterobject *, PyObject *);
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002878
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002879static PyMethodDef listreviter_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002880 {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002881 {"__reduce__", (PyCFunction)listreviter_reduce, METH_NOARGS, reduce_doc},
2882 {"__setstate__", (PyCFunction)listreviter_setstate, METH_O, setstate_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002883 {NULL, NULL} /* sentinel */
Raymond Hettingeref9bf402004-03-10 10:10:42 +00002884};
2885
Raymond Hettinger1021c442003-11-07 15:38:09 +00002886PyTypeObject PyListRevIter_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002887 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2888 "list_reverseiterator", /* tp_name */
2889 sizeof(listreviterobject), /* tp_basicsize */
2890 0, /* tp_itemsize */
2891 /* methods */
2892 (destructor)listreviter_dealloc, /* tp_dealloc */
2893 0, /* tp_print */
2894 0, /* tp_getattr */
2895 0, /* tp_setattr */
2896 0, /* tp_reserved */
2897 0, /* tp_repr */
2898 0, /* tp_as_number */
2899 0, /* tp_as_sequence */
2900 0, /* tp_as_mapping */
2901 0, /* tp_hash */
2902 0, /* tp_call */
2903 0, /* tp_str */
2904 PyObject_GenericGetAttr, /* tp_getattro */
2905 0, /* tp_setattro */
2906 0, /* tp_as_buffer */
2907 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
2908 0, /* tp_doc */
2909 (traverseproc)listreviter_traverse, /* tp_traverse */
2910 0, /* tp_clear */
2911 0, /* tp_richcompare */
2912 0, /* tp_weaklistoffset */
2913 PyObject_SelfIter, /* tp_iter */
2914 (iternextfunc)listreviter_next, /* tp_iternext */
2915 listreviter_methods, /* tp_methods */
2916 0,
Raymond Hettinger1021c442003-11-07 15:38:09 +00002917};
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002918
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002919/*[clinic input]
2920list.__reversed__
2921
2922Return a reverse iterator over the list.
2923[clinic start generated code]*/
2924
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002925static PyObject *
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002926list___reversed___impl(PyListObject *self)
2927/*[clinic end generated code: output=b166f073208c888c input=eadb6e17f8a6a280]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002928{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002929 listreviterobject *it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002931 it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
2932 if (it == NULL)
2933 return NULL;
Serhiy Storchakafdd42c42017-03-11 09:19:20 +02002934 assert(PyList_Check(self));
2935 it->it_index = PyList_GET_SIZE(self) - 1;
2936 Py_INCREF(self);
2937 it->it_seq = self;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002938 PyObject_GC_Track(it);
2939 return (PyObject *)it;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002940}
2941
2942static void
2943listreviter_dealloc(listreviterobject *it)
2944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002945 PyObject_GC_UnTrack(it);
2946 Py_XDECREF(it->it_seq);
2947 PyObject_GC_Del(it);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002948}
2949
2950static int
2951listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
2952{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953 Py_VISIT(it->it_seq);
2954 return 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002955}
2956
2957static PyObject *
2958listreviter_next(listreviterobject *it)
2959{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960 PyObject *item;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03002961 Py_ssize_t index;
2962 PyListObject *seq;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002963
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03002964 assert(it != NULL);
2965 seq = it->it_seq;
2966 if (seq == NULL) {
2967 return NULL;
2968 }
2969 assert(PyList_Check(seq));
2970
2971 index = it->it_index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002972 if (index>=0 && index < PyList_GET_SIZE(seq)) {
2973 item = PyList_GET_ITEM(seq, index);
2974 it->it_index--;
2975 Py_INCREF(item);
2976 return item;
2977 }
2978 it->it_index = -1;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +03002979 it->it_seq = NULL;
2980 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002981 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002982}
2983
Raymond Hettingerf5b64112008-12-02 21:33:45 +00002984static PyObject *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002985listreviter_len(listreviterobject *it)
2986{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002987 Py_ssize_t len = it->it_index + 1;
2988 if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
2989 len = 0;
2990 return PyLong_FromSsize_t(len);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002991}
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00002992
2993static PyObject *
2994listreviter_reduce(listreviterobject *it)
2995{
2996 return listiter_reduce_general(it, 0);
2997}
2998
2999static PyObject *
3000listreviter_setstate(listreviterobject *it, PyObject *state)
3001{
3002 Py_ssize_t index = PyLong_AsSsize_t(state);
3003 if (index == -1 && PyErr_Occurred())
3004 return NULL;
3005 if (it->it_seq != NULL) {
3006 if (index < -1)
3007 index = -1;
3008 else if (index > PyList_GET_SIZE(it->it_seq) - 1)
3009 index = PyList_GET_SIZE(it->it_seq) - 1;
3010 it->it_index = index;
3011 }
3012 Py_RETURN_NONE;
3013}
3014
3015/* common pickling support */
3016
3017static PyObject *
3018listiter_reduce_general(void *_it, int forward)
3019{
3020 PyObject *list;
3021
3022 /* the objects are not the same, index is of different types! */
3023 if (forward) {
3024 listiterobject *it = (listiterobject *)_it;
3025 if (it->it_seq)
Victor Stinner7660b882013-06-24 23:59:24 +02003026 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003027 it->it_seq, it->it_index);
3028 } else {
3029 listreviterobject *it = (listreviterobject *)_it;
3030 if (it->it_seq)
Antoine Pitroua7013882012-04-05 00:04:20 +02003031 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("reversed"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003032 it->it_seq, it->it_index);
3033 }
3034 /* empty iterator, create an empty list */
3035 list = PyList_New(0);
3036 if (list == NULL)
3037 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +02003038 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), list);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +00003039}